{"text":"#include \"tcpclient.h\"\n#include \n#include \n#include \nnamespace adrianx\n{\n\ttcp_client::tcp_client(): _error_state(0), _shutdown( 1 ),_recv_pack_size(0)\n\t{\n\t}\n\n\ttcp_client::~tcp_client()\n\t{\n\t\tclose();\n\t}\n\n\tbool tcp_client::connect( const std::string & host, uint16_t port )\n\t{\n\n\t\tif(boost::interprocess::ipcdetail::atomic_cas32( &_shutdown, 0, 1 )==0)\/\/Ѿ״̬\n\t\t\treturn false;\n\n\t\tbool ok = false;\n\t\tboost::asio::ip::tcp::resolver::iterator iterator;\n\t\tdo \n\t\t{\n\t\t\t_io_service_ptr = io_service_sptr(new boost::asio::io_service());\n\t\t\tif(!_io_service_ptr)\n\t\t\t\tbreak;\n\t\t\t_work_ptr = work_sptr(new boost::asio::io_service::work(*_io_service_ptr));\n\t\t\tif(!_work_ptr)\n\t\t\t\tbreak;\n\t\t\t_socket = socket_sptr(new boost::asio::ip::tcp::socket(*_io_service_ptr));\n\t\t\tif(!_socket)\n\t\t\t\tbreak;\n\t\t\t_strand = strand_sptr(new boost::asio::strand(*_io_service_ptr));\n\t\t\tif(!_strand)\n\t\t\t\tbreak;\n\n\t\t\tboost::system::error_code ec;\n\t\t\tboost::asio::ip::tcp::resolver resolver( *_io_service_ptr );\n\t\t\tboost::asio::ip::tcp::resolver::query query( host, boost::lexical_cast< std::string >( port ) );\n\t\t\titerator = resolver.resolve( query );\n\t\t\t\n\t\t\t_thread_ptr = thread_sptr(new boost::thread(boost::bind( &boost::asio::io_service::run, _io_service_ptr)));\n\t\t\tif(!_thread_ptr)\n\t\t\t\tbreak;\n\t\t\tok = true;\n\t\t} while (0);\n\n\t\tif(!ok)\n\t\t{\n\t\t\t_strand.reset();\n\t\t\t_socket.reset();\n\t\t\t_work_ptr.reset();\n\t\t\t_io_service_ptr.reset();\n\t\t\tboost::interprocess::ipcdetail::atomic_cas32( &_shutdown, 1, 0 );\n\t\t\treturn false;\n\t\t}\n\t\t_socket->async_connect( *iterator, _strand->wrap( boost::bind( &tcp_client::handle_connect, shared_from_this(), boost::asio::placeholders::error ) ) );\n\t\treturn true;\n\t}\n\n\tvoid tcp_client::close()\n\t{\n\t\tif( boost::interprocess::ipcdetail::atomic_cas32( &_shutdown, 1, 0 ) == 0 )\n\t\t{\n\t\t\t_strand->post( boost::bind( &tcp_client::handle_error, shared_from_this(), boost::asio::error::connection_reset));\n\t\t\t_thread_ptr->join();\n\n\t\t\t_thread_ptr.reset();\n\t\t\t_work_ptr.reset();\n\t\t\t_socket.reset();\n\t\t\t_strand.reset();\n\t\t\t_io_service_ptr.reset();\n\t\t\tclear_pending_send();\n\t\t}\n\t}\n\n\tbool tcp_client::send( uint8_t * data,uint16_t size )\n\t{\n\t\tif(has_stopped())\n\t\t\treturn false;\n\n\t\tif(push_pending_send(data,size))\n\t\t\t_strand->post(boost::bind(&tcp_client::start_send,shared_from_this()));\n\n\t\treturn true;\n\t}\n\n\tvoid tcp_client::handle_error( const boost::system::error_code & error )\n\t{\n\t\tif( boost::interprocess::ipcdetail::atomic_cas32( &_error_state, 1, 0 ) == 0 )\n\t\t{\n\t\t\tboost::system::error_code ec;\n\t\t\t_socket->shutdown( boost::asio::ip::tcp::socket::shutdown_both, ec );\n\t\t\t_socket->close( ec );\n\t\t\t_io_service_ptr->reset();\n\t\t\t_io_service_ptr->stop();\n\t\t\ton_error( error );\n\t\t}\n\t}\n\n\tbool tcp_client::has_error()\n\t{\n\t\treturn ( boost::interprocess::ipcdetail::atomic_cas32( &_error_state, 1, 1 ) == 1 );\t\n\t}\n\n\tvoid tcp_client::handle_connect( const boost::system::error_code & error )\n\t{\n\t\tif( error || has_error() ||has_stopped())\n\t\t{\n\t\t\thandle_error( error );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif( _socket->is_open() )\n\t\t\t{\n\t\t\t\ton_connected( _socket->remote_endpoint().address().to_string(), _socket->remote_endpoint().port(),\n\t\t\t\t\t_socket->local_endpoint().port()\n\t\t\t\t\t);\n\n\t\t\t\t_socket->async_receive(boost::asio::buffer( &_recv_pack_size ,sizeof(_recv_pack_size)),\n\t\t\t\t\tboost::bind(&tcp_client::handle_header_recv,shared_from_this(), boost::asio::placeholders::error));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\thandle_error( error );\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid tcp_client::handle_header_recv( const boost::system::error_code & error )\n\t{\n\t\tif( error || has_error()||has_stopped())\n\t\t{\n\t\t\thandle_error( error );\n\t\t}\n\t\telse\n\t\t{\n#if(__BYTE_ORDER==__LITTLE_ENDIAN)\t\n\t\t\t_recv_pack_size = ((_recv_pack_size & 0xff00) >> 8) | ((_recv_pack_size & 0xff) <<8);\n#endif\n\t\t\t_socket->async_receive(boost::asio::buffer(_recv_body,_recv_pack_size),boost::bind(&tcp_client::handle_body_recv,shared_from_this(), boost::asio::placeholders::error));\n\t\t}\n\t}\n\n\tvoid tcp_client::handle_body_recv( const boost::system::error_code & error )\n\t{\n\t\tif( error || has_error()||has_stopped())\n\t\t{\n\t\t\thandle_error( error );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::vector buffer(_recv_body,_recv_body+_recv_pack_size);\n\n\t\t\ton_recv(buffer);\n\n\t\t\t_socket->async_receive(boost::asio::buffer( &_recv_pack_size ,sizeof(_recv_pack_size)),\n\t\t\t\tboost::bind(&tcp_client::handle_header_recv,shared_from_this(), boost::asio::placeholders::error));\n\t\t}\n\t}\n\n\tbool tcp_client::push_pending_send( void * data,uint16_t size )\n\t{\n\t\tif(!size)\n\t\t\treturn false;\n\n\t\tuint8_t * pack = new uint8_t[size+2];\n\t\tif(!pack)\n\t\t\treturn false;\n#if(__BYTE_ORDER==__LITTLE_ENDIAN)\t\n\t\tpack[1] = size&0xff;\n\t\tpack[0] = (size&0xff00)>>8;\n#else\n\t\tpack[0] = size&0xff;\n\t\tpack[1] = (size&0xff00)>>8;\n#endif\t \n\t\tmemcpy(pack+2,data,size);\n\t\tbool need_start_send = false;\n\t\tboost::recursive_mutex::scoped_lock lock(_pending_mtx);\n\t\tif(_pending_sends.empty())\n\t\t\tneed_start_send = true;\n\t\t_pending_sends.push_back(pack);\n\t\treturn need_start_send;\n\t}\n\n\tvoid tcp_client::clear_pending_send()\n\t{\n\t\tif(_pending_sends.empty())\n\t\t\treturn;\n\t\tboost::recursive_mutex::scoped_lock lock(_pending_mtx);\n\t\twhile (!_pending_sends.empty())\n\t\t{\n\t\t\tuint8_t * pack = _pending_sends.front();\n\t\t\t_pending_sends.pop_front();\n\t\t\tdelete []pack;\n\t\t}\n\t}\n\n\tvoid tcp_client::start_send()\n\t{\n\t\tif(has_stopped())\n\t\t\treturn;\n\t\tif(_pending_sends.empty() )\n\t\t\treturn;\n\t\tboost::recursive_mutex::scoped_lock lock(_pending_mtx);\n\t\tuint8_t * pack = _pending_sends.front();\n\t\tint size = 0;\n#if(__BYTE_ORDER==__LITTLE_ENDIAN)\t\n\t\tsize|= pack[1];\n\t\tsize|= pack[0]<<8;\n#else\n\t\tsize|= pack[0];\n\t\tsize|= pack[1]<<8;\n#endif \n\t\t_socket->async_send( boost::asio::buffer(pack,size+2),\n\t\t\t\t\t\t\t\t_strand->wrap( boost::bind( &tcp_client::handle_send, shared_from_this(), \n\t\t\t\t\t\t\t\tboost::asio::placeholders::error, _pending_sends.begin())));\n\t}\n\n\tvoid tcp_client::handle_send( const boost::system::error_code & error,std::list< uint8_t *>::iterator& itr)\n\t{\n\t\tif( error || has_error() ||has_stopped())\n\t\t{\n\t\t\thandle_error(error );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tboost::recursive_mutex::scoped_lock lock(_pending_mtx);\n\t\t\tuint8_t * pack = _pending_sends.front();\n\t\t\tint size = 0;\n#if(__BYTE_ORDER==__LITTLE_ENDIAN)\t\n\t\t\tsize|= pack[1];\n\t\t\tsize|= pack[0]<<8;\n#else\n\t\t\tsize|= pack[0];\n\t\t\tsize|= pack[1]<<8;\n#endif \n\t\t\ton_send(size+2);\n\t\t\t_pending_sends.erase( itr );\n\n\t\t\tdelete []pack;\n\t\t\tstart_send();\n\t\t}\n\t}\n\n\tbool tcp_client::has_stopped()\n\t{\n\t\treturn ( boost::interprocess::ipcdetail::atomic_cas32( &_shutdown, 1, 1 ) == 1 );\n\t}\n\n}Update tcpclient.cpp#include \"tcpclient.h\"\n#include \n#include \n#include \nnamespace adrianx\n{\n\ttcp_client::tcp_client(): _error_state(0), _shutdown( 1 ),_recv_pack_size(0)\n\t{\n\t}\n\n\ttcp_client::~tcp_client()\n\t{\n\t\tclose();\n\t}\n\n\tbool tcp_client::connect( const std::string & host, uint16_t port )\n\t{\n\n\t\tif(boost::interprocess::ipcdetail::atomic_cas32( &_shutdown, 0, 1 )==0)\/\/�Ѿ���������״̬\n\t\t\treturn false;\n\n\t\tbool ok = false;\n\t\tboost::asio::ip::tcp::resolver::iterator iterator;\n\t\tdo \n\t\t{\n\t\t\t_io_service_ptr = io_service_sptr(new boost::asio::io_service());\n\t\t\tif(!_io_service_ptr)\n\t\t\t\tbreak;\n\t\t\t_work_ptr = work_sptr(new boost::asio::io_service::work(*_io_service_ptr));\n\t\t\tif(!_work_ptr)\n\t\t\t\tbreak;\n\t\t\t_socket = socket_sptr(new boost::asio::ip::tcp::socket(*_io_service_ptr));\n\t\t\tif(!_socket)\n\t\t\t\tbreak;\n\t\t\t_strand = strand_sptr(new boost::asio::strand(*_io_service_ptr));\n\t\t\tif(!_strand)\n\t\t\t\tbreak;\n\n\t\t\tboost::system::error_code ec;\n\t\t\tboost::asio::ip::tcp::resolver resolver( *_io_service_ptr );\n\t\t\tboost::asio::ip::tcp::resolver::query query( host, boost::lexical_cast< std::string >( port ) );\n\t\t\titerator = resolver.resolve( query );\n\t\t\t\n\t\t\t_thread_ptr = thread_sptr(new boost::thread(boost::bind( &boost::asio::io_service::run, _io_service_ptr)));\n\t\t\tif(!_thread_ptr)\n\t\t\t\tbreak;\n\t\t\tok = true;\n\t\t} while (0);\n\n\t\tif(!ok)\n\t\t{\n\t\t\t_strand.reset();\n\t\t\t_socket.reset();\n\t\t\t_work_ptr.reset();\n\t\t\t_io_service_ptr.reset();\n\t\t\tboost::interprocess::ipcdetail::atomic_cas32( &_shutdown, 1, 0 );\n\t\t\treturn false;\n\t\t}\n\t\t_socket->async_connect( *iterator, _strand->wrap( boost::bind( &tcp_client::handle_connect, shared_from_this(), boost::asio::placeholders::error ) ) );\n\t\treturn true;\n\t}\n\n\tvoid tcp_client::close()\n\t{\n\t\tif( boost::interprocess::ipcdetail::atomic_cas32( &_shutdown, 1, 0 ) == 0 )\n\t\t{\n\t\t\t_strand->post( boost::bind( &tcp_client::handle_error, shared_from_this(), boost::asio::error::connection_reset));\n\t\t\t_thread_ptr->join();\n\n\t\t\t_thread_ptr.reset();\n\t\t\t_work_ptr.reset();\n\t\t\t_socket.reset();\n\t\t\t_strand.reset();\n\t\t\t_io_service_ptr.reset();\n\t\t\tclear_pending_send();\n\t\t}\n\t}\n\n\tbool tcp_client::send( uint8_t * data,uint16_t size )\n\t{\n\t\tif(data == 0)\n\t\t\treturn false;\n\t\t\n\t\tif(size == 0)\n\t\t\treturn false;\n\t\t\n\t\t\n\t\tif(has_stopped())\n\t\t\treturn false;\n\n\t\tif(push_pending_send(data,size))\n\t\t\t_strand->post(boost::bind(&tcp_client::start_send,shared_from_this()));\n\n\t\treturn true;\n\t}\n\n\tvoid tcp_client::handle_error( const boost::system::error_code & error )\n\t{\n\t\tif( boost::interprocess::ipcdetail::atomic_cas32( &_error_state, 1, 0 ) == 0 )\n\t\t{\n\t\t\tboost::system::error_code ec;\n\t\t\t_socket->shutdown( boost::asio::ip::tcp::socket::shutdown_both, ec );\n\t\t\t_socket->close( ec );\n\t\t\t_io_service_ptr->reset();\n\t\t\t_io_service_ptr->stop();\n\t\t\ton_error( error );\n\t\t}\n\t}\n\n\tbool tcp_client::has_error()\n\t{\n\t\treturn ( boost::interprocess::ipcdetail::atomic_cas32( &_error_state, 1, 1 ) == 1 );\t\n\t}\n\n\tvoid tcp_client::handle_connect( const boost::system::error_code & error )\n\t{\n\t\tif( error || has_error() ||has_stopped())\n\t\t{\n\t\t\thandle_error( error );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif( _socket->is_open() )\n\t\t\t{\n\t\t\t\ton_connected( _socket->remote_endpoint().address().to_string(), _socket->remote_endpoint().port(),\n\t\t\t\t\t_socket->local_endpoint().port()\n\t\t\t\t\t);\n\n\t\t\t\t_socket->async_receive(boost::asio::buffer( &_recv_pack_size ,sizeof(_recv_pack_size)),\n\t\t\t\t\tboost::bind(&tcp_client::handle_header_recv,shared_from_this(), boost::asio::placeholders::error));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\thandle_error( error );\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid tcp_client::handle_header_recv( const boost::system::error_code & error )\n\t{\n\t\tif( error || has_error()||has_stopped())\n\t\t{\n\t\t\thandle_error( error );\n\t\t}\n\t\telse\n\t\t{\n#if(__BYTE_ORDER==__LITTLE_ENDIAN)\t\n\t\t\t_recv_pack_size = ((_recv_pack_size & 0xff00) >> 8) | ((_recv_pack_size & 0xff) <<8);\n#endif\n\t\t\t_socket->async_receive(boost::asio::buffer(_recv_body,_recv_pack_size),boost::bind(&tcp_client::handle_body_recv,shared_from_this(), boost::asio::placeholders::error));\n\t\t}\n\t}\n\n\tvoid tcp_client::handle_body_recv( const boost::system::error_code & error )\n\t{\n\t\tif( error || has_error()||has_stopped())\n\t\t{\n\t\t\thandle_error( error );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::vector buffer(_recv_body,_recv_body+_recv_pack_size);\n\n\t\t\ton_recv(buffer);\n\n\t\t\t_socket->async_receive(boost::asio::buffer( &_recv_pack_size ,sizeof(_recv_pack_size)),\n\t\t\t\tboost::bind(&tcp_client::handle_header_recv,shared_from_this(), boost::asio::placeholders::error));\n\t\t}\n\t}\n\n\tbool tcp_client::push_pending_send( void * data,uint16_t size )\n\t{\n\t\tif(!size)\n\t\t\treturn false;\n\n\t\tuint8_t * pack = new uint8_t[size+2];\n\t\tif(!pack)\n\t\t\treturn false;\n#if(__BYTE_ORDER==__LITTLE_ENDIAN)\t\n\t\tpack[1] = size&0xff;\n\t\tpack[0] = (size&0xff00)>>8;\n#else\n\t\tpack[0] = size&0xff;\n\t\tpack[1] = (size&0xff00)>>8;\n#endif\t \n\t\tmemcpy(pack+2,data,size);\n\t\tbool need_start_send = false;\n\t\tboost::recursive_mutex::scoped_lock lock(_pending_mtx);\n\t\tif(_pending_sends.empty())\n\t\t\tneed_start_send = true;\n\t\t_pending_sends.push_back(pack);\n\t\treturn need_start_send;\n\t}\n\n\tvoid tcp_client::clear_pending_send()\n\t{\n\t\tif(_pending_sends.empty())\n\t\t\treturn;\n\t\tboost::recursive_mutex::scoped_lock lock(_pending_mtx);\n\t\twhile (!_pending_sends.empty())\n\t\t{\n\t\t\tuint8_t * pack = _pending_sends.front();\n\t\t\t_pending_sends.pop_front();\n\t\t\tdelete []pack;\n\t\t}\n\t}\n\n\tvoid tcp_client::start_send()\n\t{\n\t\tif(has_stopped())\n\t\t\treturn;\n\t\tif(_pending_sends.empty() )\n\t\t\treturn;\n\t\tboost::recursive_mutex::scoped_lock lock(_pending_mtx);\n\t\tuint8_t * pack = _pending_sends.front();\n\t\tint size = 0;\n#if(__BYTE_ORDER==__LITTLE_ENDIAN)\t\n\t\tsize|= pack[1];\n\t\tsize|= pack[0]<<8;\n#else\n\t\tsize|= pack[0];\n\t\tsize|= pack[1]<<8;\n#endif \n\t\t_socket->async_send( boost::asio::buffer(pack,size+2),\n\t\t\t\t\t\t\t\t_strand->wrap( boost::bind( &tcp_client::handle_send, shared_from_this(), \n\t\t\t\t\t\t\t\tboost::asio::placeholders::error, _pending_sends.begin())));\n\t}\n\n\tvoid tcp_client::handle_send( const boost::system::error_code & error,std::list< uint8_t *>::iterator& itr)\n\t{\n\t\tif( error || has_error() ||has_stopped())\n\t\t{\n\t\t\thandle_error(error );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tboost::recursive_mutex::scoped_lock lock(_pending_mtx);\n\t\t\tuint8_t * pack = _pending_sends.front();\n\t\t\tint size = 0;\n#if(__BYTE_ORDER==__LITTLE_ENDIAN)\t\n\t\t\tsize|= pack[1];\n\t\t\tsize|= pack[0]<<8;\n#else\n\t\t\tsize|= pack[0];\n\t\t\tsize|= pack[1]<<8;\n#endif \n\t\t\ton_send(size+2);\n\t\t\t_pending_sends.erase( itr );\n\n\t\t\tdelete []pack;\n\t\t\tstart_send();\n\t\t}\n\t}\n\n\tbool tcp_client::has_stopped()\n\t{\n\t\treturn ( boost::interprocess::ipcdetail::atomic_cas32( &_shutdown, 1, 1 ) == 1 );\n\t}\n\n}\n<|endoftext|>"} {"text":"#include \"..\/tlang.h\"\n#include \n#include \n\nTLANG_NAMESPACE_BEGIN\n\nTC_TEST(\"compiler_basics_gpu\") {\n CoreState::set_trigger_gdb_when_crash(true);\n int n = 128;\n Program prog(Arch::x86_64);\n prog.config.print_ir = true;\n prog.config.arch = Arch::gpu;\n\n Global(a, i32);\n auto i = Index(0);\n layout([&]() { root.fixed(i, n).place(a); });\n\n auto dou = [](Expr a) { return a * 2; };\n\n auto func = kernel([&]() {\n Declare(i);\n For(i, 0, n, [&] {\n Local(ret) = 0;\n If(i % 2 == 0).Then([&] { ret = dou(i); }).Else([&] { ret = i; });\n a[i] = ret;\n });\n });\n\n func();\n\n for (int i = 0; i < n; i++) {\n TC_CHECK(a.val(i) == (2 - i % 2) * i);\n }\n};\n\nTLANG_NAMESPACE_END\npassed all CPU tests#include \"..\/tlang.h\"\n#include \n#include \n\nTLANG_NAMESPACE_BEGIN\n\nTC_TEST(\"compiler_basics_gpu\") {\n return;\n CoreState::set_trigger_gdb_when_crash(true);\n int n = 128;\n Program prog(Arch::x86_64);\n prog.config.print_ir = true;\n prog.config.arch = Arch::gpu;\n\n Global(a, i32);\n auto i = Index(0);\n layout([&]() { root.fixed(i, n).place(a); });\n\n auto dou = [](Expr a) { return a * 2; };\n\n auto func = kernel([&]() {\n Declare(i);\n For(i, 0, n, [&] {\n Local(ret) = 0;\n If(i % 2 == 0).Then([&] { ret = dou(i); }).Else([&] { ret = i; });\n a[i] = ret;\n });\n });\n\n func();\n\n for (int i = 0; i < n; i++) {\n TC_CHECK(a.val(i) == (2 - i % 2) * i);\n }\n};\n\nTLANG_NAMESPACE_END\n<|endoftext|>"} {"text":"\/*\n * Author: Yevgeniy Kiveisha \n * Contributions: Jon Trulson \n * Copyright (c) 2014 Intel Corporation.\n *\n * Credits to Seeed Studeo.\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \n#include \n#include \n\n#include \"th02.h\"\n\nusing namespace std;\nusing namespace upm;\n\nstruct TH02Exception : public std::exception {\n std::string message;\n TH02Exception (std::string msg) : message (msg) { }\n ~TH02Exception () throw () { }\n const char* what() const throw () { return message.c_str(); }\n};\n\nTH02::TH02 (int bus, uint8_t addr) : m_i2c(bus) {\n m_addr = addr;\n m_name = \"TH02\";\n\n mraa_result_t ret = m_i2c.address(m_addr);\n if (ret != MRAA_SUCCESS) {\n throw TH02Exception (\"Couldn't initilize I2C.\");\n }\n}\n\nTH02::~TH02 () {\n}\n\nfloat\nTH02::getTemperature () {\n uint16_t temperature = 0;\n\n \/* Start a new temperature conversion *\/\n if (m_i2c.writeReg(TH02_REG_CONFIG, TH02_CMD_MEASURE_TEMP)) {\n cerr << __FUNCTION__ << \"@\" << __LINE__ \n << \": writeReg failed\" << endl;\n return 0.0;\n }\n\n \/* Wait until conversion is done *\/\n while (getStatus() == false);\n\n temperature = m_i2c.readReg(TH02_REG_DATA_H) << 8;\n temperature |= m_i2c.readReg(TH02_REG_DATA_L);\n temperature >>= 2;\n\n return ((float(temperature) \/ 32.0) - 50.0);\n}\n\nfloat\nTH02::getHumidity () {\n uint16_t humidity = 0;\n\n \/* Start a new humidity conversion *\/\n if (m_i2c.writeReg(TH02_REG_CONFIG, TH02_CMD_MEASURE_HUMI)) {\n cerr << __FUNCTION__ << \"@\" << __LINE__ \n << \": writeReg failed\" << endl;\n return 0.0;\n }\n\n \/* Wait until conversion is done *\/\n while (getStatus() == false);\n\n humidity = m_i2c.readReg(TH02_REG_DATA_H) << 8;\n humidity |= m_i2c.readReg(TH02_REG_DATA_L);\n humidity >>= 4;\n\n return ((float(humidity) \/ 16.0) - 24.0);\n}\n\nbool\nTH02::getStatus () {\n uint8_t status = m_i2c.readReg(TH02_REG_STATUS);\n\n if (status & TH02_STATUS_RDY_MASK)\n return false; \/\/ NOT ready\n else\n return true; \/\/ ready\n}\n\nth02: remove custom exception and use standard ones\/*\n * Author: Yevgeniy Kiveisha \n * Contributions: Jon Trulson \n * Copyright (c) 2014 Intel Corporation.\n *\n * Credits to Seeed Studeo.\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \n#include \n#include \n#include \n\n#include \"th02.h\"\n\nusing namespace std;\nusing namespace upm;\n\nTH02::TH02 (int bus, uint8_t addr) : m_i2c(bus) {\n m_addr = addr;\n m_name = \"TH02\";\n\n mraa_result_t ret = m_i2c.address(m_addr);\n if (ret != MRAA_SUCCESS) {\n throw std::invalid_argument(std::string(__FUNCTION__) + \n \": mraa_i2c_address() failed\");\n }\n}\n\nTH02::~TH02 () {\n}\n\nfloat\nTH02::getTemperature () {\n uint16_t temperature = 0;\n\n \/* Start a new temperature conversion *\/\n if (m_i2c.writeReg(TH02_REG_CONFIG, TH02_CMD_MEASURE_TEMP)) {\n cerr << __FUNCTION__ << \"@\" << __LINE__ \n << \": writeReg failed\" << endl;\n return 0.0;\n }\n\n \/* Wait until conversion is done *\/\n while (getStatus() == false);\n\n temperature = m_i2c.readReg(TH02_REG_DATA_H) << 8;\n temperature |= m_i2c.readReg(TH02_REG_DATA_L);\n temperature >>= 2;\n\n return ((float(temperature) \/ 32.0) - 50.0);\n}\n\nfloat\nTH02::getHumidity () {\n uint16_t humidity = 0;\n\n \/* Start a new humidity conversion *\/\n if (m_i2c.writeReg(TH02_REG_CONFIG, TH02_CMD_MEASURE_HUMI)) {\n cerr << __FUNCTION__ << \"@\" << __LINE__ \n << \": writeReg failed\" << endl;\n return 0.0;\n }\n\n \/* Wait until conversion is done *\/\n while (getStatus() == false);\n\n humidity = m_i2c.readReg(TH02_REG_DATA_H) << 8;\n humidity |= m_i2c.readReg(TH02_REG_DATA_L);\n humidity >>= 4;\n\n return ((float(humidity) \/ 16.0) - 24.0);\n}\n\nbool\nTH02::getStatus () {\n uint8_t status = m_i2c.readReg(TH02_REG_STATUS);\n\n if (status & TH02_STATUS_RDY_MASK)\n return false; \/\/ NOT ready\n else\n return true; \/\/ ready\n}\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \"tokenizer.h\"\n\nstd::vector* tokenize(std::string str) {\n std::vector* tokens = new std::vector();\n std::string curToken = \"\";\n\n bool inString = false;\n\n for (std::string::iterator it = str.begin(); it != str.end(); it++) {\n char c = *it;\n\n if (inString && c != '\"') {\n curToken += c;\n continue;\n }\n\n switch (c) {\n\n case '\"':\n inString = !inString;\n break;\n\n case '|':\n case '<':\n case '>':\n if (curToken != \"\") {\n tokens->push_back(curToken);\n }\n tokens->push_back(std::string(1, c));\n curToken = \"\";\n break;\n\n case ' ':\n if (curToken != \"\") {\n tokens->push_back(curToken);\n }\n curToken = \"\";\n break;\n\n default:\n curToken += c;\n break;\n\n }\n\n }\n\n tokens->push_back(curToken);\n\n return tokens;\n}\nparse semicolons#include \n#include \n#include \n\n#include \"tokenizer.h\"\n\nstd::vector* tokenize(std::string str) {\n std::vector* tokens = new std::vector();\n std::string curToken = \"\";\n\n bool inString = false;\n\n for (std::string::iterator it = str.begin(); it != str.end(); it++) {\n char c = *it;\n\n if (inString && c != '\"') {\n curToken += c;\n continue;\n }\n\n switch (c) {\n\n case '\"':\n inString = !inString;\n break;\n\n case '\\n':\n case ';':\n case '|':\n case '<':\n case '>':\n if (curToken != \"\") {\n tokens->push_back(curToken);\n }\n tokens->push_back(std::string(1, c));\n curToken = \"\";\n break;\n\n case ' ':\n if (curToken != \"\") {\n tokens->push_back(curToken);\n }\n curToken = \"\";\n break;\n\n default:\n curToken += c;\n break;\n\n }\n\n }\n\n tokens->push_back(curToken);\n\n return tokens;\n}\n<|endoftext|>"} {"text":"#include \n\n#include \n#include \n\nnamespace AngelScriptIntegration {\n\nvoid handleMessage(const AngelScript::asSMessageInfo* message, void*);\n\nvoid init_message_callback_qt(AngelScript::asIScriptEngine* engine)\n{\n int r = engine->SetMessageCallback(AngelScript::asFUNCTION(handleMessage), nullptr, AngelScript::asCALL_CDECL); AngelScriptCheck(r);\n}\n\nvoid log_debug(const std::string& message);\nvoid log_info(const std::string& message);\nvoid log_warning(const std::string& message);\nvoid log_critical(const std::string& message);\n\nvoid init_logging_functions_qt(AngelScript::asIScriptEngine* engine)\n{\n int r;\n r = engine->RegisterGlobalFunction(\"void log_debug(const string &in)\", AngelScript::asFUNCTION(log_debug), AngelScript::asCALL_CDECL); AngelScriptCheck(r);\n r = engine->RegisterGlobalFunction(\"void log_info(const string &in)\", AngelScript::asFUNCTION(log_info), AngelScript::asCALL_CDECL); AngelScriptCheck(r);\n r = engine->RegisterGlobalFunction(\"void log_warning(const string &in)\", AngelScript::asFUNCTION(log_warning), AngelScript::asCALL_CDECL); AngelScriptCheck(r);\n r = engine->RegisterGlobalFunction(\"void log_critical(const string &in)\", AngelScript::asFUNCTION(log_critical), AngelScript::asCALL_CDECL); AngelScriptCheck(r);\n}\n\nvoid init_glm_vectors(AngelScript::asIScriptEngine* engine);\n\nvoid init_glm(AngelScript::asIScriptEngine* engine)\n{\n asDWORD previousMask = engine->SetDefaultAccessMask(ACCESS_MASK_GLM);\n\n\n engine->SetDefaultAccessMask(previousMask);\n}\n\nvoid log_debug(const QString& message);\nvoid log_info(const QString& message);\nvoid log_warning(const QString& message);\nvoid log_critical(const QString& message);\n\n\nvoid handleMessage(const AngelScript::asSMessageInfo* message, void*)\n{\n QString text = QString(\"Angelscript -- %0 (%1 %2):\\n%3\").arg(message->section).arg(message->row).arg(message->col).arg(message->message);\n switch(message->type)\n {\n case AngelScript::asMSGTYPE_ERROR:\n log_critical(text);\n break;\n case AngelScript::asMSGTYPE_WARNING:\n log_warning(text);\n break;\n case AngelScript::asMSGTYPE_INFORMATION:\n log_info(text);\n break;\n default:\n Q_UNREACHABLE();\n }\n}\n\nvoid log_debug(const QString& message)\n{\n log_debug(message.toStdString());\n}\n\nvoid log_info(const QString& message)\n{\n log_info(message.toStdString());\n}\n\nvoid log_warning(const QString& message)\n{\n log_warning(message.toStdString());\n}\n\nvoid log_critical(const QString& message)\n{\n log_critical(message.toStdString());\n}\n\nvoid log_debug(const std::string& message)\n{\n qDebug() << message.c_str();\n}\n\nvoid log_info(const std::string& message)\n{\n qInfo() << message.c_str();\n}\n\nvoid log_warning(const std::string& message)\n{\n qWarning() << message.c_str();\n}\n\nvoid log_critical(const std::string& message)\n{\n qCritical() << message.c_str();\n}\n\n\nconst char* AngelScriptReturnCodeAsString(AngelScript::asERetCodes returnCode)\n{\n#define CASE(x) case AngelScript::x:return #x;\n switch(returnCode)\n {\n CASE(asSUCCESS)\n\t CASE(asERROR)\n\t CASE(asCONTEXT_ACTIVE)\n\t CASE(asCONTEXT_NOT_FINISHED)\n\t CASE(asCONTEXT_NOT_PREPARED)\n\t CASE(asINVALID_ARG)\n\t CASE(asNO_FUNCTION)\n\t CASE(asNOT_SUPPORTED)\n\t CASE(asINVALID_NAME)\n\t CASE(asNAME_TAKEN)\n\t CASE(asINVALID_DECLARATION)\n\t CASE(asINVALID_OBJECT)\n\t CASE(asINVALID_TYPE)\n\t CASE(asALREADY_REGISTERED)\n\t CASE(asMULTIPLE_FUNCTIONS)\n\t CASE(asNO_MODULE)\n\t CASE(asNO_GLOBAL_VAR)\n\t CASE(asINVALID_CONFIGURATION)\n\t CASE(asINVALID_INTERFACE)\n\t CASE(asCANT_BIND_ALL_FUNCTIONS)\n\t CASE(asLOWER_ARRAY_DIMENSION_NOT_REGISTERED)\n\t CASE(asWRONG_CONFIG_GROUP)\n\t CASE(asCONFIG_GROUP_IS_IN_USE)\n\t CASE(asILLEGAL_BEHAVIOUR_FOR_TYPE)\n\t CASE(asWRONG_CALLING_CONV)\n\t CASE(asBUILD_IN_PROGRESS)\n\t CASE(asINIT_GLOBAL_VARS_FAILED)\n\t CASE(asOUT_OF_MEMORY)\n\t CASE(asMODULE_IS_IN_USE)\n default:\n return \"Unknown AngelScript ReturnCode\";\n }\n#undef CASE\n}\n\nvoid AngelScriptCheck(int r)\n{\n AngelScript::asERetCodes returnCode = static_cast(r);\n\n if(returnCode >= 0)\n return;\n\n std::string strReturnCode = AngelScriptReturnCodeAsString(returnCode);\n\n qCritical() << \"AngelScriptCheck(): Error Code \" << strReturnCode << \" detected!\";\n\n Q_ASSERT(returnCode >= 0);\n}\n\n} \/\/ AngelScriptIntegration\n\nstarted actually registering the vector classes and functions#include \n\n#include \n#include \n\nnamespace AngelScriptIntegration {\n\nvoid handleMessage(const AngelScript::asSMessageInfo* message, void*);\n\nvoid init_message_callback_qt(AngelScript::asIScriptEngine* engine)\n{\n int r = engine->SetMessageCallback(AngelScript::asFUNCTION(handleMessage), nullptr, AngelScript::asCALL_CDECL); AngelScriptCheck(r);\n}\n\nvoid log_debug(const std::string& message);\nvoid log_info(const std::string& message);\nvoid log_warning(const std::string& message);\nvoid log_critical(const std::string& message);\n\nvoid init_logging_functions_qt(AngelScript::asIScriptEngine* engine)\n{\n int r;\n r = engine->RegisterGlobalFunction(\"void log_debug(const string &in)\", AngelScript::asFUNCTION(log_debug), AngelScript::asCALL_CDECL); AngelScriptCheck(r);\n r = engine->RegisterGlobalFunction(\"void log_info(const string &in)\", AngelScript::asFUNCTION(log_info), AngelScript::asCALL_CDECL); AngelScriptCheck(r);\n r = engine->RegisterGlobalFunction(\"void log_warning(const string &in)\", AngelScript::asFUNCTION(log_warning), AngelScript::asCALL_CDECL); AngelScriptCheck(r);\n r = engine->RegisterGlobalFunction(\"void log_critical(const string &in)\", AngelScript::asFUNCTION(log_critical), AngelScript::asCALL_CDECL); AngelScriptCheck(r);\n}\n\nvoid init_glm_vectors(AngelScript::asIScriptEngine* engine);\n\nvoid init_glm(AngelScript::asIScriptEngine* engine)\n{\n asDWORD previousMask = engine->SetDefaultAccessMask(ACCESS_MASK_GLM);\n\n init_glm_vectors(engine);\n\n engine->SetDefaultAccessMask(previousMask);\n}\n\nvoid log_debug(const QString& message);\nvoid log_info(const QString& message);\nvoid log_warning(const QString& message);\nvoid log_critical(const QString& message);\n\n\nvoid handleMessage(const AngelScript::asSMessageInfo* message, void*)\n{\n QString text = QString(\"Angelscript -- %0 (%1 %2):\\n%3\").arg(message->section).arg(message->row).arg(message->col).arg(message->message);\n switch(message->type)\n {\n case AngelScript::asMSGTYPE_ERROR:\n log_critical(text);\n break;\n case AngelScript::asMSGTYPE_WARNING:\n log_warning(text);\n break;\n case AngelScript::asMSGTYPE_INFORMATION:\n log_info(text);\n break;\n default:\n Q_UNREACHABLE();\n }\n}\n\nvoid log_debug(const QString& message)\n{\n log_debug(message.toStdString());\n}\n\nvoid log_info(const QString& message)\n{\n log_info(message.toStdString());\n}\n\nvoid log_warning(const QString& message)\n{\n log_warning(message.toStdString());\n}\n\nvoid log_critical(const QString& message)\n{\n log_critical(message.toStdString());\n}\n\nvoid log_debug(const std::string& message)\n{\n qDebug() << message.c_str();\n}\n\nvoid log_info(const std::string& message)\n{\n qInfo() << message.c_str();\n}\n\nvoid log_warning(const std::string& message)\n{\n qWarning() << message.c_str();\n}\n\nvoid log_critical(const std::string& message)\n{\n qCritical() << message.c_str();\n}\n\n\nconst char* AngelScriptReturnCodeAsString(AngelScript::asERetCodes returnCode)\n{\n#define CASE(x) case AngelScript::x:return #x;\n switch(returnCode)\n {\n CASE(asSUCCESS)\n\t CASE(asERROR)\n\t CASE(asCONTEXT_ACTIVE)\n\t CASE(asCONTEXT_NOT_FINISHED)\n\t CASE(asCONTEXT_NOT_PREPARED)\n\t CASE(asINVALID_ARG)\n\t CASE(asNO_FUNCTION)\n\t CASE(asNOT_SUPPORTED)\n\t CASE(asINVALID_NAME)\n\t CASE(asNAME_TAKEN)\n\t CASE(asINVALID_DECLARATION)\n\t CASE(asINVALID_OBJECT)\n\t CASE(asINVALID_TYPE)\n\t CASE(asALREADY_REGISTERED)\n\t CASE(asMULTIPLE_FUNCTIONS)\n\t CASE(asNO_MODULE)\n\t CASE(asNO_GLOBAL_VAR)\n\t CASE(asINVALID_CONFIGURATION)\n\t CASE(asINVALID_INTERFACE)\n\t CASE(asCANT_BIND_ALL_FUNCTIONS)\n\t CASE(asLOWER_ARRAY_DIMENSION_NOT_REGISTERED)\n\t CASE(asWRONG_CONFIG_GROUP)\n\t CASE(asCONFIG_GROUP_IS_IN_USE)\n\t CASE(asILLEGAL_BEHAVIOUR_FOR_TYPE)\n\t CASE(asWRONG_CALLING_CONV)\n\t CASE(asBUILD_IN_PROGRESS)\n\t CASE(asINIT_GLOBAL_VARS_FAILED)\n\t CASE(asOUT_OF_MEMORY)\n\t CASE(asMODULE_IS_IN_USE)\n default:\n return \"Unknown AngelScript ReturnCode\";\n }\n#undef CASE\n}\n\nvoid AngelScriptCheck(int r)\n{\n AngelScript::asERetCodes returnCode = static_cast(r);\n\n if(returnCode >= 0)\n return;\n\n const char* strReturnCode = AngelScriptReturnCodeAsString(returnCode);\n\n qCritical() << \"AngelScriptCheck(): Error Code \" << strReturnCode << \" detected!\";\n\n Q_ASSERT(returnCode >= 0);\n}\n\n} \/\/ AngelScriptIntegration\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\n\nnamespace lime {\n\n\n\tstatic int id_b;\n\tstatic int id_length;\n\tstatic bool init = false;\n\tstatic bool useBuffer = false;\n\tstatic std::map hadValue;\n\tstatic std::map usingValue;\n\tstatic Mutex mutex;\n\n\n\tinline void _initializeBytes () {\n\n\t\tif (!init) {\n\n\t\t\tid_b = val_id (\"b\");\n\t\t\tid_length = val_id (\"length\");\n\n\t\t\tbuffer _buffer = alloc_buffer_len (1);\n\n\t\t\tif (buffer_data (_buffer)) {\n\n\t\t\t\tuseBuffer = true;\n\n\t\t\t}\n\n\t\t\tinit = true;\n\n\t\t}\n\n\t}\n\n\n\tBytes::Bytes () {\n\n\t\t_initializeBytes ();\n\n\t\tb = 0;\n\t\tlength = 0;\n\n\t}\n\n\n\tBytes::Bytes (value bytes) {\n\n\t\t_initializeBytes ();\n\n\t\tb = 0;\n\t\tlength = 0;\n\n\t\tSet (bytes);\n\n\t}\n\n\n\tBytes::~Bytes () {\n\n\t\tmutex.Lock ();\n\n\t\tif (hadValue.find (this) != hadValue.end ()) {\n\n\t\t\thadValue.erase (this);\n\n\t\t\tif (usingValue.find (this) == usingValue.end () && b) {\n\n\t\t\t\tfree (b);\n\n\t\t\t}\n\n\t\t}\n\n\t\tif (usingValue.find (this) != usingValue.end ()) {\n\n\t\t\tusingValue.erase (this);\n\n\t\t}\n\n\t\tmutex.Unlock ();\n\n\t}\n\n\n\tvoid Bytes::ReadFile (const char* path) {\n\n\t\tFILE_HANDLE *file = lime::fopen (path, \"rb\");\n\n\t\tif (!file) {\n\n\t\t\treturn;\n\n\t\t}\n\n\t\tlime::fseek (file, 0, SEEK_END);\n\t\tint size = lime::ftell (file);\n\t\tlime::fseek (file, 0, SEEK_SET);\n\n\t\tif (size > 0) {\n\n\t\t\tResize (size);\n\t\t\tint status = lime::fread (b, 1, size, file);\n\n\t\t}\n\n\t\tlime::fclose (file);\n\n\t}\n\n\n\tvoid Bytes::Resize (int size) {\n\n\t\tif (size != length || (length > 0 && !b)) {\n\n\t\t\tmutex.Lock ();\n\n\t\t\tif (size <= 0) {\n\n\t\t\t\tif (b) {\n\n\t\t\t\t\tif (usingValue.find (this) != usingValue.end ()) {\n\n\t\t\t\t\t\tusingValue.erase (this);\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tfree (b);\n\n\t\t\t\t\t}\n\n\t\t\t\t\tb = 0;\n\t\t\t\t\tlength = 0;\n\n\t\t\t\t}\n\n\t\t\t} else {\n\n\t\t\t\tunsigned char* data = (unsigned char*)malloc (sizeof (char) * size);\n\n\t\t\t\tif (b) {\n\n\t\t\t\t\tif (length) {\n\n\t\t\t\t\t\tmemcpy (data, b, length < size ? length : size);\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif (usingValue.find (this) != usingValue.end ()) {\n\n\t\t\t\t\t\tusingValue.erase (this);\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tfree (b);\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\tb = data;\n\t\t\t\tlength = size;\n\n\t\t\t}\n\n\t\t\tmutex.Unlock ();\n\n\t\t}\n\n\t}\n\n\n\tvoid Bytes::Set (value bytes) {\n\n\t\tmutex.Lock ();\n\n\t\tif (val_is_null (bytes)) {\n\n\t\t\tif (usingValue.find (this) != usingValue.end ()) {\n\n\t\t\t\tusingValue.erase (this);\n\n\t\t\t}\n\n\t\t\tlength = 0;\n\t\t\tb = 0;\n\n\t\t} else {\n\n\t\t\thadValue[this] = true;\n\t\t\tusingValue[this] = true;\n\n\t\t\tlength = val_int (val_field (bytes, id_length));\n\n\t\t\tif (length > 0) {\n\n\t\t\t\tvalue _b = val_field (bytes, id_b);\n\n\t\t\t\tif (val_is_string (_b)) {\n\n\t\t\t\t\tb = (unsigned char*)val_string (_b);\n\n\t\t\t\t} else {\n\n\t\t\t\t\tb = (unsigned char*)buffer_data (val_to_buffer (_b));\n\n\t\t\t\t}\n\n\t\t\t} else {\n\n\t\t\t\tb = 0;\n\n\t\t\t}\n\n\t\t}\n\n\t\tmutex.Unlock ();\n\n\t}\n\n\n\tvoid Bytes::Set (const QuickVec data) {\n\n\t\tint size = data.size ();\n\n\t\tif (size > 0) {\n\n\t\t\tResize (size);\n\t\t\tmemcpy (b, &data[0], length);\n\n\t\t} else {\n\n\t\t\tmutex.Lock ();\n\n\t\t\tif (usingValue.find (this) != usingValue.end ()) {\n\n\t\t\t\tusingValue.erase (this);\n\n\t\t\t}\n\n\t\t\tmutex.Unlock ();\n\n\t\t\tb = 0;\n\t\t\tlength = 0;\n\n\t\t}\n\n\t}\n\n\n\tvalue Bytes::Value () {\n\n\t\treturn alloc_null ();\n\n\t}\n\n\n\tvalue Bytes::Value (value bytes) {\n\n\t\tif (val_is_null (bytes) || !b) {\n\n\t\t\treturn alloc_null ();\n\n\t\t} else {\n\n\t\t\talloc_field (bytes, id_length, alloc_int (length));\n\n\t\t\tif (useBuffer) {\n\n\t\t\t\tvalue _buffer = val_field (bytes, id_b);\n\n\t\t\t\tif (val_is_null (_buffer) || (char*)b != buffer_data (val_to_buffer (_buffer))) {\n\n\t\t\t\t\tbuffer bufferValue = alloc_buffer_len (length);\n\t\t\t\t\t_buffer = buffer_val (bufferValue);\n\t\t\t\t\tmemcpy ((unsigned char*)buffer_data (bufferValue), b, length);\n\t\t\t\t\talloc_field (bytes, id_b, _buffer);\n\n\t\t\t\t}\n\n\t\t\t} else {\n\n\t\t\t\tvalue _string = val_field (bytes, id_b);\n\n\t\t\t\tif (val_is_null (_string) || (const char*)b != val_string (_string)) {\n\n\t\t\t\t\tvalue data = alloc_raw_string (length);\n\t\t\t\t\tmemcpy ((void*)val_string (data), b, length);\n\t\t\t\t\talloc_field (bytes, id_b, data);\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tmutex.Lock ();\n\t\t\thadValue[this] = true;\n\t\t\tmutex.Unlock ();\n\n\t\t\treturn bytes;\n\n\t\t}\n\n\t}\n\n\n}Fix memory leak in bytes.Value (resolve openfl\/openfl#2075)#include \n#include \n#include \n#include \n\n\nnamespace lime {\n\n\n\tstatic int id_b;\n\tstatic int id_length;\n\tstatic bool init = false;\n\tstatic bool useBuffer = false;\n\tstatic std::map hadValue;\n\tstatic std::map usingValue;\n\tstatic Mutex mutex;\n\n\n\tinline void _initializeBytes () {\n\n\t\tif (!init) {\n\n\t\t\tid_b = val_id (\"b\");\n\t\t\tid_length = val_id (\"length\");\n\n\t\t\tbuffer _buffer = alloc_buffer_len (1);\n\n\t\t\tif (buffer_data (_buffer)) {\n\n\t\t\t\tuseBuffer = true;\n\n\t\t\t}\n\n\t\t\tinit = true;\n\n\t\t}\n\n\t}\n\n\n\tBytes::Bytes () {\n\n\t\t_initializeBytes ();\n\n\t\tb = 0;\n\t\tlength = 0;\n\n\t}\n\n\n\tBytes::Bytes (value bytes) {\n\n\t\t_initializeBytes ();\n\n\t\tb = 0;\n\t\tlength = 0;\n\n\t\tSet (bytes);\n\n\t}\n\n\n\tBytes::~Bytes () {\n\n\t\tmutex.Lock ();\n\n\t\tif (hadValue.find (this) != hadValue.end ()) {\n\n\t\t\thadValue.erase (this);\n\n\t\t\tif (usingValue.find (this) == usingValue.end () && b) {\n\n\t\t\t\tfree (b);\n\n\t\t\t}\n\n\t\t}\n\n\t\tif (usingValue.find (this) != usingValue.end ()) {\n\n\t\t\tusingValue.erase (this);\n\n\t\t}\n\n\t\tmutex.Unlock ();\n\n\t}\n\n\n\tvoid Bytes::ReadFile (const char* path) {\n\n\t\tFILE_HANDLE *file = lime::fopen (path, \"rb\");\n\n\t\tif (!file) {\n\n\t\t\treturn;\n\n\t\t}\n\n\t\tlime::fseek (file, 0, SEEK_END);\n\t\tint size = lime::ftell (file);\n\t\tlime::fseek (file, 0, SEEK_SET);\n\n\t\tif (size > 0) {\n\n\t\t\tResize (size);\n\t\t\tint status = lime::fread (b, 1, size, file);\n\n\t\t}\n\n\t\tlime::fclose (file);\n\n\t}\n\n\n\tvoid Bytes::Resize (int size) {\n\n\t\tif (size != length || (length > 0 && !b)) {\n\n\t\t\tmutex.Lock ();\n\n\t\t\tif (size <= 0) {\n\n\t\t\t\tif (b) {\n\n\t\t\t\t\tif (usingValue.find (this) != usingValue.end ()) {\n\n\t\t\t\t\t\tusingValue.erase (this);\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tfree (b);\n\n\t\t\t\t\t}\n\n\t\t\t\t\tb = 0;\n\t\t\t\t\tlength = 0;\n\n\t\t\t\t}\n\n\t\t\t} else {\n\n\t\t\t\tunsigned char* data = (unsigned char*)malloc (sizeof (char) * size);\n\n\t\t\t\tif (b) {\n\n\t\t\t\t\tif (length) {\n\n\t\t\t\t\t\tmemcpy (data, b, length < size ? length : size);\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif (usingValue.find (this) != usingValue.end ()) {\n\n\t\t\t\t\t\tusingValue.erase (this);\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tfree (b);\n\n\t\t\t\t\t}\n\n\t\t\t\t} else if (usingValue.find (this) != usingValue.end ()) {\n\n\t\t\t\t\tusingValue.erase (this);\n\n\t\t\t\t}\n\n\t\t\t\tb = data;\n\t\t\t\tlength = size;\n\n\t\t\t}\n\n\t\t\tmutex.Unlock ();\n\n\t\t}\n\n\t}\n\n\n\tvoid Bytes::Set (value bytes) {\n\n\t\tmutex.Lock ();\n\n\t\tif (val_is_null (bytes)) {\n\n\t\t\tif (usingValue.find (this) != usingValue.end ()) {\n\n\t\t\t\tusingValue.erase (this);\n\n\t\t\t}\n\n\t\t\tlength = 0;\n\t\t\tb = 0;\n\n\t\t} else {\n\n\t\t\thadValue[this] = true;\n\t\t\tusingValue[this] = true;\n\n\t\t\tlength = val_int (val_field (bytes, id_length));\n\n\t\t\tif (length > 0) {\n\n\t\t\t\tvalue _b = val_field (bytes, id_b);\n\n\t\t\t\tif (val_is_string (_b)) {\n\n\t\t\t\t\tb = (unsigned char*)val_string (_b);\n\n\t\t\t\t} else {\n\n\t\t\t\t\tb = (unsigned char*)buffer_data (val_to_buffer (_b));\n\n\t\t\t\t}\n\n\t\t\t} else {\n\n\t\t\t\tb = 0;\n\n\t\t\t}\n\n\t\t}\n\n\t\tmutex.Unlock ();\n\n\t}\n\n\n\tvoid Bytes::Set (const QuickVec data) {\n\n\t\tint size = data.size ();\n\n\t\tif (size > 0) {\n\n\t\t\tResize (size);\n\t\t\tmemcpy (b, &data[0], length);\n\n\t\t} else {\n\n\t\t\tmutex.Lock ();\n\n\t\t\tif (usingValue.find (this) != usingValue.end ()) {\n\n\t\t\t\tusingValue.erase (this);\n\n\t\t\t}\n\n\t\t\tmutex.Unlock ();\n\n\t\t\tb = 0;\n\t\t\tlength = 0;\n\n\t\t}\n\n\t}\n\n\n\tvalue Bytes::Value () {\n\n\t\treturn alloc_null ();\n\n\t}\n\n\n\tvalue Bytes::Value (value bytes) {\n\n\t\tif (val_is_null (bytes) || !b) {\n\n\t\t\treturn alloc_null ();\n\n\t\t} else {\n\n\t\t\talloc_field (bytes, id_length, alloc_int (length));\n\n\t\t\tif (useBuffer) {\n\n\t\t\t\tvalue _buffer = val_field (bytes, id_b);\n\n\t\t\t\tif (val_is_null (_buffer) || (char*)b != buffer_data (val_to_buffer (_buffer))) {\n\n\t\t\t\t\tbuffer bufferValue = alloc_buffer_len (length);\n\t\t\t\t\t_buffer = buffer_val (bufferValue);\n\t\t\t\t\tmemcpy ((unsigned char*)buffer_data (bufferValue), b, length);\n\t\t\t\t\talloc_field (bytes, id_b, _buffer);\n\n\t\t\t\t}\n\n\t\t\t} else {\n\n\t\t\t\tvalue _string = val_field (bytes, id_b);\n\n\t\t\t\tif (val_is_null (_string) || (const char*)b != val_string (_string)) {\n\n\t\t\t\t\tvalue data = alloc_raw_string (length);\n\t\t\t\t\tmemcpy ((void*)val_string (data), b, length);\n\t\t\t\t\talloc_field (bytes, id_b, data);\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tmutex.Lock ();\n\t\t\thadValue[this] = true;\n\t\t\tmutex.Unlock ();\n\n\t\t\treturn bytes;\n\n\t\t}\n\n\t}\n\n\n}<|endoftext|>"} {"text":"#include \"scrollwidget.h\"\n\n#include \n\nusing namespace Tempest;\n\n\nstruct ScrollWidget::BoxLayout: public Tempest::LinearLayout {\n BoxLayout( ScrollWidget* owner,\n Tempest::Orientation ori ):LinearLayout(ori), sc(owner){}\n\n void applyLayout(){\n if(widgets().size()==0)\n return;\n\n const Margin& m = margin();\n Size sz = Size{0,0};\n Widget* helper = owner()->owner();\n if(helper){\n sz.w = std::max(helper->w(),sz.w);\n sz.h = std::max(helper->h(),sz.h);\n }\n\n int sw = 0, sh = 0;\n\n const Widget* first = widgets().size()>0 ? widgets()[0] : nullptr;\n for(const Widget* w : widgets())\n if( w->isVisible() ){\n Size s = sizeHint(w);\n if(orientation()==Horizontal){\n sw += s.w;\n if(w!=first)\n sw+=spacing();\n sh = std::max(sh,s.h);\n } else {\n sw = std::max(sw,s.w);\n sh += s.h;\n if(w!=first)\n sh+=spacing();\n }\n }\n\n sw += m.xMargin();\n sh += m.yMargin();\n\n sz.w = std::max(sz.w,sw);\n sz.h = std::max(sz.h,sh);\n owner()->resize(sz);\n\n sc->updateScrolls();\n LinearLayout::applyLayout();\n }\n\n ScrollWidget* sc;\n };\n\nstruct ScrollWidget::HelperLayout: public Tempest::Layout {\n void applyLayout(){\n Size ow = owner()->size();\n\n for(Widget* w : widgets()){\n const SizePolicy& sp = w->sizePolicy();\n Size sz = w->size();\n\n if(sp.typeH==FixedMin)\n sz.w = sp.minSize.w;\n if(sp.typeH==FixedMax)\n sz.w = sp.maxSize.w;\n if(sp.typeH==Preferred || sp.typeH==Expanding)\n sz.w = ow.w;\n\n if(sp.typeV==FixedMin)\n sz.h = sp.minSize.h;\n if(sp.typeV==FixedMax)\n sz.h = sp.maxSize.h;\n if(sp.typeV==Preferred || sp.typeV==Expanding)\n sz.h = ow.h;\n\n w->resize(sz);\n }\n }\n };\n\nScrollWidget::ScrollWidget()\n : sbH(nullptr), sbV(nullptr), vert(AsNeed), hor(AsNeed) {\n helper.setLayout(new HelperLayout());\n helper.onResize.bind(this,&ScrollWidget::resizeEv);\n\n layout().add(&helper);\n\n cen = new Widget();\n cen->setLayout(new BoxLayout(this,orient));\n helper.layout().add(cen);\n\n setScrollBars( createScrollBar(Horizontal),\n createScrollBar(Vertical ),\n false );\n\n#ifdef __MOBILE_PLATFORM__\n hideScrollBars();\n#endif\n }\n\nScrollWidget::ScrollWidget(bool noUi)\n : sbH(nullptr), sbV(nullptr), vert(AsNeed), hor(AsNeed) {\n helper.setLayout(new HelperLayout());\n helper.onResize.bind(this,&ScrollWidget::resizeEv);\n\n layout().add(&helper);\n\n cen = new Widget();\n cen->setLayout(new BoxLayout(this,orient));\n helper.layout().add(cen);\n\n if(!noUi)\n setScrollBars( createScrollBar(Horizontal),\n createScrollBar(Vertical ),\n false );\n\n#ifdef __MOBILE_PLATFORM__\n hideScrollBars();\n#endif\n }\n\nvoid ScrollWidget::setScrollBars( Tempest::ScrollBar* hor,\n Tempest::ScrollBar* vert,\n bool deleteOld ) {\n if(sbH!=nullptr)\n sbH->onValueChanged.ubind(this, &ScrollWidget::scrollH);\n if(sbV!=nullptr)\n sbV->onValueChanged.ubind(this, &ScrollWidget::scrollV);\n\n if(deleteOld){\n delete sbH;\n delete sbV;\n }\n\n sbH = hor;\n sbV = vert;\n layout().add(sbH);\n layout().add(sbV);\n\n if(sbH!=nullptr)\n sbH->onValueChanged.bind(this, &ScrollWidget::scrollH);\n if(sbV!=nullptr)\n sbV->onValueChanged.bind(this, &ScrollWidget::scrollV);\n\n setHscrollViewMode(this->hor);\n setVscrollViewMode(this->vert);\n\n updateScrolls();\n }\n\nvoid ScrollWidget::initializeList() {\n if(list!=nullptr)\n return;\n\n delete cen;\n list = new ListView(orient);\n cen = list;\n helper.layout().add(cen);\n list->onItemListChanged.bind(this,&ScrollWidget::updateScrolls);\n }\n\nvoid ScrollWidget::updateScrolls() {\n using std::max;\n using std::min;\n\n const std::vector& wx = cen->layout().widgets();\n const Widget* first = nullptr;\n const Widget* last = nullptr;\n\n for(size_t i=0;iisVisible() ){\n first = wx[i];\n break;\n }\n for(size_t i=wx.size();i>1;){\n i--;\n if( wx[i]->isVisible() ){\n last = wx[i];\n break;\n }\n }\n\n bool hasScH = (hor ==AlwaysOn || cen->w()>w());\n bool hasScV = (vert==AlwaysOn || cen->h()>h());\n\n for(bool recalc=true;recalc;){\n recalc = false;\n if(hasScH){\n if(!hasScV && cen->h()>(h()-sbH->h()) && vert==AsNeed){\n hasScV = true;\n recalc = true;\n }\n }\n\n if(hasScV){\n if(!hasScH && cen->w()>(w()-sbV->w()) && hor==AsNeed){\n hasScH = true;\n recalc = true;\n }\n }\n }\n\n const Margin& m = margin();\n const int cenW = w()-m.xMargin()-(hasScV ? sbV->w() : 0);\n const int cenH = h()-m.yMargin()-(hasScH ? sbH->h() : 0);\n\n const int sw = sbV==nullptr ? 0 : sbV->minSize().w;\n const int sh = sbH==nullptr ? 0 : sbH->minSize().h;\n\n const int dx = max(cen->w()-helper.w(),0);\n const int dy = max(cen->h()-helper.h(),0);\n if(sbH!=nullptr){\n Layout::placeIn(sbH,\n m.left, m.top+h()-sh-m.yMargin(),\n w()-m.xMargin()-(hasScV ? sh : 0), sh);\n sbH->setVisible(hasScH && dx>0);\n if(hor==AsNeed && dx<=0)\n sbH->setValue(0);\n\n int maxSc = dx, minSc=0;\n if(scAfterEndH && last!=nullptr)\n maxSc = max(cen->w()-min(last->w(),helper.w()),0);\n if(scBeforeBeginH && first!=nullptr)\n minSc = max(cen->w()-min(first->w(),helper.w()),0);\n\n if(cen && cen->w()>0){\n const int rgn = std::max(1,cen->w());\n sbH->setCentralButtonSize((sbV->centralAreaSize()*cenW)\/rgn);\n }\n sbH->setRange( minSc,maxSc );\n }\n\n if(sbV!=nullptr){\n Layout::placeIn(sbV,\n m.left+w()-sw-m.xMargin(), m.top,\n sw, h()-m.yMargin()-(hasScH ? sw : 0));\n sbV->setVisible(hasScV && dy>0);\n if(vert==AsNeed && dy<=0)\n sbV->setValue(0);\n\n int maxSc = dy, minSc = 0;\n if(scAfterEndV && last!=nullptr)\n maxSc = max(cen->h()-min(last->h(),helper.h()),0);\n if(scBeforeBeginV && first!=nullptr)\n minSc = max(cen->h()-min(first->h(),helper.h()),0);\n if(cen && cen->h()>0){\n const int rgn = std::max(1,cen->h());\n sbV->setCentralButtonSize((sbV->centralAreaSize()*cenH)\/rgn);\n }\n sbV->setRange( minSc, maxSc );\n }\n\n Layout::placeIn(&helper, m.left, m.top, cenW, cenH);\n }\n\nScrollWidget::~ScrollWidget() {\n if(list!=nullptr)\n list->onItemListChanged.ubind(this,&ScrollWidget::updateScrolls);\n helper.onResize.removeBinds();\n }\n\nTempest::Widget &ScrollWidget::centralWidget() {\n return *cen;\n }\n\nbool ScrollWidget::isListBased() const {\n return list!=nullptr;\n }\n\nListView *ScrollWidget::asListView() {\n return list;\n }\n\nconst ListView *ScrollWidget::asListView() const {\n return list;\n }\n\nvoid ScrollWidget::removeList() {\n if(list==nullptr)\n return;\n\n delete list;\n list = nullptr;\n\n cen = new Widget();\n cen->setLayout(new BoxLayout(this,orient));\n helper.layout().add(cen);\n }\n\nvoid ScrollWidget::setLayout(Orientation ori) {\n orient = ori;\n\n if(list!=nullptr)\n list->setOrientation(orient); else\n cen->setLayout(new BoxLayout(this,ori));\n }\n\nvoid ScrollWidget::hideScrollBars() {\n setScrollBarsVisible(0,0);\n }\n\nvoid ScrollWidget::setScrollBarsVisible(bool vh, bool vv) {\n if( sbH==nullptr || sbV==nullptr )\n return;\n\n if( vh==sbH->isVisible() && vv==sbV->isVisible() )\n return;\n\n sbH->setVisible(vh);\n sbV->setVisible(vv);\n resizeEv( w(), h() );\n }\n\nvoid ScrollWidget::setVscrollViewMode(scrollViewMode mode) {\n if(sbH==nullptr)\n return;\n\n vert = mode;\n switch(mode){\n case AsNeed: resizeEv(cen->w(), cen->h()); break;\n case AlwaysOff: sbV->setVisible(false); break;\n case AlwaysOn: sbV->setVisible(true); break;\n }\n }\n\nvoid ScrollWidget::setHscrollViewMode(scrollViewMode mode) {\n if(sbH==nullptr)\n return;\n\n hor = mode;\n switch(mode){\n case AsNeed: resizeEv(cen->w(), cen->h()); break;\n case AlwaysOff: sbH->setVisible(false); break;\n case AlwaysOn: sbH->setVisible(true); break;\n }\n }\n\nvoid ScrollWidget::scrollAfterEndH(bool s) {\n scAfterEndH = s;\n updateScrolls();\n }\n\nbool ScrollWidget::hasScrollAfterEndH() const {\n return scAfterEndH;\n }\n\nvoid ScrollWidget::scrollBeforeBeginH(bool s) {\n scBeforeBeginH = s;\n updateScrolls();\n }\n\nbool ScrollWidget::hasScrollBeforeBeginH() const {\n return scBeforeBeginH;\n }\n\nvoid ScrollWidget::scrollAfterEndV(bool s) {\n scAfterEndV = s;\n updateScrolls();\n }\n\nbool ScrollWidget::hasScrollAfterEndV() const {\n return scAfterEndV;\n }\n\nvoid ScrollWidget::scrollBeforeBeginV(bool s) {\n scBeforeBeginV = s;\n updateScrolls();\n }\n\nbool ScrollWidget::hasScrollBeforeBeginV() const {\n return scBeforeBeginV;\n }\n\nvoid ScrollWidget::mouseWheelEvent(Tempest::MouseEvent &e) {\n if(sbV==nullptr)\n return;\n\n if( !rect().contains(e.x+x(), e.y+y()) || !sbV->isVisible() ){\n e.ignore();\n return;\n }\n\n if(e.delta>0)\n sbV->setValue(sbV->value() - sbV->largeStep()); else\n if(e.delta<0)\n sbV->setValue(sbV->value() + sbV->largeStep());\n }\n\nvoid ScrollWidget::mouseMoveEvent(Tempest::MouseEvent &e) {\n e.ignore();\n }\n\nvoid ScrollWidget::gestureEvent(Tempest::AbstractGestureEvent &e) {\n e.ignore();\n\n if( e.gestureType()==Tempest::AbstractGestureEvent::gtDragGesture ){\n Tempest::DragGesture &d = (Tempest::DragGesture&)(e);\n if(sbH!=nullptr && sbH->range()>w() && !sbH->isVisible()){\n int v = sbH->value();\n int dpos = d.dpos.x;\n\n sbH->setValue(sbH->value() - dpos );\n if( v!=sbH->value() )\n e.accept();\n }\n if(sbV!=nullptr && sbV->range()>h() && !sbV->isVisible()){\n int v = sbV->value();\n int dpos = d.dpos.y;\n\n sbV->setValue(sbV->value() - dpos );\n if( v!=sbV->value() )\n e.accept();\n }\n }\n }\n\nvoid ScrollWidget::resizeEvent(SizeEvent &) {\n resizeEv(helper.w(), helper.h());\n }\n\nScrollBar *ScrollWidget::createScrollBar(Orientation ori) {\n return new ScrollBar(ori);\n }\n\nvoid ScrollWidget::scrollH( int v ) {\n if(sbH!=nullptr){\n sbH->setValue( v );\n cen->setPosition(-sbH->value(), cen->y());\n } else\n cen->setPosition(cen->x(), -v);\n }\n\nvoid ScrollWidget::scrollV(int v) {\n if(sbV!=nullptr){\n sbV->setValue( v );\n cen->setPosition(cen->x(), -sbV->value());\n } else\n cen->setPosition(cen->x(), -v);\n }\n\nvoid ScrollWidget::resizeEv(int,int) {\n updateScrolls();\n }\n\nTempest::Size ScrollWidget::sizeHint(const Tempest::Widget *wid) {\n int w = wid->sizePolicy().minSize.w,\n h = wid->sizePolicy().minSize.h;\n\n if( wid->sizePolicy().typeH==Tempest::FixedMax )\n w = wid->sizePolicy().maxSize.w;\n if( wid->sizePolicy().typeV==Tempest::FixedMax )\n h = wid->sizePolicy().maxSize.h;\n\n return Tempest::Size(w,h);\n }\nupdate scroll after remove list-delegate#include \"scrollwidget.h\"\n\n#include \n\nusing namespace Tempest;\n\n\nstruct ScrollWidget::BoxLayout: public Tempest::LinearLayout {\n BoxLayout( ScrollWidget* owner,\n Tempest::Orientation ori ):LinearLayout(ori), sc(owner){}\n\n void applyLayout(){\n if(widgets().size()==0)\n return;\n\n const Margin& m = margin();\n Size sz = Size{0,0};\n Widget* helper = owner()->owner();\n if(helper){\n sz.w = std::max(helper->w(),sz.w);\n sz.h = std::max(helper->h(),sz.h);\n }\n\n int sw = 0, sh = 0;\n\n const Widget* first = widgets().size()>0 ? widgets()[0] : nullptr;\n for(const Widget* w : widgets())\n if( w->isVisible() ){\n Size s = sizeHint(w);\n if(orientation()==Horizontal){\n sw += s.w;\n if(w!=first)\n sw+=spacing();\n sh = std::max(sh,s.h);\n } else {\n sw = std::max(sw,s.w);\n sh += s.h;\n if(w!=first)\n sh+=spacing();\n }\n }\n\n sw += m.xMargin();\n sh += m.yMargin();\n\n sz.w = std::max(sz.w,sw);\n sz.h = std::max(sz.h,sh);\n owner()->resize(sz);\n\n sc->updateScrolls();\n LinearLayout::applyLayout();\n }\n\n ScrollWidget* sc;\n };\n\nstruct ScrollWidget::HelperLayout: public Tempest::Layout {\n void applyLayout(){\n Size ow = owner()->size();\n\n for(Widget* w : widgets()){\n const SizePolicy& sp = w->sizePolicy();\n Size sz = w->size();\n\n if(sp.typeH==FixedMin)\n sz.w = sp.minSize.w;\n if(sp.typeH==FixedMax)\n sz.w = sp.maxSize.w;\n if(sp.typeH==Preferred || sp.typeH==Expanding)\n sz.w = ow.w;\n\n if(sp.typeV==FixedMin)\n sz.h = sp.minSize.h;\n if(sp.typeV==FixedMax)\n sz.h = sp.maxSize.h;\n if(sp.typeV==Preferred || sp.typeV==Expanding)\n sz.h = ow.h;\n\n w->resize(sz);\n }\n }\n };\n\nScrollWidget::ScrollWidget()\n : sbH(nullptr), sbV(nullptr), vert(AsNeed), hor(AsNeed) {\n helper.setLayout(new HelperLayout());\n helper.onResize.bind(this,&ScrollWidget::resizeEv);\n\n layout().add(&helper);\n\n cen = new Widget();\n cen->setLayout(new BoxLayout(this,orient));\n helper.layout().add(cen);\n\n setScrollBars( createScrollBar(Horizontal),\n createScrollBar(Vertical ),\n false );\n\n#ifdef __MOBILE_PLATFORM__\n hideScrollBars();\n#endif\n }\n\nScrollWidget::ScrollWidget(bool noUi)\n : sbH(nullptr), sbV(nullptr), vert(AsNeed), hor(AsNeed) {\n helper.setLayout(new HelperLayout());\n helper.onResize.bind(this,&ScrollWidget::resizeEv);\n\n layout().add(&helper);\n\n cen = new Widget();\n cen->setLayout(new BoxLayout(this,orient));\n helper.layout().add(cen);\n\n if(!noUi)\n setScrollBars( createScrollBar(Horizontal),\n createScrollBar(Vertical ),\n false );\n\n#ifdef __MOBILE_PLATFORM__\n hideScrollBars();\n#endif\n }\n\nvoid ScrollWidget::setScrollBars( Tempest::ScrollBar* hor,\n Tempest::ScrollBar* vert,\n bool deleteOld ) {\n if(sbH!=nullptr)\n sbH->onValueChanged.ubind(this, &ScrollWidget::scrollH);\n if(sbV!=nullptr)\n sbV->onValueChanged.ubind(this, &ScrollWidget::scrollV);\n\n if(deleteOld){\n delete sbH;\n delete sbV;\n }\n\n sbH = hor;\n sbV = vert;\n layout().add(sbH);\n layout().add(sbV);\n\n if(sbH!=nullptr)\n sbH->onValueChanged.bind(this, &ScrollWidget::scrollH);\n if(sbV!=nullptr)\n sbV->onValueChanged.bind(this, &ScrollWidget::scrollV);\n\n setHscrollViewMode(this->hor);\n setVscrollViewMode(this->vert);\n\n updateScrolls();\n }\n\nvoid ScrollWidget::initializeList() {\n if(list!=nullptr)\n return;\n\n delete cen;\n list = new ListView(orient);\n cen = list;\n helper.layout().add(cen);\n list->onItemListChanged.bind(this,&ScrollWidget::updateScrolls);\n }\n\nvoid ScrollWidget::updateScrolls() {\n using std::max;\n using std::min;\n\n const std::vector& wx = cen->layout().widgets();\n const Widget* first = nullptr;\n const Widget* last = nullptr;\n\n for(size_t i=0;iisVisible() ){\n first = wx[i];\n break;\n }\n for(size_t i=wx.size();i>1;){\n i--;\n if( wx[i]->isVisible() ){\n last = wx[i];\n break;\n }\n }\n\n bool hasScH = (hor ==AlwaysOn || cen->w()>w());\n bool hasScV = (vert==AlwaysOn || cen->h()>h());\n\n for(bool recalc=true;recalc;){\n recalc = false;\n if(hasScH){\n if(!hasScV && cen->h()>(h()-sbH->h()) && vert==AsNeed){\n hasScV = true;\n recalc = true;\n }\n }\n\n if(hasScV){\n if(!hasScH && cen->w()>(w()-sbV->w()) && hor==AsNeed){\n hasScH = true;\n recalc = true;\n }\n }\n }\n\n const Margin& m = margin();\n const int cenW = w()-m.xMargin()-(hasScV ? sbV->w() : 0);\n const int cenH = h()-m.yMargin()-(hasScH ? sbH->h() : 0);\n\n const int sw = sbV==nullptr ? 0 : sbV->minSize().w;\n const int sh = sbH==nullptr ? 0 : sbH->minSize().h;\n\n const int dx = max(cen->w()-helper.w(),0);\n const int dy = max(cen->h()-helper.h(),0);\n if(sbH!=nullptr){\n Layout::placeIn(sbH,\n m.left, m.top+h()-sh-m.yMargin(),\n w()-m.xMargin()-(hasScV ? sh : 0), sh);\n sbH->setVisible(hasScH && dx>0);\n if(hor==AsNeed && dx<=0)\n sbH->setValue(0);\n\n int maxSc = dx, minSc=0;\n if(scAfterEndH && last!=nullptr)\n maxSc = max(cen->w()-min(last->w(),helper.w()),0);\n if(scBeforeBeginH && first!=nullptr)\n minSc = max(cen->w()-min(first->w(),helper.w()),0);\n\n if(cen && cen->w()>0){\n const int rgn = std::max(1,cen->w());\n sbH->setCentralButtonSize((sbV->centralAreaSize()*cenW)\/rgn);\n }\n sbH->setRange( minSc,maxSc );\n }\n\n if(sbV!=nullptr){\n Layout::placeIn(sbV,\n m.left+w()-sw-m.xMargin(), m.top,\n sw, h()-m.yMargin()-(hasScH ? sw : 0));\n sbV->setVisible(hasScV && dy>0);\n if(vert==AsNeed && dy<=0)\n sbV->setValue(0);\n\n int maxSc = dy, minSc = 0;\n if(scAfterEndV && last!=nullptr)\n maxSc = max(cen->h()-min(last->h(),helper.h()),0);\n if(scBeforeBeginV && first!=nullptr)\n minSc = max(cen->h()-min(first->h(),helper.h()),0);\n if(cen && cen->h()>0){\n const int rgn = std::max(1,cen->h());\n sbV->setCentralButtonSize((sbV->centralAreaSize()*cenH)\/rgn);\n }\n sbV->setRange( minSc, maxSc );\n }\n\n Layout::placeIn(&helper, m.left, m.top, cenW, cenH);\n }\n\nScrollWidget::~ScrollWidget() {\n if(list!=nullptr)\n list->onItemListChanged.ubind(this,&ScrollWidget::updateScrolls);\n helper.onResize.removeBinds();\n }\n\nTempest::Widget &ScrollWidget::centralWidget() {\n return *cen;\n }\n\nbool ScrollWidget::isListBased() const {\n return list!=nullptr;\n }\n\nListView *ScrollWidget::asListView() {\n return list;\n }\n\nconst ListView *ScrollWidget::asListView() const {\n return list;\n }\n\nvoid ScrollWidget::removeList() {\n if(list==nullptr)\n return;\n\n delete list;\n list = nullptr;\n\n cen = new Widget();\n cen->setLayout(new BoxLayout(this,orient));\n helper.layout().add(cen);\n\n updateScrolls();\n }\n\nvoid ScrollWidget::setLayout(Orientation ori) {\n orient = ori;\n\n if(list!=nullptr)\n list->setOrientation(orient); else\n cen->setLayout(new BoxLayout(this,ori));\n }\n\nvoid ScrollWidget::hideScrollBars() {\n setScrollBarsVisible(0,0);\n }\n\nvoid ScrollWidget::setScrollBarsVisible(bool vh, bool vv) {\n if( sbH==nullptr || sbV==nullptr )\n return;\n\n if( vh==sbH->isVisible() && vv==sbV->isVisible() )\n return;\n\n sbH->setVisible(vh);\n sbV->setVisible(vv);\n resizeEv( w(), h() );\n }\n\nvoid ScrollWidget::setVscrollViewMode(scrollViewMode mode) {\n if(sbH==nullptr)\n return;\n\n vert = mode;\n switch(mode){\n case AsNeed: resizeEv(cen->w(), cen->h()); break;\n case AlwaysOff: sbV->setVisible(false); break;\n case AlwaysOn: sbV->setVisible(true); break;\n }\n }\n\nvoid ScrollWidget::setHscrollViewMode(scrollViewMode mode) {\n if(sbH==nullptr)\n return;\n\n hor = mode;\n switch(mode){\n case AsNeed: resizeEv(cen->w(), cen->h()); break;\n case AlwaysOff: sbH->setVisible(false); break;\n case AlwaysOn: sbH->setVisible(true); break;\n }\n }\n\nvoid ScrollWidget::scrollAfterEndH(bool s) {\n scAfterEndH = s;\n updateScrolls();\n }\n\nbool ScrollWidget::hasScrollAfterEndH() const {\n return scAfterEndH;\n }\n\nvoid ScrollWidget::scrollBeforeBeginH(bool s) {\n scBeforeBeginH = s;\n updateScrolls();\n }\n\nbool ScrollWidget::hasScrollBeforeBeginH() const {\n return scBeforeBeginH;\n }\n\nvoid ScrollWidget::scrollAfterEndV(bool s) {\n scAfterEndV = s;\n updateScrolls();\n }\n\nbool ScrollWidget::hasScrollAfterEndV() const {\n return scAfterEndV;\n }\n\nvoid ScrollWidget::scrollBeforeBeginV(bool s) {\n scBeforeBeginV = s;\n updateScrolls();\n }\n\nbool ScrollWidget::hasScrollBeforeBeginV() const {\n return scBeforeBeginV;\n }\n\nvoid ScrollWidget::mouseWheelEvent(Tempest::MouseEvent &e) {\n if(sbV==nullptr)\n return;\n\n if( !rect().contains(e.x+x(), e.y+y()) || !sbV->isVisible() ){\n e.ignore();\n return;\n }\n\n if(e.delta>0)\n sbV->setValue(sbV->value() - sbV->largeStep()); else\n if(e.delta<0)\n sbV->setValue(sbV->value() + sbV->largeStep());\n }\n\nvoid ScrollWidget::mouseMoveEvent(Tempest::MouseEvent &e) {\n e.ignore();\n }\n\nvoid ScrollWidget::gestureEvent(Tempest::AbstractGestureEvent &e) {\n e.ignore();\n\n if( e.gestureType()==Tempest::AbstractGestureEvent::gtDragGesture ){\n Tempest::DragGesture &d = (Tempest::DragGesture&)(e);\n if(sbH!=nullptr && sbH->range()>w() && !sbH->isVisible()){\n int v = sbH->value();\n int dpos = d.dpos.x;\n\n sbH->setValue(sbH->value() - dpos );\n if( v!=sbH->value() )\n e.accept();\n }\n if(sbV!=nullptr && sbV->range()>h() && !sbV->isVisible()){\n int v = sbV->value();\n int dpos = d.dpos.y;\n\n sbV->setValue(sbV->value() - dpos );\n if( v!=sbV->value() )\n e.accept();\n }\n }\n }\n\nvoid ScrollWidget::resizeEvent(SizeEvent &) {\n resizeEv(helper.w(), helper.h());\n }\n\nScrollBar *ScrollWidget::createScrollBar(Orientation ori) {\n return new ScrollBar(ori);\n }\n\nvoid ScrollWidget::scrollH( int v ) {\n if(sbH!=nullptr){\n sbH->setValue( v );\n cen->setPosition(-sbH->value(), cen->y());\n } else\n cen->setPosition(cen->x(), -v);\n }\n\nvoid ScrollWidget::scrollV(int v) {\n if(sbV!=nullptr){\n sbV->setValue( v );\n cen->setPosition(cen->x(), -sbV->value());\n } else\n cen->setPosition(cen->x(), -v);\n }\n\nvoid ScrollWidget::resizeEv(int,int) {\n updateScrolls();\n }\n\nTempest::Size ScrollWidget::sizeHint(const Tempest::Widget *wid) {\n int w = wid->sizePolicy().minSize.w,\n h = wid->sizePolicy().minSize.h;\n\n if( wid->sizePolicy().typeH==Tempest::FixedMax )\n w = wid->sizePolicy().maxSize.w;\n if( wid->sizePolicy().typeV==Tempest::FixedMax )\n h = wid->sizePolicy().maxSize.h;\n\n return Tempest::Size(w,h);\n }\n<|endoftext|>"} {"text":"\/\/\n\/\/ Name:\t\tStartupDlg.cpp\n\/\/\n\/\/ Copyright (c) 2001 Virtual Terrain Project\n\/\/ Free for all uses, see license.txt for details.\n\/\/\n\n#ifdef __GNUG__\n\t#pragma implementation \"StartupDlg.cpp\"\n#endif\n\n\/\/ For compilers that support precompilation, includes \"wx\/wx.h\".\n#include \"wx\/wxprec.h\"\n\n#ifndef WX_PRECOMP\n# include \"wx\/wx.h\"\n#endif\n\n#if defined(UNIX)\n# include \n# include \n# include \n#endif\n\n#include \"vtlib\/vtlib.h\"\n#include \"vtlib\/core\/Terrain.h\"\n#include \"vtlib\/core\/TerrainScene.h\"\n\n#include \"StartupDlg.h\"\n#include \"..\/Enviro.h\"\t\/\/ for GetCurrentTerrain\n#include \"..\/Options.h\"\n#include \"vtdata\/boost\/directory.h\"\n\n#include \"app.h\"\n#include \"TParamsDlg.h\"\n#include \"TParamsTabDlg.h\"\n\n\/\/\n\/\/ This function is used to find all files in a given directory,\n\/\/ and if they match a wildcard, add them to a combo box.\n\/\/\nvoid AddFilenamesToComboBox(wxComboBox *box, const char *directory,\n\t\t\t\t\t\t\tconst char *wildcard, int omit_chars)\n{\n\tusing namespace boost::filesystem;\n\n\tfor (dir_it it((const char *)directory); it != dir_it(); ++it)\n\t{\n\t\tif (get(it) || get(it))\n\t\t\tcontinue;\n\n\t\tstd::string name1 = *it;\n\t\twxString name = name1.c_str();\n\t\tif (name.Matches(wildcard))\n\t\t{\n\t\t\tif (omit_chars)\n\t\t\t\tbox->Append(name.Left(name.Length()-omit_chars));\n\t\t\telse\n\t\t\t\tbox->Append(name);\n\t\t}\n\t}\n}\n\n\/\/\n\/\/ Helper: find the largest texture size supported by OpenGL\n\/\/\n#ifdef WIN32\nstatic void ShowOGLInfo(HDC hdc)\n#else\nstatic void ShowOGLInfo()\n#endif\n{\n#if defined(WIN32)\n\tPIXELFORMATDESCRIPTOR pfd =\n\t{\n\t\tsizeof(PIXELFORMATDESCRIPTOR), \/\/ size of this pfd \n\t\t1,\t\t\t\t\t \/\/ version number \n\t\tPFD_DRAW_TO_WINDOW |\t\/\/ support window \n\t\tPFD_SUPPORT_OPENGL |\t\/\/ support OpenGL \n\t\tPFD_DOUBLEBUFFER,\t \/\/ double buffered \n\t\tPFD_TYPE_RGBA,\t\t \/\/ RGBA type \n\t\t24,\t\t\t\t\t \/\/ 24-bit color depth \n\t\t0, 0, 0, 0, 0, 0,\t \/\/ color bits ignored \n\t\t0, 0, 0,\t\t\t\t\/\/ no alpha buffer \n\t\t0, 0, 0, 0,\t\t\t \/\/ accum bits ignored \n\t\t32, 0, 0,\t\t\t \/\/ 32-bit z-buffer \n\t\tPFD_MAIN_PLANE,\t\t \/\/ main layer\n\t\t0,\t\t\t\t\t \/\/ reserved \n\t\t0, 0, 0\t\t\t\t \/\/ layer masks ignored\n\t};\n\tint iPixelFormat;\n\n\t\/\/ get the best available match of pixel format for the device context \n\tiPixelFormat = ChoosePixelFormat(hdc, &pfd);\n\t\/\/ make that the pixel format of the device context \n\tSetPixelFormat(hdc, iPixelFormat, &pfd);\n\n\tHGLRC device = wglCreateContext(hdc);\n\tif (device == NULL)\n\t{\n\t\tDWORD lasterror = GetLastError();\n\t\t\/\/ 2000 The pixel format is invalid. ERROR_INVALID_PIXEL_FORMAT \n\t}\n\twglMakeCurrent(hdc, device);\n#elif defined(UNIX)\n\tstatic int dblBuf[] = {GLX_RGBA, GLX_RED_SIZE, 1, GLX_GREEN_SIZE, 1,\n\t\t\t\t\t\t\tGLX_BLUE_SIZE, 1, GLX_DEPTH_SIZE, 1,\n\t\t\t\t\t\t\tGLX_DOUBLEBUFFER, None};\n\tDisplay *dpy;\n\tWindow win;\n\tXVisualInfo *vi;\n\tColormap cmap;\n\tXSetWindowAttributes swa;\n\tGLXContext cx;\n\tXEvent event;\n\tBool needRedraw = False, recalcModelView = True;\n\tint dummy;\n\n\tdpy = XOpenDisplay(NULL);\n\tif (dpy == NULL) \n\t\twxFatalError( \"could not open display\" );\n\n\tif (!glXQueryExtension(dpy, &dummy, &dummy))\n\t\twxFatalError( \"X server has no OpenGL GLX extension\" );\n\n\tvi = glXChooseVisual(dpy, DefaultScreen(dpy), dblBuf);\n\tif (vi == NULL)\n\t\twxFatalError( \"no RGB visual with double and depth buffer\" );\n\tif (vi->c_class != TrueColor)\n\t\twxFatalError( \"TrueColor visual required for this program\" );\n\n\tcmap = XCreateColormap(dpy, RootWindow(dpy, vi->screen),\n\t\t\t\t\t\t vi->visual, AllocNone);\n\tswa.colormap = cmap;\n\tswa.border_pixel = 0;\n\tswa.event_mask = ExposureMask | ButtonPressMask | StructureNotifyMask;\n\twin = XCreateWindow(dpy, RootWindow(dpy, vi->screen),\n\t\t\t\t\t\t0, 0, 300, 300, 0, vi->depth,\n\t\t\t\t\t\tInputOutput, vi->visual,\n\t\t\t\t\t\tCWBorderPixel | CWColormap | CWEventMask, &swa);\n\n\tXSetStandardProperties(dpy, win, \"test\", \"test\",\n\t\t\t\t\t\t None, NULL, 0, NULL);\n\n\tcx = glXCreateContext(dpy, vi, None, True);\n\tif (cx == NULL)\n\t\twxFatalError( \"could not create rendering context\" );\n\n\tglXMakeCurrent(dpy, win, cx);\n#else\n# error \"I don't know this platform.\"\n#endif\n\n\tGLint value;\n\tglGetIntegerv(GL_MAX_TEXTURE_SIZE, &value);\n\tGLenum error = glGetError();\n\tif (error == GL_INVALID_OPERATION)\n\t\tvalue = 0;\n\n\twxString str;\n\tstr.Printf(\"OpenGL Version: %s\\nVendor: %s\\nRenderer: %s\\n\"\n\t\t\"Maximum Texture Dimension: %d\\nExtensions: %s\",\n\t\tglGetString(GL_VERSION), glGetString(GL_VENDOR),\n\t\tglGetString(GL_RENDERER), value, glGetString(GL_EXTENSIONS));\n\n\twxDialog dlg(NULL, -1, \"OpenGL Info\", wxDefaultPosition);\n\tTextDialogFunc(&dlg, TRUE);\n\twxTextCtrl* pText = (wxTextCtrl*) dlg.FindWindow( ID_TEXT );\n\tpText->SetValue(str);\n\n\tdlg.ShowModal();\n\n#ifdef WIN32\n\twglDeleteContext(device);\n#elif defined(UNIX)\n\tglXDestroyContext(dpy, cx);\n\tXDestroyWindow(dpy, win);\n\tXCloseDisplay(dpy);\n#endif\n}\n\n\/\/ WDR: class implementations\n\n\/\/----------------------------------------------------------------------------\n\/\/ StartupDlg\n\/\/----------------------------------------------------------------------------\n\nvoid StartupDlg::GetOptionsFrom(EnviroOptions &opt)\n{\n\tm_bStartEarth = (opt.m_bEarthView == TRUE);\n\tm_bStartTerrain = !opt.m_bEarthView;\n\tm_strImage = opt.m_strImage;\n\tm_strTName = opt.m_strInitTerrain;\n\tm_bFullscreen = (opt.m_bFullscreen == TRUE);\n\tm_bGravity = (opt.m_bGravity == TRUE);\n\tm_bHtmlpane = (opt.m_bHtmlpane == TRUE);\n\tm_bFloatingToolbar = (opt.m_bFloatingToolbar == TRUE);\n\tm_bSound = (opt.m_bSound == TRUE);\n\tm_bVCursor = (opt.m_bVCursor == TRUE);\n\tm_bSpeedTest = (opt.m_bSpeedTest == TRUE);\n\tm_bQuakeNavigation = (opt.m_bQuakeNavigation == TRUE);\n\tm_fPlantScale = opt.m_fPlantScale;\n\tm_bShadows = (opt.m_bShadows == TRUE);\n}\n\nvoid StartupDlg::PutOptionsTo(EnviroOptions &opt)\n{\n\topt.m_bEarthView = (m_bStartEarth == 1);\n\topt.m_strImage = m_strImage;\n\topt.m_strInitTerrain = m_strTName;\n\topt.m_bFullscreen = m_bFullscreen;\n\topt.m_bGravity = m_bGravity;\n\topt.m_bHtmlpane = m_bHtmlpane;\n\topt.m_bFloatingToolbar = m_bFloatingToolbar;\n\topt.m_bSound = m_bSound;\n\topt.m_bVCursor = m_bVCursor;\n\topt.m_bSpeedTest = m_bSpeedTest;\n\topt.m_bQuakeNavigation = m_bQuakeNavigation;\n\topt.m_fPlantScale = m_fPlantScale;\n\topt.m_bShadows = m_bShadows;\n}\n\nvoid StartupDlg::UpdateState()\n{\n\tm_psImage->Enable(m_bStartEarth);\n\tm_pImage->Enable(m_bStartEarth);\n\tm_pTName->Enable(!m_bStartEarth);\n\tm_pTSelect->Enable(!m_bStartEarth);\n}\n\n\/\/ WDR: event table for StartupDlg\n\nBEGIN_EVENT_TABLE(StartupDlg,AutoDialog)\n\tEVT_BUTTON( ID_TSELECT, StartupDlg::OnSelectTerrain )\n\tEVT_BUTTON( wxID_OK, StartupDlg::OnOK )\n\tEVT_BUTTON( ID_OPENGL, StartupDlg::OnOpenGLInfo )\n\tEVT_RADIOBUTTON( ID_EARTHVIEW, StartupDlg::OnEarthView )\n\tEVT_RADIOBUTTON( ID_TERRAIN, StartupDlg::OnTerrain )\n\tEVT_BUTTON( ID_EDITPROP, StartupDlg::OnEditProp )\nEND_EVENT_TABLE()\n\nStartupDlg::StartupDlg( wxWindow *parent, wxWindowID id, const wxString &title,\n\tconst wxPoint &position, const wxSize& size, long style ) :\n\tAutoDialog( parent, id, title, position, size, style )\n{\n\tStartupDialogFunc( this, TRUE ); \n}\n\nvoid StartupDlg::EditParameters(const char *filename) \n{\n\tTParamsDlg dlg(this, -1, \"Terrain Creation Parameters\", wxDefaultPosition);\n\n\tTParams Params;\n\tif (Params.LoadFromFile(filename))\n\t\tdlg.SetParams(Params);\n\n\tdlg.CenterOnParent();\n\tint result = dlg.ShowModal();\n\tif (result == wxID_OK)\n\t{\n\t\tdlg.GetParams(Params);\n\t\tif (!Params.SaveToFile(filename))\n\t\t{\n\t\t\twxString str;\n\t\t\tstr.Printf(\"Couldn't save to file %s.\\n\"\n\t\t\t\t\t \"Please make sure the file is not read-only.\", filename);\n\t\t\twxMessageBox(str);\n\t\t}\n\t}\n}\n\n\/\/ WDR: handler implementations for StartupDlg\n\n#if 0\nvoid StartupDlg::OnSelectDataPath( wxCommandEvent &event )\n{\n\twxDirDialog dlg(this, \"Please indicate your data directory\", m_strDataPath);\n\tif (dlg.ShowModal() == wxID_OK)\n\t{\n\t\tm_strDataPath = dlg.GetPath();\n#if WIN32\n\t\twxString path_separator = \"\\\\\";\n#else\n\t\twxString path_separator = \"\/\";\n#endif\n\t\tm_strDataPath += path_separator;\n\t\tTransferDataToWindow();\n\t}\n}\n#endif\n\nvoid StartupDlg::OnEditProp( wxCommandEvent &event )\n{\n\tvtTerrain *pTerr = GetTerrainScene()->FindTerrainByName(m_strTName);\n\tif (pTerr)\n\t\tEditParameters(pTerr->GetParamFile());\n}\n\nvoid StartupDlg::OnTerrain( wxCommandEvent &event )\n{\n\tTransferDataFromWindow();\n\tUpdateState();\n}\n\nvoid StartupDlg::OnEarthView( wxCommandEvent &event )\n{\n\tTransferDataFromWindow();\n\tUpdateState();\n}\n\nvoid StartupDlg::OnOpenGLInfo( wxCommandEvent &event )\n{\n\t\/\/ check the OpenGL max texture size\n#ifdef WIN32\n\twxClientDC wdc(this);\n\tHDC hdc = (HDC) wdc.GetHDC();\n\tShowOGLInfo(hdc);\n#else\n\tShowOGLInfo();\n#endif\n}\n\nvoid StartupDlg::OnOK( wxCommandEvent &event )\n{\n\twxDialog::OnOK(event);\n}\n\nvoid StartupDlg::OnInitDialog(wxInitDialogEvent& event) \n{\n\tvtTerrain *pTerr = GetTerrainScene()->FindTerrainByName(m_strTName);\n\tif (pTerr)\n\t\tm_strTName = pTerr->GetName();\n\telse\n\t\tm_strTName = \"none\";\n\n\tm_pTName = GetTname();\n\tm_pTSelect = GetTselect();\n\tm_psImage = GetImagetext();\n\tm_pImage = GetImage();\n\n\tStringArray &paths = g_Options.m_DataPaths;\n\tfor (int i = 0; i < paths.GetSize(); i++)\n\t{\n\t\tvtString path = *paths[i];\n\t\tpath += \"WholeEarth\/\";\n\t\tAddFilenamesToComboBox(m_pImage, path, \"*_0106.png\", 9);\n\t}\n\tint sel = m_pImage->FindString(m_strImage);\n\tif (sel != -1)\n\t\tm_pImage->SetSelection(sel);\n\n\tUpdateState();\n\n\tAddValidator(ID_EARTHVIEW, &m_bStartEarth);\n\tAddValidator(ID_TERRAIN, &m_bStartTerrain);\n\n\tAddValidator(ID_FULLSCREEN, &m_bFullscreen);\n\tAddValidator(ID_GRAVITY, &m_bGravity);\n\tAddValidator(ID_HTML_PANE, &m_bHtmlpane);\n\tAddValidator(ID_FLOATING, &m_bFloatingToolbar);\n\tAddValidator(ID_SOUND, &m_bSound);\n\tAddValidator(ID_VCURSOR, &m_bVCursor);\n\tAddValidator(ID_SHADOWS, &m_bShadows);\n\n\tAddValidator(ID_TNAME, &m_strTName);\n\tAddValidator(ID_IMAGE, &m_strImage);\n\tAddNumValidator(ID_PLANTSIZE, &m_fPlantScale);\n\n\twxWindow::OnInitDialog(event);\n}\n\nvoid StartupDlg::OnSelectTerrain( wxCommandEvent &event )\n{\n\tTransferDataFromWindow();\n\n\tAskForTerrainName(this, m_strTName);\n\n\tTransferDataToWindow();\n}\n\n\nremoved TParamsTabDlg.h\/\/\n\/\/ Name:\t\tStartupDlg.cpp\n\/\/\n\/\/ Copyright (c) 2001 Virtual Terrain Project\n\/\/ Free for all uses, see license.txt for details.\n\/\/\n\n#ifdef __GNUG__\n\t#pragma implementation \"StartupDlg.cpp\"\n#endif\n\n\/\/ For compilers that support precompilation, includes \"wx\/wx.h\".\n#include \"wx\/wxprec.h\"\n\n#ifndef WX_PRECOMP\n# include \"wx\/wx.h\"\n#endif\n\n#if defined(UNIX)\n# include \n# include \n# include \n#endif\n\n#include \"vtlib\/vtlib.h\"\n#include \"vtlib\/core\/Terrain.h\"\n#include \"vtlib\/core\/TerrainScene.h\"\n\n#include \"StartupDlg.h\"\n#include \"..\/Enviro.h\"\t\/\/ for GetCurrentTerrain\n#include \"..\/Options.h\"\n#include \"vtdata\/boost\/directory.h\"\n\n#include \"app.h\"\n#include \"TParamsDlg.h\"\n\n\/\/\n\/\/ This function is used to find all files in a given directory,\n\/\/ and if they match a wildcard, add them to a combo box.\n\/\/\nvoid AddFilenamesToComboBox(wxComboBox *box, const char *directory,\n\t\t\t\t\t\t\tconst char *wildcard, int omit_chars)\n{\n\tusing namespace boost::filesystem;\n\n\tfor (dir_it it((const char *)directory); it != dir_it(); ++it)\n\t{\n\t\tif (get(it) || get(it))\n\t\t\tcontinue;\n\n\t\tstd::string name1 = *it;\n\t\twxString name = name1.c_str();\n\t\tif (name.Matches(wildcard))\n\t\t{\n\t\t\tif (omit_chars)\n\t\t\t\tbox->Append(name.Left(name.Length()-omit_chars));\n\t\t\telse\n\t\t\t\tbox->Append(name);\n\t\t}\n\t}\n}\n\n\/\/\n\/\/ Helper: find the largest texture size supported by OpenGL\n\/\/\n#ifdef WIN32\nstatic void ShowOGLInfo(HDC hdc)\n#else\nstatic void ShowOGLInfo()\n#endif\n{\n#if defined(WIN32)\n\tPIXELFORMATDESCRIPTOR pfd =\n\t{\n\t\tsizeof(PIXELFORMATDESCRIPTOR), \/\/ size of this pfd \n\t\t1,\t\t\t\t\t \/\/ version number \n\t\tPFD_DRAW_TO_WINDOW |\t\/\/ support window \n\t\tPFD_SUPPORT_OPENGL |\t\/\/ support OpenGL \n\t\tPFD_DOUBLEBUFFER,\t \/\/ double buffered \n\t\tPFD_TYPE_RGBA,\t\t \/\/ RGBA type \n\t\t24,\t\t\t\t\t \/\/ 24-bit color depth \n\t\t0, 0, 0, 0, 0, 0,\t \/\/ color bits ignored \n\t\t0, 0, 0,\t\t\t\t\/\/ no alpha buffer \n\t\t0, 0, 0, 0,\t\t\t \/\/ accum bits ignored \n\t\t32, 0, 0,\t\t\t \/\/ 32-bit z-buffer \n\t\tPFD_MAIN_PLANE,\t\t \/\/ main layer\n\t\t0,\t\t\t\t\t \/\/ reserved \n\t\t0, 0, 0\t\t\t\t \/\/ layer masks ignored\n\t};\n\tint iPixelFormat;\n\n\t\/\/ get the best available match of pixel format for the device context \n\tiPixelFormat = ChoosePixelFormat(hdc, &pfd);\n\t\/\/ make that the pixel format of the device context \n\tSetPixelFormat(hdc, iPixelFormat, &pfd);\n\n\tHGLRC device = wglCreateContext(hdc);\n\tif (device == NULL)\n\t{\n\t\tDWORD lasterror = GetLastError();\n\t\t\/\/ 2000 The pixel format is invalid. ERROR_INVALID_PIXEL_FORMAT \n\t}\n\twglMakeCurrent(hdc, device);\n#elif defined(UNIX)\n\tstatic int dblBuf[] = {GLX_RGBA, GLX_RED_SIZE, 1, GLX_GREEN_SIZE, 1,\n\t\t\t\t\t\t\tGLX_BLUE_SIZE, 1, GLX_DEPTH_SIZE, 1,\n\t\t\t\t\t\t\tGLX_DOUBLEBUFFER, None};\n\tDisplay *dpy;\n\tWindow win;\n\tXVisualInfo *vi;\n\tColormap cmap;\n\tXSetWindowAttributes swa;\n\tGLXContext cx;\n\tXEvent event;\n\tBool needRedraw = False, recalcModelView = True;\n\tint dummy;\n\n\tdpy = XOpenDisplay(NULL);\n\tif (dpy == NULL) \n\t\twxFatalError( \"could not open display\" );\n\n\tif (!glXQueryExtension(dpy, &dummy, &dummy))\n\t\twxFatalError( \"X server has no OpenGL GLX extension\" );\n\n\tvi = glXChooseVisual(dpy, DefaultScreen(dpy), dblBuf);\n\tif (vi == NULL)\n\t\twxFatalError( \"no RGB visual with double and depth buffer\" );\n\tif (vi->c_class != TrueColor)\n\t\twxFatalError( \"TrueColor visual required for this program\" );\n\n\tcmap = XCreateColormap(dpy, RootWindow(dpy, vi->screen),\n\t\t\t\t\t\t vi->visual, AllocNone);\n\tswa.colormap = cmap;\n\tswa.border_pixel = 0;\n\tswa.event_mask = ExposureMask | ButtonPressMask | StructureNotifyMask;\n\twin = XCreateWindow(dpy, RootWindow(dpy, vi->screen),\n\t\t\t\t\t\t0, 0, 300, 300, 0, vi->depth,\n\t\t\t\t\t\tInputOutput, vi->visual,\n\t\t\t\t\t\tCWBorderPixel | CWColormap | CWEventMask, &swa);\n\n\tXSetStandardProperties(dpy, win, \"test\", \"test\",\n\t\t\t\t\t\t None, NULL, 0, NULL);\n\n\tcx = glXCreateContext(dpy, vi, None, True);\n\tif (cx == NULL)\n\t\twxFatalError( \"could not create rendering context\" );\n\n\tglXMakeCurrent(dpy, win, cx);\n#else\n# error \"I don't know this platform.\"\n#endif\n\n\tGLint value;\n\tglGetIntegerv(GL_MAX_TEXTURE_SIZE, &value);\n\tGLenum error = glGetError();\n\tif (error == GL_INVALID_OPERATION)\n\t\tvalue = 0;\n\n\twxString str;\n\tstr.Printf(\"OpenGL Version: %s\\nVendor: %s\\nRenderer: %s\\n\"\n\t\t\"Maximum Texture Dimension: %d\\nExtensions: %s\",\n\t\tglGetString(GL_VERSION), glGetString(GL_VENDOR),\n\t\tglGetString(GL_RENDERER), value, glGetString(GL_EXTENSIONS));\n\n\twxDialog dlg(NULL, -1, \"OpenGL Info\", wxDefaultPosition);\n\tTextDialogFunc(&dlg, TRUE);\n\twxTextCtrl* pText = (wxTextCtrl*) dlg.FindWindow( ID_TEXT );\n\tpText->SetValue(str);\n\n\tdlg.ShowModal();\n\n#ifdef WIN32\n\twglDeleteContext(device);\n#elif defined(UNIX)\n\tglXDestroyContext(dpy, cx);\n\tXDestroyWindow(dpy, win);\n\tXCloseDisplay(dpy);\n#endif\n}\n\n\/\/ WDR: class implementations\n\n\/\/----------------------------------------------------------------------------\n\/\/ StartupDlg\n\/\/----------------------------------------------------------------------------\n\nvoid StartupDlg::GetOptionsFrom(EnviroOptions &opt)\n{\n\tm_bStartEarth = (opt.m_bEarthView == TRUE);\n\tm_bStartTerrain = !opt.m_bEarthView;\n\tm_strImage = opt.m_strImage;\n\tm_strTName = opt.m_strInitTerrain;\n\tm_bFullscreen = (opt.m_bFullscreen == TRUE);\n\tm_bGravity = (opt.m_bGravity == TRUE);\n\tm_bHtmlpane = (opt.m_bHtmlpane == TRUE);\n\tm_bFloatingToolbar = (opt.m_bFloatingToolbar == TRUE);\n\tm_bSound = (opt.m_bSound == TRUE);\n\tm_bVCursor = (opt.m_bVCursor == TRUE);\n\tm_bSpeedTest = (opt.m_bSpeedTest == TRUE);\n\tm_bQuakeNavigation = (opt.m_bQuakeNavigation == TRUE);\n\tm_fPlantScale = opt.m_fPlantScale;\n\tm_bShadows = (opt.m_bShadows == TRUE);\n}\n\nvoid StartupDlg::PutOptionsTo(EnviroOptions &opt)\n{\n\topt.m_bEarthView = (m_bStartEarth == 1);\n\topt.m_strImage = m_strImage;\n\topt.m_strInitTerrain = m_strTName;\n\topt.m_bFullscreen = m_bFullscreen;\n\topt.m_bGravity = m_bGravity;\n\topt.m_bHtmlpane = m_bHtmlpane;\n\topt.m_bFloatingToolbar = m_bFloatingToolbar;\n\topt.m_bSound = m_bSound;\n\topt.m_bVCursor = m_bVCursor;\n\topt.m_bSpeedTest = m_bSpeedTest;\n\topt.m_bQuakeNavigation = m_bQuakeNavigation;\n\topt.m_fPlantScale = m_fPlantScale;\n\topt.m_bShadows = m_bShadows;\n}\n\nvoid StartupDlg::UpdateState()\n{\n\tm_psImage->Enable(m_bStartEarth);\n\tm_pImage->Enable(m_bStartEarth);\n\tm_pTName->Enable(!m_bStartEarth);\n\tm_pTSelect->Enable(!m_bStartEarth);\n}\n\n\/\/ WDR: event table for StartupDlg\n\nBEGIN_EVENT_TABLE(StartupDlg,AutoDialog)\n\tEVT_BUTTON( ID_TSELECT, StartupDlg::OnSelectTerrain )\n\tEVT_BUTTON( wxID_OK, StartupDlg::OnOK )\n\tEVT_BUTTON( ID_OPENGL, StartupDlg::OnOpenGLInfo )\n\tEVT_RADIOBUTTON( ID_EARTHVIEW, StartupDlg::OnEarthView )\n\tEVT_RADIOBUTTON( ID_TERRAIN, StartupDlg::OnTerrain )\n\tEVT_BUTTON( ID_EDITPROP, StartupDlg::OnEditProp )\nEND_EVENT_TABLE()\n\nStartupDlg::StartupDlg( wxWindow *parent, wxWindowID id, const wxString &title,\n\tconst wxPoint &position, const wxSize& size, long style ) :\n\tAutoDialog( parent, id, title, position, size, style )\n{\n\tStartupDialogFunc( this, TRUE ); \n}\n\nvoid StartupDlg::EditParameters(const char *filename) \n{\n\tTParamsDlg dlg(this, -1, \"Terrain Creation Parameters\", wxDefaultPosition);\n\n\tTParams Params;\n\tif (Params.LoadFromFile(filename))\n\t\tdlg.SetParams(Params);\n\n\tdlg.CenterOnParent();\n\tint result = dlg.ShowModal();\n\tif (result == wxID_OK)\n\t{\n\t\tdlg.GetParams(Params);\n\t\tif (!Params.SaveToFile(filename))\n\t\t{\n\t\t\twxString str;\n\t\t\tstr.Printf(\"Couldn't save to file %s.\\n\"\n\t\t\t\t\t \"Please make sure the file is not read-only.\", filename);\n\t\t\twxMessageBox(str);\n\t\t}\n\t}\n}\n\n\/\/ WDR: handler implementations for StartupDlg\n\n#if 0\nvoid StartupDlg::OnSelectDataPath( wxCommandEvent &event )\n{\n\twxDirDialog dlg(this, \"Please indicate your data directory\", m_strDataPath);\n\tif (dlg.ShowModal() == wxID_OK)\n\t{\n\t\tm_strDataPath = dlg.GetPath();\n#if WIN32\n\t\twxString path_separator = \"\\\\\";\n#else\n\t\twxString path_separator = \"\/\";\n#endif\n\t\tm_strDataPath += path_separator;\n\t\tTransferDataToWindow();\n\t}\n}\n#endif\n\nvoid StartupDlg::OnEditProp( wxCommandEvent &event )\n{\n\tvtTerrain *pTerr = GetTerrainScene()->FindTerrainByName(m_strTName);\n\tif (pTerr)\n\t\tEditParameters(pTerr->GetParamFile());\n}\n\nvoid StartupDlg::OnTerrain( wxCommandEvent &event )\n{\n\tTransferDataFromWindow();\n\tUpdateState();\n}\n\nvoid StartupDlg::OnEarthView( wxCommandEvent &event )\n{\n\tTransferDataFromWindow();\n\tUpdateState();\n}\n\nvoid StartupDlg::OnOpenGLInfo( wxCommandEvent &event )\n{\n\t\/\/ check the OpenGL max texture size\n#ifdef WIN32\n\twxClientDC wdc(this);\n\tHDC hdc = (HDC) wdc.GetHDC();\n\tShowOGLInfo(hdc);\n#else\n\tShowOGLInfo();\n#endif\n}\n\nvoid StartupDlg::OnOK( wxCommandEvent &event )\n{\n\twxDialog::OnOK(event);\n}\n\nvoid StartupDlg::OnInitDialog(wxInitDialogEvent& event) \n{\n\tvtTerrain *pTerr = GetTerrainScene()->FindTerrainByName(m_strTName);\n\tif (pTerr)\n\t\tm_strTName = pTerr->GetName();\n\telse\n\t\tm_strTName = \"none\";\n\n\tm_pTName = GetTname();\n\tm_pTSelect = GetTselect();\n\tm_psImage = GetImagetext();\n\tm_pImage = GetImage();\n\n\tStringArray &paths = g_Options.m_DataPaths;\n\tfor (int i = 0; i < paths.GetSize(); i++)\n\t{\n\t\tvtString path = *paths[i];\n\t\tpath += \"WholeEarth\/\";\n\t\tAddFilenamesToComboBox(m_pImage, path, \"*_0106.png\", 9);\n\t}\n\tint sel = m_pImage->FindString(m_strImage);\n\tif (sel != -1)\n\t\tm_pImage->SetSelection(sel);\n\n\tUpdateState();\n\n\tAddValidator(ID_EARTHVIEW, &m_bStartEarth);\n\tAddValidator(ID_TERRAIN, &m_bStartTerrain);\n\n\tAddValidator(ID_FULLSCREEN, &m_bFullscreen);\n\tAddValidator(ID_GRAVITY, &m_bGravity);\n\tAddValidator(ID_HTML_PANE, &m_bHtmlpane);\n\tAddValidator(ID_FLOATING, &m_bFloatingToolbar);\n\tAddValidator(ID_SOUND, &m_bSound);\n\tAddValidator(ID_VCURSOR, &m_bVCursor);\n\tAddValidator(ID_SHADOWS, &m_bShadows);\n\n\tAddValidator(ID_TNAME, &m_strTName);\n\tAddValidator(ID_IMAGE, &m_strImage);\n\tAddNumValidator(ID_PLANTSIZE, &m_fPlantScale);\n\n\twxWindow::OnInitDialog(event);\n}\n\nvoid StartupDlg::OnSelectTerrain( wxCommandEvent &event )\n{\n\tTransferDataFromWindow();\n\n\tAskForTerrainName(this, m_strTName);\n\n\tTransferDataToWindow();\n}\n\n\n<|endoftext|>"} {"text":"\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n(Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\/\n\nCopyright (c) 2000-2010 Torus Knot Software Ltd\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n-----------------------------------------------------------------------------\n*\/\n#include \"PlayPenSamples.h\"\n\n\n\/\/---------------------------------------------------------------------\nPlayPen_testManualBlend::PlayPen_testManualBlend()\n{\n\tmInfo[\"Title\"] = \"PlayPen: Manual Blend\";\n\tmInfo[\"Description\"] = \"Manual blending\";\n\n}\nvoid PlayPen_testManualBlend::setupContent()\n{\n\t\/\/ create material\n\tMaterialPtr mat = MaterialManager::getSingleton().create(\"TestMat\", \n\t\tTRANSIENT_RESOURCE_GROUP);\n\tPass * p = mat->getTechnique(0)->getPass(0);\n\tp->setLightingEnabled(false);\n\tp->createTextureUnitState(\"Dirt.jpg\");\n\tTextureUnitState* t = p->createTextureUnitState(\"ogrelogo.png\");\n\tt->setColourOperationEx(LBX_BLEND_MANUAL, LBS_TEXTURE, LBS_CURRENT, \n\t\tColourValue::White, ColourValue::White, 0.75);\n\n\tEntity *planeEnt = mSceneMgr->createEntity(\"Plane\", SceneManager::PT_PLANE);\n\tmSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(planeEnt);\n\tplaneEnt->setMaterialName(\"TestMat\");\n\n\tmCamera->setPosition(0,0,600);\n\tmCamera->lookAt(Vector3::ZERO);\n}\n\/\/---------------------------------------------------------------------\nPlayPen_testProjectSphere::PlayPen_testProjectSphere()\n{\n\tmInfo[\"Title\"] = \"PlayPen: Project Sphere\";\n\tmInfo[\"Description\"] = \"Projecting a sphere's bounds onto the camera\";\n\n}\nvoid PlayPen_testProjectSphere::setupContent()\n{\n\tmSceneMgr->setAmbientLight(ColourValue::White);\n\n\n\tPlane plane;\n\tplane.normal = Vector3::UNIT_Y;\n\tplane.d = 0;\n\tMeshManager::getSingleton().createPlane(\"Myplane\",\n\t\tTRANSIENT_RESOURCE_GROUP, plane,\n\t\t4500,4500,10,10,true,1,5,5,Vector3::UNIT_Z);\n\tEntity* pPlaneEnt = mSceneMgr->createEntity( \"plane\", \"Myplane\" );\n\tpPlaneEnt->setMaterialName(\"Examples\/GrassFloor\");\n\tpPlaneEnt->setCastShadows(false);\n\tmSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt);\n\n\tmProjectionSphere = new Sphere(Vector3(0, 2000, 0), 1500.0);\n\n\tManualObject* debugSphere = mSceneMgr->createManualObject(\"debugSphere\");\n\tdebugSphere->begin(\"BaseWhiteNoLighting\", RenderOperation::OT_LINE_STRIP);\n\tfor (int i = 0; i <= 20; ++i)\n\t{\n\t\tVector3 basePos(mProjectionSphere->getRadius(), 0, 0);\n\t\tQuaternion quat;\n\t\tquat.FromAngleAxis(Radian(((float)i\/(float)20)*Math::TWO_PI), Vector3::UNIT_Y);\n\t\tbasePos = quat * basePos;\n\t\tdebugSphere->position(basePos);\n\t}\n\tfor (int i = 0; i <= 20; ++i)\n\t{\n\t\tVector3 basePos(mProjectionSphere->getRadius(), 0, 0);\n\t\tQuaternion quat;\n\t\tquat.FromAngleAxis(Radian(((float)i\/(float)20)*Math::TWO_PI), Vector3::UNIT_Z);\n\t\tbasePos = quat * basePos;\n\t\tdebugSphere->position(basePos);\n\t}\n\tdebugSphere->end();\n\n\tmSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0,2000,0))->attachObject(debugSphere);\n\n\tMaterialPtr mat = MaterialManager::getSingleton().create(\"scissormat\", \n\t\tTRANSIENT_RESOURCE_GROUP);\n\tPass* p = mat->getTechnique(0)->getPass(0);\n\tp->setDepthWriteEnabled(false);\n\tp->setSceneBlending(SBT_TRANSPARENT_ALPHA);\n\tTextureUnitState* t = p->createTextureUnitState();\n\tt->setColourOperationEx(LBX_SOURCE1, LBS_MANUAL, LBS_CURRENT, \n\t\tColourValue::Red);\n\tt->setAlphaOperation(LBX_SOURCE1, LBS_MANUAL, LBS_CURRENT, 0.5f);\n\n\n\tmScissorRect = mSceneMgr->createManualObject(\"mScissorRect\");\n\tmScissorRect->setUseIdentityProjection(true);\n\tmScissorRect->setUseIdentityView(true);\n\tAxisAlignedBox aabb;\n\taabb.setInfinite();\n\tmScissorRect->setBoundingBox(aabb);\n\tmScissorRect->begin(mat->getName());\n\tmScissorRect->position(Vector3::ZERO);\n\tmScissorRect->position(Vector3::ZERO);\n\tmScissorRect->position(Vector3::ZERO);\n\tmScissorRect->quad(0, 1, 2, 3);\n\tmScissorRect->end();\n\tmSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(mScissorRect);\n\n\tmCamera->setPosition(0,3000,5000);\n\tmCamera->lookAt(mProjectionSphere->getCenter());\n\n\n}\nbool PlayPen_testProjectSphere::frameStarted(const Ogre::FrameEvent& evt)\n{\n\tReal left, top, right, bottom;\n\tmCamera->projectSphere(*mProjectionSphere, &left, &top, &right, &bottom);\n\n\tmScissorRect->beginUpdate(0);\n\tmScissorRect->position(left, top, 0);\n\tmScissorRect->position(left, bottom, 0);\n\tmScissorRect->position(right, bottom, 0);\n\tmScissorRect->position(right, top, 0);\n\tmScissorRect->quad(0,1,2,3);\n\tmScissorRect->end();\n\n\treturn PlayPenBase::frameStarted(evt);\n\n}\n\n\/\/---------------------------------------------------------------------\nPlayPen_testCameraSetDirection::PlayPen_testCameraSetDirection()\n: mUseParentNode(false)\n, mUseFixedYaw(true)\n, mFocus(100,200,-300)\n{\n\tmInfo[\"Title\"] = \"PlayPen: Camera Set Direction\";\n\tmInfo[\"Description\"] = \"Testing various settings for Camera::setDirection\";\n\n}\nvoid PlayPen_testCameraSetDirection::setupContent()\n{\n\tmSceneMgr->setAmbientLight(ColourValue::White);\n\n\tEntity* e = mSceneMgr->createEntity(\"1\", \"knot.mesh\");\n\tmSceneMgr->getRootSceneNode()->createChildSceneNode(mFocus)->attachObject(e);\n\n\n\tmCamera->setPosition(200,1000,1000);\n\tmCamera->lookAt(mFocus);\n\n\tmTrayMgr->createButton(OgreBites::TL_BOTTOM, \"Look At\", \"Look At\");\n\tmTrayMgr->createCheckBox(OgreBites::TL_BOTTOM, \"tglParent\", \"Use Parent Node\");\n\tOgreBites::CheckBox* chk = mTrayMgr->createCheckBox(OgreBites::TL_BOTTOM, \"tglFixedYaw\", \"Use Fixed Yaw\");\n\tchk->setChecked(true, false);\n\tmTrayMgr->showCursor();\n\tsetDragLook(true);\n\n\tmParentNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(1000, 2000, -1000));\n\n}\nvoid PlayPen_testCameraSetDirection::buttonHit(OgreBites::Button* button)\n{\n\tmCamera->lookAt(mFocus);\n}\n\nvoid PlayPen_testCameraSetDirection::checkBoxToggled(OgreBites::CheckBox* box)\n{\n\tif (box->getName() == \"tglParent\")\n\t{\n\t\tmUseParentNode = !mUseParentNode;\n\n\t\tif (mUseParentNode)\n\t\t\tmParentNode->attachObject(mCamera);\n\t\telse\n\t\t\tmParentNode->detachAllObjects();\n\t}\n\telse if (box->getName() == \"tglFixedYaw\")\n\t{\n\t\tmUseFixedYaw = !mUseFixedYaw;\n\t\tif (mUseFixedYaw)\n\t\t\tmCamera->setFixedYawAxis(true);\n\t\telse\n\t\t\tmCamera->setFixedYawAxis(false);\n\n\t}\n}\n\/\/---------------------------------------------------------------------\nPlayPen_testManualLOD::PlayPen_testManualLOD()\n{\n\tmInfo[\"Title\"] = \"PlayPen: Test Manual LOD\";\n\tmInfo[\"Description\"] = \"Testing meshes with manual LODs assigned\";\n}\n\/\/---------------------------------------------------------------------\nString PlayPen_testManualLOD::getLODMesh()\n{\n\tMeshPtr msh1 = (MeshPtr)MeshManager::getSingleton().load(\"robot.mesh\", \n\t\tResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);\n\n\tmsh1->createManualLodLevel(200, \"razor.mesh\");\n\tmsh1->createManualLodLevel(500, \"sphere.mesh\");\n\n\treturn msh1->getName();\n\n}\n\/\/---------------------------------------------------------------------\nvoid PlayPen_testManualLOD::setupContent()\n{\n\tString meshName = getLODMesh();\n\n\tEntity *ent;\n\tfor (int i = 0; i < 5; ++i)\n\t{\n\t\tent = mSceneMgr->createEntity(\"robot\" + StringConverter::toString(i), meshName);\n\t\t\/\/ Add entity to the scene node\n\t\tmSceneMgr->getRootSceneNode()->createChildSceneNode(\n\t\t\tVector3(0,0,(i*50)-(5*50\/2)))->attachObject(ent);\n\t}\n\tmAnimState = ent->getAnimationState(\"Walk\");\n\tmAnimState->setEnabled(true);\n\n\n\n\t\/\/ Give it a little ambience with lights\n\tLight* l;\n\tl = mSceneMgr->createLight(\"BlueLight\");\n\tl->setPosition(-200,-80,-100);\n\tl->setDiffuseColour(0.5, 0.5, 1.0);\n\n\tl = mSceneMgr->createLight(\"GreenLight\");\n\tl->setPosition(0,0,-100);\n\tl->setDiffuseColour(0.5, 1.0, 0.5);\n\n\t\/\/ Position the camera\n\tmCamera->setPosition(100,50,100);\n\tmCamera->lookAt(-50,50,0);\n\n\tmSceneMgr->setAmbientLight(ColourValue::White);\n\n}\n\/\/---------------------------------------------------------------------\nbool PlayPen_testManualLOD::frameStarted(const Ogre::FrameEvent& evt)\n{\n\tmAnimState->addTime(evt.timeSinceLastFrame);\n\n\treturn PlayPenBase::frameStarted(evt);\n}\n\/\/---------------------------------------------------------------------\nPlayPen_testManualLODFromFile::PlayPen_testManualLODFromFile()\n{\n\tmInfo[\"Title\"] = \"PlayPen: Test Manual LOD (file)\";\n\tmInfo[\"Description\"] = \"Testing meshes with manual LODs assigned, loaded from a file\";\n}\n\/\/---------------------------------------------------------------------\nString PlayPen_testManualLODFromFile::getLODMesh()\n{\n\tMeshPtr msh1 = (MeshPtr)MeshManager::getSingleton().load(\"robot.mesh\", \n\t\tResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);\n\n\tmsh1->createManualLodLevel(200, \"razor.mesh\");\n\tmsh1->createManualLodLevel(500, \"sphere.mesh\");\n\n\t\/\/ this time, we save this data to a file and re-load it\n\n\tMeshSerializer ser;\n\tconst ResourceGroupManager::LocationList& ll = \n\t\tResourceGroupManager::getSingleton().getResourceLocationList(ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);\n\tString prefix;\n\tfor (ResourceGroupManager::LocationList::const_iterator i = ll.begin(); i != ll.end(); ++i)\n\t{\n\t\tif (StringUtil::endsWith((*i)->archive->getName(), \"media\"))\n\t\t{\n\t\t\tprefix = (*i)->archive->getName();\n\t\t}\n\t}\n\tser.exportMesh(msh1.get(), prefix + \"\/testlod.mesh\");\n\n\treturn \"testlod.mesh\";\n\n}\n\n\n\n\nJust make sure meshes are being reloaded in LOD test\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n(Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\/\n\nCopyright (c) 2000-2010 Torus Knot Software Ltd\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n-----------------------------------------------------------------------------\n*\/\n#include \"PlayPenSamples.h\"\n\n\n\/\/---------------------------------------------------------------------\nPlayPen_testManualBlend::PlayPen_testManualBlend()\n{\n\tmInfo[\"Title\"] = \"PlayPen: Manual Blend\";\n\tmInfo[\"Description\"] = \"Manual blending\";\n\n}\nvoid PlayPen_testManualBlend::setupContent()\n{\n\t\/\/ create material\n\tMaterialPtr mat = MaterialManager::getSingleton().create(\"TestMat\", \n\t\tTRANSIENT_RESOURCE_GROUP);\n\tPass * p = mat->getTechnique(0)->getPass(0);\n\tp->setLightingEnabled(false);\n\tp->createTextureUnitState(\"Dirt.jpg\");\n\tTextureUnitState* t = p->createTextureUnitState(\"ogrelogo.png\");\n\tt->setColourOperationEx(LBX_BLEND_MANUAL, LBS_TEXTURE, LBS_CURRENT, \n\t\tColourValue::White, ColourValue::White, 0.75);\n\n\tEntity *planeEnt = mSceneMgr->createEntity(\"Plane\", SceneManager::PT_PLANE);\n\tmSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(planeEnt);\n\tplaneEnt->setMaterialName(\"TestMat\");\n\n\tmCamera->setPosition(0,0,600);\n\tmCamera->lookAt(Vector3::ZERO);\n}\n\/\/---------------------------------------------------------------------\nPlayPen_testProjectSphere::PlayPen_testProjectSphere()\n{\n\tmInfo[\"Title\"] = \"PlayPen: Project Sphere\";\n\tmInfo[\"Description\"] = \"Projecting a sphere's bounds onto the camera\";\n\n}\nvoid PlayPen_testProjectSphere::setupContent()\n{\n\tmSceneMgr->setAmbientLight(ColourValue::White);\n\n\n\tPlane plane;\n\tplane.normal = Vector3::UNIT_Y;\n\tplane.d = 0;\n\tMeshManager::getSingleton().createPlane(\"Myplane\",\n\t\tTRANSIENT_RESOURCE_GROUP, plane,\n\t\t4500,4500,10,10,true,1,5,5,Vector3::UNIT_Z);\n\tEntity* pPlaneEnt = mSceneMgr->createEntity( \"plane\", \"Myplane\" );\n\tpPlaneEnt->setMaterialName(\"Examples\/GrassFloor\");\n\tpPlaneEnt->setCastShadows(false);\n\tmSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt);\n\n\tmProjectionSphere = new Sphere(Vector3(0, 2000, 0), 1500.0);\n\n\tManualObject* debugSphere = mSceneMgr->createManualObject(\"debugSphere\");\n\tdebugSphere->begin(\"BaseWhiteNoLighting\", RenderOperation::OT_LINE_STRIP);\n\tfor (int i = 0; i <= 20; ++i)\n\t{\n\t\tVector3 basePos(mProjectionSphere->getRadius(), 0, 0);\n\t\tQuaternion quat;\n\t\tquat.FromAngleAxis(Radian(((float)i\/(float)20)*Math::TWO_PI), Vector3::UNIT_Y);\n\t\tbasePos = quat * basePos;\n\t\tdebugSphere->position(basePos);\n\t}\n\tfor (int i = 0; i <= 20; ++i)\n\t{\n\t\tVector3 basePos(mProjectionSphere->getRadius(), 0, 0);\n\t\tQuaternion quat;\n\t\tquat.FromAngleAxis(Radian(((float)i\/(float)20)*Math::TWO_PI), Vector3::UNIT_Z);\n\t\tbasePos = quat * basePos;\n\t\tdebugSphere->position(basePos);\n\t}\n\tdebugSphere->end();\n\n\tmSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0,2000,0))->attachObject(debugSphere);\n\n\tMaterialPtr mat = MaterialManager::getSingleton().create(\"scissormat\", \n\t\tTRANSIENT_RESOURCE_GROUP);\n\tPass* p = mat->getTechnique(0)->getPass(0);\n\tp->setDepthWriteEnabled(false);\n\tp->setSceneBlending(SBT_TRANSPARENT_ALPHA);\n\tTextureUnitState* t = p->createTextureUnitState();\n\tt->setColourOperationEx(LBX_SOURCE1, LBS_MANUAL, LBS_CURRENT, \n\t\tColourValue::Red);\n\tt->setAlphaOperation(LBX_SOURCE1, LBS_MANUAL, LBS_CURRENT, 0.5f);\n\n\n\tmScissorRect = mSceneMgr->createManualObject(\"mScissorRect\");\n\tmScissorRect->setUseIdentityProjection(true);\n\tmScissorRect->setUseIdentityView(true);\n\tAxisAlignedBox aabb;\n\taabb.setInfinite();\n\tmScissorRect->setBoundingBox(aabb);\n\tmScissorRect->begin(mat->getName());\n\tmScissorRect->position(Vector3::ZERO);\n\tmScissorRect->position(Vector3::ZERO);\n\tmScissorRect->position(Vector3::ZERO);\n\tmScissorRect->quad(0, 1, 2, 3);\n\tmScissorRect->end();\n\tmSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(mScissorRect);\n\n\tmCamera->setPosition(0,3000,5000);\n\tmCamera->lookAt(mProjectionSphere->getCenter());\n\n\n}\nbool PlayPen_testProjectSphere::frameStarted(const Ogre::FrameEvent& evt)\n{\n\tReal left, top, right, bottom;\n\tmCamera->projectSphere(*mProjectionSphere, &left, &top, &right, &bottom);\n\n\tmScissorRect->beginUpdate(0);\n\tmScissorRect->position(left, top, 0);\n\tmScissorRect->position(left, bottom, 0);\n\tmScissorRect->position(right, bottom, 0);\n\tmScissorRect->position(right, top, 0);\n\tmScissorRect->quad(0,1,2,3);\n\tmScissorRect->end();\n\n\treturn PlayPenBase::frameStarted(evt);\n\n}\n\n\/\/---------------------------------------------------------------------\nPlayPen_testCameraSetDirection::PlayPen_testCameraSetDirection()\n: mUseParentNode(false)\n, mUseFixedYaw(true)\n, mFocus(100,200,-300)\n{\n\tmInfo[\"Title\"] = \"PlayPen: Camera Set Direction\";\n\tmInfo[\"Description\"] = \"Testing various settings for Camera::setDirection\";\n\n}\nvoid PlayPen_testCameraSetDirection::setupContent()\n{\n\tmSceneMgr->setAmbientLight(ColourValue::White);\n\n\tEntity* e = mSceneMgr->createEntity(\"1\", \"knot.mesh\");\n\tmSceneMgr->getRootSceneNode()->createChildSceneNode(mFocus)->attachObject(e);\n\n\n\tmCamera->setPosition(200,1000,1000);\n\tmCamera->lookAt(mFocus);\n\n\tmTrayMgr->createButton(OgreBites::TL_BOTTOM, \"Look At\", \"Look At\");\n\tmTrayMgr->createCheckBox(OgreBites::TL_BOTTOM, \"tglParent\", \"Use Parent Node\");\n\tOgreBites::CheckBox* chk = mTrayMgr->createCheckBox(OgreBites::TL_BOTTOM, \"tglFixedYaw\", \"Use Fixed Yaw\");\n\tchk->setChecked(true, false);\n\tmTrayMgr->showCursor();\n\tsetDragLook(true);\n\n\tmParentNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(1000, 2000, -1000));\n\n}\nvoid PlayPen_testCameraSetDirection::buttonHit(OgreBites::Button* button)\n{\n\tmCamera->lookAt(mFocus);\n}\n\nvoid PlayPen_testCameraSetDirection::checkBoxToggled(OgreBites::CheckBox* box)\n{\n\tif (box->getName() == \"tglParent\")\n\t{\n\t\tmUseParentNode = !mUseParentNode;\n\n\t\tif (mUseParentNode)\n\t\t\tmParentNode->attachObject(mCamera);\n\t\telse\n\t\t\tmParentNode->detachAllObjects();\n\t}\n\telse if (box->getName() == \"tglFixedYaw\")\n\t{\n\t\tmUseFixedYaw = !mUseFixedYaw;\n\t\tif (mUseFixedYaw)\n\t\t\tmCamera->setFixedYawAxis(true);\n\t\telse\n\t\t\tmCamera->setFixedYawAxis(false);\n\n\t}\n}\n\/\/---------------------------------------------------------------------\nPlayPen_testManualLOD::PlayPen_testManualLOD()\n{\n\tmInfo[\"Title\"] = \"PlayPen: Test Manual LOD\";\n\tmInfo[\"Description\"] = \"Testing meshes with manual LODs assigned\";\n}\n\/\/---------------------------------------------------------------------\nString PlayPen_testManualLOD::getLODMesh()\n{\n\tMeshPtr msh1 = (MeshPtr)MeshManager::getSingleton().load(\"robot.mesh\", \n\t\tResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);\n\n\tmsh1->createManualLodLevel(200, \"razor.mesh\");\n\tmsh1->createManualLodLevel(500, \"sphere.mesh\");\n\n\treturn msh1->getName();\n\n}\n\/\/---------------------------------------------------------------------\nvoid PlayPen_testManualLOD::setupContent()\n{\n\tString meshName = getLODMesh();\n\n\tEntity *ent;\n\tfor (int i = 0; i < 5; ++i)\n\t{\n\t\tent = mSceneMgr->createEntity(\"robot\" + StringConverter::toString(i), meshName);\n\t\t\/\/ Add entity to the scene node\n\t\tmSceneMgr->getRootSceneNode()->createChildSceneNode(\n\t\t\tVector3(0,0,(i*50)-(5*50\/2)))->attachObject(ent);\n\t}\n\tmAnimState = ent->getAnimationState(\"Walk\");\n\tmAnimState->setEnabled(true);\n\n\n\n\t\/\/ Give it a little ambience with lights\n\tLight* l;\n\tl = mSceneMgr->createLight(\"BlueLight\");\n\tl->setPosition(-200,-80,-100);\n\tl->setDiffuseColour(0.5, 0.5, 1.0);\n\n\tl = mSceneMgr->createLight(\"GreenLight\");\n\tl->setPosition(0,0,-100);\n\tl->setDiffuseColour(0.5, 1.0, 0.5);\n\n\t\/\/ Position the camera\n\tmCamera->setPosition(100,50,100);\n\tmCamera->lookAt(-50,50,0);\n\n\tmSceneMgr->setAmbientLight(ColourValue::White);\n\n}\n\/\/---------------------------------------------------------------------\nbool PlayPen_testManualLOD::frameStarted(const Ogre::FrameEvent& evt)\n{\n\tmAnimState->addTime(evt.timeSinceLastFrame);\n\n\treturn PlayPenBase::frameStarted(evt);\n}\n\/\/---------------------------------------------------------------------\nPlayPen_testManualLODFromFile::PlayPen_testManualLODFromFile()\n{\n\tmInfo[\"Title\"] = \"PlayPen: Test Manual LOD (file)\";\n\tmInfo[\"Description\"] = \"Testing meshes with manual LODs assigned, loaded from a file\";\n}\n\/\/---------------------------------------------------------------------\nString PlayPen_testManualLODFromFile::getLODMesh()\n{\n\tMeshPtr msh1 = (MeshPtr)MeshManager::getSingleton().load(\"robot.mesh\", \n\t\tResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);\n\n\tmsh1->createManualLodLevel(200, \"razor.mesh\");\n\tmsh1->createManualLodLevel(500, \"sphere.mesh\");\n\n\t\/\/ this time, we save this data to a file and re-load it\n\n\tMeshSerializer ser;\n\tconst ResourceGroupManager::LocationList& ll = \n\t\tResourceGroupManager::getSingleton().getResourceLocationList(ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);\n\tString prefix;\n\tfor (ResourceGroupManager::LocationList::const_iterator i = ll.begin(); i != ll.end(); ++i)\n\t{\n\t\tif (StringUtil::endsWith((*i)->archive->getName(), \"media\"))\n\t\t{\n\t\t\tprefix = (*i)->archive->getName();\n\t\t}\n\t}\n\tser.exportMesh(msh1.get(), prefix + \"\/testlod.mesh\");\n\n\tMeshManager::getSingleton().removeAll();\n\n\treturn \"testlod.mesh\";\n\n}\n\n\n\n\n<|endoftext|>"} {"text":"decrease query count before dispatching callback<|endoftext|>"} {"text":"more than one seed<|endoftext|>"} {"text":"Fixing a small error.<|endoftext|>"} {"text":"moved the callback before client connect<|endoftext|>"} {"text":"fix(specializer): check number of args before reusing function<|endoftext|>"} {"text":"try fix start new network problem<|endoftext|>"} {"text":"\/\/ Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"paddle\/fluid\/framework\/op_registry.h\"\n#include \"paddle\/fluid\/framework\/operator.h\"\n\nnamespace paddle {\nnamespace framework {\nclass OpDesc;\nclass Scope;\ntemplate \nclass EmptyGradOpMaker;\n} \/\/ namespace framework\nnamespace imperative {\nclass OpBase;\n} \/\/ namespace imperative\n} \/\/ namespace paddle\n\nnamespace paddle {\nnamespace operators {\n\nclass DependOp : public framework::OperatorBase {\n public:\n DependOp(const std::string &type,\n const framework::VariableNameMap &inputs,\n const framework::VariableNameMap &outputs,\n const framework::AttributeMap &attrs)\n : OperatorBase(type, inputs, outputs, attrs) {}\n\n private:\n void RunImpl(const framework::Scope &scope,\n const platform::Place &place) const override {\n \/\/ NOTE(zhiqiu): depend op has empty compute, and it\n \/\/ can be skiped in the executor.\n OP_INOUT_CHECK(HasInputs(\"X\"), \"Input\", \"X\", \"Feed\");\n OP_INOUT_CHECK(HasOutputs(\"Out\"), \"Output\", \"Out\", \"Feed\");\n\n auto x_name = Input(\"X\");\n auto out_name = Output(\"Out\");\n PADDLE_ENFORCE_EQ(x_name,\n out_name,\n platform::errors::PreconditionNotMet(\n \"Input(X) and Output(Out) varibale should be the \"\n \"same, but got Input is %s and Output is %s.\",\n x_name,\n out_name));\n return;\n }\n};\n\nclass DependOpProtoMaker : public framework::OpProtoAndCheckerMaker {\n public:\n void Make() override {\n AddInput(\"X\", \"Tensor, the dependence is added for.\");\n AddInput(\"Dep\", \"The tensors that should be generated before X.\")\n .AsDuplicable();\n AddOutput(\"Out\", \"Tensor, the same as input X\");\n AddComment(R\"DOC(\nDepend Operator, allows to add explicit dependency between tensors.\nFor example, given two ops:\nb = opA(a)\ny = opB(x)\n\nif tensor b and tensor x has some inner dependency, for example, x share data with b,\nwe need to add explicit dependency for x <- b, otherwise the these two operators may\nbe executed parellel in static graph. We can use depend op as below,\n\nb = opA(a)\nx = depend(x, b)\ny = opB(x)\n\n)DOC\");\n }\n};\n\nDECLARE_NO_NEED_BUFFER_VARS_INFERER(DependNoNeedBufferVarsInferer, \"X\", \"Dep\");\n\n} \/\/ namespace operators\n} \/\/ namespace paddle\n\nnamespace ops = paddle::operators;\n\nREGISTER_OPERATOR(\n depend,\n ops::DependOp,\n paddle::framework::EmptyGradOpMaker,\n paddle::framework::EmptyGradOpMaker,\n ops::DependOpProtoMaker,\n ops::DependNoNeedBufferVarsInferer);\nAdd InferShape for Depend OP (#47907)\/\/ Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"paddle\/fluid\/framework\/op_registry.h\"\n#include \"paddle\/fluid\/framework\/operator.h\"\n\nnamespace paddle {\nnamespace framework {\nclass OpDesc;\nclass Scope;\ntemplate \nclass EmptyGradOpMaker;\n} \/\/ namespace framework\nnamespace imperative {\nclass OpBase;\n} \/\/ namespace imperative\n} \/\/ namespace paddle\n\nnamespace paddle {\nnamespace operators {\n\nclass DependOp : public framework::OperatorBase {\n public:\n DependOp(const std::string &type,\n const framework::VariableNameMap &inputs,\n const framework::VariableNameMap &outputs,\n const framework::AttributeMap &attrs)\n : OperatorBase(type, inputs, outputs, attrs) {}\n\n private:\n void RunImpl(const framework::Scope &scope,\n const platform::Place &place) const override {\n \/\/ NOTE(zhiqiu): depend op has empty compute, and it\n \/\/ can be skiped in the executor.\n OP_INOUT_CHECK(HasInputs(\"X\"), \"Input\", \"X\", \"Feed\");\n OP_INOUT_CHECK(HasOutputs(\"Out\"), \"Output\", \"Out\", \"Feed\");\n\n auto x_name = Input(\"X\");\n auto out_name = Output(\"Out\");\n PADDLE_ENFORCE_EQ(x_name,\n out_name,\n platform::errors::PreconditionNotMet(\n \"Input(X) and Output(Out) varibale should be the \"\n \"same, but got Input is %s and Output is %s.\",\n x_name,\n out_name));\n return;\n }\n};\n\nclass DependOpShapeInference : public framework::InferShapeBase {\n public:\n void operator()(framework::InferShapeContext *ctx) const override {}\n};\n\nclass DependOpProtoMaker : public framework::OpProtoAndCheckerMaker {\n public:\n void Make() override {\n AddInput(\"X\", \"Tensor, the dependence is added for.\");\n AddInput(\"Dep\", \"The tensors that should be generated before X.\")\n .AsDuplicable();\n AddOutput(\"Out\", \"Tensor, the same as input X\");\n AddComment(R\"DOC(\nDepend Operator, allows to add explicit dependency between tensors.\nFor example, given two ops:\nb = opA(a)\ny = opB(x)\n\nif tensor b and tensor x has some inner dependency, for example, x share data with b,\nwe need to add explicit dependency for x <- b, otherwise the these two operators may\nbe executed parellel in static graph. We can use depend op as below,\n\nb = opA(a)\nx = depend(x, b)\ny = opB(x)\n\n)DOC\");\n }\n};\n\nDECLARE_NO_NEED_BUFFER_VARS_INFERER(DependNoNeedBufferVarsInferer, \"X\", \"Dep\");\n\n} \/\/ namespace operators\n} \/\/ namespace paddle\n\nnamespace ops = paddle::operators;\n\nREGISTER_OPERATOR(\n depend,\n ops::DependOp,\n paddle::framework::EmptyGradOpMaker,\n paddle::framework::EmptyGradOpMaker,\n ops::DependOpProtoMaker,\n ops::DependOpShapeInference,\n ops::DependNoNeedBufferVarsInferer);\n<|endoftext|>"} {"text":"drop checkpoints<|endoftext|>"} {"text":"Slowallel but works<|endoftext|>"} {"text":"~ realignment<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2011 Scott MacDonald. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n *\/\n#include \"worldgen\/levelgenerator.h\"\n#include \"worldgen\/roomgenerator.h\"\n#include \"worldgen\/roomdata.h\"\n#include \"common\/utils.h\"\n#include \"common\/random.h\"\n\n#include \"level.h\"\n\n#include \"room.h\"\n\n\/**\n * Level generator constructor. Creates a new level generator that is ready\n * to construct as many random levels as you wish.\n *\n * \\param random Reference to the dungeon generator's random\n * \\param width Width of the level\n * \\param height Height of the level\n *\/\nLevelGenerator::LevelGenerator( Random& random,\n int width,\n int height )\n : mRandom( random ),\n mLevelWidth( width ),\n mLevelHeight( height ),\n mTileGrid( width, height )\n{\n assert( width > 5 );\n assert( height > 5 );\n}\n\n\/**\n * Destructor\n *\/\nLevelGenerator::~LevelGenerator()\n{\n}\n\n\/**\n * Generates and returns a random level\n *\/\nLevel* LevelGenerator::generate()\n{\n RoomGenerator roomGenerator( mRandom );\n std::vector levelRooms;\n\n \/\/ Turn the level border tiles into impassable bedrock tiles to prevent\n \/\/ the player (or anyone really) from escaping into the void\n mTileGrid.carveRoom( Rect( 1, 1, mLevelWidth-2, mLevelHeight-2 ),\n 1,\n Tile( TILE_IMPASSABLE ),\n Tile( TILE_EMPTY ) );\n\n \/\/ Generate the requested number of rooms\n for ( int i = 0; i < 150; ++i )\n {\n \/\/ Generate a random room\n ERoomSize roomSize = generateRandomRoomSize( ROOM_SIZE_LARGE );\n RoomData *pRoomData = roomGenerator.generate( roomSize );\n\n \/\/ Generate a random position to place it in\n Point placeAt = findRandomPointFor( deref(pRoomData) );\n\n \/\/ Try to place the room's tile grid into our level's tile grid. If it\n \/\/ doesn't succeed, make sure to delete the room data before trying\n \/\/ another room\n if ( canPlaceRoomAt( deref(pRoomData), placeAt ) )\n {\n mTileGrid.insert( placeAt, pRoomData->tiles );\n levelRooms.push_back( pRoomData );\n }\n else\n {\n Delete( pRoomData );\n }\n }\n\n \/\/ Show debug stats about rooms generated and whatnot\n\n\n \/\/ Hook everything up\n\n \/\/ Return the generated level\n return new Level( mTileGrid );\n}\n\nERoomSize LevelGenerator::generateRandomRoomSize( ERoomSize maxRoomSize ) const\n{\n \/\/ This needs to be improved\n int whichOne = mRandom.randInt( 0, 100 );\n\n if ( whichOne < 10 )\n {\n return ROOM_SIZE_TINY;\n }\n else if ( whichOne < 30 )\n {\n return ROOM_SIZE_SMALL;\n }\n else if ( whichOne < 90 )\n {\n return ROOM_SIZE_MEDIUM;\n }\n else\n {\n return ROOM_SIZE_LARGE;\n }\n}\n\n\/**\n * Finds a random position to attempt to place a room at\n *\n * \\param roomData The room you are trying to place\n * \\return A randomly determined position\n *\/\nPoint LevelGenerator::findRandomPointFor( const RoomData& roomData ) const\n{\n int maxX = mLevelWidth - roomData.totalArea.width() - 2;\n int maxY = mLevelHeight - roomData.totalArea.height() - 2;\n\n return Point( mRandom.randInt( 1, maxX ),\n mRandom.randInt( 1, maxY ) );\n}\n\n\/**\n * Checks if the given room can be placed at the requested location\n *\n * \\param roomData Data for the room you are trying to place\n * \\param pos Position you are trying to place the room at\n * \\return True if the room can be positioned there, false otherwise\n *\/\nbool LevelGenerator::canPlaceRoomAt( const RoomData& roomData,\n const Point& pos ) const\n{\n return mTileGrid.isAreaEmpty( roomData.totalArea.translate( pos ) );\n}changed a comment\/*\n * Copyright (C) 2011 Scott MacDonald. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n *\/\n#include \"worldgen\/levelgenerator.h\"\n#include \"worldgen\/roomgenerator.h\"\n#include \"worldgen\/roomdata.h\"\n#include \"common\/utils.h\"\n#include \"common\/random.h\"\n\n#include \"level.h\"\n\n#include \"room.h\"\n\n\/**\n * Level generator constructor. Creates a new level generator that is ready\n * to construct as many random levels as you wish.\n *\n * \\param random Reference to the dungeon generator's random\n * \\param width Width of the level\n * \\param height Height of the level\n *\/\nLevelGenerator::LevelGenerator( Random& random,\n int width,\n int height )\n : mRandom( random ),\n mLevelWidth( width ),\n mLevelHeight( height ),\n mTileGrid( width, height )\n{\n assert( width > 5 );\n assert( height > 5 );\n}\n\n\/**\n * Destructor\n *\/\nLevelGenerator::~LevelGenerator()\n{\n}\n\n\/**\n * Generates and returns a random level\n *\/\nLevel* LevelGenerator::generate()\n{\n RoomGenerator roomGenerator( mRandom );\n std::vector levelRooms;\n\n \/\/ Turn the level border tiles into impassable bedrock tiles to prevent\n \/\/ the player (or anyone really) from escaping into the void\n mTileGrid.carveRoom( Rect( 1, 1, mLevelWidth-2, mLevelHeight-2 ),\n 1,\n Tile( TILE_IMPASSABLE ),\n Tile( TILE_EMPTY ) );\n\n \/\/ Generate the requested number of rooms\n for ( int i = 0; i < 150; ++i )\n {\n \/\/ Generate a random room\n ERoomSize roomSize = generateRandomRoomSize( ROOM_SIZE_LARGE );\n RoomData *pRoomData = roomGenerator.generate( roomSize );\n\n \/\/ Generate a random position to place it in\n Point placeAt = findRandomPointFor( deref(pRoomData) );\n\n \/\/ Try to place the room's tile grid into our level's tile grid. If it\n \/\/ doesn't succeed, make sure to delete the room data before trying\n \/\/ another room\n if ( canPlaceRoomAt( deref(pRoomData), placeAt ) )\n {\n mTileGrid.insert( placeAt, pRoomData->tiles );\n levelRooms.push_back( pRoomData );\n }\n else\n {\n Delete( pRoomData );\n }\n }\n\n \/\/ Show debug stats about rooms generated and whatnot\n\n \/\/ Connect rooms together\n\n \/\/ Return the generated level\n return new Level( mTileGrid );\n}\n\n\/**\n * Creates a random room size, depending on the maximum room size passed\n *\/\nERoomSize LevelGenerator::generateRandomRoomSize( ERoomSize maxRoomSize ) const\n{\n \/\/ This needs to be improved\n int whichOne = mRandom.randInt( 0, 100 );\n\n if ( whichOne < 10 )\n {\n return ROOM_SIZE_TINY;\n }\n else if ( whichOne < 30 )\n {\n return ROOM_SIZE_SMALL;\n }\n else if ( whichOne < 90 )\n {\n return ROOM_SIZE_MEDIUM;\n }\n else\n {\n return ROOM_SIZE_LARGE;\n }\n}\n\n\/**\n * Finds a random position to attempt to place a room at\n *\n * \\param roomData The room you are trying to place\n * \\return A randomly determined position\n *\/\nPoint LevelGenerator::findRandomPointFor( const RoomData& roomData ) const\n{\n int maxX = mLevelWidth - roomData.totalArea.width() - 2;\n int maxY = mLevelHeight - roomData.totalArea.height() - 2;\n\n return Point( mRandom.randInt( 1, maxX ),\n mRandom.randInt( 1, maxY ) );\n}\n\n\/**\n * Checks if the given room can be placed at the requested location\n *\n * \\param roomData Data for the room you are trying to place\n * \\param pos Position you are trying to place the room at\n * \\return True if the room can be positioned there, false otherwise\n *\/\nbool LevelGenerator::canPlaceRoomAt( const RoomData& roomData,\n const Point& pos ) const\n{\n return mTileGrid.isAreaEmpty( roomData.totalArea.translate( pos ) );\n}<|endoftext|>"} {"text":"\/**\n ******************************************************************************\n * Xenia : Xbox 360 Emulator Research Project *\n ******************************************************************************\n * Copyright 2013 Ben Vanik. All rights reserved. *\n * Released under the BSD license - see LICENSE in the root for more details. *\n ******************************************************************************\n *\/\n\n#include \"xenia\/base\/logging.h\"\n#include \"xenia\/kernel\/kernel_state.h\"\n#include \"xenia\/kernel\/objects\/xthread.h\"\n#include \"xenia\/kernel\/objects\/xsemaphore.h\"\n#include \"xenia\/kernel\/util\/shim_utils.h\"\n#include \"xenia\/kernel\/xboxkrnl_private.h\"\n#include \"xenia\/kernel\/xobject.h\"\n#include \"xenia\/xbox.h\"\n\nnamespace xe {\nnamespace kernel {\n\nSHIM_CALL ObOpenObjectByName_shim(PPCContext* ppc_context,\n KernelState* kernel_state) {\n \/\/ r3 = ptr to info?\n \/\/ +0 = -4\n \/\/ +4 = name ptr\n \/\/ +8 = 0\n \/\/ r4 = ExEventObjectType | ExSemaphoreObjectType | ExTimerObjectType\n \/\/ r5 = 0\n \/\/ r6 = out_ptr (handle?)\n uint32_t obj_attributes_ptr = SHIM_GET_ARG_32(0);\n uint32_t object_type_ptr = SHIM_GET_ARG_32(1);\n uint32_t unk = SHIM_GET_ARG_32(2);\n uint32_t handle_ptr = SHIM_GET_ARG_32(3);\n\n auto name =\n X_ANSI_STRING::to_string_indirect(SHIM_MEM_BASE, obj_attributes_ptr + 4);\n\n XELOGD(\"ObOpenObjectByName(%.8X(name=%s), %.8X, %.8X, %.8X)\",\n obj_attributes_ptr, name.c_str(), object_type_ptr, unk, handle_ptr);\n\n X_HANDLE handle = X_INVALID_HANDLE_VALUE;\n X_STATUS result =\n kernel_state->object_table()->GetObjectByName(name, &handle);\n if (XSUCCEEDED(result)) {\n SHIM_SET_MEM_32(handle_ptr, handle);\n }\n\n SHIM_SET_RETURN_32(result);\n}\n\nSHIM_CALL ObReferenceObjectByHandle_shim(PPCContext* ppc_context,\n KernelState* kernel_state) {\n uint32_t handle = SHIM_GET_ARG_32(0);\n uint32_t object_type_ptr = SHIM_GET_ARG_32(1);\n uint32_t out_object_ptr = SHIM_GET_ARG_32(2);\n\n XELOGD(\"ObReferenceObjectByHandle(%.8X, %.8X, %.8X)\", handle, object_type_ptr,\n out_object_ptr);\n\n X_STATUS result = X_STATUS_SUCCESS;\n\n auto object = kernel_state->object_table()->LookupObject(handle);\n if (object) {\n \/\/ TODO(benvanik): verify type with object_type_ptr\n\n \/\/ TODO(benvanik): get native value, if supported.\n uint32_t native_ptr;\n switch (object_type_ptr) {\n case 0x00000000: { \/\/ whatever?\n switch (object->type()) {\n \/\/ TODO(benvanik): need to track native_ptr in XObject, allocate as\n \/\/ needed?\n \/*case XObject::kTypeEvent: {\n XEvent* ev = (XEvent*)object;\n } break;*\/\n case XObject::kTypeThread: {\n auto thread = object.get();\n native_ptr = thread->guest_object();\n } break;\n default: {\n assert_unhandled_case(object->type());\n native_ptr = 0xDEADF00D;\n } break;\n }\n } break;\n case 0xD017BEEF: { \/\/ ExSemaphoreObjectType\n assert(object->type() == XObject::kTypeSemaphore);\n auto sem = object.get();\n\n native_ptr = sem->guest_object();\n } break;\n case 0xD01BBEEF: { \/\/ ExThreadObjectType\n assert(object->type() == XObject::kTypeThread);\n auto thread = object.get();\n\n native_ptr = thread->guest_object();\n } break;\n default: {\n assert_unhandled_case(object_type_ptr);\n native_ptr = 0xDEADF00D;\n } break;\n }\n\n \/\/ Caller takes the reference.\n \/\/ It's released in ObDereferenceObject.\n object->Retain();\n if (out_object_ptr) {\n SHIM_SET_MEM_32(out_object_ptr, native_ptr);\n }\n } else {\n result = X_STATUS_INVALID_HANDLE;\n }\n\n SHIM_SET_RETURN_32(result);\n}\n\nSHIM_CALL ObDereferenceObject_shim(PPCContext* ppc_context,\n KernelState* kernel_state) {\n uint32_t native_ptr = SHIM_GET_ARG_32(0);\n\n XELOGD(\"ObDereferenceObject(%.8X)\", native_ptr);\n\n \/\/ Check if a dummy value from ObReferenceObjectByHandle.\n if (native_ptr == 0xDEADF00D) {\n SHIM_SET_RETURN_32(0);\n return;\n }\n\n void* object_ptr = SHIM_MEM_ADDR(native_ptr);\n auto object = XObject::GetNativeObject(kernel_state, object_ptr);\n if (object) {\n object->Release();\n }\n\n SHIM_SET_RETURN_32(0);\n}\n\ndword_result_t NtDuplicateObject(dword_t handle, lpdword_t new_handle_ptr,\n dword_t options) {\n \/\/ NOTE: new_handle_ptr can be zero to just close a handle.\n \/\/ NOTE: this function seems to be used to get the current thread handle\n \/\/ (passed handle=-2).\n \/\/ This function actually just creates a new handle to the same object.\n \/\/ Most games use it to get real handles to the current thread or whatever.\n\n X_HANDLE new_handle = X_INVALID_HANDLE_VALUE;\n X_STATUS result =\n kernel_state()->object_table()->DuplicateHandle(handle, &new_handle);\n\n if (new_handle_ptr) {\n *new_handle_ptr = new_handle;\n }\n\n if (options == 1 \/* DUPLICATE_CLOSE_SOURCE *\/) {\n \/\/ Always close the source object.\n kernel_state()->object_table()->RemoveHandle(handle);\n }\n\n return result;\n}\nDECLARE_XBOXKRNL_EXPORT(NtDuplicateObject, ExportTag::kImplemented);\n\ndword_result_t NtClose(dword_t handle) {\n return kernel_state()->object_table()->RemoveHandle(handle);\n}\nDECLARE_XBOXKRNL_EXPORT(NtClose, ExportTag::kImplemented);\n\n} \/\/ namespace kernel\n} \/\/ namespace xe\n\nvoid xe::kernel::xboxkrnl::RegisterObExports(\n xe::cpu::ExportResolver* export_resolver, KernelState* kernel_state) {\n SHIM_SET_MAPPING(\"xboxkrnl.exe\", ObOpenObjectByName, state);\n SHIM_SET_MAPPING(\"xboxkrnl.exe\", ObReferenceObjectByHandle, state);\n SHIM_SET_MAPPING(\"xboxkrnl.exe\", ObDereferenceObject, state);\n}\nObLookupThreadByThreadId \/ ObOpenObjectByPointer\/**\n ******************************************************************************\n * Xenia : Xbox 360 Emulator Research Project *\n ******************************************************************************\n * Copyright 2013 Ben Vanik. All rights reserved. *\n * Released under the BSD license - see LICENSE in the root for more details. *\n ******************************************************************************\n *\/\n\n#include \"xenia\/base\/logging.h\"\n#include \"xenia\/kernel\/kernel_state.h\"\n#include \"xenia\/kernel\/objects\/xthread.h\"\n#include \"xenia\/kernel\/objects\/xsemaphore.h\"\n#include \"xenia\/kernel\/util\/shim_utils.h\"\n#include \"xenia\/kernel\/xboxkrnl_private.h\"\n#include \"xenia\/kernel\/xobject.h\"\n#include \"xenia\/xbox.h\"\n\nnamespace xe {\nnamespace kernel {\n\nSHIM_CALL ObOpenObjectByName_shim(PPCContext* ppc_context,\n KernelState* kernel_state) {\n \/\/ r3 = ptr to info?\n \/\/ +0 = -4\n \/\/ +4 = name ptr\n \/\/ +8 = 0\n \/\/ r4 = ExEventObjectType | ExSemaphoreObjectType | ExTimerObjectType\n \/\/ r5 = 0\n \/\/ r6 = out_ptr (handle?)\n uint32_t obj_attributes_ptr = SHIM_GET_ARG_32(0);\n uint32_t object_type_ptr = SHIM_GET_ARG_32(1);\n uint32_t unk = SHIM_GET_ARG_32(2);\n uint32_t handle_ptr = SHIM_GET_ARG_32(3);\n\n auto name =\n X_ANSI_STRING::to_string_indirect(SHIM_MEM_BASE, obj_attributes_ptr + 4);\n\n XELOGD(\"ObOpenObjectByName(%.8X(name=%s), %.8X, %.8X, %.8X)\",\n obj_attributes_ptr, name.c_str(), object_type_ptr, unk, handle_ptr);\n\n X_HANDLE handle = X_INVALID_HANDLE_VALUE;\n X_STATUS result =\n kernel_state->object_table()->GetObjectByName(name, &handle);\n if (XSUCCEEDED(result)) {\n SHIM_SET_MEM_32(handle_ptr, handle);\n }\n\n SHIM_SET_RETURN_32(result);\n}\n\nSHIM_CALL ObReferenceObjectByHandle_shim(PPCContext* ppc_context,\n KernelState* kernel_state) {\n uint32_t handle = SHIM_GET_ARG_32(0);\n uint32_t object_type_ptr = SHIM_GET_ARG_32(1);\n uint32_t out_object_ptr = SHIM_GET_ARG_32(2);\n\n XELOGD(\"ObReferenceObjectByHandle(%.8X, %.8X, %.8X)\", handle, object_type_ptr,\n out_object_ptr);\n\n X_STATUS result = X_STATUS_SUCCESS;\n\n auto object = kernel_state->object_table()->LookupObject(handle);\n if (object) {\n \/\/ TODO(benvanik): verify type with object_type_ptr\n\n \/\/ TODO(benvanik): get native value, if supported.\n uint32_t native_ptr;\n switch (object_type_ptr) {\n case 0x00000000: { \/\/ whatever?\n switch (object->type()) {\n \/\/ TODO(benvanik): need to track native_ptr in XObject, allocate as\n \/\/ needed?\n \/*case XObject::kTypeEvent: {\n XEvent* ev = (XEvent*)object;\n } break;*\/\n case XObject::kTypeThread: {\n auto thread = object.get();\n native_ptr = thread->guest_object();\n } break;\n default: {\n assert_unhandled_case(object->type());\n native_ptr = 0xDEADF00D;\n } break;\n }\n } break;\n case 0xD017BEEF: { \/\/ ExSemaphoreObjectType\n assert(object->type() == XObject::kTypeSemaphore);\n auto sem = object.get();\n\n native_ptr = sem->guest_object();\n } break;\n case 0xD01BBEEF: { \/\/ ExThreadObjectType\n assert(object->type() == XObject::kTypeThread);\n auto thread = object.get();\n\n native_ptr = thread->guest_object();\n } break;\n default: {\n assert_unhandled_case(object_type_ptr);\n native_ptr = 0xDEADF00D;\n } break;\n }\n\n \/\/ Caller takes the reference.\n \/\/ It's released in ObDereferenceObject.\n object->Retain();\n if (out_object_ptr) {\n SHIM_SET_MEM_32(out_object_ptr, native_ptr);\n }\n } else {\n result = X_STATUS_INVALID_HANDLE;\n }\n\n SHIM_SET_RETURN_32(result);\n}\n\nSHIM_CALL ObDereferenceObject_shim(PPCContext* ppc_context,\n KernelState* kernel_state) {\n uint32_t native_ptr = SHIM_GET_ARG_32(0);\n\n XELOGD(\"ObDereferenceObject(%.8X)\", native_ptr);\n\n \/\/ Check if a dummy value from ObReferenceObjectByHandle.\n if (native_ptr == 0xDEADF00D) {\n SHIM_SET_RETURN_32(0);\n return;\n }\n\n void* object_ptr = SHIM_MEM_ADDR(native_ptr);\n auto object = XObject::GetNativeObject(kernel_state, object_ptr);\n if (object) {\n object->Release();\n }\n\n SHIM_SET_RETURN_32(0);\n}\n\ndword_result_t ObLookupThreadByThreadId(dword_t thread_id, lpdword_t out_object_ptr) {\n auto thread = kernel_state()->GetThreadByID(thread_id);\n if (!thread) {\n return X_STATUS_NOT_FOUND;\n }\n\n \/\/ Retain the object. Will be released in ObDereferenceObject.\n thread->Retain();\n *out_object_ptr = thread->guest_object();\n auto hdr = kernel_memory()->TranslateVirtual(thread->guest_object());\n assert_true(hdr->type == 6);\n\n return X_STATUS_SUCCESS;\n}\nDECLARE_XBOXKRNL_EXPORT(ObLookupThreadByThreadId, ExportTag::kStub);\n\ndword_result_t ObOpenObjectByPointer(lpvoid_t object_ptr, lpdword_t out_handle_ptr) {\n auto object = XObject::GetNativeObject(kernel_state(), object_ptr);\n if (!object) {\n return X_STATUS_UNSUCCESSFUL;\n }\n\n \/\/ Retain the handle. Will be released in NtClose.\n object->RetainHandle();\n *out_handle_ptr = object->handle();\n return X_STATUS_SUCCESS;\n}\nDECLARE_XBOXKRNL_EXPORT(ObOpenObjectByPointer, ExportTag::kStub);\n\ndword_result_t NtDuplicateObject(dword_t handle, lpdword_t new_handle_ptr,\n dword_t options) {\n \/\/ NOTE: new_handle_ptr can be zero to just close a handle.\n \/\/ NOTE: this function seems to be used to get the current thread handle\n \/\/ (passed handle=-2).\n \/\/ This function actually just creates a new handle to the same object.\n \/\/ Most games use it to get real handles to the current thread or whatever.\n\n X_HANDLE new_handle = X_INVALID_HANDLE_VALUE;\n X_STATUS result =\n kernel_state()->object_table()->DuplicateHandle(handle, &new_handle);\n\n if (new_handle_ptr) {\n *new_handle_ptr = new_handle;\n }\n\n if (options == 1 \/* DUPLICATE_CLOSE_SOURCE *\/) {\n \/\/ Always close the source object.\n kernel_state()->object_table()->RemoveHandle(handle);\n }\n\n return result;\n}\nDECLARE_XBOXKRNL_EXPORT(NtDuplicateObject, ExportTag::kImplemented);\n\ndword_result_t NtClose(dword_t handle) {\n \/\/ FIXME: This needs to be removed once handle count reaches 0!\n return kernel_state()->object_table()->RemoveHandle(handle);\n}\nDECLARE_XBOXKRNL_EXPORT(NtClose, ExportTag::kImplemented);\n\n} \/\/ namespace kernel\n} \/\/ namespace xe\n\nvoid xe::kernel::xboxkrnl::RegisterObExports(\n xe::cpu::ExportResolver* export_resolver, KernelState* kernel_state) {\n SHIM_SET_MAPPING(\"xboxkrnl.exe\", ObOpenObjectByName, state);\n SHIM_SET_MAPPING(\"xboxkrnl.exe\", ObReferenceObjectByHandle, state);\n SHIM_SET_MAPPING(\"xboxkrnl.exe\", ObDereferenceObject, state);\n}\n<|endoftext|>"} {"text":"#include \n#include \"submodular-flow.hpp\"\n#include \n#include \n#include \n\nSubmodularFlow::SubmodularFlow()\n : m_constant_term(0),\n m_num_nodes(0),\n m_c_si(),\n m_c_it(),\n m_phi_si(),\n m_phi_it(),\n m_labels(),\n m_num_cliques(0),\n m_cliques(),\n m_neighbors()\n{ }\n\nSubmodularFlow::NodeId SubmodularFlow::AddNode(int n) {\n ASSERT(n >= 1);\n NodeId first_node = m_num_nodes;\n for (int i = 0; i < n; ++i) {\n m_c_si.push_back(0);\n m_c_it.push_back(0);\n m_phi_si.push_back(0);\n m_phi_it.push_back(0);\n m_labels.push_back(-1);\n m_neighbors.push_back(NeighborList());\n m_num_nodes++;\n }\n return first_node;\n}\n\nint SubmodularFlow::GetLabel(NodeId n) const {\n return m_labels[n];\n}\n\nvoid SubmodularFlow::AddUnaryTerm(NodeId n, REAL E0, REAL E1) {\n \/\/ Reparametize so that E0, E1 >= 0\n if (E0 < 0) {\n AddConstantTerm(E0);\n E0 = 0;\n E1 -= E0;\n }\n if (E1 < 0) {\n AddConstantTerm(E1);\n E1 = 0;\n E0 -= E1;\n }\n m_c_si[n] += E0;\n m_c_it[n] += E1;\n}\n\nvoid SubmodularFlow::AddUnaryTerm(NodeId n, REAL coeff) {\n AddUnaryTerm(n, 0, coeff);\n}\n\nvoid SubmodularFlow::AddClique(const CliquePtr& cp) {\n m_cliques.push_back(cp);\n for (NodeId i : cp->Nodes()) {\n ASSERT(0 <= i && i < m_num_nodes);\n m_neighbors[i].push_back(m_num_cliques);\n }\n m_num_cliques++;\n cp->NormalizeEnergy(*this);\n}\n\nvoid SubmodularFlow::AddClique(const std::vector& nodes, const std::vector& energyTable) {\n CliquePtr cp(new EnergyTableClique(nodes, energyTable));\n AddClique(cp);\n}\n\n\/\/\/\/\/\/\/\/ Push Relabel methods \/\/\/\/\/\/\/\/\/\/\/\n\nvoid SubmodularFlow::add_to_active_list(NodeId u, Layer& layer) {\n \/\/ BOOST_USING_STD_MIN();\n \/\/ BOOST_USING_STD_MAX();\n layer.active_vertices.push_front(u);\n max_active = std::max BOOST_PREVENT_MACRO_SUBSTITUTION(dis[u], max_active);\n min_active = std::min BOOST_PREVENT_MACRO_SUBSTITUTION(dis[u], min_active);\n layer_list_ptr[u] = layer.active_vertices.begin();\n}\n\nvoid SubmodularFlow::remove_from_active_list(NodeId u) {\n layers[dis[u]].active_vertices.erase(layer_list_ptr[u]);\n}\n\nvoid SubmodularFlow::PushRelabelInit()\n{\n \/\/ super source and sink\n s = m_num_nodes; t = m_num_nodes + 1;\n max_active = 0; min_active = m_num_nodes + 2; \/\/ n\n\n dis.clear(); excess.clear(); current_arc_index.clear();\n m_arc_list.clear(); layers.clear();\n\n \/\/ init data structures\n for (int i = 0; i < m_num_nodes + 2; ++i) {\n dis.push_back(0);\n excess.push_back(0);\n current_arc_index.push_back(0);\n std::vector arc_list;\n m_arc_list.push_back(arc_list);\n Layer layer;\n layers.push_back(layer);\n }\n dis[s] = m_num_nodes + 2; \/\/ n = m_num_nodes + 2\n\n for (int i = 0; i < 2 * (m_num_nodes + 2); ++i) {\n Layer layer;\n layers.push_back(layer);\n }\n\n \/\/ saturate arcs out of s.\n for (NodeId i = 0; i < m_num_nodes; ++i) {\n m_phi_si[i] = m_c_si[i];\n if (m_c_si[i] > 0) {\n excess[s] -= m_c_si[i];\n excess[i] += m_c_si[i];\n\t add_to_active_list(i, layers[0]);\n }\n }\n\n \/\/ initialize arc lists\n Arc arc;\n for (NodeId i = 0; i < m_num_nodes; ++i) {\n \/\/ arcs from source\n arc.i = s;\n arc.j = i;\n arc.c = -1;\n m_arc_list[arc.i].push_back(arc);\n\n \/\/ arcs to source\n arc.i = i;\n arc.j = s;\n m_arc_list[arc.i].push_back(arc);\n\n \/\/ arcs to sink\n arc.j = t;\n m_arc_list[arc.i].push_back(arc);\n\n \/\/ arcs from sink\n arc.i = t;\n arc.j = i;\n m_arc_list[arc.i].push_back(arc);\n }\n\n \/\/ Arcs between nodes of clique\n for (int cid = 0; cid < m_num_cliques; ++cid) {\n CliquePtr cp = m_cliques[cid];\n for (NodeId i : cp->Nodes()) {\n for (NodeId j : cp->Nodes()) {\n if (i == j) continue;\n arc.i = i;\n arc.j = j;\n arc.c = cid;\n m_arc_list[i].push_back(arc);\n }\n }\n }\n}\n\nvoid SubmodularFlow::PushRelabelStep()\n{\n Layer& layer = layers[max_active];\n list_iterator u_iter = layer.active_vertices.begin();\n\n if (u_iter == layer.active_vertices.end())\n --max_active;\n else {\n NodeId i = *u_iter;\n remove_from_active_list(i);\n boost::optional arc = FindPushableEdge(i);\n if (arc)\n Push(*arc);\n else\n Relabel(i);\n }\n}\n\nbool SubmodularFlow::PushRelabelNotDone()\n{\n return max_active >= min_active;\n}\n\nvoid SubmodularFlow::PushRelabel()\n{\n PushRelabelInit();\n\n \/\/ find active i w\/ largest distance\n while (PushRelabelNotDone()) {\n PushRelabelStep();\n }\n}\n\nREAL SubmodularFlow::ResCap(Arc arc) {\n if (arc.i == s) {\n return m_c_si[arc.j] - m_phi_it[arc.j];\n } else if (arc.j == s) {\n return m_phi_si[arc.i];\n } else if (arc.i == t) {\n return m_phi_it[arc.j];\n } else if (arc.j == t) {\n return m_c_it[arc.i] - m_phi_it[arc.i];\n } else {\n return m_cliques[arc.c]->ExchangeCapacity(arc.i, arc.j);\n }\n}\n\nboost::optional SubmodularFlow::FindPushableEdge(NodeId i) {\n \/\/ Use current arc?\n for (Arc arc : m_arc_list[i]) {\n if (dis[i] == dis[arc.j] + 1 && ResCap(arc) > 0) {\n\t return boost::optional(arc);\n }\n }\n return boost::optional();\n}\n\nvoid SubmodularFlow::Push(Arc arc) {\n REAL delta; \/\/ amount to push\n\n \/\/ Note, we never have arc.i == s or t\n if (arc.j == s) { \/\/ reverse arc\n delta = std::min(excess[arc.i], m_phi_si[arc.i]);\n m_phi_si[arc.i] -= delta;\n } else if (arc.j == t) {\n delta = std::min(excess[arc.i], m_c_it[arc.i] - m_phi_it[arc.i]);\n m_phi_it[arc.i] += delta;\n } else { \/\/ Clique arc\n std::cout << \"Pushing on clique arc\" << std::endl;\n delta = std::min(excess[arc.i], m_cliques[arc.c]->ExchangeCapacity(arc.i, arc.j));\n std::vector& alpha_ci = m_cliques[arc.c]->AlphaCi();\n alpha_ci[arc.i] += delta;\n alpha_ci[arc.j] -= delta;\n }\n \/\/ Update (residual capacities) and excesses\n excess[arc.i] -= delta;\n excess[arc.j] += delta;\n if (excess[arc.j] > 0 && arc.j != s && arc.j != t) {\n remove_from_active_list(arc.j);\n add_to_active_list(arc.j, layers[dis[arc.j]]);\n }\n if (excess[arc.i] > 0) {\n add_to_active_list(arc.i, layers[dis[arc.i]]);\n }\n}\n\nvoid SubmodularFlow::Relabel(NodeId i) {\n dis[i] = std::numeric_limits::max();\n for(Arc arc : m_arc_list[i]) {\n if (ResCap(arc) > 0) {\n dis[i] = std::min (dis[i], dis[arc.j] + 1);\n }\n }\n \/\/ if (dis[i] < dis[s])\n add_to_active_list(i, layers[dis[i]]);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ end of push relabel \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid SubmodularFlow::ComputeMinCut() {\n for (NodeId i = 0; i < m_num_nodes; ++i) {\n dis[i] = std::numeric_limits::max();\n m_labels[i] = 1;\n }\n dis[t] = 0;\n \/\/ curr is the current level of nodes to be visited;\n \/\/ next is the next layer to visit.\n std::queue curr, next;\n next.push(t);\n\n int level = 1;\n while (!next.empty()) {\n \/\/ Next becomes curr; empty next\n std::swap(curr, next);\n std::queue empty;\n std::swap(next, empty);\n\n while (!curr.empty()) {\n NodeId u = curr.front();\n curr.pop();\n for (Arc arc : m_arc_list[u]) {\n arc.i = arc.j;\n arc.j = u;\n if (ResCap(arc) > 0 && arc.i != s && arc.i != t\n && dis[arc.i] == std::numeric_limits::max()) {\n m_labels[arc.i] = 0;\n next.push(arc.i);\n dis[arc.i] = level;\n }\n }\n }\n ++level;\n }\n for (int label : m_labels)\n std::cout << label << std::endl;\n}\n\nREAL SubmodularFlow::ComputeEnergy() const {\n return ComputeEnergy(m_labels);\n}\n\nREAL SubmodularFlow::ComputeEnergy(const std::vector& labels) const {\n REAL total = m_constant_term;\n for (NodeId i = 0; i < m_num_nodes; ++i) {\n if (labels[i] == 1) total += m_c_it[i];\n else total += m_c_si[i];\n }\n for (const CliquePtr& cp : m_cliques) {\n total += cp->ComputeEnergy(labels);\n }\n return total;\n}\n\nvoid EnergyTableClique::NormalizeEnergy(SubmodularFlow& sf) {\n const size_t n = this->m_nodes.size();\n const Assignment num_assignments = 1 << n;\n const REAL constant_term = m_energy[num_assignments - 1];\n std::vector marginals;\n Assignment assgn = num_assignments - 1; \/\/ The all 1 assignment\n for (size_t i = 0; i < n; ++i) {\n Assignment next_assgn = assgn ^ (1 << i);\n marginals.push_back(m_energy[assgn] - m_energy[next_assgn]);\n assgn = next_assgn;\n }\n\n for (Assignment a = 0; a < num_assignments; ++a) {\n m_energy[a] -= constant_term;\n for (size_t i = 0; i < n; ++i) {\n if (!(a & (1 << i))) m_energy[a] += marginals[i];\n }\n }\n\n sf.AddConstantTerm(constant_term);\n for (size_t i = 0; i < n; ++i) {\n sf.AddUnaryTerm(this->m_nodes[i], -marginals[i], 0);\n }\n}\n\nREAL EnergyTableClique::ComputeEnergy(const std::vector& labels) const {\n Assignment assgn = 0;\n for (size_t i = 0; i < this->m_nodes.size(); ++i) {\n NodeId n = this->m_nodes[i];\n if (labels[n] == 1) {\n assgn |= 1 << i;\n }\n }\n return m_energy[assgn];\n}\n\nREAL EnergyTableClique::ExchangeCapacity(NodeId u, NodeId v) const {\n \/\/ This is not the most efficient way to do things, but it works\n const size_t u_idx = std::find(this->m_nodes.begin(), this->m_nodes.end(), u) - this->m_nodes.begin();\n const size_t v_idx = std::find(this->m_nodes.begin(), this->m_nodes.end(), v) - this->m_nodes.begin();\n\n REAL min_energy = std::numeric_limits::max();\n Assignment num_assgns = 1 << this->m_nodes.size();\n for (Assignment assgn = 0; assgn < num_assgns; ++assgn) {\n REAL alpha_C = 0;\n for (size_t i = 0; i < this->m_alpha_Ci.size(); ++i) {\n if (assgn & (1 << i)) alpha_C += this->m_alpha_Ci[i];\n }\n if (assgn & (1 << u_idx) && !(assgn & (1 << v_idx))) {\n \/\/ then assgn is a set separating u from v\n REAL energy = m_energy[assgn] - alpha_C;\n if (energy < min_energy) min_energy = energy;\n }\n }\n return min_energy;\n}\nChanged the remove behavior to something inefficient but something I understand to remove segfault.#include \n#include \"submodular-flow.hpp\"\n#include \n#include \n#include \n\nSubmodularFlow::SubmodularFlow()\n : m_constant_term(0),\n m_num_nodes(0),\n m_c_si(),\n m_c_it(),\n m_phi_si(),\n m_phi_it(),\n m_labels(),\n m_num_cliques(0),\n m_cliques(),\n m_neighbors()\n{ }\n\nSubmodularFlow::NodeId SubmodularFlow::AddNode(int n) {\n ASSERT(n >= 1);\n NodeId first_node = m_num_nodes;\n for (int i = 0; i < n; ++i) {\n m_c_si.push_back(0);\n m_c_it.push_back(0);\n m_phi_si.push_back(0);\n m_phi_it.push_back(0);\n m_labels.push_back(-1);\n m_neighbors.push_back(NeighborList());\n m_num_nodes++;\n }\n return first_node;\n}\n\nint SubmodularFlow::GetLabel(NodeId n) const {\n return m_labels[n];\n}\n\nvoid SubmodularFlow::AddUnaryTerm(NodeId n, REAL E0, REAL E1) {\n \/\/ Reparametize so that E0, E1 >= 0\n if (E0 < 0) {\n AddConstantTerm(E0);\n E0 = 0;\n E1 -= E0;\n }\n if (E1 < 0) {\n AddConstantTerm(E1);\n E1 = 0;\n E0 -= E1;\n }\n m_c_si[n] += E0;\n m_c_it[n] += E1;\n}\n\nvoid SubmodularFlow::AddUnaryTerm(NodeId n, REAL coeff) {\n AddUnaryTerm(n, 0, coeff);\n}\n\nvoid SubmodularFlow::AddClique(const CliquePtr& cp) {\n m_cliques.push_back(cp);\n for (NodeId i : cp->Nodes()) {\n ASSERT(0 <= i && i < m_num_nodes);\n m_neighbors[i].push_back(m_num_cliques);\n }\n m_num_cliques++;\n cp->NormalizeEnergy(*this);\n}\n\nvoid SubmodularFlow::AddClique(const std::vector& nodes, const std::vector& energyTable) {\n CliquePtr cp(new EnergyTableClique(nodes, energyTable));\n AddClique(cp);\n}\n\n\/\/\/\/\/\/\/\/ Push Relabel methods \/\/\/\/\/\/\/\/\/\/\/\n\nvoid SubmodularFlow::add_to_active_list(NodeId u, Layer& layer) {\n layer.active_vertices.push_front(u);\n max_active = std::max BOOST_PREVENT_MACRO_SUBSTITUTION(dis[u], max_active);\n min_active = std::min BOOST_PREVENT_MACRO_SUBSTITUTION(dis[u], min_active);\n layer_list_ptr[u] = layer.active_vertices.begin();\n}\n\n\/\/ Inefficient but doing the remove manually since\n\/\/ I don't have a perfect understanding\/translation of the boost code.\nvoid SubmodularFlow::remove_from_active_list(NodeId u) {\n std::list temp;\n for (NodeId i : layers[dis[u]].active_vertices) {\n if (u != i) temp.push_back(i);\n }\n std::swap(layers[dis[u]].active_vertices, temp);\n}\n\nvoid SubmodularFlow::PushRelabelInit()\n{\n \/\/ super source and sink\n s = m_num_nodes; t = m_num_nodes + 1;\n max_active = 0; min_active = m_num_nodes + 2; \/\/ n\n\n dis.clear(); excess.clear(); current_arc_index.clear();\n m_arc_list.clear(); layers.clear();\n\n \/\/ init data structures\n for (int i = 0; i < m_num_nodes + 2; ++i) {\n dis.push_back(0);\n excess.push_back(0);\n current_arc_index.push_back(0);\n std::vector arc_list;\n m_arc_list.push_back(arc_list);\n Layer layer;\n layers.push_back(layer);\n }\n dis[s] = m_num_nodes + 2; \/\/ n = m_num_nodes + 2\n\n \/\/ Adding extra layers\n for (int i = 0; i < 2 * (m_num_nodes + 2); ++i) {\n Layer layer;\n layers.push_back(layer);\n }\n\n \/\/ saturate arcs out of s.\n for (NodeId i = 0; i < m_num_nodes; ++i) {\n m_phi_si[i] = m_c_si[i];\n if (m_c_si[i] > 0) {\n excess[s] -= m_c_si[i];\n excess[i] += m_c_si[i];\n\t add_to_active_list(i, layers[0]);\n }\n }\n\n \/\/ initialize arc lists\n Arc arc;\n for (NodeId i = 0; i < m_num_nodes; ++i) {\n \/\/ arcs from source\n arc.i = s;\n arc.j = i;\n arc.c = -1;\n m_arc_list[arc.i].push_back(arc);\n\n \/\/ arcs to source\n arc.i = i;\n arc.j = s;\n m_arc_list[arc.i].push_back(arc);\n\n \/\/ arcs to sink\n arc.j = t;\n m_arc_list[arc.i].push_back(arc);\n\n \/\/ arcs from sink\n arc.i = t;\n arc.j = i;\n m_arc_list[arc.i].push_back(arc);\n }\n\n \/\/ Arcs between nodes of clique\n for (int cid = 0; cid < m_num_cliques; ++cid) {\n CliquePtr cp = m_cliques[cid];\n for (NodeId i : cp->Nodes()) {\n for (NodeId j : cp->Nodes()) {\n if (i == j) continue;\n arc.i = i;\n arc.j = j;\n arc.c = cid;\n m_arc_list[i].push_back(arc);\n }\n }\n }\n}\n\nvoid SubmodularFlow::PushRelabelStep()\n{\n Layer& layer = layers[max_active];\n list_iterator u_iter = layer.active_vertices.begin();\n\n if (u_iter == layer.active_vertices.end())\n --max_active;\n else {\n NodeId i = *u_iter;\n remove_from_active_list(i);\n boost::optional arc = FindPushableEdge(i);\n if (arc)\n Push(*arc);\n else\n Relabel(i);\n }\n}\n\nbool SubmodularFlow::PushRelabelNotDone()\n{\n return max_active >= min_active;\n}\n\nvoid SubmodularFlow::PushRelabel()\n{\n PushRelabelInit();\n\n \/\/ find active i w\/ largest distance\n while (PushRelabelNotDone()) {\n PushRelabelStep();\n }\n}\n\nREAL SubmodularFlow::ResCap(Arc arc) {\n if (arc.i == s) {\n return m_c_si[arc.j] - m_phi_it[arc.j];\n } else if (arc.j == s) {\n return m_phi_si[arc.i];\n } else if (arc.i == t) {\n return m_phi_it[arc.j];\n } else if (arc.j == t) {\n return m_c_it[arc.i] - m_phi_it[arc.i];\n } else {\n return m_cliques[arc.c]->ExchangeCapacity(arc.i, arc.j);\n }\n}\n\nboost::optional SubmodularFlow::FindPushableEdge(NodeId i) {\n \/\/ Use current arc?\n for (Arc arc : m_arc_list[i]) {\n if (dis[i] == dis[arc.j] + 1 && ResCap(arc) > 0) {\n\t return boost::optional(arc);\n }\n }\n return boost::optional();\n}\n\nvoid SubmodularFlow::Push(Arc arc) {\n REAL delta; \/\/ amount to push\n\n \/\/ Note, we never have arc.i == s or t\n if (arc.j == s) { \/\/ reverse arc\n delta = std::min(excess[arc.i], m_phi_si[arc.i]);\n m_phi_si[arc.i] -= delta;\n } else if (arc.j == t) {\n delta = std::min(excess[arc.i], m_c_it[arc.i] - m_phi_it[arc.i]);\n m_phi_it[arc.i] += delta;\n } else { \/\/ Clique arc\n std::cout << \"Pushing on clique arc\" << std::endl;\n delta = std::min(excess[arc.i], m_cliques[arc.c]->ExchangeCapacity(arc.i, arc.j));\n std::vector& alpha_ci = m_cliques[arc.c]->AlphaCi();\n alpha_ci[arc.i] += delta;\n alpha_ci[arc.j] -= delta;\n }\n \/\/ Update (residual capacities) and excesses\n excess[arc.i] -= delta;\n excess[arc.j] += delta;\n if (excess[arc.j] > 0 && arc.j != s && arc.j != t) {\n remove_from_active_list(arc.j);\n add_to_active_list(arc.j, layers[dis[arc.j]]);\n }\n if (excess[arc.i] > 0) {\n add_to_active_list(arc.i, layers[dis[arc.i]]);\n }\n}\n\nvoid SubmodularFlow::Relabel(NodeId i) {\n dis[i] = std::numeric_limits::max();\n for(Arc arc : m_arc_list[i]) {\n if (ResCap(arc) > 0) {\n dis[i] = std::min (dis[i], dis[arc.j] + 1);\n }\n }\n \/\/ if (dis[i] < dis[s])\n \/\/ Adding all active vertices back for now.\n add_to_active_list(i, layers[dis[i]]);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ end of push relabel \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid SubmodularFlow::ComputeMinCut() {\n for (NodeId i = 0; i < m_num_nodes; ++i) {\n dis[i] = std::numeric_limits::max();\n m_labels[i] = 1;\n }\n dis[t] = 0;\n \/\/ curr is the current level of nodes to be visited;\n \/\/ next is the next layer to visit.\n std::queue curr, next;\n next.push(t);\n\n int level = 1;\n while (!next.empty()) {\n \/\/ Next becomes curr; empty next\n std::swap(curr, next);\n std::queue empty;\n std::swap(next, empty);\n\n while (!curr.empty()) {\n NodeId u = curr.front();\n curr.pop();\n for (Arc arc : m_arc_list[u]) {\n arc.i = arc.j;\n arc.j = u;\n if (ResCap(arc) > 0 && arc.i != s && arc.i != t\n && dis[arc.i] == std::numeric_limits::max()) {\n m_labels[arc.i] = 0;\n next.push(arc.i);\n dis[arc.i] = level;\n }\n }\n }\n ++level;\n }\n for (int label : m_labels)\n std::cout << label << std::endl;\n}\n\nREAL SubmodularFlow::ComputeEnergy() const {\n return ComputeEnergy(m_labels);\n}\n\nREAL SubmodularFlow::ComputeEnergy(const std::vector& labels) const {\n REAL total = m_constant_term;\n for (NodeId i = 0; i < m_num_nodes; ++i) {\n if (labels[i] == 1) total += m_c_it[i];\n else total += m_c_si[i];\n }\n for (const CliquePtr& cp : m_cliques) {\n total += cp->ComputeEnergy(labels);\n }\n return total;\n}\n\nvoid EnergyTableClique::NormalizeEnergy(SubmodularFlow& sf) {\n const size_t n = this->m_nodes.size();\n const Assignment num_assignments = 1 << n;\n const REAL constant_term = m_energy[num_assignments - 1];\n std::vector marginals;\n Assignment assgn = num_assignments - 1; \/\/ The all 1 assignment\n for (size_t i = 0; i < n; ++i) {\n Assignment next_assgn = assgn ^ (1 << i);\n marginals.push_back(m_energy[assgn] - m_energy[next_assgn]);\n assgn = next_assgn;\n }\n\n for (Assignment a = 0; a < num_assignments; ++a) {\n m_energy[a] -= constant_term;\n for (size_t i = 0; i < n; ++i) {\n if (!(a & (1 << i))) m_energy[a] += marginals[i];\n }\n }\n\n sf.AddConstantTerm(constant_term);\n for (size_t i = 0; i < n; ++i) {\n sf.AddUnaryTerm(this->m_nodes[i], -marginals[i], 0);\n }\n}\n\nREAL EnergyTableClique::ComputeEnergy(const std::vector& labels) const {\n Assignment assgn = 0;\n for (size_t i = 0; i < this->m_nodes.size(); ++i) {\n NodeId n = this->m_nodes[i];\n if (labels[n] == 1) {\n assgn |= 1 << i;\n }\n }\n return m_energy[assgn];\n}\n\nREAL EnergyTableClique::ExchangeCapacity(NodeId u, NodeId v) const {\n \/\/ This is not the most efficient way to do things, but it works\n const size_t u_idx = std::find(this->m_nodes.begin(), this->m_nodes.end(), u) - this->m_nodes.begin();\n const size_t v_idx = std::find(this->m_nodes.begin(), this->m_nodes.end(), v) - this->m_nodes.begin();\n\n REAL min_energy = std::numeric_limits::max();\n Assignment num_assgns = 1 << this->m_nodes.size();\n for (Assignment assgn = 0; assgn < num_assgns; ++assgn) {\n REAL alpha_C = 0;\n for (size_t i = 0; i < this->m_alpha_Ci.size(); ++i) {\n if (assgn & (1 << i)) alpha_C += this->m_alpha_Ci[i];\n }\n if (assgn & (1 << u_idx) && !(assgn & (1 << v_idx))) {\n \/\/ then assgn is a set separating u from v\n REAL energy = m_energy[assgn] - alpha_C;\n if (energy < min_energy) min_energy = energy;\n }\n }\n return min_energy;\n}\n<|endoftext|>"} {"text":"Expand route tests to unroute existing routes.<|endoftext|>"} {"text":"#include \"SyntaxTree.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"parser.tab.hh\"\n\n#include \"template.common.h\"\n#include \"template.cs.h\"\n\nusing namespace std;\nusing namespace Rakjin::Krystal;\n\n\/\/ class Node\n\/\/ {\n\/\/ public:\n Node::Node(Rakjin::Context* _context)\n {\n context = _context;\n }\n\n Node::~Node()\n {\n }\n\n int Node::getType() { return 0; } \/\/TODO: remove getType() if unnecessary\n size_t Node::getHash(vector* referencingStack) { return 0; }\n string* Node::getParsed(int as) { return 0; }\n\n\/\/ };\n\n\/\/ class NodeKst : public Node\n\/\/ {\n \/\/ list* commands;\n \/\/ string* fileName;\n \/\/ public:\n NodeKst::NodeKst(Rakjin::Context* _context, list* _commands, string* _fileName) : Node(_context)\n {\n commands = _commands;\n fileName = _fileName;\n }\n\n int NodeKst::getType()\n {\n return CsNodeType::kst;\n }\n\n size_t NodeKst::getHash(vector* referencingStack)\n {\n return 0;\n }\n\n string* NodeKst::getParsed(int as)\n {\n stringstream parsed;\n\n parsed << boost::format(TCS_HEADER) % *fileName;\n parsed << TCS_USINGS;\n\n string namespaceByFileName = fileName->substr(0, fileName->find(\".\"));\n\n parsed << boost::format(TCS_NAMESPACE_BEGIN) % namespaceByFileName;\n\n list::iterator i = commands->begin();\n list::iterator end = commands->end();\n\n string* temp;\n\n for (; i != end; ++i)\n {\n temp = (*i)->getParsed(CsParseAs::Default);\n temp = indent(temp);\n parsed << *temp;\n parsed << \"\\n\";\n }\n\n parsed << TCS_NAMESPACE_END;\n\n parsed << \"\\n\\n\";\n\n return new string(parsed.str());\n }\n\/\/ };\n\n\/\/ class NodeInclude : public Node\n\/\/ {\n\/\/ string* value;\n\/\/ public:\n NodeInclude::NodeInclude(Rakjin::Context* _context, string* _value) : Node(_context)\n {\n value = _value;\n }\n\n int NodeInclude::getType()\n {\n return CsNodeType::include;\n }\n\n size_t NodeInclude::getHash(vector* referencingStack)\n {\n return 0;\n }\n\n string* NodeInclude::getParsed(int as)\n {\n stringstream parsed;\n\n parsed << \"#include \\\"\";\n parsed << *(value);\n parsed << \"\\\"\";\n\n return new string(parsed.str());\n }\n\/\/ };\n\n\/\/ class NodePacket : public Node\n\/\/ {\n\/\/ string* packetName;\n\/\/ list* packetMembers;\n\/\/ public:\n NodePacket::NodePacket(Rakjin::Context* _context, string* _packetName, list* _packetMembers) : Node(_context)\n {\n packetName = _packetName;\n packetMembers = _packetMembers;\n }\n\n int NodePacket::getType()\n {\n return CsNodeType::packet;\n }\n\n size_t NodePacket::getHash(vector* referencingStack)\n {\n if (referencingStack == NULL)\n {\n referencingStack = new vector();\n }\n else \/\/ check circular reference\n {\n vector::iterator end = referencingStack->end();\n for (vector::iterator i = referencingStack->begin(); i != end; i++)\n {\n if (*i == this)\n {\n throw(runtime_error(\"Circular reference between packets\"));\n }\n }\n }\n\n referencingStack->push_back(this);\n\n size_t packetHash = getHashCode(packetName);\n\n list::iterator i = packetMembers->begin();\n list::iterator end = packetMembers->end();\n for (; i != end; ++i)\n {\n combineHashCode(packetHash, (*i)->getHash(referencingStack));\n }\n\n referencingStack->pop_back();\n\n return packetHash;\n }\n\n string* NodePacket::getParsed(int as)\n {\n stringstream parsed;\n\n switch (as)\n {\n case CsParseAs::Default:\n {\n parsed << boost::format(TCS_PACKET_BEGIN) % *packetName;\n parsed << \"\\t packet hash: \" << getHash(NULL) << \"\\n\";\n list::iterator i = packetMembers->begin();\n list::iterator end = packetMembers->end();\n for (; i != end; ++i)\n {\n parsed << \"\\t\" << *((*i)->getParsed(CsParseAs::Default));\n }\n parsed << TCS_PACKET_END;\n }\n break;\n }\n\n return new string(parsed.str());\n }\n\/\/ };\n\n\/\/ class NodePacketMember : public Node\n\/\/ {\n\/\/ Node* memberType;\n\/\/ Node* memberName;\n\/\/ public:\n NodePacketMember::NodePacketMember(Rakjin::Context* _context, Node* _memberType, Node* _memberName) : Node(_context)\n {\n memberType = _memberType;\n memberName = _memberName;\n }\n\n int NodePacketMember::getType()\n {\n return CsNodeType::packetMember;\n }\n\n size_t NodePacketMember::getHash(vector* referencingStack)\n {\n assert(referencingStack != NULL);\n\n size_t packetMemberHash = memberType->getHash(referencingStack);\n combineHashCode(packetMemberHash, memberName->getHash(referencingStack));\n\n return packetMemberHash;\n }\n\n string* NodePacketMember::getParsed(int as)\n {\n stringstream parsed;\n\n switch (as)\n {\n case CsParseAs::Default:\n {\n parsed << boost::format(TCS_PACKET_MEMBER_AS_DEFAULT)\n % *(memberType->getParsed(CsParseAs::Default))\n % *(memberName->getParsed(CsParseAs::Default));\n }\n break;\n }\n\n return new string(parsed.str());\n }\n\/\/ };\n\n\/\/ class NodePacketMemberType : public Node\n\/\/ {\n\/\/ int typeType; \/\/ one of PRIMITIVE_DATA_TYPE, REFERENCE_DATA_TYPE, MAP, LIST\n\/\/ string* value; \/\/ \"int\", \"bool\", ..., \"MyPacket\", \"Skill\" or NULL when type is MAP or LIST\n\/\/ Node* generic1; \/\/ LIST\n\/\/ Node* generic2; \/\/ MAP \n\/\/ Node* generic3; \/\/ reserved\n\/\/ public:\n NodePacketMemberType::NodePacketMemberType(Rakjin::Context* _context, int _type, string* _value) : Node(_context)\n {\n typeType = _type;\n value = _value;\n generic1 = NULL;\n generic2 = NULL;\n generic3 = NULL;\n }\n\n NodePacketMemberType::NodePacketMemberType(Rakjin::Context* _context, int _type, Node* _generic1) : Node(_context)\n {\n typeType = _type;\n value = NULL;\n generic1 = _generic1;\n generic2 = NULL;\n generic3 = NULL;\n }\n\n NodePacketMemberType::NodePacketMemberType(Rakjin::Context* _context, int _type, Node* _generic1, Node* _generic2) : Node(_context)\n {\n typeType = _type;\n value = NULL;\n generic1 = _generic1;\n generic2 = _generic2;\n generic3 = NULL;\n }\n\n NodePacketMemberType::NodePacketMemberType(Rakjin::Context* _context, int _type, Node* _generic1, Node* _generic2, Node* _generic3) : Node(_context)\n {\n typeType = _type;\n value = NULL;\n generic1 = _generic1;\n generic2 = _generic2;\n generic3 = _generic3;\n }\n\n int NodePacketMemberType::getType()\n {\n return CsNodeType::packetMemberType;\n }\n\n size_t NodePacketMemberType::getHash(vector* referencingStack)\n {\n assert(referencingStack != NULL);\n\n size_t packetMemberTypeHash = 0;\n switch(typeType)\n {\n case Parser::token::PRIMITIVE_DATA_TYPE:\n packetMemberTypeHash = getHashCode(value);\n break;\n\n case Parser::token::REFERENCE_DATA_TYPE:\n \/\/ lookup Context::declarations table\n Node* typePacketNode = context->getDeclarationNode(value);\n if (typePacketNode == NULL)\n {\n throw(runtime_error(\"No such packet type.\"));\n }\n packetMemberTypeHash = typePacketNode->getHash(referencingStack);\n break; \n }\n\n return packetMemberTypeHash;\n }\n\n string* NodePacketMemberType::getParsed(int as)\n {\n stringstream parsed;\n\n switch (typeType) {\n\n case Parser::token::PRIMITIVE_DATA_TYPE:\n parsed << *value;\n break;\n\n case Parser::token::REFERENCE_DATA_TYPE:\n parsed << *value;\n break;\n\n case Parser::token::MAP:\n parsed << \"Dictionary\";\n parsed << \"<\" << *(generic1->getParsed(CsParseAs::Default)) << \", \" << *(generic2->getParsed(CsParseAs::Default)) << \">\";\n break;\n\n case Parser::token::LIST:\n parsed << \"List\";\n parsed << \"<\" << *(generic1->getParsed(CsParseAs::Default)) << \">\";\n break;\n\n default:\n throw(runtime_error(\"Unknown NodePacketMemberType type.\"));\n break;\n }\n\n return new string(parsed.str());\n }\n\/\/ };\n\n\/\/ class NodePacketMemberName : public Node\n\/\/ {\n\/\/ string* value;\n\/\/ public:\n NodePacketMemberName::NodePacketMemberName(Rakjin::Context* _context, string* _value) : Node(_context)\n {\n value = _value;\n }\n\n int NodePacketMemberName::getType()\n {\n return CsNodeType::packetMemberName;\n }\n\n size_t NodePacketMemberName::getHash(vector* referencingStack)\n {\n size_t packetMemberNameHash = getHashCode(value);\n return packetMemberNameHash;\n }\n\n string* NodePacketMemberName::getParsed(int as)\n {\n return value;\n }\n\/\/ };\n\nadd blocks to switch-case#include \"SyntaxTree.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"parser.tab.hh\"\n\n#include \"template.common.h\"\n#include \"template.cs.h\"\n\nusing namespace std;\nusing namespace Rakjin::Krystal;\n\n\/\/ class Node\n\/\/ {\n\/\/ public:\n Node::Node(Rakjin::Context* _context)\n {\n context = _context;\n }\n\n Node::~Node()\n {\n }\n\n int Node::getType() { return 0; } \/\/TODO: remove getType() if unnecessary\n size_t Node::getHash(vector* referencingStack) { return 0; }\n string* Node::getParsed(int as) { return 0; }\n\n\/\/ };\n\n\/\/ class NodeKst : public Node\n\/\/ {\n \/\/ list* commands;\n \/\/ string* fileName;\n \/\/ public:\n NodeKst::NodeKst(Rakjin::Context* _context, list* _commands, string* _fileName) : Node(_context)\n {\n commands = _commands;\n fileName = _fileName;\n }\n\n int NodeKst::getType()\n {\n return CsNodeType::kst;\n }\n\n size_t NodeKst::getHash(vector* referencingStack)\n {\n return 0;\n }\n\n string* NodeKst::getParsed(int as)\n {\n stringstream parsed;\n\n parsed << boost::format(TCS_HEADER) % *fileName;\n parsed << TCS_USINGS;\n\n string namespaceByFileName = fileName->substr(0, fileName->find(\".\"));\n\n parsed << boost::format(TCS_NAMESPACE_BEGIN) % namespaceByFileName;\n\n list::iterator i = commands->begin();\n list::iterator end = commands->end();\n\n string* temp;\n\n for (; i != end; ++i)\n {\n temp = (*i)->getParsed(CsParseAs::Default);\n temp = indent(temp);\n parsed << *temp;\n parsed << \"\\n\";\n }\n\n parsed << TCS_NAMESPACE_END;\n\n parsed << \"\\n\\n\";\n\n return new string(parsed.str());\n }\n\/\/ };\n\n\/\/ class NodeInclude : public Node\n\/\/ {\n\/\/ string* value;\n\/\/ public:\n NodeInclude::NodeInclude(Rakjin::Context* _context, string* _value) : Node(_context)\n {\n value = _value;\n }\n\n int NodeInclude::getType()\n {\n return CsNodeType::include;\n }\n\n size_t NodeInclude::getHash(vector* referencingStack)\n {\n return 0;\n }\n\n string* NodeInclude::getParsed(int as)\n {\n stringstream parsed;\n\n parsed << \"#include \\\"\";\n parsed << *(value);\n parsed << \"\\\"\";\n\n return new string(parsed.str());\n }\n\/\/ };\n\n\/\/ class NodePacket : public Node\n\/\/ {\n\/\/ string* packetName;\n\/\/ list* packetMembers;\n\/\/ public:\n NodePacket::NodePacket(Rakjin::Context* _context, string* _packetName, list* _packetMembers) : Node(_context)\n {\n packetName = _packetName;\n packetMembers = _packetMembers;\n }\n\n int NodePacket::getType()\n {\n return CsNodeType::packet;\n }\n\n size_t NodePacket::getHash(vector* referencingStack)\n {\n if (referencingStack == NULL)\n {\n referencingStack = new vector();\n }\n else \/\/ check circular reference\n {\n vector::iterator end = referencingStack->end();\n for (vector::iterator i = referencingStack->begin(); i != end; i++)\n {\n if (*i == this)\n {\n throw(runtime_error(\"Circular reference between packets\"));\n }\n }\n }\n\n referencingStack->push_back(this);\n\n size_t packetHash = getHashCode(packetName);\n\n list::iterator i = packetMembers->begin();\n list::iterator end = packetMembers->end();\n for (; i != end; ++i)\n {\n combineHashCode(packetHash, (*i)->getHash(referencingStack));\n }\n\n referencingStack->pop_back();\n\n return packetHash;\n }\n\n string* NodePacket::getParsed(int as)\n {\n stringstream parsed;\n\n switch (as)\n {\n case CsParseAs::Default:\n {\n parsed << boost::format(TCS_PACKET_BEGIN) % *packetName;\n parsed << \"\\t packet hash: \" << getHash(NULL) << \"\\n\";\n list::iterator i = packetMembers->begin();\n list::iterator end = packetMembers->end();\n for (; i != end; ++i)\n {\n parsed << \"\\t\" << *((*i)->getParsed(CsParseAs::Default));\n }\n parsed << TCS_PACKET_END;\n }\n break;\n }\n\n return new string(parsed.str());\n }\n\/\/ };\n\n\/\/ class NodePacketMember : public Node\n\/\/ {\n\/\/ Node* memberType;\n\/\/ Node* memberName;\n\/\/ public:\n NodePacketMember::NodePacketMember(Rakjin::Context* _context, Node* _memberType, Node* _memberName) : Node(_context)\n {\n memberType = _memberType;\n memberName = _memberName;\n }\n\n int NodePacketMember::getType()\n {\n return CsNodeType::packetMember;\n }\n\n size_t NodePacketMember::getHash(vector* referencingStack)\n {\n assert(referencingStack != NULL);\n\n size_t packetMemberHash = memberType->getHash(referencingStack);\n combineHashCode(packetMemberHash, memberName->getHash(referencingStack));\n\n return packetMemberHash;\n }\n\n string* NodePacketMember::getParsed(int as)\n {\n stringstream parsed;\n\n switch (as)\n {\n case CsParseAs::Default:\n {\n parsed << boost::format(TCS_PACKET_MEMBER_AS_DEFAULT)\n % *(memberType->getParsed(CsParseAs::Default))\n % *(memberName->getParsed(CsParseAs::Default));\n }\n break;\n }\n\n return new string(parsed.str());\n }\n\/\/ };\n\n\/\/ class NodePacketMemberType : public Node\n\/\/ {\n\/\/ int typeType; \/\/ one of PRIMITIVE_DATA_TYPE, REFERENCE_DATA_TYPE, MAP, LIST\n\/\/ string* value; \/\/ \"int\", \"bool\", ..., \"MyPacket\", \"Skill\" or NULL when type is MAP or LIST\n\/\/ Node* generic1; \/\/ LIST\n\/\/ Node* generic2; \/\/ MAP \n\/\/ Node* generic3; \/\/ reserved\n\/\/ public:\n NodePacketMemberType::NodePacketMemberType(Rakjin::Context* _context, int _type, string* _value) : Node(_context)\n {\n typeType = _type;\n value = _value;\n generic1 = NULL;\n generic2 = NULL;\n generic3 = NULL;\n }\n\n NodePacketMemberType::NodePacketMemberType(Rakjin::Context* _context, int _type, Node* _generic1) : Node(_context)\n {\n typeType = _type;\n value = NULL;\n generic1 = _generic1;\n generic2 = NULL;\n generic3 = NULL;\n }\n\n NodePacketMemberType::NodePacketMemberType(Rakjin::Context* _context, int _type, Node* _generic1, Node* _generic2) : Node(_context)\n {\n typeType = _type;\n value = NULL;\n generic1 = _generic1;\n generic2 = _generic2;\n generic3 = NULL;\n }\n\n NodePacketMemberType::NodePacketMemberType(Rakjin::Context* _context, int _type, Node* _generic1, Node* _generic2, Node* _generic3) : Node(_context)\n {\n typeType = _type;\n value = NULL;\n generic1 = _generic1;\n generic2 = _generic2;\n generic3 = _generic3;\n }\n\n int NodePacketMemberType::getType()\n {\n return CsNodeType::packetMemberType;\n }\n\n size_t NodePacketMemberType::getHash(vector* referencingStack)\n {\n assert(referencingStack != NULL);\n\n size_t packetMemberTypeHash = 0;\n switch(typeType)\n {\n case Parser::token::PRIMITIVE_DATA_TYPE:\n {\n packetMemberTypeHash = getHashCode(value);\n }\n break;\n\n case Parser::token::REFERENCE_DATA_TYPE:\n {\n \/\/ lookup Context::declarations table\n Node* typePacketNode = context->getDeclarationNode(value);\n if (typePacketNode == NULL)\n {\n throw(runtime_error(\"No such packet type.\"));\n }\n packetMemberTypeHash = typePacketNode->getHash(referencingStack);\n }\n break;\n }\n\n return packetMemberTypeHash;\n }\n\n string* NodePacketMemberType::getParsed(int as)\n {\n stringstream parsed;\n\n switch (typeType) {\n\n case Parser::token::PRIMITIVE_DATA_TYPE:\n parsed << *value;\n break;\n\n case Parser::token::REFERENCE_DATA_TYPE:\n parsed << *value;\n break;\n\n case Parser::token::MAP:\n parsed << \"Dictionary\";\n parsed << \"<\" << *(generic1->getParsed(CsParseAs::Default)) << \", \" << *(generic2->getParsed(CsParseAs::Default)) << \">\";\n break;\n\n case Parser::token::LIST:\n parsed << \"List\";\n parsed << \"<\" << *(generic1->getParsed(CsParseAs::Default)) << \">\";\n break;\n\n default:\n throw(runtime_error(\"Unknown NodePacketMemberType type.\"));\n break;\n }\n\n return new string(parsed.str());\n }\n\/\/ };\n\n\/\/ class NodePacketMemberName : public Node\n\/\/ {\n\/\/ string* value;\n\/\/ public:\n NodePacketMemberName::NodePacketMemberName(Rakjin::Context* _context, string* _value) : Node(_context)\n {\n value = _value;\n }\n\n int NodePacketMemberName::getType()\n {\n return CsNodeType::packetMemberName;\n }\n\n size_t NodePacketMemberName::getHash(vector* referencingStack)\n {\n size_t packetMemberNameHash = getHashCode(value);\n return packetMemberNameHash;\n }\n\n string* NodePacketMemberName::getParsed(int as)\n {\n return value;\n }\n\/\/ };\n\n<|endoftext|>"} {"text":"\/*********************************************************************\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2013, Unbounded Robotics Inc.\n * Copyright (c) 2012, Willow Garage, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of the Willow Garage nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *********************************************************************\/\n\n\/* Author: Michael Ferguson, Ioan Sucan, E. Gil Jones *\/\n\n#include \n#include \n\nusing namespace moveit::core;\nstatic const std::string LOGNAME(\"SimpleControllerManager\");\n\nnamespace moveit_simple_controller_manager\n{\nbool FollowJointTrajectoryControllerHandle::sendTrajectory(const moveit_msgs::RobotTrajectory& trajectory)\n{\n ROS_DEBUG_STREAM_NAMED(LOGNAME, \"new trajectory to \" << name_);\n\n if (!controller_action_client_)\n return false;\n\n if (!trajectory.multi_dof_joint_trajectory.points.empty())\n {\n ROS_WARN_NAMED(LOGNAME, \"%s cannot execute multi-dof trajectories.\", name_.c_str());\n }\n\n if (done_)\n ROS_DEBUG_STREAM_NAMED(LOGNAME, \"sending trajectory to \" << name_);\n else\n ROS_DEBUG_STREAM_NAMED(LOGNAME, \"sending continuation for the currently executed trajectory to \" << name_);\n\n control_msgs::FollowJointTrajectoryGoal goal = goal_template_;\n goal.trajectory = trajectory.joint_trajectory;\n controller_action_client_->sendGoal(\n goal, boost::bind(&FollowJointTrajectoryControllerHandle::controllerDoneCallback, this, _1, _2),\n boost::bind(&FollowJointTrajectoryControllerHandle::controllerActiveCallback, this),\n boost::bind(&FollowJointTrajectoryControllerHandle::controllerFeedbackCallback, this, _1));\n done_ = false;\n last_exec_ = moveit_controller_manager::ExecutionStatus::RUNNING;\n return true;\n}\n\nvoid FollowJointTrajectoryControllerHandle::configure(XmlRpc::XmlRpcValue& config)\n{\n if (config.hasMember(\"path_tolerance\"))\n configure(config[\"path_tolerance\"], \"path_tolerance\", goal_template_.path_tolerance);\n if (config.hasMember(\"goal_tolerance\"))\n configure(config[\"goal_tolerance\"], \"goal_tolerance\", goal_template_.goal_tolerance);\n if (config.hasMember(\"goal_time_tolerance\"))\n goal_template_.goal_time_tolerance = ros::Duration(parseDouble(config[\"goal_time_tolerance\"]));\n}\n\nnamespace\n{\nenum ToleranceVariables\n{\n POSITION,\n VELOCITY,\n ACCELERATION\n};\ntemplate \ndouble& variable(control_msgs::JointTolerance& msg);\n\ntemplate <>\ninline double& variable(control_msgs::JointTolerance& msg)\n{\n return msg.position;\n}\ntemplate <>\ninline double& variable(control_msgs::JointTolerance& msg)\n{\n return msg.velocity;\n}\ntemplate <>\ninline double& variable(control_msgs::JointTolerance& msg)\n{\n return msg.acceleration;\n}\n\nstatic std::map VAR_NAME = { { POSITION, \"position\" },\n { VELOCITY, \"velocity\" },\n { ACCELERATION, \"acceleration\" } };\nstatic std::map)> VAR_ACCESS = { { POSITION, &variable },\n { VELOCITY, &variable },\n { ACCELERATION,\n &variable } };\n\nconst char* errorCodeToMessage(int error_code)\n{\n switch (error_code)\n {\n case control_msgs::FollowJointTrajectoryResult::SUCCESSFUL:\n return \"SUCCESSFUL\";\n case control_msgs::FollowJointTrajectoryResult::INVALID_GOAL:\n return \"INVALID_GOAL\";\n case control_msgs::FollowJointTrajectoryResult::INVALID_JOINTS:\n return \"INVALID_JOINTS\";\n case control_msgs::FollowJointTrajectoryResult::OLD_HEADER_TIMESTAMP:\n return \"OLD_HEADER_TIMESTAMP\";\n case control_msgs::FollowJointTrajectoryResult::PATH_TOLERANCE_VIOLATED:\n return \"PATH_TOLERANCE_VIOLATED\";\n case control_msgs::FollowJointTrajectoryResult::GOAL_TOLERANCE_VIOLATED:\n return \"GOAL_TOLERANCE_VIOLATED\";\n default:\n return \"unknown error\";\n }\n}\n}\n\nvoid FollowJointTrajectoryControllerHandle::configure(XmlRpc::XmlRpcValue& config, const std::string& config_name,\n std::vector& tolerances)\n{\n if (isStruct(config)) \/\/ config should be either a struct of position, velocity, acceleration\n {\n for (ToleranceVariables var : { POSITION, VELOCITY, ACCELERATION })\n {\n if (!config.hasMember(VAR_NAME[var]))\n continue;\n XmlRpc::XmlRpcValue values = config[VAR_NAME[var]];\n if (isArray(values, joints_.size()))\n {\n size_t i = 0;\n for (const auto& joint_name : joints_)\n VAR_ACCESS[var](getTolerance(tolerances, joint_name)) = parseDouble(values[i++]);\n }\n else\n { \/\/ use common value for all joints\n double value = parseDouble(values);\n for (const auto& joint_name : joints_)\n VAR_ACCESS[var](getTolerance(tolerances, joint_name)) = value;\n }\n }\n }\n else if (isArray(config)) \/\/ or an array of JointTolerance msgs\n {\n for (size_t i = 0; i < config.size(); ++i)\n {\n control_msgs::JointTolerance& tol = getTolerance(tolerances, config[i][\"name\"]);\n for (ToleranceVariables var : { POSITION, VELOCITY, ACCELERATION })\n {\n if (!config[i].hasMember(VAR_NAME[var]))\n continue;\n VAR_ACCESS[var](tol) = parseDouble(config[i][VAR_NAME[var]]);\n }\n }\n }\n else\n ROS_WARN_STREAM_NAMED(LOGNAME, \"Invalid \" << config_name);\n}\n\ncontrol_msgs::JointTolerance& FollowJointTrajectoryControllerHandle::getTolerance(\n std::vector& tolerances, const std::string& name)\n{\n auto it =\n std::lower_bound(tolerances.begin(), tolerances.end(), name,\n [](const control_msgs::JointTolerance& lhs, const std::string& rhs) { return lhs.name < rhs; });\n if (it == tolerances.cend() || it->name != name)\n { \/\/ insert new entry if not yet available\n it = tolerances.insert(it, control_msgs::JointTolerance());\n it->name = name;\n }\n return *it;\n}\n\nvoid FollowJointTrajectoryControllerHandle::controllerDoneCallback(\n const actionlib::SimpleClientGoalState& state, const control_msgs::FollowJointTrajectoryResultConstPtr& result)\n{\n \/\/ Output custom error message for FollowJointTrajectoryResult if necessary\n if (!result)\n ROS_WARN_STREAM_NAMED(LOGNAME, \"Controller \" << name_ << \" done, no result returned\");\n else if (result->error_code == control_msgs::FollowJointTrajectoryResult::SUCCESSFUL)\n ROS_INFO_STREAM_NAMED(LOGNAME, \"Controller \" << name_ << \" successfully finished\");\n else\n ROS_WARN_STREAM_NAMED(LOGNAME, \"Controller \" << name_ << \"failed with error \"\n << errorCodeToMessage(result->error_code));\n finishControllerExecution(state);\n}\n\nvoid FollowJointTrajectoryControllerHandle::controllerActiveCallback()\n{\n ROS_DEBUG_STREAM_NAMED(LOGNAME, name_ << \" started execution\");\n}\n\nvoid FollowJointTrajectoryControllerHandle::controllerFeedbackCallback(\n const control_msgs::FollowJointTrajectoryFeedbackConstPtr& feedback)\n{\n}\n\n} \/\/ end namespace moveit_simple_controller_manager\nfixup! cleanup SimpleControllerManager\/*********************************************************************\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2013, Unbounded Robotics Inc.\n * Copyright (c) 2012, Willow Garage, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of the Willow Garage nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *********************************************************************\/\n\n\/* Author: Michael Ferguson, Ioan Sucan, E. Gil Jones *\/\n\n#include \n#include \n\nusing namespace moveit::core;\nstatic const std::string LOGNAME(\"SimpleControllerManager\");\n\nnamespace moveit_simple_controller_manager\n{\nbool FollowJointTrajectoryControllerHandle::sendTrajectory(const moveit_msgs::RobotTrajectory& trajectory)\n{\n ROS_DEBUG_STREAM_NAMED(LOGNAME, \"new trajectory to \" << name_);\n\n if (!controller_action_client_)\n return false;\n\n if (!trajectory.multi_dof_joint_trajectory.points.empty())\n {\n ROS_WARN_NAMED(LOGNAME, \"%s cannot execute multi-dof trajectories.\", name_.c_str());\n }\n\n if (done_)\n ROS_DEBUG_STREAM_NAMED(LOGNAME, \"sending trajectory to \" << name_);\n else\n ROS_DEBUG_STREAM_NAMED(LOGNAME, \"sending continuation for the currently executed trajectory to \" << name_);\n\n control_msgs::FollowJointTrajectoryGoal goal = goal_template_;\n goal.trajectory = trajectory.joint_trajectory;\n controller_action_client_->sendGoal(\n goal, boost::bind(&FollowJointTrajectoryControllerHandle::controllerDoneCallback, this, _1, _2),\n boost::bind(&FollowJointTrajectoryControllerHandle::controllerActiveCallback, this),\n boost::bind(&FollowJointTrajectoryControllerHandle::controllerFeedbackCallback, this, _1));\n done_ = false;\n last_exec_ = moveit_controller_manager::ExecutionStatus::RUNNING;\n return true;\n}\n\nvoid FollowJointTrajectoryControllerHandle::configure(XmlRpc::XmlRpcValue& config)\n{\n if (config.hasMember(\"path_tolerance\"))\n configure(config[\"path_tolerance\"], \"path_tolerance\", goal_template_.path_tolerance);\n if (config.hasMember(\"goal_tolerance\"))\n configure(config[\"goal_tolerance\"], \"goal_tolerance\", goal_template_.goal_tolerance);\n if (config.hasMember(\"goal_time_tolerance\"))\n goal_template_.goal_time_tolerance = ros::Duration(parseDouble(config[\"goal_time_tolerance\"]));\n}\n\nnamespace\n{\nenum ToleranceVariables\n{\n POSITION,\n VELOCITY,\n ACCELERATION\n};\ntemplate \ndouble& variable(control_msgs::JointTolerance& msg);\n\ntemplate <>\ninline double& variable(control_msgs::JointTolerance& msg)\n{\n return msg.position;\n}\ntemplate <>\ninline double& variable(control_msgs::JointTolerance& msg)\n{\n return msg.velocity;\n}\ntemplate <>\ninline double& variable(control_msgs::JointTolerance& msg)\n{\n return msg.acceleration;\n}\n\nstatic std::map VAR_NAME = { { POSITION, \"position\" },\n { VELOCITY, \"velocity\" },\n { ACCELERATION, \"acceleration\" } };\nstatic std::map)> VAR_ACCESS = { { POSITION, &variable },\n { VELOCITY, &variable },\n { ACCELERATION,\n &variable } };\n\nconst char* errorCodeToMessage(int error_code)\n{\n switch (error_code)\n {\n case control_msgs::FollowJointTrajectoryResult::SUCCESSFUL:\n return \"SUCCESSFUL\";\n case control_msgs::FollowJointTrajectoryResult::INVALID_GOAL:\n return \"INVALID_GOAL\";\n case control_msgs::FollowJointTrajectoryResult::INVALID_JOINTS:\n return \"INVALID_JOINTS\";\n case control_msgs::FollowJointTrajectoryResult::OLD_HEADER_TIMESTAMP:\n return \"OLD_HEADER_TIMESTAMP\";\n case control_msgs::FollowJointTrajectoryResult::PATH_TOLERANCE_VIOLATED:\n return \"PATH_TOLERANCE_VIOLATED\";\n case control_msgs::FollowJointTrajectoryResult::GOAL_TOLERANCE_VIOLATED:\n return \"GOAL_TOLERANCE_VIOLATED\";\n default:\n return \"unknown error\";\n }\n}\n}\n\nvoid FollowJointTrajectoryControllerHandle::configure(XmlRpc::XmlRpcValue& config, const std::string& config_name,\n std::vector& tolerances)\n{\n if (isStruct(config)) \/\/ config should be either a struct of position, velocity, acceleration\n {\n for (ToleranceVariables var : { POSITION, VELOCITY, ACCELERATION })\n {\n if (!config.hasMember(VAR_NAME[var]))\n continue;\n XmlRpc::XmlRpcValue values = config[VAR_NAME[var]];\n if (isArray(values, joints_.size()))\n {\n size_t i = 0;\n for (const auto& joint_name : joints_)\n VAR_ACCESS[var](getTolerance(tolerances, joint_name)) = parseDouble(values[i++]);\n }\n else\n { \/\/ use common value for all joints\n double value = parseDouble(values);\n for (const auto& joint_name : joints_)\n VAR_ACCESS[var](getTolerance(tolerances, joint_name)) = value;\n }\n }\n }\n else if (isArray(config)) \/\/ or an array of JointTolerance msgs\n {\n for (size_t i = 0; i < config.size(); ++i)\n {\n control_msgs::JointTolerance& tol = getTolerance(tolerances, config[i][\"name\"]);\n for (ToleranceVariables var : { POSITION, VELOCITY, ACCELERATION })\n {\n if (!config[i].hasMember(VAR_NAME[var]))\n continue;\n VAR_ACCESS[var](tol) = parseDouble(config[i][VAR_NAME[var]]);\n }\n }\n }\n else\n ROS_WARN_STREAM_NAMED(LOGNAME, \"Invalid \" << config_name);\n}\n\ncontrol_msgs::JointTolerance& FollowJointTrajectoryControllerHandle::getTolerance(\n std::vector& tolerances, const std::string& name)\n{\n auto it =\n std::lower_bound(tolerances.begin(), tolerances.end(), name,\n [](const control_msgs::JointTolerance& lhs, const std::string& rhs) { return lhs.name < rhs; });\n if (it == tolerances.cend() || it->name != name)\n { \/\/ insert new entry if not yet available\n it = tolerances.insert(it, control_msgs::JointTolerance());\n it->name = name;\n }\n return *it;\n}\n\nvoid FollowJointTrajectoryControllerHandle::controllerDoneCallback(\n const actionlib::SimpleClientGoalState& state, const control_msgs::FollowJointTrajectoryResultConstPtr& result)\n{\n \/\/ Output custom error message for FollowJointTrajectoryResult if necessary\n if (!result)\n ROS_WARN_STREAM_NAMED(LOGNAME, \"Controller \" << name_ << \" done, no result returned\");\n else if (result->error_code == control_msgs::FollowJointTrajectoryResult::SUCCESSFUL)\n ROS_INFO_STREAM_NAMED(LOGNAME, \"Controller \" << name_ << \" successfully finished\");\n else\n ROS_WARN_STREAM_NAMED(LOGNAME, \"Controller \" << name_ << \"failed with error \"\n << errorCodeToMessage(result->error_code) << \": \"\n << result->error_string);\n finishControllerExecution(state);\n}\n\nvoid FollowJointTrajectoryControllerHandle::controllerActiveCallback()\n{\n ROS_DEBUG_STREAM_NAMED(LOGNAME, name_ << \" started execution\");\n}\n\nvoid FollowJointTrajectoryControllerHandle::controllerFeedbackCallback(\n const control_msgs::FollowJointTrajectoryFeedbackConstPtr& feedback)\n{\n}\n\n} \/\/ end namespace moveit_simple_controller_manager\n<|endoftext|>"} {"text":"\/*************************************************************\\\n * TextEngine.cpp *\n * This file was created by Jeremy Greenburg *\n * As part of The God Core game for the University of *\n * Tennessee at Martin's University Scholars Organization *\n * *\n * This file contains the definition of the TextEngine class *\n * For more information, see TextEngine.h *\n\\*************************************************************\/\n\n\/\/ TextEngine declaration and std::string\n#include \"TextEngine.h\"\n\n\/\/ std::ifstream\n#include \n\n\/\/ Standard I\/O for debugging\n#include \n\n\/\/ OpenGL API\n#include \n#include \n\nusing namespace std;\n\n\/\/ Initializing the constants\nconst char* TextEngine::TEXT_PATH = \"Resources\\\\Scripts\\\\\";\nconst char* TextEngine::SAVE_PATH = \"Resources\\\\Save Data\\\\\";\nconst float TextEngine::LINE_OFFSET = 10;\n\nvoid TextEngine::displayText(float x, float y,\n\tfloat r, float g, float b,\n\tvoid* font, vector text)\n{\n\tvector::iterator it;\n\n\t\/\/ Iterates throguh the text vector and prints it to the screen\n\tfor (it = text.begin(); it != text.end(); it++)\n\t{\n\t\tglColor3f(r, g, b);\n\t\tglRasterPos2f(x, y);\n\n\t\tfor (unsigned int i = 0; i < it->length(); i++)\n\t\t{\n\t\t\tglutBitmapCharacter(font, (*it)[i]);\n\t\t}\n\n\t\t\/\/ Because glut does not print newlines\n\t\ty += LINE_OFFSET;\n\t}\n}\n\nvector TextEngine::findText(string fileName, string tag)\n{\n\t\/\/ The tags are listed between dollar signs\n\tstring fullTag = '$' + tag + '$';\n\n\tstring fullPath = TEXT_PATH + fileName;\n\n\tifstream infile(fullPath);\n\n\t\/\/ Buffer to read in data\n\tstring buff;\n\t\/\/ Array to store strings\n\tvector data;\n\n\t\/\/ Find the string(s) to read in\n\tgetline(infile, buff);\n\twhile (infile && buff != fullTag)\n\t{\n\t\tgetline(infile, buff);\n\t}\n\n\t\/\/ Store the string(s)\n\tgetline(infile, buff);\n\twhile (infile && buff != \"$END$\")\n\t{\n\t\tdata.push_back(buff);\n\t\tgetline(infile, buff);\n\t}\n\n\tinfile.close();\n\n\treturn data;\n}\n\nvoid TextEngine::openFile(float x, float y,\n\tfloat r, float g, float b,\n\tstring fileName, string tag)\n{\n\tvector input = findText(fileName, tag);\n\n\tdisplayText(x, y, r, g, b,\n\t\tGLUT_BITMAP_HELVETICA_12,\n\t\tinput);\n}\n\nvector TextEngine::getText(string fileName, string tag)\n{\n\tvector input = findText(fileName, tag);\n\n\treturn input;\n}\n\nvoid TextEngine::printString(float x, float y, float r, float g, float b,\n\tstring text)\n{\n\tglColor3f(r, g, b);\n\tglRasterPos2f(x, y);\n\n\tfor (unsigned int i = 0; i < text.length(); i++)\n\t{\n\t\tglutBitmapCharacter(GLUT_BITMAP_HELVETICA_12, text[i]);\n\t}\n\n\t\/\/ Vertical spacing\n\ty += LINE_OFFSET;\n}Removed unnecessary code\/*************************************************************\\\n * TextEngine.cpp *\n * This file was created by Jeremy Greenburg *\n * As part of The God Core game for the University of *\n * Tennessee at Martin's University Scholars Organization *\n * *\n * This file contains the definition of the TextEngine class *\n * For more information, see TextEngine.h *\n\\*************************************************************\/\n\n\/\/ TextEngine declaration and std::string\n#include \"TextEngine.h\"\n\n\/\/ std::ifstream\n#include \n\n\/\/ Standard I\/O for debugging\n#include \n\n\/\/ OpenGL API\n#include \n#include \n\nusing namespace std;\n\n\/\/ Initializing the constants\nconst char* TextEngine::TEXT_PATH = \"Resources\\\\Scripts\\\\\";\nconst float TextEngine::LINE_OFFSET = 10;\n\nvoid TextEngine::displayText(float x, float y,\n\tfloat r, float g, float b,\n\tvoid* font, vector text)\n{\n\tvector::iterator it;\n\n\t\/\/ Iterates throguh the text vector and prints it to the screen\n\tfor (it = text.begin(); it != text.end(); it++)\n\t{\n\t\tglColor3f(r, g, b);\n\t\tglRasterPos2f(x, y);\n\n\t\tfor (unsigned int i = 0; i < it->length(); i++)\n\t\t{\n\t\t\tglutBitmapCharacter(font, (*it)[i]);\n\t\t}\n\n\t\t\/\/ Because glut does not print newlines\n\t\ty += LINE_OFFSET;\n\t}\n}\n\nvector TextEngine::findText(string fileName, string tag)\n{\n\t\/\/ The tags are listed between dollar signs\n\tstring fullTag = '$' + tag + '$';\n\n\tstring fullPath = TEXT_PATH + fileName;\n\n\tifstream infile(fullPath);\n\n\t\/\/ Buffer to read in data\n\tstring buff;\n\t\/\/ Array to store strings\n\tvector data;\n\n\t\/\/ Find the string(s) to read in\n\tgetline(infile, buff);\n\twhile (infile && buff != fullTag)\n\t{\n\t\tgetline(infile, buff);\n\t}\n\n\t\/\/ Store the string(s)\n\tgetline(infile, buff);\n\twhile (infile && buff != \"$END$\")\n\t{\n\t\tdata.push_back(buff);\n\t\tgetline(infile, buff);\n\t}\n\n\tinfile.close();\n\n\treturn data;\n}\n\nvoid TextEngine::openFile(float x, float y,\n\tfloat r, float g, float b,\n\tstring fileName, string tag)\n{\n\tvector input = findText(fileName, tag);\n\n\tdisplayText(x, y, r, g, b,\n\t\tGLUT_BITMAP_HELVETICA_12,\n\t\tinput);\n}\n\nvector TextEngine::getText(string fileName, string tag)\n{\n\tvector input = findText(fileName, tag);\n\n\treturn input;\n}\n\nvoid TextEngine::printString(float x, float y, float r, float g, float b,\n\tstring text)\n{\n\tglColor3f(r, g, b);\n\tglRasterPos2f(x, y);\n\n\tfor (unsigned int i = 0; i < text.length(); i++)\n\t{\n\t\tglutBitmapCharacter(GLUT_BITMAP_HELVETICA_12, text[i]);\n\t}\n\n\t\/\/ Vertical spacing\n\ty += LINE_OFFSET;\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n> File Name: main.cpp\n> Project Name: Hearthstone++\n> Author: Chan-Ho Chris Ohk\n> Purpose: Main entry of Hearthstone++ tool.\n> Created Time: 2018\/08\/18\n> Copyright (c) 2018, Chan-Ho Chris Ohk\n*************************************************************************\/\nint main()\n{\n return 0;\n}[ci skip] Implement basic structure\/*************************************************************************\n> File Name: main.cpp\n> Project Name: Hearthstone++\n> Author: Chan-Ho Chris Ohk\n> Purpose: Main entry of Hearthstone++ tool.\n> Created Time: 2018\/08\/18\n> Copyright (c) 2018, Chan-Ho Chris Ohk\n*************************************************************************\/\n#include \n\n#include \n#include \n#include \n\ninline std::string ToString(const clara::Opt& opt)\n{\n std::ostringstream oss;\n oss << (clara::Parser() | opt);\n return oss.str();\n}\n\ninline std::string ToString(const clara::Parser& p)\n{\n std::ostringstream oss;\n oss << p;\n return oss.str();\n}\n\ninline void ExportFile(const std::string& fileName)\n{\n std::ofstream outputFile(fileName + \".md\");\n if (outputFile)\n {\n \/\/ TODO: export card data\n }\n else\n {\n fprintf(stderr, \"Failed to write file %s\\n\", fileName.c_str());\n exit(EXIT_FAILURE);\n }\n}\n\nint main(int argc, char* argv[])\n{\n \/\/ Parse command\n bool showHelp = false;\n std::string expansionNameA, expansionNameU, expansionNameI;\n\n \/\/ Parsing\n auto parser =\n clara::Help(showHelp) |\n clara::Opt(expansionNameA, \"expansionName\")[\"-a\"][\"--all\"](\n \"Export all card list to markdown format by grouping the \"\n \"expansion\") |\n clara::Opt(expansionNameU, \"expansionName\")[\"-u\"][\"--unique\"](\n \"Export unique card list to markdown format by grouping the \"\n \"expansion\") |\n clara::Opt(expansionNameI, \"expansionName\")[\"-i\"][\"--implemented\"](\n \"Export implemented card list to markdown format by \"\n \"grouping \"\n \"the expansion\");\n\n auto result = parser.parse(clara::Args(argc, argv));\n if (!result)\n {\n std::cerr << \"Error in command line: \" << result.errorMessage() << '\\n';\n exit(EXIT_FAILURE);\n }\n\n if (showHelp)\n {\n std::cout << ToString(parser) << '\\n';\n exit(EXIT_SUCCESS);\n }\n\n if (!expansionNameA.empty())\n {\n }\n\n if (!expansionNameU.empty())\n {\n }\n\n if (!expansionNameI.empty())\n {\n }\n\n exit(EXIT_SUCCESS);\n}<|endoftext|>"} {"text":"#include \n\n#include \n#include \n#include \n#include \n\nnamespace BABYLON {\n\nWorleyNoise3DBlock::WorleyNoise3DBlock(const std::string& iName)\n : NodeMaterialBlock{iName, NodeMaterialBlockTargets::Neutral}\n , manhattanDistance{false}\n , seed{this, &WorleyNoise3DBlock::get_seed}\n , jitter{this, &WorleyNoise3DBlock::get_jitter}\n , output{this, &WorleyNoise3DBlock::get_output}\n{\n registerInput(\"seed\", NodeMaterialBlockConnectionPointTypes::Vector3);\n registerInput(\"jitter\", NodeMaterialBlockConnectionPointTypes::Float);\n\n registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes::Vector2);\n}\n\nWorleyNoise3DBlock::~WorleyNoise3DBlock() = default;\n\nstd::string WorleyNoise3DBlock::getClassName() const\n{\n return \"WorleyNoise3DBlock\";\n}\n\nNodeMaterialConnectionPointPtr& WorleyNoise3DBlock::get_seed()\n{\n return _inputs[0];\n}\n\nNodeMaterialConnectionPointPtr& WorleyNoise3DBlock::get_jitter()\n{\n return _inputs[1];\n}\n\nNodeMaterialConnectionPointPtr& WorleyNoise3DBlock::get_output()\n{\n return _outputs[0];\n}\n\nWorleyNoise3DBlock& WorleyNoise3DBlock::_buildBlock(NodeMaterialBuildState& state)\n{\n NodeMaterialBlock::_buildBlock(state);\n\n if (!seed()->isConnected()) {\n return *this;\n }\n\n if (!_outputs[0]->hasEndpoints()) {\n return *this;\n }\n\n const char* functionString = R\"ShaderCode(\n\n vec3 permute(vec3 x){\n return mod((34.0 * x + 1.0) * x, 289.0);\n }\n\n vec3 dist(vec3 x, vec3 y, vec3 z, bool manhattanDistance){\n return manhattanDistance ? abs(x) + abs(y) + abs(z) : (x * x + y * y + z * z);\n }\n\n vec2 worley(vec3 P, float jitter, bool manhattanDistance){\n float K = 0.142857142857; \/\/ 1\/7\n float Ko = 0.428571428571; \/\/ 1\/2-K\/2\n float K2 = 0.020408163265306; \/\/ 1\/(7*7)\n float Kz = 0.166666666667; \/\/ 1\/6\n float Kzo = 0.416666666667; \/\/ 1\/2-1\/6*2\n\n vec3 Pi = mod(floor(P), 289.0);\n vec3 Pf = fract(P) - 0.5;\n\n vec3 Pfx = Pf.x + vec3(1.0, 0.0, -1.0);\n vec3 Pfy = Pf.y + vec3(1.0, 0.0, -1.0);\n vec3 Pfz = Pf.z + vec3(1.0, 0.0, -1.0);\n\n vec3 p = permute(Pi.x + vec3(-1.0, 0.0, 1.0));\n vec3 p1 = permute(p + Pi.y - 1.0);\n vec3 p2 = permute(p + Pi.y);\n vec3 p3 = permute(p + Pi.y + 1.0);\n\n vec3 p11 = permute(p1 + Pi.z - 1.0);\n vec3 p12 = permute(p1 + Pi.z);\n vec3 p13 = permute(p1 + Pi.z + 1.0);\n\n vec3 p21 = permute(p2 + Pi.z - 1.0);\n vec3 p22 = permute(p2 + Pi.z);\n vec3 p23 = permute(p2 + Pi.z + 1.0);\n\n vec3 p31 = permute(p3 + Pi.z - 1.0);\n vec3 p32 = permute(p3 + Pi.z);\n vec3 p33 = permute(p3 + Pi.z + 1.0);\n\n vec3 ox11 = fract(p11*K) - Ko;\n vec3 oy11 = mod(floor(p11*K), 7.0)*K - Ko;\n vec3 oz11 = floor(p11*K2)*Kz - Kzo; \/\/ p11 < 289 guaranteed\n\n vec3 ox12 = fract(p12*K) - Ko;\n vec3 oy12 = mod(floor(p12*K), 7.0)*K - Ko;\n vec3 oz12 = floor(p12*K2)*Kz - Kzo;\n\n vec3 ox13 = fract(p13*K) - Ko;\n vec3 oy13 = mod(floor(p13*K), 7.0)*K - Ko;\n vec3 oz13 = floor(p13*K2)*Kz - Kzo;\n\n vec3 ox21 = fract(p21*K) - Ko;\n vec3 oy21 = mod(floor(p21*K), 7.0)*K - Ko;\n vec3 oz21 = floor(p21*K2)*Kz - Kzo;\n\n vec3 ox22 = fract(p22*K) - Ko;\n vec3 oy22 = mod(floor(p22*K), 7.0)*K - Ko;\n vec3 oz22 = floor(p22*K2)*Kz - Kzo;\n\n vec3 ox23 = fract(p23*K) - Ko;\n vec3 oy23 = mod(floor(p23*K), 7.0)*K - Ko;\n vec3 oz23 = floor(p23*K2)*Kz - Kzo;\n\n vec3 ox31 = fract(p31*K) - Ko;\n vec3 oy31 = mod(floor(p31*K), 7.0)*K - Ko;\n vec3 oz31 = floor(p31*K2)*Kz - Kzo;\n\n vec3 ox32 = fract(p32*K) - Ko;\n vec3 oy32 = mod(floor(p32*K), 7.0)*K - Ko;\n vec3 oz32 = floor(p32*K2)*Kz - Kzo;\n\n vec3 ox33 = fract(p33*K) - Ko;\n vec3 oy33 = mod(floor(p33*K), 7.0)*K - Ko;\n vec3 oz33 = floor(p33*K2)*Kz - Kzo;\n\n vec3 dx11 = Pfx + jitter*ox11;\n vec3 dy11 = Pfy.x + jitter*oy11;\n vec3 dz11 = Pfz.x + jitter*oz11;\n\n vec3 dx12 = Pfx + jitter*ox12;\n vec3 dy12 = Pfy.x + jitter*oy12;\n vec3 dz12 = Pfz.y + jitter*oz12;\n\n vec3 dx13 = Pfx + jitter*ox13;\n vec3 dy13 = Pfy.x + jitter*oy13;\n vec3 dz13 = Pfz.z + jitter*oz13;\n\n vec3 dx21 = Pfx + jitter*ox21;\n vec3 dy21 = Pfy.y + jitter*oy21;\n vec3 dz21 = Pfz.x + jitter*oz21;\n\n vec3 dx22 = Pfx + jitter*ox22;\n vec3 dy22 = Pfy.y + jitter*oy22;\n vec3 dz22 = Pfz.y + jitter*oz22;\n\n vec3 dx23 = Pfx + jitter*ox23;\n vec3 dy23 = Pfy.y + jitter*oy23;\n vec3 dz23 = Pfz.z + jitter*oz23;\n\n vec3 dx31 = Pfx + jitter*ox31;\n vec3 dy31 = Pfy.z + jitter*oy31;\n vec3 dz31 = Pfz.x + jitter*oz31;\n\n vec3 dx32 = Pfx + jitter*ox32;\n vec3 dy32 = Pfy.z + jitter*oy32;\n vec3 dz32 = Pfz.y + jitter*oz32;\n\n vec3 dx33 = Pfx + jitter*ox33;\n vec3 dy33 = Pfy.z + jitter*oy33;\n vec3 dz33 = Pfz.z + jitter*oz33;\n\n vec3 d11 = dist(dx11, dy11, dz11, manhattanDistance);\n vec3 d12 =dist(dx12, dy12, dz12, manhattanDistance);\n vec3 d13 = dist(dx13, dy13, dz13, manhattanDistance);\n vec3 d21 = dist(dx21, dy21, dz21, manhattanDistance);\n vec3 d22 = dist(dx22, dy22, dz22, manhattanDistance);\n vec3 d23 = dist(dx23, dy23, dz23, manhattanDistance);\n vec3 d31 = dist(dx31, dy31, dz31, manhattanDistance);\n vec3 d32 = dist(dx32, dy32, dz32, manhattanDistance);\n vec3 d33 = dist(dx33, dy33, dz33, manhattanDistance);\n\n vec3 d1a = min(d11, d12);\n d12 = max(d11, d12);\n d11 = min(d1a, d13); \/\/ Smallest now not in d12 or d13\n d13 = max(d1a, d13);\n d12 = min(d12, d13); \/\/ 2nd smallest now not in d13\n vec3 d2a = min(d21, d22);\n d22 = max(d21, d22);\n d21 = min(d2a, d23); \/\/ Smallest now not in d22 or d23\n d23 = max(d2a, d23);\n d22 = min(d22, d23); \/\/ 2nd smallest now not in d23\n vec3 d3a = min(d31, d32);\n d32 = max(d31, d32);\n d31 = min(d3a, d33); \/\/ Smallest now not in d32 or d33\n d33 = max(d3a, d33);\n d32 = min(d32, d33); \/\/ 2nd smallest now not in d33\n vec3 da = min(d11, d21);\n d21 = max(d11, d21);\n d11 = min(da, d31); \/\/ Smallest now in d11\n d31 = max(da, d31); \/\/ 2nd smallest now not in d31\n d11.xy = (d11.x < d11.y) ? d11.xy : d11.yx;\n d11.xz = (d11.x < d11.z) ? d11.xz : d11.zx; \/\/ d11.x now smallest\n d12 = min(d12, d21); \/\/ 2nd smallest now not in d21\n d12 = min(d12, d22); \/\/ nor in d22\n d12 = min(d12, d31); \/\/ nor in d31\n d12 = min(d12, d32); \/\/ nor in d32\n d11.yz = min(d11.yz,d12.xy); \/\/ nor in d12.yz\n d11.y = min(d11.y,d12.z); \/\/ Only two more to go\n d11.y = min(d11.y,d11.z); \/\/ Done! (Phew!)\n return sqrt(d11.xy); \/\/ F1, F2\n }\n\n )ShaderCode\";\n\n state._emitFunction(\"worley3D\", functionString, \"\/\/ Worley3D\");\n state.compilationString\n += _declareOutput(_outputs[0], state)\n + StringTools::printf(\" = worley(%s, %s, %d);\\r\\n\", seed()->associatedVariableName().c_str(),\n jitter()->associatedVariableName().c_str(), manhattanDistance);\n\n return *this;\n}\n\nstd::string WorleyNoise3DBlock::_dumpPropertiesCode()\n{\n auto codeString = StringTools::printf(\"%s.manhattanDistance = %d;\\r\\n\", _codeVariableName.c_str(),\n manhattanDistance);\n\n return codeString;\n}\n\njson WorleyNoise3DBlock::serialize() const\n{\n return nullptr;\n}\n\nvoid WorleyNoise3DBlock::_deserialize(const json& \/*serializationObject*\/, Scene* \/*scene*\/,\n const std::string& \/*rootUrl*\/)\n{\n}\n\n} \/\/ end of namespace BABYLON\nUpdated WorleyNoise3DBlock::_dumpPropertiesCode function to use base code string from superclass#include \n\n#include \n#include \n#include \n#include \n\nnamespace BABYLON {\n\nWorleyNoise3DBlock::WorleyNoise3DBlock(const std::string& iName)\n : NodeMaterialBlock{iName, NodeMaterialBlockTargets::Neutral}\n , manhattanDistance{false}\n , seed{this, &WorleyNoise3DBlock::get_seed}\n , jitter{this, &WorleyNoise3DBlock::get_jitter}\n , output{this, &WorleyNoise3DBlock::get_output}\n{\n registerInput(\"seed\", NodeMaterialBlockConnectionPointTypes::Vector3);\n registerInput(\"jitter\", NodeMaterialBlockConnectionPointTypes::Float);\n\n registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes::Vector2);\n}\n\nWorleyNoise3DBlock::~WorleyNoise3DBlock() = default;\n\nstd::string WorleyNoise3DBlock::getClassName() const\n{\n return \"WorleyNoise3DBlock\";\n}\n\nNodeMaterialConnectionPointPtr& WorleyNoise3DBlock::get_seed()\n{\n return _inputs[0];\n}\n\nNodeMaterialConnectionPointPtr& WorleyNoise3DBlock::get_jitter()\n{\n return _inputs[1];\n}\n\nNodeMaterialConnectionPointPtr& WorleyNoise3DBlock::get_output()\n{\n return _outputs[0];\n}\n\nWorleyNoise3DBlock& WorleyNoise3DBlock::_buildBlock(NodeMaterialBuildState& state)\n{\n NodeMaterialBlock::_buildBlock(state);\n\n if (!seed()->isConnected()) {\n return *this;\n }\n\n if (!_outputs[0]->hasEndpoints()) {\n return *this;\n }\n\n const char* functionString = R\"ShaderCode(\n\n vec3 permute(vec3 x){\n return mod((34.0 * x + 1.0) * x, 289.0);\n }\n\n vec3 dist(vec3 x, vec3 y, vec3 z, bool manhattanDistance){\n return manhattanDistance ? abs(x) + abs(y) + abs(z) : (x * x + y * y + z * z);\n }\n\n vec2 worley(vec3 P, float jitter, bool manhattanDistance){\n float K = 0.142857142857; \/\/ 1\/7\n float Ko = 0.428571428571; \/\/ 1\/2-K\/2\n float K2 = 0.020408163265306; \/\/ 1\/(7*7)\n float Kz = 0.166666666667; \/\/ 1\/6\n float Kzo = 0.416666666667; \/\/ 1\/2-1\/6*2\n\n vec3 Pi = mod(floor(P), 289.0);\n vec3 Pf = fract(P) - 0.5;\n\n vec3 Pfx = Pf.x + vec3(1.0, 0.0, -1.0);\n vec3 Pfy = Pf.y + vec3(1.0, 0.0, -1.0);\n vec3 Pfz = Pf.z + vec3(1.0, 0.0, -1.0);\n\n vec3 p = permute(Pi.x + vec3(-1.0, 0.0, 1.0));\n vec3 p1 = permute(p + Pi.y - 1.0);\n vec3 p2 = permute(p + Pi.y);\n vec3 p3 = permute(p + Pi.y + 1.0);\n\n vec3 p11 = permute(p1 + Pi.z - 1.0);\n vec3 p12 = permute(p1 + Pi.z);\n vec3 p13 = permute(p1 + Pi.z + 1.0);\n\n vec3 p21 = permute(p2 + Pi.z - 1.0);\n vec3 p22 = permute(p2 + Pi.z);\n vec3 p23 = permute(p2 + Pi.z + 1.0);\n\n vec3 p31 = permute(p3 + Pi.z - 1.0);\n vec3 p32 = permute(p3 + Pi.z);\n vec3 p33 = permute(p3 + Pi.z + 1.0);\n\n vec3 ox11 = fract(p11*K) - Ko;\n vec3 oy11 = mod(floor(p11*K), 7.0)*K - Ko;\n vec3 oz11 = floor(p11*K2)*Kz - Kzo; \/\/ p11 < 289 guaranteed\n\n vec3 ox12 = fract(p12*K) - Ko;\n vec3 oy12 = mod(floor(p12*K), 7.0)*K - Ko;\n vec3 oz12 = floor(p12*K2)*Kz - Kzo;\n\n vec3 ox13 = fract(p13*K) - Ko;\n vec3 oy13 = mod(floor(p13*K), 7.0)*K - Ko;\n vec3 oz13 = floor(p13*K2)*Kz - Kzo;\n\n vec3 ox21 = fract(p21*K) - Ko;\n vec3 oy21 = mod(floor(p21*K), 7.0)*K - Ko;\n vec3 oz21 = floor(p21*K2)*Kz - Kzo;\n\n vec3 ox22 = fract(p22*K) - Ko;\n vec3 oy22 = mod(floor(p22*K), 7.0)*K - Ko;\n vec3 oz22 = floor(p22*K2)*Kz - Kzo;\n\n vec3 ox23 = fract(p23*K) - Ko;\n vec3 oy23 = mod(floor(p23*K), 7.0)*K - Ko;\n vec3 oz23 = floor(p23*K2)*Kz - Kzo;\n\n vec3 ox31 = fract(p31*K) - Ko;\n vec3 oy31 = mod(floor(p31*K), 7.0)*K - Ko;\n vec3 oz31 = floor(p31*K2)*Kz - Kzo;\n\n vec3 ox32 = fract(p32*K) - Ko;\n vec3 oy32 = mod(floor(p32*K), 7.0)*K - Ko;\n vec3 oz32 = floor(p32*K2)*Kz - Kzo;\n\n vec3 ox33 = fract(p33*K) - Ko;\n vec3 oy33 = mod(floor(p33*K), 7.0)*K - Ko;\n vec3 oz33 = floor(p33*K2)*Kz - Kzo;\n\n vec3 dx11 = Pfx + jitter*ox11;\n vec3 dy11 = Pfy.x + jitter*oy11;\n vec3 dz11 = Pfz.x + jitter*oz11;\n\n vec3 dx12 = Pfx + jitter*ox12;\n vec3 dy12 = Pfy.x + jitter*oy12;\n vec3 dz12 = Pfz.y + jitter*oz12;\n\n vec3 dx13 = Pfx + jitter*ox13;\n vec3 dy13 = Pfy.x + jitter*oy13;\n vec3 dz13 = Pfz.z + jitter*oz13;\n\n vec3 dx21 = Pfx + jitter*ox21;\n vec3 dy21 = Pfy.y + jitter*oy21;\n vec3 dz21 = Pfz.x + jitter*oz21;\n\n vec3 dx22 = Pfx + jitter*ox22;\n vec3 dy22 = Pfy.y + jitter*oy22;\n vec3 dz22 = Pfz.y + jitter*oz22;\n\n vec3 dx23 = Pfx + jitter*ox23;\n vec3 dy23 = Pfy.y + jitter*oy23;\n vec3 dz23 = Pfz.z + jitter*oz23;\n\n vec3 dx31 = Pfx + jitter*ox31;\n vec3 dy31 = Pfy.z + jitter*oy31;\n vec3 dz31 = Pfz.x + jitter*oz31;\n\n vec3 dx32 = Pfx + jitter*ox32;\n vec3 dy32 = Pfy.z + jitter*oy32;\n vec3 dz32 = Pfz.y + jitter*oz32;\n\n vec3 dx33 = Pfx + jitter*ox33;\n vec3 dy33 = Pfy.z + jitter*oy33;\n vec3 dz33 = Pfz.z + jitter*oz33;\n\n vec3 d11 = dist(dx11, dy11, dz11, manhattanDistance);\n vec3 d12 =dist(dx12, dy12, dz12, manhattanDistance);\n vec3 d13 = dist(dx13, dy13, dz13, manhattanDistance);\n vec3 d21 = dist(dx21, dy21, dz21, manhattanDistance);\n vec3 d22 = dist(dx22, dy22, dz22, manhattanDistance);\n vec3 d23 = dist(dx23, dy23, dz23, manhattanDistance);\n vec3 d31 = dist(dx31, dy31, dz31, manhattanDistance);\n vec3 d32 = dist(dx32, dy32, dz32, manhattanDistance);\n vec3 d33 = dist(dx33, dy33, dz33, manhattanDistance);\n\n vec3 d1a = min(d11, d12);\n d12 = max(d11, d12);\n d11 = min(d1a, d13); \/\/ Smallest now not in d12 or d13\n d13 = max(d1a, d13);\n d12 = min(d12, d13); \/\/ 2nd smallest now not in d13\n vec3 d2a = min(d21, d22);\n d22 = max(d21, d22);\n d21 = min(d2a, d23); \/\/ Smallest now not in d22 or d23\n d23 = max(d2a, d23);\n d22 = min(d22, d23); \/\/ 2nd smallest now not in d23\n vec3 d3a = min(d31, d32);\n d32 = max(d31, d32);\n d31 = min(d3a, d33); \/\/ Smallest now not in d32 or d33\n d33 = max(d3a, d33);\n d32 = min(d32, d33); \/\/ 2nd smallest now not in d33\n vec3 da = min(d11, d21);\n d21 = max(d11, d21);\n d11 = min(da, d31); \/\/ Smallest now in d11\n d31 = max(da, d31); \/\/ 2nd smallest now not in d31\n d11.xy = (d11.x < d11.y) ? d11.xy : d11.yx;\n d11.xz = (d11.x < d11.z) ? d11.xz : d11.zx; \/\/ d11.x now smallest\n d12 = min(d12, d21); \/\/ 2nd smallest now not in d21\n d12 = min(d12, d22); \/\/ nor in d22\n d12 = min(d12, d31); \/\/ nor in d31\n d12 = min(d12, d32); \/\/ nor in d32\n d11.yz = min(d11.yz,d12.xy); \/\/ nor in d12.yz\n d11.y = min(d11.y,d12.z); \/\/ Only two more to go\n d11.y = min(d11.y,d11.z); \/\/ Done! (Phew!)\n return sqrt(d11.xy); \/\/ F1, F2\n }\n\n )ShaderCode\";\n\n state._emitFunction(\"worley3D\", functionString, \"\/\/ Worley3D\");\n state.compilationString\n += _declareOutput(_outputs[0], state)\n + StringTools::printf(\" = worley(%s, %s, %d);\\r\\n\", seed()->associatedVariableName().c_str(),\n jitter()->associatedVariableName().c_str(), manhattanDistance);\n\n return *this;\n}\n\nstd::string WorleyNoise3DBlock::_dumpPropertiesCode()\n{\n auto codeString = NodeMaterialBlock::_dumpPropertiesCode()\n + StringTools::printf(\"%s.manhattanDistance = %d;\\r\\n\",\n _codeVariableName.c_str(), manhattanDistance);\n\n return codeString;\n}\n\njson WorleyNoise3DBlock::serialize() const\n{\n return nullptr;\n}\n\nvoid WorleyNoise3DBlock::_deserialize(const json& \/*serializationObject*\/, Scene* \/*scene*\/,\n const std::string& \/*rootUrl*\/)\n{\n}\n\n} \/\/ end of namespace BABYLON\n<|endoftext|>"} {"text":"Add stats test<|endoftext|>"} {"text":"#ifndef STAN_MATH_FWD_FUN_QUAD_FORM_HPP\n#define STAN_MATH_FWD_FUN_QUAD_FORM_HPP\n\n#include \n#include \n#include \n\nnamespace stan {\nnamespace math {\n\n\/**\n * Return the quadratic form \\f$ B^T A B \\f$.\n *\n * Symmetry of the resulting matrix is not guaranteed due to numerical\n * precision.\n *\n * @tparam Ta type of elements in the square matrix\n * @tparam Ra number of rows in the square matrix, can be Eigen::Dynamic\n * @tparam Ca number of columns in the square matrix, can be Eigen::Dynamic\n * @tparam Tb type of elements in the second matrix\n * @tparam Rb number of rows in the second matrix, can be Eigen::Dynamic\n * @tparam Cb number of columns in the second matrix, can be Eigen::Dynamic\n *\n * @param A square matrix\n * @param B second matrix\n * @return The quadratic form, which is a symmetric matrix of size Cb.\n * @throws std::invalid_argument if A is not square, or if A cannot be\n * multiplied by B\n *\/\ntemplate ...>\ninline Eigen::Matrix, Cb, Cb> quad_form(\n const Eigen::Matrix& A, const Eigen::Matrix& B) {\n check_square(\"quad_form\", \"A\", A);\n check_multiplicable(\"quad_form\", \"A\", A, \"B\", B);\n return multiply(transpose(B), multiply(A, B));\n}\n\n\/**\n * Return the quadratic form \\f$ B^T A B \\f$.\n *\n * @tparam Ta type of elements in the square matrix\n * @tparam Ra number of rows in the square matrix, can be Eigen::Dynamic\n * @tparam Ca number of columns in the square matrix, can be Eigen::Dynamic\n * @tparam Tb type of elements in the vector\n * @tparam Rb number of rows in the vector, can be Eigen::Dynamic\n *\n * @param A square matrix\n * @param B vector\n * @return The quadratic form (a scalar).\n * @throws std::invalid_argument if A is not square, or if A cannot be\n * multiplied by B\n *\/\ntemplate ...>\ninline return_type_t quad_form(const Eigen::Matrix& A,\n const Eigen::Matrix& B) {\n check_square(\"quad_form\", \"A\", A);\n check_multiplicable(\"quad_form\", \"A\", A, \"B\", B);\n return dot_product(B, multiply(A, B));\n}\n\n} \/\/ namespace math\n} \/\/ namespace stan\n\n#endif\nfix for a header#ifndef STAN_MATH_FWD_FUN_QUAD_FORM_HPP\n#define STAN_MATH_FWD_FUN_QUAD_FORM_HPP\n\n#include \n#include \n#include \n\nnamespace stan {\nnamespace math {\n\n\/**\n * Return the quadratic form \\f$ B^T A B \\f$.\n *\n * Symmetry of the resulting matrix is not guaranteed due to numerical\n * precision.\n *\n * @tparam Ta type of elements in the square matrix\n * @tparam Ra number of rows in the square matrix, can be Eigen::Dynamic\n * @tparam Ca number of columns in the square matrix, can be Eigen::Dynamic\n * @tparam Tb type of elements in the second matrix\n * @tparam Rb number of rows in the second matrix, can be Eigen::Dynamic\n * @tparam Cb number of columns in the second matrix, can be Eigen::Dynamic\n *\n * @param A square matrix\n * @param B second matrix\n * @return The quadratic form, which is a symmetric matrix of size Cb.\n * @throws std::invalid_argument if A is not square, or if A cannot be\n * multiplied by B\n *\/\ntemplate ...>\ninline Eigen::Matrix, Cb, Cb> quad_form(\n const Eigen::Matrix& A, const Eigen::Matrix& B) {\n check_square(\"quad_form\", \"A\", A);\n check_multiplicable(\"quad_form\", \"A\", A, \"B\", B);\n return multiply(transpose(B), multiply(A, B));\n}\n\n\/**\n * Return the quadratic form \\f$ B^T A B \\f$.\n *\n * @tparam Ta type of elements in the square matrix\n * @tparam Ra number of rows in the square matrix, can be Eigen::Dynamic\n * @tparam Ca number of columns in the square matrix, can be Eigen::Dynamic\n * @tparam Tb type of elements in the vector\n * @tparam Rb number of rows in the vector, can be Eigen::Dynamic\n *\n * @param A square matrix\n * @param B vector\n * @return The quadratic form (a scalar).\n * @throws std::invalid_argument if A is not square, or if A cannot be\n * multiplied by B\n *\/\ntemplate ...>\ninline return_type_t quad_form(const Eigen::Matrix& A,\n const Eigen::Matrix& B) {\n check_square(\"quad_form\", \"A\", A);\n check_multiplicable(\"quad_form\", \"A\", A, \"B\", B);\n return dot_product(B, multiply(A, B));\n}\n\n} \/\/ namespace math\n} \/\/ namespace stan\n\n#endif\n<|endoftext|>"} {"text":"Revert \"Avoid bogus warnings (GCC 4.4.6)\"<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: aeitem.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: obo $ $Date: 2006-09-17 14:58:07 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_svtools.hxx\"\n#ifndef GCC\n#endif\n\n#include \n\n#define _SVSTDARR_USHORTS\n#include \n#include \n#include \"aeitem.hxx\"\n\n\/\/ STATIC DATA -----------------------------------------------------------\n\nDBG_NAME(SfxAllEnumItem)\n\nTYPEINIT1_AUTOFACTORY(SfxAllEnumItem, SfxEnumItem)\n\n\/\/ -----------------------------------------------------------------------\n\nstruct SfxAllEnumValue_Impl\n{\n USHORT nValue;\n XubString aText;\n};\n\nSV_DECL_PTRARR_DEL(SfxAllEnumValueArr, SfxAllEnumValue_Impl*, 0, 8)\nSV_IMPL_PTRARR(SfxAllEnumValueArr, SfxAllEnumValue_Impl*)\n\n\/\/ -----------------------------------------------------------------------\n\nSfxAllEnumItem::SfxAllEnumItem() :\n SfxEnumItem(),\n pValues( 0 ),\n pDisabledValues( 0 )\n{\n}\n\nSfxAllEnumItem::SfxAllEnumItem( USHORT which, USHORT nVal, const XubString &rText ):\n SfxEnumItem(which, nVal),\n pValues( 0 ),\n pDisabledValues( 0 )\n{\n DBG_CTOR(SfxAllEnumItem, 0);\n InsertValue( nVal, rText );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSfxAllEnumItem::SfxAllEnumItem(USHORT which, USHORT nVal):\n SfxEnumItem(which, nVal),\n pValues( 0 ),\n pDisabledValues( 0 )\n{\n DBG_CTOR(SfxAllEnumItem, 0);\n InsertValue( nVal );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSfxAllEnumItem::SfxAllEnumItem( USHORT which, SvStream &rStream ):\n SfxEnumItem(which, rStream),\n pValues( 0 ),\n pDisabledValues( 0 )\n{\n DBG_CTOR(SfxAllEnumItem, 0);\n InsertValue( GetValue() );\n}\n\n\/\/ -----------------------------------------------------------------------\n\n\nSfxAllEnumItem::SfxAllEnumItem(USHORT which):\n SfxEnumItem(which, 0),\n pValues( 0 ),\n pDisabledValues( 0 )\n{\n DBG_CTOR(SfxAllEnumItem, 0);\n}\n\n\n\/\/ -----------------------------------------------------------------------\n\nSfxAllEnumItem::SfxAllEnumItem(const SfxAllEnumItem &rCopy):\n SfxEnumItem(rCopy),\n pValues(0),\n pDisabledValues( 0 )\n{\n DBG_CTOR(SfxAllEnumItem, 0);\n if ( !rCopy.pValues )\n return;\n\n pValues = new SfxAllEnumValueArr;\n\n for ( USHORT nPos = 0; nPos < rCopy.pValues->Count(); ++nPos )\n {\n SfxAllEnumValue_Impl *pVal = new SfxAllEnumValue_Impl;\n pVal->nValue = rCopy.pValues->GetObject(nPos)->nValue;\n pVal->aText = rCopy.pValues->GetObject(nPos)->aText;\n const SfxAllEnumValue_Impl *pTemp = pVal;\n pValues->Insert( pTemp, nPos );\n }\n\n if( rCopy.pDisabledValues )\n {\n pDisabledValues = new SvUShorts;\n for ( USHORT nPos = 0; nPos < rCopy.pDisabledValues->Count(); ++nPos )\n {\n pDisabledValues->Insert( rCopy.pDisabledValues->GetObject(nPos),\n nPos );\n }\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSfxAllEnumItem::~SfxAllEnumItem()\n{\n DBG_DTOR(SfxAllEnumItem, 0);\n delete pValues;\n delete pDisabledValues;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nUSHORT SfxAllEnumItem::GetValueCount() const\n{\n DBG_CHKTHIS(SfxAllEnumItem, 0);\n return pValues ? pValues->Count() : 0;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nXubString SfxAllEnumItem::GetValueTextByPos( USHORT nPos ) const\n{\n DBG_CHKTHIS(SfxAllEnumItem, 0);\n DBG_ASSERT( pValues && nPos < pValues->Count(), \"enum overflow\" );\n return pValues->GetObject(nPos)->aText;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nUSHORT SfxAllEnumItem::GetValueByPos( USHORT nPos ) const\n{\n DBG_CHKTHIS(SfxAllEnumItem, 0);\n DBG_ASSERT( pValues && nPos < pValues->Count(), \"enum overflow\" );\n return pValues->GetObject(nPos)->nValue;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSfxPoolItem* SfxAllEnumItem::Clone( SfxItemPool * ) const\n{\n DBG_CHKTHIS(SfxAllEnumItem, 0);\n return new SfxAllEnumItem(*this);\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSfxPoolItem* SfxAllEnumItem::Create( SvStream & rStream, USHORT ) const\n{\n DBG_CHKTHIS(SfxAllEnumItem, 0);\n return new SfxAllEnumItem( Which(), rStream );\n}\n\n\n\/\/ -----------------------------------------------------------------------\n\nUSHORT SfxAllEnumItem::_GetPosByValue( USHORT nVal ) const\n\n\/* [Beschreibung]\n\n Im Ggs. zu liefert\n diese interne Methode bei nicht vorhandenen Values die Position,\n an der der Wert liegen w\"urde.\n*\/\n\n{\n DBG_CHKTHIS(SfxAllEnumItem, 0);\n\n if ( !pValues )\n return 0;\n\n \/\/!O: binaere Suche oder SortArray verwenden\n USHORT nPos;\n for ( nPos = 0; nPos < pValues->Count(); ++nPos )\n if ( pValues->GetObject(nPos)->nValue >= nVal )\n return nPos;\n return nPos;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nUSHORT SfxAllEnumItem::GetPosByValue( USHORT nValue ) const\n\n\/* [Beschreibung]\n\n Liefert im Gegensatz zu \n immer nValue zur\"uck, solange nicht mindestens ein Wert mit einer der\n Methoden eingef\"ugt wurde.\n*\/\n\n{\n DBG_CHKTHIS(SfxAllEnumItem, 0);\n\n if ( !pValues || !pValues->Count() )\n return nValue;\n\n return SfxEnumItem::GetPosByValue( nValue );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid SfxAllEnumItem::InsertValue( USHORT nValue, const XubString &rValue )\n{\n DBG_CHKTHIS(SfxAllEnumItem, 0);\n SfxAllEnumValue_Impl *pVal = new SfxAllEnumValue_Impl;\n pVal->nValue = nValue;\n pVal->aText = rValue;\n const SfxAllEnumValue_Impl *pTemp = pVal;\n if ( !pValues )\n pValues = new SfxAllEnumValueArr;\n else if ( GetPosByValue( nValue ) != USHRT_MAX )\n \/\/ remove when exists\n RemoveValue( nValue );\n \/\/ then insert\n pValues->Insert( pTemp, _GetPosByValue(nValue) ); \/\/! doppelte?!\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid SfxAllEnumItem::InsertValue( USHORT nValue )\n{\n DBG_CHKTHIS(SfxAllEnumItem, 0);\n SfxAllEnumValue_Impl *pVal = new SfxAllEnumValue_Impl;\n pVal->nValue = nValue;\n pVal->aText = XubString::CreateFromInt32( nValue );\n const SfxAllEnumValue_Impl *pTemp = pVal;\n if ( !pValues )\n pValues = new SfxAllEnumValueArr;\n\n pValues->Insert( pTemp, _GetPosByValue(nValue) ); \/\/! doppelte?!\n}\n\nvoid SfxAllEnumItem::DisableValue( USHORT nValue )\n{\n DBG_CHKTHIS(SfxAllEnumItem, 0);\n if ( !pDisabledValues )\n pDisabledValues = new SvUShorts;\n\n pDisabledValues->Insert( nValue, pDisabledValues->Count() );\n}\n\nBOOL SfxAllEnumItem::IsEnabled( USHORT nValue ) const\n{\n if ( pDisabledValues )\n {\n for ( USHORT i=0; iCount(); i++ )\n if ( (*pDisabledValues)[i] == nValue )\n return FALSE;\n }\n\n return TRUE;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid SfxAllEnumItem::RemoveValue( USHORT nValue )\n{\n DBG_CHKTHIS(SfxAllEnumItem, 0);\n USHORT nPos = GetPosByValue(nValue);\n DBG_ASSERT( nPos != USHRT_MAX, \"removing value not in enum\" );\n pValues->Remove( nPos );\n}\n\n\/\/ -----------------------------------------------------------------------\n\n\nvoid SfxAllEnumItem::RemoveAllValues()\n{\n DBG_CHKTHIS(SfxAllEnumItem, 0);\n if ( pValues )\n pValues->DeleteAndDestroy( 0, pValues->Count() );\n}\n\n\n\nINTEGRATION: CWS vgbugs07 (1.9.200); FILE MERGED 2007\/06\/04 13:31:38 vg 1.9.200.1: #i76605# Remove -I ...\/inc\/module hack introduced by hedaburemove01\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: aeitem.cxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: hr $ $Date: 2007-06-27 21:38:06 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_svtools.hxx\"\n#ifndef GCC\n#endif\n\n#include \n\n#define _SVSTDARR_USHORTS\n#include \n#include \n#include \n\n\/\/ STATIC DATA -----------------------------------------------------------\n\nDBG_NAME(SfxAllEnumItem)\n\nTYPEINIT1_AUTOFACTORY(SfxAllEnumItem, SfxEnumItem)\n\n\/\/ -----------------------------------------------------------------------\n\nstruct SfxAllEnumValue_Impl\n{\n USHORT nValue;\n XubString aText;\n};\n\nSV_DECL_PTRARR_DEL(SfxAllEnumValueArr, SfxAllEnumValue_Impl*, 0, 8)\nSV_IMPL_PTRARR(SfxAllEnumValueArr, SfxAllEnumValue_Impl*)\n\n\/\/ -----------------------------------------------------------------------\n\nSfxAllEnumItem::SfxAllEnumItem() :\n SfxEnumItem(),\n pValues( 0 ),\n pDisabledValues( 0 )\n{\n}\n\nSfxAllEnumItem::SfxAllEnumItem( USHORT which, USHORT nVal, const XubString &rText ):\n SfxEnumItem(which, nVal),\n pValues( 0 ),\n pDisabledValues( 0 )\n{\n DBG_CTOR(SfxAllEnumItem, 0);\n InsertValue( nVal, rText );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSfxAllEnumItem::SfxAllEnumItem(USHORT which, USHORT nVal):\n SfxEnumItem(which, nVal),\n pValues( 0 ),\n pDisabledValues( 0 )\n{\n DBG_CTOR(SfxAllEnumItem, 0);\n InsertValue( nVal );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSfxAllEnumItem::SfxAllEnumItem( USHORT which, SvStream &rStream ):\n SfxEnumItem(which, rStream),\n pValues( 0 ),\n pDisabledValues( 0 )\n{\n DBG_CTOR(SfxAllEnumItem, 0);\n InsertValue( GetValue() );\n}\n\n\/\/ -----------------------------------------------------------------------\n\n\nSfxAllEnumItem::SfxAllEnumItem(USHORT which):\n SfxEnumItem(which, 0),\n pValues( 0 ),\n pDisabledValues( 0 )\n{\n DBG_CTOR(SfxAllEnumItem, 0);\n}\n\n\n\/\/ -----------------------------------------------------------------------\n\nSfxAllEnumItem::SfxAllEnumItem(const SfxAllEnumItem &rCopy):\n SfxEnumItem(rCopy),\n pValues(0),\n pDisabledValues( 0 )\n{\n DBG_CTOR(SfxAllEnumItem, 0);\n if ( !rCopy.pValues )\n return;\n\n pValues = new SfxAllEnumValueArr;\n\n for ( USHORT nPos = 0; nPos < rCopy.pValues->Count(); ++nPos )\n {\n SfxAllEnumValue_Impl *pVal = new SfxAllEnumValue_Impl;\n pVal->nValue = rCopy.pValues->GetObject(nPos)->nValue;\n pVal->aText = rCopy.pValues->GetObject(nPos)->aText;\n const SfxAllEnumValue_Impl *pTemp = pVal;\n pValues->Insert( pTemp, nPos );\n }\n\n if( rCopy.pDisabledValues )\n {\n pDisabledValues = new SvUShorts;\n for ( USHORT nPos = 0; nPos < rCopy.pDisabledValues->Count(); ++nPos )\n {\n pDisabledValues->Insert( rCopy.pDisabledValues->GetObject(nPos),\n nPos );\n }\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSfxAllEnumItem::~SfxAllEnumItem()\n{\n DBG_DTOR(SfxAllEnumItem, 0);\n delete pValues;\n delete pDisabledValues;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nUSHORT SfxAllEnumItem::GetValueCount() const\n{\n DBG_CHKTHIS(SfxAllEnumItem, 0);\n return pValues ? pValues->Count() : 0;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nXubString SfxAllEnumItem::GetValueTextByPos( USHORT nPos ) const\n{\n DBG_CHKTHIS(SfxAllEnumItem, 0);\n DBG_ASSERT( pValues && nPos < pValues->Count(), \"enum overflow\" );\n return pValues->GetObject(nPos)->aText;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nUSHORT SfxAllEnumItem::GetValueByPos( USHORT nPos ) const\n{\n DBG_CHKTHIS(SfxAllEnumItem, 0);\n DBG_ASSERT( pValues && nPos < pValues->Count(), \"enum overflow\" );\n return pValues->GetObject(nPos)->nValue;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSfxPoolItem* SfxAllEnumItem::Clone( SfxItemPool * ) const\n{\n DBG_CHKTHIS(SfxAllEnumItem, 0);\n return new SfxAllEnumItem(*this);\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSfxPoolItem* SfxAllEnumItem::Create( SvStream & rStream, USHORT ) const\n{\n DBG_CHKTHIS(SfxAllEnumItem, 0);\n return new SfxAllEnumItem( Which(), rStream );\n}\n\n\n\/\/ -----------------------------------------------------------------------\n\nUSHORT SfxAllEnumItem::_GetPosByValue( USHORT nVal ) const\n\n\/* [Beschreibung]\n\n Im Ggs. zu liefert\n diese interne Methode bei nicht vorhandenen Values die Position,\n an der der Wert liegen w\"urde.\n*\/\n\n{\n DBG_CHKTHIS(SfxAllEnumItem, 0);\n\n if ( !pValues )\n return 0;\n\n \/\/!O: binaere Suche oder SortArray verwenden\n USHORT nPos;\n for ( nPos = 0; nPos < pValues->Count(); ++nPos )\n if ( pValues->GetObject(nPos)->nValue >= nVal )\n return nPos;\n return nPos;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nUSHORT SfxAllEnumItem::GetPosByValue( USHORT nValue ) const\n\n\/* [Beschreibung]\n\n Liefert im Gegensatz zu \n immer nValue zur\"uck, solange nicht mindestens ein Wert mit einer der\n Methoden eingef\"ugt wurde.\n*\/\n\n{\n DBG_CHKTHIS(SfxAllEnumItem, 0);\n\n if ( !pValues || !pValues->Count() )\n return nValue;\n\n return SfxEnumItem::GetPosByValue( nValue );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid SfxAllEnumItem::InsertValue( USHORT nValue, const XubString &rValue )\n{\n DBG_CHKTHIS(SfxAllEnumItem, 0);\n SfxAllEnumValue_Impl *pVal = new SfxAllEnumValue_Impl;\n pVal->nValue = nValue;\n pVal->aText = rValue;\n const SfxAllEnumValue_Impl *pTemp = pVal;\n if ( !pValues )\n pValues = new SfxAllEnumValueArr;\n else if ( GetPosByValue( nValue ) != USHRT_MAX )\n \/\/ remove when exists\n RemoveValue( nValue );\n \/\/ then insert\n pValues->Insert( pTemp, _GetPosByValue(nValue) ); \/\/! doppelte?!\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid SfxAllEnumItem::InsertValue( USHORT nValue )\n{\n DBG_CHKTHIS(SfxAllEnumItem, 0);\n SfxAllEnumValue_Impl *pVal = new SfxAllEnumValue_Impl;\n pVal->nValue = nValue;\n pVal->aText = XubString::CreateFromInt32( nValue );\n const SfxAllEnumValue_Impl *pTemp = pVal;\n if ( !pValues )\n pValues = new SfxAllEnumValueArr;\n\n pValues->Insert( pTemp, _GetPosByValue(nValue) ); \/\/! doppelte?!\n}\n\nvoid SfxAllEnumItem::DisableValue( USHORT nValue )\n{\n DBG_CHKTHIS(SfxAllEnumItem, 0);\n if ( !pDisabledValues )\n pDisabledValues = new SvUShorts;\n\n pDisabledValues->Insert( nValue, pDisabledValues->Count() );\n}\n\nBOOL SfxAllEnumItem::IsEnabled( USHORT nValue ) const\n{\n if ( pDisabledValues )\n {\n for ( USHORT i=0; iCount(); i++ )\n if ( (*pDisabledValues)[i] == nValue )\n return FALSE;\n }\n\n return TRUE;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid SfxAllEnumItem::RemoveValue( USHORT nValue )\n{\n DBG_CHKTHIS(SfxAllEnumItem, 0);\n USHORT nPos = GetPosByValue(nValue);\n DBG_ASSERT( nPos != USHRT_MAX, \"removing value not in enum\" );\n pValues->Remove( nPos );\n}\n\n\/\/ -----------------------------------------------------------------------\n\n\nvoid SfxAllEnumItem::RemoveAllValues()\n{\n DBG_CHKTHIS(SfxAllEnumItem, 0);\n if ( pValues )\n pValues->DeleteAndDestroy( 0, pValues->Count() );\n}\n\n\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: ddeimp.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: vg $ $Date: 2007-09-20 16:30:19 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _DDEIMP_HXX\n#define _DDEIMP_HXX\n\n#ifdef OS2\n\n#include \"ddemlos2.h\"\n\n#define WORD USHORT\n#define DWORD ULONG\n#define LPBYTE BYTE*\n#define LPWORD USHORT*\n#define LPDWORD ULONG*\n#define LPCTSTR PCSZ\n\n#else\n\n#include \n#include \n#include \n#include \"ddewrap.hxx\"\n\n\/*\nextern \"C\"\n{\n#define BOOL WIN_BOOL\n#define BYTE WIN_BYTE\n#undef BOOL\n#undef BYTE\n};\n*\/\n\n#endif\n\n#ifndef _STRING_HXX \/\/autogen\n#include \n#endif\n#ifndef _LIST_HXX \/\/autogen\n#include \n#endif\n#ifndef _SHL_HXX \/\/autogen\n#include \n#endif\n\nclass DdeService;\nclass DdeTopic;\nclass DdeItem;\nclass DdeTopics;\nclass DdeItems;\n\n\/\/ ----------------\n\/\/ - Conversation -\n\/\/ ----------------\n\nstruct Conversation\n{\n HCONV hConv;\n DdeTopic* pTopic;\n};\n\nDECLARE_LIST( ConvList, Conversation* );\n\n\/\/ ---------------\n\/\/ - DdeInternal -\n\/\/ ---------------\n\nclass DdeInternal\n{\npublic:\n#ifdef WNT\n static HDDEDATA CALLBACK CliCallback\n ( WORD, WORD, HCONV, HSZ, HSZ, HDDEDATA, DWORD, DWORD );\n static HDDEDATA CALLBACK SvrCallback\n ( WORD, WORD, HCONV, HSZ, HSZ, HDDEDATA, DWORD, DWORD );\n static HDDEDATA CALLBACK InfCallback\n ( WORD, WORD, HCONV, HSZ, HSZ, HDDEDATA, DWORD, DWORD );\n#else\n#if defined ( MTW ) || ( defined ( GCC ) && defined ( OS2 )) || defined( ICC )\n static HDDEDATA CALLBACK __EXPORT CliCallback\n ( WORD, WORD, HCONV, HSZ, HSZ, HDDEDATA, DWORD, DWORD );\n static HDDEDATA CALLBACK __EXPORT SvrCallback\n ( WORD, WORD, HCONV, HSZ, HSZ, HDDEDATA, DWORD, DWORD );\n static HDDEDATA CALLBACK __EXPORT InfCallback\n ( WORD, WORD, HCONV, HSZ, HSZ, HDDEDATA, DWORD, DWORD );\n#else\n static HDDEDATA CALLBACK _export CliCallback\n ( WORD, WORD, HCONV, HSZ, HSZ, HDDEDATA, DWORD, DWORD );\n static HDDEDATA CALLBACK _export SvrCallback\n ( WORD, WORD, HCONV, HSZ, HSZ, HDDEDATA, DWORD, DWORD );\n static HDDEDATA CALLBACK _export InfCallback\n ( WORD, WORD, HCONV, HSZ, HSZ, HDDEDATA, DWORD, DWORD );\n#endif\n#endif\n static DdeService* FindService( HSZ );\n static DdeTopic* FindTopic( DdeService&, HSZ );\n static DdeItem* FindItem( DdeTopic&, HSZ );\n};\n\n\/\/ -------------\n\/\/ - DdeString -\n\/\/ -------------\n\nclass DdeString : public String\n{\nprotected:\n HSZ hString;\n DWORD hInst;\n\npublic:\n DdeString( DWORD, const sal_Unicode* );\n DdeString( DWORD, const String& );\n ~DdeString();\n\n int operator==( HSZ );\n operator HSZ();\n};\n\n\/\/ --------------\n\/\/ - DdeDataImp -\n\/\/ --------------\n\nstruct DdeDataImp\n{\n HDDEDATA hData;\n LPBYTE pData;\n long nData;\n ULONG nFmt;\n};\n\nclass DdeConnections;\nclass DdeServices;\n\nstruct DdeInstData\n{\n USHORT nRefCount;\n DdeConnections* pConnections;\n \/\/ Server\n long hCurConvSvr;\n ULONG hDdeInstSvr;\n short nInstanceSvr;\n DdeServices* pServicesSvr;\n \/\/ Client\n ULONG hDdeInstCli;\n short nInstanceCli;\n};\n\n#ifndef SHL_SVDDE\n#define SHL_SVDDE SHL_SHL2\n#endif\n\ninline DdeInstData* ImpGetInstData()\n{\n return (DdeInstData*)(*GetAppData( SHL_SVDDE ));\n}\nDdeInstData* ImpInitInstData();\nvoid ImpDeinitInstData();\n\n#endif \/\/ _DDEIMP_HXX\nINTEGRATION: CWS changefileheader (1.6.170); FILE MERGED 2008\/04\/01 15:45:28 thb 1.6.170.2: #i85898# Stripping all external header guards 2008\/03\/31 13:02:31 rt 1.6.170.1: #i87441# Change license header to LPGL v3.\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: ddeimp.hxx,v $\n * $Revision: 1.7 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _DDEIMP_HXX\n#define _DDEIMP_HXX\n\n#ifdef OS2\n\n#include \"ddemlos2.h\"\n\n#define WORD USHORT\n#define DWORD ULONG\n#define LPBYTE BYTE*\n#define LPWORD USHORT*\n#define LPDWORD ULONG*\n#define LPCTSTR PCSZ\n\n#else\n\n#include \n#include \n#include \n#include \"ddewrap.hxx\"\n\n\/*\nextern \"C\"\n{\n#define BOOL WIN_BOOL\n#define BYTE WIN_BYTE\n#undef BOOL\n#undef BYTE\n};\n*\/\n\n#endif\n#include \n#include \n#include \n\nclass DdeService;\nclass DdeTopic;\nclass DdeItem;\nclass DdeTopics;\nclass DdeItems;\n\n\/\/ ----------------\n\/\/ - Conversation -\n\/\/ ----------------\n\nstruct Conversation\n{\n HCONV hConv;\n DdeTopic* pTopic;\n};\n\nDECLARE_LIST( ConvList, Conversation* );\n\n\/\/ ---------------\n\/\/ - DdeInternal -\n\/\/ ---------------\n\nclass DdeInternal\n{\npublic:\n#ifdef WNT\n static HDDEDATA CALLBACK CliCallback\n ( WORD, WORD, HCONV, HSZ, HSZ, HDDEDATA, DWORD, DWORD );\n static HDDEDATA CALLBACK SvrCallback\n ( WORD, WORD, HCONV, HSZ, HSZ, HDDEDATA, DWORD, DWORD );\n static HDDEDATA CALLBACK InfCallback\n ( WORD, WORD, HCONV, HSZ, HSZ, HDDEDATA, DWORD, DWORD );\n#else\n#if defined ( MTW ) || ( defined ( GCC ) && defined ( OS2 )) || defined( ICC )\n static HDDEDATA CALLBACK __EXPORT CliCallback\n ( WORD, WORD, HCONV, HSZ, HSZ, HDDEDATA, DWORD, DWORD );\n static HDDEDATA CALLBACK __EXPORT SvrCallback\n ( WORD, WORD, HCONV, HSZ, HSZ, HDDEDATA, DWORD, DWORD );\n static HDDEDATA CALLBACK __EXPORT InfCallback\n ( WORD, WORD, HCONV, HSZ, HSZ, HDDEDATA, DWORD, DWORD );\n#else\n static HDDEDATA CALLBACK _export CliCallback\n ( WORD, WORD, HCONV, HSZ, HSZ, HDDEDATA, DWORD, DWORD );\n static HDDEDATA CALLBACK _export SvrCallback\n ( WORD, WORD, HCONV, HSZ, HSZ, HDDEDATA, DWORD, DWORD );\n static HDDEDATA CALLBACK _export InfCallback\n ( WORD, WORD, HCONV, HSZ, HSZ, HDDEDATA, DWORD, DWORD );\n#endif\n#endif\n static DdeService* FindService( HSZ );\n static DdeTopic* FindTopic( DdeService&, HSZ );\n static DdeItem* FindItem( DdeTopic&, HSZ );\n};\n\n\/\/ -------------\n\/\/ - DdeString -\n\/\/ -------------\n\nclass DdeString : public String\n{\nprotected:\n HSZ hString;\n DWORD hInst;\n\npublic:\n DdeString( DWORD, const sal_Unicode* );\n DdeString( DWORD, const String& );\n ~DdeString();\n\n int operator==( HSZ );\n operator HSZ();\n};\n\n\/\/ --------------\n\/\/ - DdeDataImp -\n\/\/ --------------\n\nstruct DdeDataImp\n{\n HDDEDATA hData;\n LPBYTE pData;\n long nData;\n ULONG nFmt;\n};\n\nclass DdeConnections;\nclass DdeServices;\n\nstruct DdeInstData\n{\n USHORT nRefCount;\n DdeConnections* pConnections;\n \/\/ Server\n long hCurConvSvr;\n ULONG hDdeInstSvr;\n short nInstanceSvr;\n DdeServices* pServicesSvr;\n \/\/ Client\n ULONG hDdeInstCli;\n short nInstanceCli;\n};\n\n#ifndef SHL_SVDDE\n#define SHL_SVDDE SHL_SHL2\n#endif\n\ninline DdeInstData* ImpGetInstData()\n{\n return (DdeInstData*)(*GetAppData( SHL_SVDDE ));\n}\nDdeInstData* ImpInitInstData();\nvoid ImpDeinitInstData();\n\n#endif \/\/ _DDEIMP_HXX\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: unoctabl.cxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: rt $ $Date: 2003-09-19 08:32:58 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_\n#include \n#endif\n\n#include \n\n#include \"xtable.hxx\"\n#include \"unoshcol.hxx\"\n\nusing namespace ::com::sun::star;\nusing namespace ::rtl;\nusing namespace ::cppu;\n\nclass SvxUnoColorTable : public WeakImplHelper2< container::XNameContainer, lang::XServiceInfo >\n{\nprivate:\n XColorTable* pTable;\n\npublic:\n SvxUnoColorTable() throw();\n virtual ~SvxUnoColorTable() throw();\n\n \/\/ XServiceInfo\n virtual OUString SAL_CALL getImplementationName( ) throw( uno::RuntimeException );\n virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName ) throw( uno::RuntimeException);\n virtual uno::Sequence< OUString > SAL_CALL getSupportedServiceNames( ) throw( uno::RuntimeException);\n\n static OUString getImplementationName_Static() throw()\n {\n return OUString(RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.drawing.SvxUnoColorTable\"));\n }\n\n static uno::Sequence< OUString > getSupportedServiceNames_Static(void) throw();\n\n \/\/ XNameContainer\n virtual void SAL_CALL insertByName( const OUString& aName, const uno::Any& aElement ) throw( lang::IllegalArgumentException, container::ElementExistException, lang::WrappedTargetException, uno::RuntimeException);\n virtual void SAL_CALL removeByName( const OUString& Name ) throw( container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException);\n\n \/\/ XNameReplace\n virtual void SAL_CALL replaceByName( const OUString& aName, const uno::Any& aElement ) throw( lang::IllegalArgumentException, container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException);\n\n \/\/ XNameAccess\n virtual uno::Any SAL_CALL getByName( const OUString& aName ) throw( container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException);\n\n virtual uno::Sequence< OUString > SAL_CALL getElementNames( ) throw( uno::RuntimeException);\n\n virtual sal_Bool SAL_CALL hasByName( const OUString& aName ) throw( uno::RuntimeException);\n\n \/\/ XElementAccess\n virtual uno::Type SAL_CALL getElementType( ) throw( uno::RuntimeException);\n virtual sal_Bool SAL_CALL hasElements( ) throw( uno::RuntimeException);\n};\n\nSvxUnoColorTable::SvxUnoColorTable() throw()\n{\n pTable = new XColorTable( SvtPathOptions().GetPalettePath() );\n}\n\nSvxUnoColorTable::~SvxUnoColorTable() throw()\n{\n delete pTable;\n}\n\nsal_Bool SAL_CALL SvxUnoColorTable::supportsService( const OUString& ServiceName ) throw(uno::RuntimeException)\n{\n uno::Sequence< OUString > aSNL( getSupportedServiceNames() );\n const OUString * pArray = aSNL.getConstArray();\n\n for( INT32 i = 0; i < aSNL.getLength(); i++ )\n if( pArray[i] == ServiceName )\n return TRUE;\n\n return FALSE;\n}\n\nOUString SAL_CALL SvxUnoColorTable::getImplementationName() throw( uno::RuntimeException )\n{\n return OUString( RTL_CONSTASCII_USTRINGPARAM(\"SvxUnoColorTable\") );\n}\n\nuno::Sequence< OUString > SAL_CALL SvxUnoColorTable::getSupportedServiceNames( )\n throw( uno::RuntimeException )\n{\n return getSupportedServiceNames_Static();\n}\n\nuno::Sequence< OUString > SvxUnoColorTable::getSupportedServiceNames_Static(void) throw()\n{\n uno::Sequence< OUString > aSNS( 1 );\n aSNS.getArray()[0] = OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.drawing.ColorTable\" ));\n return aSNS;\n}\n\n\/\/ XNameContainer\nvoid SAL_CALL SvxUnoColorTable::insertByName( const OUString& aName, const uno::Any& aElement )\n throw( lang::IllegalArgumentException, container::ElementExistException, lang::WrappedTargetException, uno::RuntimeException )\n{\n if( hasByName( aName ) )\n throw container::ElementExistException();\n\n INT32 nColor;\n if( aElement >>= nColor )\n throw lang::IllegalArgumentException();\n\n if( pTable )\n {\n XColorEntry* pEntry = new XColorEntry( Color( (ColorData)nColor ), aName );\n pTable->Insert( pTable->Count(), pEntry );\n }\n}\n\nvoid SAL_CALL SvxUnoColorTable::removeByName( const OUString& Name )\n throw( container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException)\n{\n long nIndex = pTable ? ((XPropertyTable*)pTable)->Get( Name ) : -1;\n if( nIndex == -1 )\n throw container::NoSuchElementException();\n\n pTable->Remove( nIndex );\n}\n\n\/\/ XNameReplace\nvoid SAL_CALL SvxUnoColorTable::replaceByName( const OUString& aName, const uno::Any& aElement )\n throw( lang::IllegalArgumentException, container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException )\n{\n INT32 nColor;\n if( aElement >>= nColor )\n throw lang::IllegalArgumentException();\n\n long nIndex = pTable ? ((XPropertyTable*)pTable)->Get( aName ) : -1;\n if( nIndex == -1 )\n throw container::NoSuchElementException();\n\n XColorEntry* pEntry = new XColorEntry( Color( (ColorData)nColor ), aName );\n delete pTable->Replace( nIndex, pEntry );\n}\n\n\/\/ XNameAccess\nuno::Any SAL_CALL SvxUnoColorTable::getByName( const OUString& aName )\n throw( container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException)\n{\n long nIndex = pTable ? ((XPropertyTable*)pTable)->Get( aName ) : -1;\n if( nIndex == -1 )\n throw container::NoSuchElementException();\n\n XColorEntry* pEntry = pTable->Get( nIndex );\n uno::Any aAny;\n aAny <<= (sal_Int32) pEntry->GetColor().GetRGBColor();\n return aAny;\n}\n\nuno::Sequence< OUString > SAL_CALL SvxUnoColorTable::getElementNames( )\n throw( uno::RuntimeException )\n{\n const long nCount = pTable ? pTable->Count() : 0;\n\n uno::Sequence< OUString > aSeq( nCount );\n OUString* pStrings = aSeq.getArray();\n\n for( long nIndex = 0; nIndex < nCount; nIndex++ )\n {\n XColorEntry* pEntry = pTable->Get( nIndex );\n pStrings[nIndex] = pEntry->GetName();\n }\n\n return aSeq;\n}\n\nsal_Bool SAL_CALL SvxUnoColorTable::hasByName( const OUString& aName )\n throw( uno::RuntimeException )\n{\n long nIndex = pTable ? ((XPropertyTable*)pTable)->Get( aName ) : -1;\n return nIndex != -1;\n}\n\n\/\/ XElementAccess\nuno::Type SAL_CALL SvxUnoColorTable::getElementType( )\n throw( uno::RuntimeException )\n{\n return ::getCppuType((const sal_Int32*)0);\n}\n\nsal_Bool SAL_CALL SvxUnoColorTable::hasElements( )\n throw( uno::RuntimeException )\n{\n return pTable && pTable->Count() != 0;\n}\n\n\/**\n * Create a colortable\n *\/\nuno::Reference< uno::XInterface > SAL_CALL SvxUnoColorTable_createInstance(const uno::Reference< lang::XMultiServiceFactory > & rSMgr) throw(uno::Exception)\n{\n return *new SvxUnoColorTable();\n}\n\n\/\/\n\/\/ export this service\n\/\/\n\n#ifndef SVX_LIGHT\n#include \"UnoGraphicExporter.hxx\"\n#endif\n\n#ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_\n#include \n#endif\n\n#ifndef _OSL_DIAGNOSE_H_\n#include \n#endif\n\n#include \n#include \n\nextern \"C\"\n{\n\nvoid SAL_CALL component_getImplementationEnvironment( const sal_Char ** ppEnvTypeName, uno_Environment ** ppEnv )\n{\n *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;\n}\n\nvoid SAL_CALL writeInfo( registry::XRegistryKey * pRegistryKey, const OUString& rImplementationName, const uno::Sequence< OUString >& rServices )\n{\n uno::Reference< registry::XRegistryKey > xNewKey(\n pRegistryKey->createKey(\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"\/\") ) + rImplementationName + OUString(RTL_CONSTASCII_USTRINGPARAM( \"\/UNO\/SERVICES\") ) ) );\n\n for( sal_Int32 i = 0; i < rServices.getLength(); i++ )\n xNewKey->createKey( rServices.getConstArray()[i]);\n}\n\nsal_Bool SAL_CALL component_writeInfo( void * pServiceManager, void * pRegistryKey )\n{\n if( pRegistryKey )\n {\n try\n {\n registry::XRegistryKey *pKey = reinterpret_cast< registry::XRegistryKey * >( pRegistryKey );\n\n writeInfo( pKey, SvxShapeCollection::getImplementationName_Static(), SvxShapeCollection::getSupportedServiceNames_Static() );\n writeInfo( pKey, SvxUnoColorTable::getImplementationName_Static(), SvxUnoColorTable::getSupportedServiceNames_Static() );\n#ifndef SVX_LIGHT\n writeInfo( pKey, svx::GraphicExporter_getImplementationName(), svx::GraphicExporter_getSupportedServiceNames() );\n#endif\n }\n catch (registry::InvalidRegistryException &)\n {\n OSL_ENSURE( sal_False, \"### InvalidRegistryException!\" );\n }\n }\n\n return sal_True;\n}\n\nvoid * SAL_CALL component_getFactory( const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey )\n{\n void * pRet = 0;\n if( pServiceManager )\n {\n uno::Reference< lang::XSingleServiceFactory > xFactory;\n\n if( rtl_str_compare( pImplName, \"com.sun.star.drawing.SvxUnoColorTable\" ) == 0 )\n {\n xFactory = createSingleFactory( reinterpret_cast< lang::XMultiServiceFactory * >( pServiceManager ),\n SvxUnoColorTable::getImplementationName_Static(),\n SvxUnoColorTable_createInstance,\n SvxUnoColorTable::getSupportedServiceNames_Static() );\n }\n else if( rtl_str_compare( pImplName, \"com.sun.star.drawing.SvxShapeCollection\" ) == 0 )\n {\n xFactory = createSingleFactory( reinterpret_cast< lang::XMultiServiceFactory * >( pServiceManager ),\n SvxShapeCollection::getImplementationName_Static(),\n SvxShapeCollection_createInstance,\n SvxShapeCollection::getSupportedServiceNames_Static() );\n }\n#ifndef SVX_LIGHT\n else if( svx::GraphicExporter_getImplementationName().equalsAscii( pImplName ) )\n {\n xFactory = ::cppu::createSingleFactory( reinterpret_cast< lang::XMultiServiceFactory * >( pServiceManager ),\n svx::GraphicExporter_getImplementationName(),\n svx::GraphicExporter_createInstance,\n svx::GraphicExporter_getSupportedServiceNames() );\n }\n#endif\n if( xFactory.is())\n {\n xFactory->acquire();\n pRet = xFactory.get();\n }\n }\n\n return pRet;\n}\n\n}\n\n\nINTEGRATION: CWS sj05 (1.7.410); FILE MERGED 2004\/02\/05 17:25:00 sj 1.7.410.4: name changes 2003\/11\/27 16:46:21 sj 1.7.410.3: RESYNC: (1.7-1.8); FILE MERGED 2003\/10\/24 15:07:41 sj 1.7.410.2: fixed upper\/lower case include mismatch 2003\/09\/12 17:03:02 sj 1.7.410.1: added autoshape functionality\/*************************************************************************\n *\n * $RCSfile: unoctabl.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: rt $ $Date: 2004-04-02 14:17:02 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_\n#include \n#endif\n#include \"..\/customshapes\/EnhancedCustomShapeEngine.hxx\"\n#include \n\n#include \"xtable.hxx\"\n#include \"unoshcol.hxx\"\n\nusing namespace ::com::sun::star;\nusing namespace ::rtl;\nusing namespace ::cppu;\n\nclass SvxUnoColorTable : public WeakImplHelper2< container::XNameContainer, lang::XServiceInfo >\n{\nprivate:\n XColorTable* pTable;\n\npublic:\n SvxUnoColorTable() throw();\n virtual ~SvxUnoColorTable() throw();\n\n \/\/ XServiceInfo\n virtual OUString SAL_CALL getImplementationName( ) throw( uno::RuntimeException );\n virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName ) throw( uno::RuntimeException);\n virtual uno::Sequence< OUString > SAL_CALL getSupportedServiceNames( ) throw( uno::RuntimeException);\n\n static OUString getImplementationName_Static() throw()\n {\n return OUString(RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.drawing.SvxUnoColorTable\"));\n }\n\n static uno::Sequence< OUString > getSupportedServiceNames_Static(void) throw();\n\n \/\/ XNameContainer\n virtual void SAL_CALL insertByName( const OUString& aName, const uno::Any& aElement ) throw( lang::IllegalArgumentException, container::ElementExistException, lang::WrappedTargetException, uno::RuntimeException);\n virtual void SAL_CALL removeByName( const OUString& Name ) throw( container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException);\n\n \/\/ XNameReplace\n virtual void SAL_CALL replaceByName( const OUString& aName, const uno::Any& aElement ) throw( lang::IllegalArgumentException, container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException);\n\n \/\/ XNameAccess\n virtual uno::Any SAL_CALL getByName( const OUString& aName ) throw( container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException);\n\n virtual uno::Sequence< OUString > SAL_CALL getElementNames( ) throw( uno::RuntimeException);\n\n virtual sal_Bool SAL_CALL hasByName( const OUString& aName ) throw( uno::RuntimeException);\n\n \/\/ XElementAccess\n virtual uno::Type SAL_CALL getElementType( ) throw( uno::RuntimeException);\n virtual sal_Bool SAL_CALL hasElements( ) throw( uno::RuntimeException);\n};\n\nSvxUnoColorTable::SvxUnoColorTable() throw()\n{\n pTable = new XColorTable( SvtPathOptions().GetPalettePath() );\n}\n\nSvxUnoColorTable::~SvxUnoColorTable() throw()\n{\n delete pTable;\n}\n\nsal_Bool SAL_CALL SvxUnoColorTable::supportsService( const OUString& ServiceName ) throw(uno::RuntimeException)\n{\n uno::Sequence< OUString > aSNL( getSupportedServiceNames() );\n const OUString * pArray = aSNL.getConstArray();\n\n for( INT32 i = 0; i < aSNL.getLength(); i++ )\n if( pArray[i] == ServiceName )\n return TRUE;\n\n return FALSE;\n}\n\nOUString SAL_CALL SvxUnoColorTable::getImplementationName() throw( uno::RuntimeException )\n{\n return OUString( RTL_CONSTASCII_USTRINGPARAM(\"SvxUnoColorTable\") );\n}\n\nuno::Sequence< OUString > SAL_CALL SvxUnoColorTable::getSupportedServiceNames( )\n throw( uno::RuntimeException )\n{\n return getSupportedServiceNames_Static();\n}\n\nuno::Sequence< OUString > SvxUnoColorTable::getSupportedServiceNames_Static(void) throw()\n{\n uno::Sequence< OUString > aSNS( 1 );\n aSNS.getArray()[0] = OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.drawing.ColorTable\" ));\n return aSNS;\n}\n\n\/\/ XNameContainer\nvoid SAL_CALL SvxUnoColorTable::insertByName( const OUString& aName, const uno::Any& aElement )\n throw( lang::IllegalArgumentException, container::ElementExistException, lang::WrappedTargetException, uno::RuntimeException )\n{\n if( hasByName( aName ) )\n throw container::ElementExistException();\n\n INT32 nColor;\n if( aElement >>= nColor )\n throw lang::IllegalArgumentException();\n\n if( pTable )\n {\n XColorEntry* pEntry = new XColorEntry( Color( (ColorData)nColor ), aName );\n pTable->Insert( pTable->Count(), pEntry );\n }\n}\n\nvoid SAL_CALL SvxUnoColorTable::removeByName( const OUString& Name )\n throw( container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException)\n{\n long nIndex = pTable ? ((XPropertyTable*)pTable)->Get( Name ) : -1;\n if( nIndex == -1 )\n throw container::NoSuchElementException();\n\n pTable->Remove( nIndex );\n}\n\n\/\/ XNameReplace\nvoid SAL_CALL SvxUnoColorTable::replaceByName( const OUString& aName, const uno::Any& aElement )\n throw( lang::IllegalArgumentException, container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException )\n{\n INT32 nColor;\n if( aElement >>= nColor )\n throw lang::IllegalArgumentException();\n\n long nIndex = pTable ? ((XPropertyTable*)pTable)->Get( aName ) : -1;\n if( nIndex == -1 )\n throw container::NoSuchElementException();\n\n XColorEntry* pEntry = new XColorEntry( Color( (ColorData)nColor ), aName );\n delete pTable->Replace( nIndex, pEntry );\n}\n\n\/\/ XNameAccess\nuno::Any SAL_CALL SvxUnoColorTable::getByName( const OUString& aName )\n throw( container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException)\n{\n long nIndex = pTable ? ((XPropertyTable*)pTable)->Get( aName ) : -1;\n if( nIndex == -1 )\n throw container::NoSuchElementException();\n\n XColorEntry* pEntry = pTable->Get( nIndex );\n uno::Any aAny;\n aAny <<= (sal_Int32) pEntry->GetColor().GetRGBColor();\n return aAny;\n}\n\nuno::Sequence< OUString > SAL_CALL SvxUnoColorTable::getElementNames( )\n throw( uno::RuntimeException )\n{\n const long nCount = pTable ? pTable->Count() : 0;\n\n uno::Sequence< OUString > aSeq( nCount );\n OUString* pStrings = aSeq.getArray();\n\n for( long nIndex = 0; nIndex < nCount; nIndex++ )\n {\n XColorEntry* pEntry = pTable->Get( nIndex );\n pStrings[nIndex] = pEntry->GetName();\n }\n\n return aSeq;\n}\n\nsal_Bool SAL_CALL SvxUnoColorTable::hasByName( const OUString& aName )\n throw( uno::RuntimeException )\n{\n long nIndex = pTable ? ((XPropertyTable*)pTable)->Get( aName ) : -1;\n return nIndex != -1;\n}\n\n\/\/ XElementAccess\nuno::Type SAL_CALL SvxUnoColorTable::getElementType( )\n throw( uno::RuntimeException )\n{\n return ::getCppuType((const sal_Int32*)0);\n}\n\nsal_Bool SAL_CALL SvxUnoColorTable::hasElements( )\n throw( uno::RuntimeException )\n{\n return pTable && pTable->Count() != 0;\n}\n\n\/**\n * Create a colortable\n *\/\nuno::Reference< uno::XInterface > SAL_CALL SvxUnoColorTable_createInstance(const uno::Reference< lang::XMultiServiceFactory > & rSMgr) throw(uno::Exception)\n{\n return *new SvxUnoColorTable();\n}\nuno::Reference< uno::XInterface > SAL_CALL create_EnhancedCustomShapeEngine( const uno::Reference< lang::XMultiServiceFactory >& rxFact ) throw(uno::Exception)\n{\n return *new EnhancedCustomShapeEngine( rxFact );\n}\n\n\/\/\n\/\/ export this service\n\/\/\n\n#ifndef SVX_LIGHT\n#include \"UnoGraphicExporter.hxx\"\n#endif\n\n#ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_\n#include \n#endif\n\n#ifndef _OSL_DIAGNOSE_H_\n#include \n#endif\n\n#include \n#include \n\nextern \"C\"\n{\n\nvoid SAL_CALL component_getImplementationEnvironment( const sal_Char ** ppEnvTypeName, uno_Environment ** ppEnv )\n{\n *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;\n}\n\nvoid SAL_CALL writeInfo( registry::XRegistryKey * pRegistryKey, const OUString& rImplementationName, const uno::Sequence< OUString >& rServices )\n{\n uno::Reference< registry::XRegistryKey > xNewKey(\n pRegistryKey->createKey(\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"\/\") ) + rImplementationName + OUString(RTL_CONSTASCII_USTRINGPARAM( \"\/UNO\/SERVICES\") ) ) );\n\n for( sal_Int32 i = 0; i < rServices.getLength(); i++ )\n xNewKey->createKey( rServices.getConstArray()[i]);\n}\n\nsal_Bool SAL_CALL component_writeInfo( void * pServiceManager, void * pRegistryKey )\n{\n if( pRegistryKey )\n {\n try\n {\n registry::XRegistryKey *pKey = reinterpret_cast< registry::XRegistryKey * >( pRegistryKey );\n\n writeInfo( pKey, SvxShapeCollection::getImplementationName_Static(), SvxShapeCollection::getSupportedServiceNames_Static() );\n writeInfo( pKey, SvxUnoColorTable::getImplementationName_Static(), SvxUnoColorTable::getSupportedServiceNames_Static() );\n writeInfo( pKey, EnhancedCustomShapeEngine_getImplementationName(), EnhancedCustomShapeEngine_getSupportedServiceNames() );\n#ifndef SVX_LIGHT\n writeInfo( pKey, svx::GraphicExporter_getImplementationName(), svx::GraphicExporter_getSupportedServiceNames() );\n#endif\n }\n catch (registry::InvalidRegistryException &)\n {\n OSL_ENSURE( sal_False, \"### InvalidRegistryException!\" );\n }\n }\n\n return sal_True;\n}\n\nvoid * SAL_CALL component_getFactory( const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey )\n{\n void * pRet = 0;\n if( pServiceManager )\n {\n uno::Reference< lang::XSingleServiceFactory > xFactory;\n\n if( rtl_str_compare( pImplName, \"com.sun.star.drawing.SvxUnoColorTable\" ) == 0 )\n {\n xFactory = createSingleFactory( reinterpret_cast< lang::XMultiServiceFactory * >( pServiceManager ),\n SvxUnoColorTable::getImplementationName_Static(),\n SvxUnoColorTable_createInstance,\n SvxUnoColorTable::getSupportedServiceNames_Static() );\n }\n else if ( rtl_str_compare( pImplName, \"com.sun.star.drawing.EnhancedCustomShapeEngine\" ) == 0 )\n {\n xFactory = createSingleFactory( reinterpret_cast< NMSP_LANG::XMultiServiceFactory* >( pServiceManager ),\n EnhancedCustomShapeEngine_getImplementationName(),\n create_EnhancedCustomShapeEngine,\n EnhancedCustomShapeEngine_getSupportedServiceNames() );\n }\n else if( rtl_str_compare( pImplName, \"com.sun.star.drawing.SvxShapeCollection\" ) == 0 )\n {\n xFactory = createSingleFactory( reinterpret_cast< lang::XMultiServiceFactory * >( pServiceManager ),\n SvxShapeCollection::getImplementationName_Static(),\n SvxShapeCollection_createInstance,\n SvxShapeCollection::getSupportedServiceNames_Static() );\n }\n#ifndef SVX_LIGHT\n else if( svx::GraphicExporter_getImplementationName().equalsAscii( pImplName ) )\n {\n xFactory = ::cppu::createSingleFactory( reinterpret_cast< lang::XMultiServiceFactory * >( pServiceManager ),\n svx::GraphicExporter_getImplementationName(),\n svx::GraphicExporter_createInstance,\n svx::GraphicExporter_getSupportedServiceNames() );\n }\n#endif\n if( xFactory.is())\n {\n xFactory->acquire();\n pRet = xFactory.get();\n }\n }\n\n return pRet;\n}\n\n}\n\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: unodtabl.cxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: kz $ $Date: 2005-01-21 17:01:34 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _COM_SUN_STAR_DRAWING_LINEDASH_HPP_\n#include \n#endif\n\n#ifndef _SFXITEMPOOL_HXX\n#include \n#endif\n\n#ifndef _SFXITEMSET_HXX \/\/autogen\n#include \n#endif\n\n#include \n\n#ifndef _SVX_UNONAMEITEMTABLE_HXX_\n#include \"UnoNameItemTable.hxx\"\n#endif\n\n#ifndef _SVX_XLNDSIT_HXX\n#include \"xlndsit.hxx\"\n#endif\n\n#ifndef _SVX_UNOMID_HXX\n#include \"unomid.hxx\"\n#endif\n\n#include \"xdash.hxx\"\n#include \"svdmodel.hxx\"\n#include \"unofill.hxx\"\n\nusing namespace ::com::sun::star;\nusing namespace ::rtl;\nusing namespace ::cppu;\n\nclass SvxUnoDashTable : public SvxUnoNameItemTable\n{\npublic:\n SvxUnoDashTable( SdrModel* pModel ) throw();\n virtual ~SvxUnoDashTable() throw();\n\n virtual NameOrIndex* createItem() const throw();\n\n \/\/ XServiceInfo\n virtual OUString SAL_CALL getImplementationName( ) throw( uno::RuntimeException );\n virtual uno::Sequence< OUString > SAL_CALL getSupportedServiceNames( ) throw( uno::RuntimeException);\n\n \/\/ XElementAccess\n virtual uno::Type SAL_CALL getElementType( ) throw( uno::RuntimeException);\n};\n\nSvxUnoDashTable::SvxUnoDashTable( SdrModel* pModel ) throw()\n: SvxUnoNameItemTable( pModel, XATTR_LINEDASH, MID_LINEDASH )\n{\n}\n\nSvxUnoDashTable::~SvxUnoDashTable() throw()\n{\n}\n\nOUString SAL_CALL SvxUnoDashTable::getImplementationName() throw( uno::RuntimeException )\n{\n return OUString( RTL_CONSTASCII_USTRINGPARAM(\"SvxUnoDashTable\") );\n}\n\nuno::Sequence< OUString > SAL_CALL SvxUnoDashTable::getSupportedServiceNames( )\n throw( uno::RuntimeException )\n{\n uno::Sequence< OUString > aSNS( 1 );\n aSNS.getArray()[0] = OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.drawing.DashTable\" ));\n return aSNS;\n}\n\nNameOrIndex* SvxUnoDashTable::createItem() const throw()\n{\n XLineDashItem* pNewItem = new XLineDashItem();\n pNewItem->SetWhich( XATTR_LINEDASH ); \/\/ set which id for pooling\n return pNewItem;\n}\n\n\/\/ XElementAccess\nuno::Type SAL_CALL SvxUnoDashTable::getElementType( )\n throw( uno::RuntimeException )\n{\n return ::getCppuType((const struct drawing::LineDash*)0);\n}\n\n\/**\n * Create a gradienttable\n *\/\nuno::Reference< uno::XInterface > SAL_CALL SvxUnoDashTable_createInstance( SdrModel* pModel )\n{\n return *new SvxUnoDashTable(pModel);\n}\n\n\n\nINTEGRATION: CWS ooo19126 (1.10.430); FILE MERGED 2005\/09\/05 14:28:08 rt 1.10.430.1: #i54170# Change license header: remove SISSL\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: unodtabl.cxx,v $\n *\n * $Revision: 1.11 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 01:03:50 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _COM_SUN_STAR_DRAWING_LINEDASH_HPP_\n#include \n#endif\n\n#ifndef _SFXITEMPOOL_HXX\n#include \n#endif\n\n#ifndef _SFXITEMSET_HXX \/\/autogen\n#include \n#endif\n\n#include \n\n#ifndef _SVX_UNONAMEITEMTABLE_HXX_\n#include \"UnoNameItemTable.hxx\"\n#endif\n\n#ifndef _SVX_XLNDSIT_HXX\n#include \"xlndsit.hxx\"\n#endif\n\n#ifndef _SVX_UNOMID_HXX\n#include \"unomid.hxx\"\n#endif\n\n#include \"xdash.hxx\"\n#include \"svdmodel.hxx\"\n#include \"unofill.hxx\"\n\nusing namespace ::com::sun::star;\nusing namespace ::rtl;\nusing namespace ::cppu;\n\nclass SvxUnoDashTable : public SvxUnoNameItemTable\n{\npublic:\n SvxUnoDashTable( SdrModel* pModel ) throw();\n virtual ~SvxUnoDashTable() throw();\n\n virtual NameOrIndex* createItem() const throw();\n\n \/\/ XServiceInfo\n virtual OUString SAL_CALL getImplementationName( ) throw( uno::RuntimeException );\n virtual uno::Sequence< OUString > SAL_CALL getSupportedServiceNames( ) throw( uno::RuntimeException);\n\n \/\/ XElementAccess\n virtual uno::Type SAL_CALL getElementType( ) throw( uno::RuntimeException);\n};\n\nSvxUnoDashTable::SvxUnoDashTable( SdrModel* pModel ) throw()\n: SvxUnoNameItemTable( pModel, XATTR_LINEDASH, MID_LINEDASH )\n{\n}\n\nSvxUnoDashTable::~SvxUnoDashTable() throw()\n{\n}\n\nOUString SAL_CALL SvxUnoDashTable::getImplementationName() throw( uno::RuntimeException )\n{\n return OUString( RTL_CONSTASCII_USTRINGPARAM(\"SvxUnoDashTable\") );\n}\n\nuno::Sequence< OUString > SAL_CALL SvxUnoDashTable::getSupportedServiceNames( )\n throw( uno::RuntimeException )\n{\n uno::Sequence< OUString > aSNS( 1 );\n aSNS.getArray()[0] = OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.drawing.DashTable\" ));\n return aSNS;\n}\n\nNameOrIndex* SvxUnoDashTable::createItem() const throw()\n{\n XLineDashItem* pNewItem = new XLineDashItem();\n pNewItem->SetWhich( XATTR_LINEDASH ); \/\/ set which id for pooling\n return pNewItem;\n}\n\n\/\/ XElementAccess\nuno::Type SAL_CALL SvxUnoDashTable::getElementType( )\n throw( uno::RuntimeException )\n{\n return ::getCppuType((const struct drawing::LineDash*)0);\n}\n\n\/**\n * Create a gradienttable\n *\/\nuno::Reference< uno::XInterface > SAL_CALL SvxUnoDashTable_createInstance( SdrModel* pModel )\n{\n return *new SvxUnoDashTable(pModel);\n}\n\n\n\n<|endoftext|>"} {"text":"coverity#705919 Dereference before null check<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: txtinit.cxx,v $\n *\n * $Revision: 1.1.1.1 $\n *\n * last change: $Author: hr $ $Date: 2000-09-19 00:08:26 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifdef PRECOMPILED\n#include \"core_pch.hxx\"\n#endif\n\n#pragma hdrstop\n\n#include \"errhdl.hxx\"\n#include \"txtcfg.hxx\"\n#include \"swcache.hxx\"\n#include \"fntcache.hxx\" \/\/ pFntCache ( SwFont\/ScrFont-PrtFont Cache )\n#include \"swfntcch.hxx\" \/\/ pSwFontCache ( SwAttrSet\/SwFont Cache )\n#include \"txtfrm.hxx\"\n#include \"txtcache.hxx\"\n#include \"porlay.hxx\"\n#include \"porglue.hxx\"\n#include \"porexp.hxx\"\n#include \"porrst.hxx\"\n#include \"portab.hxx\"\n#include \"porfly.hxx\"\n#include \"portox.hxx\"\n#include \"porref.hxx\"\n#include \"porftn.hxx\"\n#include \"porhyph.hxx\"\n#include \"pordrop.hxx\"\n#include \"tempauto.hxx\" \/\/ Temporaere Autokorrekturliste\n#include \"blink.hxx\" \/\/ Blink-Manager\n#include \"init.hxx\" \/\/ Deklarationen fuer _TextInit() und _TextFinit()\n#include \"txtfly.hxx\" \/\/ SwContourCache\n#include \"dbg_lay.hxx\" \/\/ Layout Debug Fileausgabe\n\nSwCache *SwTxtFrm::pTxtCache = 0;\nlong SwTxtFrm::nMinPrtLine = 0;\nSwContourCache *pContourCache = 0;\nSwDropCapCache *pDropCapCache = 0;\n\n#ifndef PROFILE\n\/\/ Code zum Initialisieren von Statics im eigenen Code-Segment\n#pragma code_seg( \"SWSTATICS\" )\n#endif\n\nIMPL_FIXEDMEMPOOL_NEWDEL( SwTxtLine, 50, 50 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwParaPortion, 50, 50 ) \/\/Absaetze\nIMPL_FIXEDMEMPOOL_NEWDEL( SwLineLayout, 150, 150 ) \/\/Zeilen\nIMPL_FIXEDMEMPOOL_NEWDEL( SwHolePortion, 150, 150 ) \/\/z.B. Blanks am Zeilenende\nIMPL_FIXEDMEMPOOL_NEWDEL( SwTxtPortion, 200, 100 ) \/\/Attributwechsel\n\n#ifndef PROFILE\n#pragma code_seg()\n#endif\n\n\/*************************************************************************\n * _TextInit(), _TextFinit()\n *************************************************************************\/\n\n\/\/ Werden _nur_ in init.cxx verwendet, dort stehen extern void _TextFinit()\n\/\/ und extern void _TextInit(...)\n\nvoid _TextInit()\n{\n pFntCache = new SwFntCache;\n pSwFontCache = new SwFontCache;\n pSpellCol = new Color( COL_LIGHTRED );\n pWaveCol = new Color( COL_GRAY );\n\n \/\/Pauschale groesse 250, plus 100 pro Shell\n SwCache *pTxtCache = new SwCache( 250, 100\n#ifndef PRODUCT\n , \"static SwTxtFrm::pTxtCache\"\n#endif\n );\n SwTxtFrm::SetTxtCache( pTxtCache );\n PROTOCOL_INIT\n}\n\nvoid _TextFinit()\n{\n delete SwTxtFrm::GetTxtCache();\n delete pSwFontCache;\n delete pFntCache;\n delete pTempAuto;\n delete pBlink;\n delete pSpellCol;\n delete pWaveCol;\n delete pContourCache;\n SwDropPortion::DeleteDropCapCache();\n PROTOCOL_STOP\n}\n\n\n\nFix #90364#: Good looking screen output\/*************************************************************************\n *\n * $RCSfile: txtinit.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: ama $ $Date: 2001-10-01 14:33:00 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifdef PRECOMPILED\n#include \"core_pch.hxx\"\n#endif\n\n#pragma hdrstop\n\n#include \"errhdl.hxx\"\n#include \"txtcfg.hxx\"\n#include \"swcache.hxx\"\n#include \"fntcache.hxx\" \/\/ pFntCache ( SwFont\/ScrFont-PrtFont Cache )\n#include \"swfntcch.hxx\" \/\/ pSwFontCache ( SwAttrSet\/SwFont Cache )\n#include \"txtfrm.hxx\"\n#include \"txtcache.hxx\"\n#include \"porlay.hxx\"\n#include \"porglue.hxx\"\n#include \"porexp.hxx\"\n#include \"porrst.hxx\"\n#include \"portab.hxx\"\n#include \"porfly.hxx\"\n#include \"portox.hxx\"\n#include \"porref.hxx\"\n#include \"porftn.hxx\"\n#include \"porhyph.hxx\"\n#include \"pordrop.hxx\"\n#include \"tempauto.hxx\" \/\/ Temporaere Autokorrekturliste\n#include \"blink.hxx\" \/\/ Blink-Manager\n#include \"init.hxx\" \/\/ Deklarationen fuer _TextInit() und _TextFinit()\n#include \"txtfly.hxx\" \/\/ SwContourCache\n#include \"dbg_lay.hxx\" \/\/ Layout Debug Fileausgabe\n\nSwCache *SwTxtFrm::pTxtCache = 0;\nlong SwTxtFrm::nMinPrtLine = 0;\nSwContourCache *pContourCache = 0;\nSwDropCapCache *pDropCapCache = 0;\n\n#ifndef PROFILE\n\/\/ Code zum Initialisieren von Statics im eigenen Code-Segment\n#pragma code_seg( \"SWSTATICS\" )\n#endif\n\nIMPL_FIXEDMEMPOOL_NEWDEL( SwTxtLine, 50, 50 )\nIMPL_FIXEDMEMPOOL_NEWDEL( SwParaPortion, 50, 50 ) \/\/Absaetze\nIMPL_FIXEDMEMPOOL_NEWDEL( SwLineLayout, 150, 150 ) \/\/Zeilen\nIMPL_FIXEDMEMPOOL_NEWDEL( SwHolePortion, 150, 150 ) \/\/z.B. Blanks am Zeilenende\nIMPL_FIXEDMEMPOOL_NEWDEL( SwTxtPortion, 200, 100 ) \/\/Attributwechsel\n\n#ifndef PROFILE\n#pragma code_seg()\n#endif\n\n\/*************************************************************************\n * _TextInit(), _TextFinit()\n *************************************************************************\/\n\n\/\/ Werden _nur_ in init.cxx verwendet, dort stehen extern void _TextFinit()\n\/\/ und extern void _TextInit(...)\n\nvoid _TextInit()\n{\n pFntCache = new SwFntCache;\n pSwFontCache = new SwFontCache;\n pSpellCol = new Color( COL_LIGHTRED );\n pWaveCol = new Color( COL_GRAY );\n\n \/\/Pauschale groesse 250, plus 100 pro Shell\n SwCache *pTxtCache = new SwCache( 250, 100\n#ifndef PRODUCT\n , \"static SwTxtFrm::pTxtCache\"\n#endif\n );\n SwTxtFrm::SetTxtCache( pTxtCache );\n PROTOCOL_INIT\n}\n\nvoid _TextFinit()\n{\n PROTOCOL_STOP\n delete SwTxtFrm::GetTxtCache();\n delete pSwFontCache;\n delete pFntCache;\n delete pTempAuto;\n delete pBlink;\n delete pSpellCol;\n delete pWaveCol;\n delete pContourCache;\n SwDropPortion::DeleteDropCapCache();\n}\n\n\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: fields.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: rt $ $Date: 2003-09-25 07:40:18 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil -*- *\/\n\n#ifndef WW_FIELDS_HXX\n#include \"fields.hxx\"\n#endif\n\n#ifndef _ERRHDL_HXX\n#include \/\/ASSERT (use our own ww header later for asserts)\n#endif\n\nnamespace ww\n{\n const char *GetEnglishFieldName(eField eIndex) throw()\n {\n \/\/0 Signifies the field names I can't find.\n static const char *aFieldNames[] =\n {\n \/* 0*\/ 0,\n \/* 1*\/ 0,\n \/* 2*\/ 0,\n \/* 3*\/ \"REF\",\n \/* 4*\/ \"XE\",\n \/* 5*\/ 0,\n \/* 6*\/ \"SET\",\n \/* 7*\/ \"IF\",\n \/* 8*\/ \"INDEX\",\n \/* 9*\/ \"TC\",\n \/*10*\/ \"STYLEREF\",\n \/*11*\/ \"RD\",\n \/*12*\/ \"SEQ\",\n \/*13*\/ \"TOC\",\n \/*14*\/ \"INFO\",\n \/*15*\/ \"TITLE\",\n \/*16*\/ \"SUBJECT\",\n \/*17*\/ \"AUTHOR\",\n \/*18*\/ \"KEYWORDS\",\n \/*19*\/ \"COMMENTS\",\n \/*20*\/ \"LASTSAVEDBY\",\n \/*21*\/ \"CREATEDATE\",\n \/*22*\/ \"SAVEDATE\",\n \/*23*\/ \"PRINTDATE\",\n \/*24*\/ \"REVNUM\",\n \/*25*\/ \"EDITTIME\",\n \/*26*\/ \"NUMPAGE\",\n \/*27*\/ \"NUMWORDS\",\n \/*28*\/ \"NUMCHARS\",\n \/*29*\/ \"FILENAME\",\n \/*30*\/ \"TEMPLATE\",\n \/*31*\/ \"DATE\",\n \/*32*\/ \"TIME\",\n \/*33*\/ \"PAGE\",\n \/*34*\/ \"=\",\n \/*35*\/ \"QUOTE\",\n \/*36*\/ 0,\n \/*37*\/ \"PAGEREF\",\n \/*38*\/ \"ASK\",\n \/*39*\/ \"FILLIN\",\n \/*40*\/ 0,\n \/*41*\/ \"NEXT\",\n \/*42*\/ \"NEXTIF\",\n \/*43*\/ \"SKIPIF\",\n \/*44*\/ \"MERGEREC\",\n \/*45*\/ 0,\n \/*46*\/ 0,\n \/*47*\/ 0,\n \/*48*\/ \"PRINT\",\n \/*49*\/ \"EQ\",\n \/*50*\/ \"GOTOBUTTON\",\n \/*51*\/ \"MACROBUTTON\",\n \/*52*\/ \"AUTONUMOUT\",\n \/*53*\/ \"AUTONUMLGL\",\n \/*54*\/ \"AUTONUM\",\n \/*55*\/ 0,\n \/*56*\/ \"LINK\",\n \/*57*\/ \"SYMBOL\",\n \/*58*\/ \"EMBED\",\n \/*59*\/ \"MERGEFIELD\",\n \/*60*\/ \"USERNAME\",\n \/*61*\/ \"USERINITIALS\",\n \/*62*\/ \"USERADDRESS\",\n \/*63*\/ \"BARCODE\",\n \/*64*\/ \"DOCVARIABLE\",\n \/*65*\/ \"SECTION\",\n \/*66*\/ \"SECTIONPAGES\",\n \/*67*\/ \"INCLUDEPICTURE\",\n \/*68*\/ \"INCLUDETEXT\",\n \/*69*\/ \"FILESIZE\",\n \/*70*\/ \"FORMTEXT\",\n \/*71*\/ \"FORMCHECKBOX\",\n \/*72*\/ \"NOTEREF\",\n \/*73*\/ \"TOA\",\n \/*74*\/ \"TA\",\n \/*75*\/ \"MERGESEQ\",\n \/*76*\/ 0,\n \/*77*\/ \"PRIVATE\",\n \/*78*\/ \"DATABASE\",\n \/*79*\/ \"AUTOTEXT\",\n \/*80*\/ \"COMPARE\",\n \/*81*\/ 0,\n \/*82*\/ 0,\n \/*83*\/ \"FORMDROPDOWN\",\n \/*84*\/ \"ADVANCE\",\n \/*85*\/ \"DOCPROPERTY\",\n \/*86*\/ 0,\n \/*87*\/ \"CONTROL\",\n \/*88*\/ \"HYPERLINK\",\n \/*89*\/ \"AUTOTEXTLIST\",\n \/*90*\/ \"LISTNUM\",\n \/*91*\/ 0,\n \/*92*\/ \"BIDIOUTLINE\",\n \/*93*\/ \"ADDRESSBLOCK\",\n \/*94*\/ \"GREETINGLINE\",\n \/*95*\/ \"SHAPE\"\n };\n\n if (eIndex >= sizeof(aFieldNames) \/ sizeof(aFieldNames[0]))\n eIndex = eNONE;\n ASSERT(eIndex != eNONE, \"Unknown WinWord Field, let cmc know\");\n return aFieldNames[eIndex];\n }\n}\n\n\/* vi:set tabstop=4 shiftwidth=4 expandtab: *\/\nINTEGRATION: CWS mullingarfilterteam18 (1.2.64); FILE MERGED 2003\/11\/17 17:09:45 cmc 1.2.64.1: #i9055# add in some defaults to case statements, etc\/*************************************************************************\n *\n * $RCSfile: fields.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: obo $ $Date: 2004-01-13 17:04:24 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil -*- *\/\n\n#ifndef WW_FIELDS_HXX\n#include \"fields.hxx\"\n#endif\n\n#ifndef _ERRHDL_HXX\n#include \/\/ASSERT (use our own ww header later for asserts)\n#endif\n\nnamespace ww\n{\n const char *GetEnglishFieldName(eField eIndex) throw()\n {\n \/\/0 Signifies the field names I can't find.\n static const char *aFieldNames[] =\n {\n \/* 0*\/ 0,\n \/* 1*\/ 0,\n \/* 2*\/ 0,\n \/* 3*\/ \"REF\",\n \/* 4*\/ \"XE\",\n \/* 5*\/ 0,\n \/* 6*\/ \"SET\",\n \/* 7*\/ \"IF\",\n \/* 8*\/ \"INDEX\",\n \/* 9*\/ \"TC\",\n \/*10*\/ \"STYLEREF\",\n \/*11*\/ \"RD\",\n \/*12*\/ \"SEQ\",\n \/*13*\/ \"TOC\",\n \/*14*\/ \"INFO\",\n \/*15*\/ \"TITLE\",\n \/*16*\/ \"SUBJECT\",\n \/*17*\/ \"AUTHOR\",\n \/*18*\/ \"KEYWORDS\",\n \/*19*\/ \"COMMENTS\",\n \/*20*\/ \"LASTSAVEDBY\",\n \/*21*\/ \"CREATEDATE\",\n \/*22*\/ \"SAVEDATE\",\n \/*23*\/ \"PRINTDATE\",\n \/*24*\/ \"REVNUM\",\n \/*25*\/ \"EDITTIME\",\n \/*26*\/ \"NUMPAGE\",\n \/*27*\/ \"NUMWORDS\",\n \/*28*\/ \"NUMCHARS\",\n \/*29*\/ \"FILENAME\",\n \/*30*\/ \"TEMPLATE\",\n \/*31*\/ \"DATE\",\n \/*32*\/ \"TIME\",\n \/*33*\/ \"PAGE\",\n \/*34*\/ \"=\",\n \/*35*\/ \"QUOTE\",\n \/*36*\/ 0,\n \/*37*\/ \"PAGEREF\",\n \/*38*\/ \"ASK\",\n \/*39*\/ \"FILLIN\",\n \/*40*\/ 0,\n \/*41*\/ \"NEXT\",\n \/*42*\/ \"NEXTIF\",\n \/*43*\/ \"SKIPIF\",\n \/*44*\/ \"MERGEREC\",\n \/*45*\/ 0,\n \/*46*\/ 0,\n \/*47*\/ 0,\n \/*48*\/ \"PRINT\",\n \/*49*\/ \"EQ\",\n \/*50*\/ \"GOTOBUTTON\",\n \/*51*\/ \"MACROBUTTON\",\n \/*52*\/ \"AUTONUMOUT\",\n \/*53*\/ \"AUTONUMLGL\",\n \/*54*\/ \"AUTONUM\",\n \/*55*\/ 0,\n \/*56*\/ \"LINK\",\n \/*57*\/ \"SYMBOL\",\n \/*58*\/ \"EMBED\",\n \/*59*\/ \"MERGEFIELD\",\n \/*60*\/ \"USERNAME\",\n \/*61*\/ \"USERINITIALS\",\n \/*62*\/ \"USERADDRESS\",\n \/*63*\/ \"BARCODE\",\n \/*64*\/ \"DOCVARIABLE\",\n \/*65*\/ \"SECTION\",\n \/*66*\/ \"SECTIONPAGES\",\n \/*67*\/ \"INCLUDEPICTURE\",\n \/*68*\/ \"INCLUDETEXT\",\n \/*69*\/ \"FILESIZE\",\n \/*70*\/ \"FORMTEXT\",\n \/*71*\/ \"FORMCHECKBOX\",\n \/*72*\/ \"NOTEREF\",\n \/*73*\/ \"TOA\",\n \/*74*\/ \"TA\",\n \/*75*\/ \"MERGESEQ\",\n \/*76*\/ 0,\n \/*77*\/ \"PRIVATE\",\n \/*78*\/ \"DATABASE\",\n \/*79*\/ \"AUTOTEXT\",\n \/*80*\/ \"COMPARE\",\n \/*81*\/ 0,\n \/*82*\/ 0,\n \/*83*\/ \"FORMDROPDOWN\",\n \/*84*\/ \"ADVANCE\",\n \/*85*\/ \"DOCPROPERTY\",\n \/*86*\/ 0,\n \/*87*\/ \"CONTROL\",\n \/*88*\/ \"HYPERLINK\",\n \/*89*\/ \"AUTOTEXTLIST\",\n \/*90*\/ \"LISTNUM\",\n \/*91*\/ 0,\n \/*92*\/ \"BIDIOUTLINE\",\n \/*93*\/ \"ADDRESSBLOCK\",\n \/*94*\/ \"GREETINGLINE\",\n \/*95*\/ \"SHAPE\"\n };\n\n size_t nIndex = static_cast(eIndex);\n if (nIndex >= sizeof(aFieldNames) \/ sizeof(aFieldNames[0]))\n eIndex = eNONE;\n ASSERT(eIndex != eNONE, \"Unknown WinWord Field, let cmc know\");\n return aFieldNames[eIndex];\n }\n}\n\n\/* vi:set tabstop=4 shiftwidth=4 expandtab: *\/\n<|endoftext|>"} {"text":"support ww2, etc via fftester<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: condedit.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: jp $ $Date: 2001-07-11 17:05:38 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\/\/ include ---------------------------------------------------------------\n\n#pragma hdrstop\n\n#ifndef _OFF_APP_HXX \/\/autogen\n#include \n#endif\n#ifndef _SOT_FORMATS_HXX \/\/autogen\n#include \n#endif\n\n#ifndef _CONDEDIT_HXX\n#include \n#endif\n\n#define DB_DD_DELIM 0x0b\n\n\/\/ STATIC DATA -----------------------------------------------------------\n\n\/*--------------------------------------------------------------------\n Beschreibung:\n --------------------------------------------------------------------*\/\n\nConditionEdit::ConditionEdit( Window* pParent, const ResId& rResId )\n : Edit( pParent, rResId ),\n DropTargetHelper( this ),\n bBrackets( TRUE ), bEnableDrop( TRUE ), bHasDroppedData( FALSE )\n{\n}\n\n\/*--------------------------------------------------------------------\n Beschreibung: Drop moeglich, bzw Format bekannt?\n --------------------------------------------------------------------*\/\n\nsal_Int8 ConditionEdit::AcceptDrop( const AcceptDropEvent& rEvt )\n{\n return IsFormatSupported( GetDataFlavorExVector(),\n SOT_FORMATSTR_ID_SBA_FIELDDATAEXCHANGE )\n ? DND_ACTION_COPY\n : DND_ACTION_NONE;\n}\n\nsal_Int8 ConditionEdit::ExecuteDrop( const ExecuteDropEvent& rEvt )\n{\n sal_Int8 nRet = DND_ACTION_NONE;\n if( bEnableDrop )\n {\n String sTxt;\n TransferableDataHelper aData( rEvt.maDropEvent.Transferable );\n if( aData.GetString( SOT_FORMATSTR_ID_SBA_FIELDDATAEXCHANGE, sTxt ) &&\n sTxt.Len() )\n {\n String sDBName;\n if (bBrackets)\n sDBName += '[';\n sDBName += sTxt.GetToken(0, DB_DD_DELIM);\n sDBName += '.';\n sDBName += sTxt.GetToken(1, DB_DD_DELIM);\n sDBName += '.';\n sDBName += sTxt.GetToken(3, DB_DD_DELIM); \/\/ ColumnName\n if (bBrackets)\n sDBName += ']';\n\n SetText( sDBName );\n bHasDroppedData = TRUE;\n nRet = DND_ACTION_COPY;\n }\n }\n return nRet;\n}\n\n\n#89874# drop action updated\/*************************************************************************\n *\n * $RCSfile: condedit.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: os $ $Date: 2001-07-30 14:00:10 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\/\/ include ---------------------------------------------------------------\n\n#pragma hdrstop\n\n#ifndef _OFF_APP_HXX \/\/autogen\n#include \n#endif\n#ifndef _SOT_FORMATS_HXX \/\/autogen\n#include \n#endif\n\n#ifndef _CONDEDIT_HXX\n#include \n#endif\n#ifndef _SVX_DBAEXCHANGE_HXX_\n#include \n#endif\nusing namespace ::svx;\nusing namespace ::rtl;\nusing namespace ::com::sun::star::uno;\n#define DB_DD_DELIM 0x0b\n\n\/\/ STATIC DATA -----------------------------------------------------------\n\n\/*--------------------------------------------------------------------\n Beschreibung:\n --------------------------------------------------------------------*\/\n\nConditionEdit::ConditionEdit( Window* pParent, const ResId& rResId )\n : Edit( pParent, rResId ),\n DropTargetHelper( this ),\n bBrackets( TRUE ), bEnableDrop( TRUE ), bHasDroppedData( FALSE )\n{\n}\n\n\/*--------------------------------------------------------------------\n Beschreibung: Drop moeglich, bzw Format bekannt?\n --------------------------------------------------------------------*\/\n\nsal_Int8 ConditionEdit::AcceptDrop( const AcceptDropEvent& rEvt )\n{\n return OColumnTransferable::canExtractColumnDescriptor\n ( GetDataFlavorExVector(),\n CTF_COLUMN_DESCRIPTOR )\n ? DND_ACTION_COPY\n : DND_ACTION_NONE;\n}\n\nsal_Int8 ConditionEdit::ExecuteDrop( const ExecuteDropEvent& rEvt )\n{\n sal_Int8 nRet = DND_ACTION_NONE;\n if( bEnableDrop )\n {\n String sTxt;\n TransferableDataHelper aData( rEvt.maDropEvent.Transferable );\n\n DataFlavorExVector& rVector = aData.GetDataFlavorExVector();\n if(OColumnTransferable::canExtractColumnDescriptor(rVector, CTF_COLUMN_DESCRIPTOR))\n {\n ODataAccessDescriptor aColDesc = OColumnTransferable::extractColumnDescriptor(\n aData);\n String sDBName;\n if (bBrackets)\n sDBName += '[';\n OUString sTmp;\n aColDesc[daDataSource] >>= sTmp;\n sDBName += String(sTmp);\n sDBName += '.';\n\n aColDesc[daCommand] >>= sTmp;\n sDBName += String(sTmp);\n sDBName += '.';\n\n aColDesc[daColumnName] >>= sTmp;\n sDBName += String(sTmp);\n if (bBrackets)\n sDBName += ']';\n\n SetText( sDBName );\n bHasDroppedData = TRUE;\n nRet = DND_ACTION_COPY;\n }\n }\n return nRet;\n}\n\n\n<|endoftext|>"} {"text":"\/\/ Copyright (C) 2017 Elviss Strazdins\n\/\/ This file is part of the Ouzel engine.\n\n#ifdef _WIN32\n#ifndef NOMINMAX\n#define NOMINMAX\n#endif\n#include \n#include \n#else\n#include \n#include \n#include \n#include \n#include \n#endif\n#include \"Network.hpp\"\n#include \"utils\/Log.hpp\"\n\nnamespace ouzel\n{\n namespace network\n {\n Network::Network()\n {\n }\n\n Network::~Network()\n {\n if (endpoint != NULL_SOCKET)\n {\n#ifdef _WIN32\n int result = closesocket(endpoint);\n#else\n int result = close(endpoint);\n#endif\n\n if (result < 0)\n {\n int error = getLastError();\n Log(Log::Level::ERR) << \"Failed to close socket, error: \" << error;\n }\n }\n\n#ifdef _WIN32\n WSACleanup();\n#endif\n }\n\n int Network::getLastError()\n {\n#ifdef _WIN32\n return WSAGetLastError();\n#else\n return errno;\n#endif\n }\n\n bool Network::getAddress(const std::string& address, uint32_t& result)\n {\n addrinfo* info;\n int ret = getaddrinfo(address.c_str(), nullptr, nullptr, &info);\n\n#ifdef _WIN32\n if (ret != 0 && WSAGetLastError() == WSANOTINITIALISED)\n {\n if (!initWSA()) return false;\n\n ret = getaddrinfo(addressStr.c_str(), portStr.empty() ? nullptr : portStr.c_str(), nullptr, &info);\n }\n#endif\n\n if (ret != 0)\n {\n int error = getLastError();\n Log(Log::Level::ERR) << \"Failed to get address info of \" << address << \", error: \" << error;\n return false;\n }\n\n sockaddr_in* addr = reinterpret_cast(info->ai_addr);\n result = addr->sin_addr.s_addr;\n \n freeaddrinfo(info);\n \n return true;\n }\n\n bool Network::init()\n {\n#ifdef _WIN32\n WORD sockVersion = MAKEWORD(2, 2);\n WSADATA wsaData;\n int error = WSAStartup(sockVersion, &wsaData);\n if (error != 0)\n {\n Log(Log::Level::ERR) << \"Failed to start Winsock failed, error: \" << error;\n return false;\n }\n \n if (wsaData.wVersion != sockVersion)\n {\n Log(Log::Level::ERR) << \"Incorrect Winsock version\";\n WSACleanup();\n return false;\n }\n#endif\n\n return true;\n }\n\n bool Network::listen(const std::string& address, uint16_t port)\n {\n return true;\n }\n\n bool Network::connect(const std::string& address, uint16_t port)\n {\n return true;\n }\n\n bool Network::disconnect()\n {\n return true;\n }\n } \/\/ namespace network\n} \/\/ namespace ouzel\nConvert the IP address to host endianness Don't call initWSA\/\/ Copyright (C) 2017 Elviss Strazdins\n\/\/ This file is part of the Ouzel engine.\n\n#ifdef _WIN32\n#ifndef NOMINMAX\n#define NOMINMAX\n#endif\n#include \n#include \n#else\n#include \n#include \n#include \n#include \n#include \n#endif\n#include \"Network.hpp\"\n#include \"utils\/Log.hpp\"\n\nnamespace ouzel\n{\n namespace network\n {\n Network::Network()\n {\n }\n\n Network::~Network()\n {\n if (endpoint != NULL_SOCKET)\n {\n#ifdef _WIN32\n int result = closesocket(endpoint);\n#else\n int result = close(endpoint);\n#endif\n\n if (result < 0)\n {\n int error = getLastError();\n Log(Log::Level::ERR) << \"Failed to close socket, error: \" << error;\n }\n }\n\n#ifdef _WIN32\n WSACleanup();\n#endif\n }\n\n int Network::getLastError()\n {\n#ifdef _WIN32\n return WSAGetLastError();\n#else\n return errno;\n#endif\n }\n\n bool Network::getAddress(const std::string& address, uint32_t& result)\n {\n addrinfo* info;\n int ret = getaddrinfo(address.c_str(), nullptr, nullptr, &info);\n\n if (ret != 0)\n {\n int error = getLastError();\n Log(Log::Level::ERR) << \"Failed to get address info of \" << address << \", error: \" << error;\n return false;\n }\n\n sockaddr_in* addr = reinterpret_cast(info->ai_addr);\n result = ntohl(addr->sin_addr.s_addr);\n \n freeaddrinfo(info);\n \n return true;\n }\n\n bool Network::init()\n {\n#ifdef _WIN32\n WORD sockVersion = MAKEWORD(2, 2);\n WSADATA wsaData;\n int error = WSAStartup(sockVersion, &wsaData);\n if (error != 0)\n {\n Log(Log::Level::ERR) << \"Failed to start Winsock failed, error: \" << error;\n return false;\n }\n \n if (wsaData.wVersion != sockVersion)\n {\n Log(Log::Level::ERR) << \"Incorrect Winsock version\";\n WSACleanup();\n return false;\n }\n#endif\n\n return true;\n }\n\n bool Network::listen(const std::string& address, uint16_t port)\n {\n return true;\n }\n\n bool Network::connect(const std::string& address, uint16_t port)\n {\n return true;\n }\n\n bool Network::disconnect()\n {\n return true;\n }\n } \/\/ namespace network\n} \/\/ namespace ouzel\n<|endoftext|>"} {"text":"\/*\n * Copyright 2017-2018 Baidu Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"openrasp_output_detect.h\"\n#include \"openrasp_hook.h\"\n#include \"openrasp_ini.h\"\n#include \"agent\/shared_config_manager.h\"\n#include \"utils\/regex.h\"\n\nZEND_DECLARE_MODULE_GLOBALS(openrasp_output_detect)\n\nstatic void _check_header_content_type_if_html(void *data, void *arg TSRMLS_DC);\nstatic int _detect_param_occur_in_html_output(const char *param, OpenRASPActionType action TSRMLS_DC);\nstatic bool _gpc_parameter_filter(const zval *param TSRMLS_DC);\nstatic bool _is_content_type_html(TSRMLS_D);\n\n#if (PHP_MAJOR_VERSION == 5) && (PHP_MINOR_VERSION <= 3)\n\nvoid openrasp_detect_output(INTERNAL_FUNCTION_PARAMETERS)\n{\n OUTPUT_G(output_detect) = true;\n char *input;\n int input_len;\n long mode;\n\n if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s|l\", &input, &input_len, &mode) == FAILURE)\n {\n RETVAL_FALSE;\n }\n if (_is_content_type_html(TSRMLS_C))\n {\n OpenRASPActionType action = openrasp::scm->get_buildin_check_action(XSS_USER_INPUT);\n int status = _detect_param_occur_in_html_output(input, action TSRMLS_CC);\n if (status == SUCCESS)\n {\n status = (AC_BLOCK == action) ? SUCCESS : FAILURE;\n }\n if (status == SUCCESS)\n {\n reset_response(TSRMLS_C);\n RETVAL_STRING(\"\", 1);\n }\n }\n}\n\n#else\n\nstatic php_output_handler *openrasp_output_handler_init(const char *handler_name, size_t handler_name_len, size_t chunk_size, int flags TSRMLS_DC);\nstatic void openrasp_clean_output_start(const char *name, size_t name_len TSRMLS_DC);\nstatic int openrasp_output_handler(void **nothing, php_output_context *output_context);\n\nstatic int openrasp_output_handler(void **nothing, php_output_context *output_context)\n{\n PHP_OUTPUT_TSRMLS(output_context);\n OUTPUT_G(output_detect) = true;\n int status = FAILURE;\n if (_is_content_type_html(TSRMLS_C) &&\n (output_context->op & PHP_OUTPUT_HANDLER_START) &&\n (output_context->op & PHP_OUTPUT_HANDLER_FINAL))\n {\n OpenRASPActionType action = openrasp::scm->get_buildin_check_action(XSS_USER_INPUT);\n status = _detect_param_occur_in_html_output(output_context->in.data, action TSRMLS_CC);\n if (status == SUCCESS)\n {\n status = (AC_BLOCK == action) ? SUCCESS : FAILURE;\n }\n if (status == SUCCESS)\n {\n reset_response(TSRMLS_C);\n }\n }\n return status;\n}\n\nstatic php_output_handler *openrasp_output_handler_init(const char *handler_name, size_t handler_name_len, size_t chunk_size, int flags TSRMLS_DC)\n{\n if (chunk_size)\n {\n return nullptr;\n }\n return php_output_handler_create_internal(handler_name, handler_name_len, openrasp_output_handler, chunk_size, flags TSRMLS_CC);\n}\n\nstatic void openrasp_clean_output_start(const char *name, size_t name_len TSRMLS_DC)\n{\n php_output_handler *h;\n\n if (h = openrasp_output_handler_init(name, name_len, 0, PHP_OUTPUT_HANDLER_STDFLAGS TSRMLS_CC))\n {\n php_output_handler_start(h TSRMLS_CC);\n }\n}\n\n#endif\n\nstatic void _check_header_content_type_if_html(void *data, void *arg TSRMLS_DC)\n{\n bool *is_html = static_cast(arg);\n if (*is_html)\n {\n sapi_header_struct *sapi_header = (sapi_header_struct *)data;\n static const char *suffix = \"Content-type\";\n char *header = (char *)(sapi_header->header);\n size_t header_len = strlen(header);\n size_t suffix_len = strlen(suffix);\n if (header_len > suffix_len &&\n strncmp(suffix, header, suffix_len) == 0 &&\n NULL == strstr(header, \"text\/html\"))\n {\n *is_html = false;\n }\n }\n}\n\nstatic bool _gpc_parameter_filter(const zval *param TSRMLS_DC)\n{\n if (Z_TYPE_P(param) == IS_STRING && Z_STRLEN_P(param) > OPENRASP_CONFIG(xss.min_param_length))\n {\n if (openrasp::regex_match(Z_STRVAL_P(param), OPENRASP_CONFIG(xss.filter_regex).c_str()))\n {\n return true;\n }\n }\n return false;\n}\n\nstatic int _detect_param_occur_in_html_output(const char *param, OpenRASPActionType action TSRMLS_DC)\n{\n int status = FAILURE;\n if (!PG(http_globals)[TRACK_VARS_GET] &&\n !zend_is_auto_global(\"_GET\", strlen(\"_GET\") TSRMLS_CC) &&\n Z_TYPE_P(PG(http_globals)[TRACK_VARS_GET]) != IS_ARRAY)\n {\n return FAILURE;\n }\n HashTable *ht = Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_GET]);\n int count = 0;\n for (zend_hash_internal_pointer_reset(ht);\n zend_hash_has_more_elements(ht) == SUCCESS;\n zend_hash_move_forward(ht))\n {\n zval **ele_value;\n if (zend_hash_get_current_data(ht, (void **)&ele_value) != SUCCESS)\n {\n continue;\n }\n if (_gpc_parameter_filter(*ele_value TSRMLS_CC))\n {\n if (++count > OPENRASP_CONFIG(xss.max_detection_num))\n {\n zval *attack_params = NULL;\n MAKE_STD_ZVAL(attack_params);\n array_init(attack_params);\n add_assoc_long(attack_params, \"count\", count);\n zval *plugin_message = NULL;\n MAKE_STD_ZVAL(plugin_message);\n ZVAL_STRING(plugin_message, _(\"Excessively suspected xss parameters\"), 1);\n openrasp_buildin_php_risk_handle(action, XSS_USER_INPUT, 100, attack_params, plugin_message TSRMLS_CC);\n return SUCCESS;\n }\n if (NULL != strstr(param, Z_STRVAL_PP(ele_value)))\n {\n zval *attack_params = NULL;\n MAKE_STD_ZVAL(attack_params);\n array_init(attack_params);\n add_assoc_string(attack_params, \"parameter\", Z_STRVAL_PP(ele_value), 1);\n zval *plugin_message = NULL;\n MAKE_STD_ZVAL(plugin_message);\n char *message_str = NULL;\n spprintf(&message_str, 0, _(\"Reflected XSS attack detected: using get parameter: '%s'\"), Z_STRVAL_PP(ele_value));\n ZVAL_STRING(plugin_message, message_str, 1);\n efree(message_str);\n openrasp_buildin_php_risk_handle(action, XSS_USER_INPUT, 100, attack_params, plugin_message TSRMLS_CC);\n return SUCCESS;\n }\n }\n }\n return status;\n}\n\nstatic bool _is_content_type_html(TSRMLS_D)\n{\n bool is_html = true;\n zend_llist_apply_with_argument(&SG(sapi_headers).headers, _check_header_content_type_if_html, &is_html TSRMLS_CC);\n return is_html;\n}\n\nstatic void openrasp_output_detect_init_globals(zend_openrasp_output_detect_globals *openrasp_output_detect_globals)\n{\n openrasp_output_detect_globals->output_detect = false;\n}\n\nPHP_MINIT_FUNCTION(openrasp_output_detect)\n{\n ZEND_INIT_MODULE_GLOBALS(openrasp_output_detect, openrasp_output_detect_init_globals, nullptr);\n#if (PHP_MAJOR_VERSION == 5) && (PHP_MINOR_VERSION > 3)\n php_output_handler_alias_register(ZEND_STRL(\"openrasp_ob_handler\"), openrasp_output_handler_init TSRMLS_CC);\n#endif\n return SUCCESS;\n}\n\nPHP_RINIT_FUNCTION(openrasp_output_detect)\n{\n OUTPUT_G(output_detect) = false;\n if (!openrasp_check_type_ignored(XSS_USER_INPUT TSRMLS_CC))\n {\n#if (PHP_MAJOR_VERSION == 5) && (PHP_MINOR_VERSION <= 3)\n if (php_start_ob_buffer_named(\"openrasp_ob_handler\", 0, 1 TSRMLS_CC) == FAILURE)\n {\n openrasp_error(E_WARNING, RUNTIME_ERROR, _(\"Failure start OpenRASP output buffering.\"));\n }\n#else\n openrasp_clean_output_start(ZEND_STRL(\"openrasp_ob_handler\") TSRMLS_CC);\n#endif\n }\n return SUCCESS;\n}[PHP5] fix 5.3 xss userinput\/*\n * Copyright 2017-2018 Baidu Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"openrasp_output_detect.h\"\n#include \"openrasp_hook.h\"\n#include \"openrasp_ini.h\"\n#include \"agent\/shared_config_manager.h\"\n#include \"utils\/regex.h\"\n\nZEND_DECLARE_MODULE_GLOBALS(openrasp_output_detect)\n\nstatic void _check_header_content_type_if_html(void *data, void *arg TSRMLS_DC);\nstatic int _detect_param_occur_in_html_output(const char *param, OpenRASPActionType action TSRMLS_DC);\nstatic bool _gpc_parameter_filter(const zval *param TSRMLS_DC);\nstatic bool _is_content_type_html(TSRMLS_D);\n\n#if (PHP_MAJOR_VERSION == 5) && (PHP_MINOR_VERSION <= 3)\n\nvoid openrasp_detect_output(INTERNAL_FUNCTION_PARAMETERS)\n{\n OUTPUT_G(output_detect) = true;\n char *input;\n int input_len;\n long mode;\n\n if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s|l\", &input, &input_len, &mode) == FAILURE)\n {\n RETVAL_FALSE;\n }\n if (_is_content_type_html(TSRMLS_C))\n {\n OpenRASPActionType action = openrasp::scm->get_buildin_check_action(XSS_USER_INPUT);\n int status = _detect_param_occur_in_html_output(input, action TSRMLS_CC);\n if (status == SUCCESS)\n {\n status = (AC_BLOCK == action) ? SUCCESS : FAILURE;\n }\n if (status == SUCCESS)\n {\n reset_response(TSRMLS_C);\n RETVAL_STRING(\"\", 1);\n }\n }\n RETVAL_STRINGL(input, input_len, 1);\n}\n\n#else\n\nstatic php_output_handler *openrasp_output_handler_init(const char *handler_name, size_t handler_name_len, size_t chunk_size, int flags TSRMLS_DC);\nstatic void openrasp_clean_output_start(const char *name, size_t name_len TSRMLS_DC);\nstatic int openrasp_output_handler(void **nothing, php_output_context *output_context);\n\nstatic int openrasp_output_handler(void **nothing, php_output_context *output_context)\n{\n PHP_OUTPUT_TSRMLS(output_context);\n OUTPUT_G(output_detect) = true;\n int status = FAILURE;\n if (_is_content_type_html(TSRMLS_C) &&\n (output_context->op & PHP_OUTPUT_HANDLER_START) &&\n (output_context->op & PHP_OUTPUT_HANDLER_FINAL))\n {\n OpenRASPActionType action = openrasp::scm->get_buildin_check_action(XSS_USER_INPUT);\n status = _detect_param_occur_in_html_output(output_context->in.data, action TSRMLS_CC);\n if (status == SUCCESS)\n {\n status = (AC_BLOCK == action) ? SUCCESS : FAILURE;\n }\n if (status == SUCCESS)\n {\n reset_response(TSRMLS_C);\n }\n }\n return status;\n}\n\nstatic php_output_handler *openrasp_output_handler_init(const char *handler_name, size_t handler_name_len, size_t chunk_size, int flags TSRMLS_DC)\n{\n if (chunk_size)\n {\n return nullptr;\n }\n return php_output_handler_create_internal(handler_name, handler_name_len, openrasp_output_handler, chunk_size, flags TSRMLS_CC);\n}\n\nstatic void openrasp_clean_output_start(const char *name, size_t name_len TSRMLS_DC)\n{\n php_output_handler *h;\n\n if (h = openrasp_output_handler_init(name, name_len, 0, PHP_OUTPUT_HANDLER_STDFLAGS TSRMLS_CC))\n {\n php_output_handler_start(h TSRMLS_CC);\n }\n}\n\n#endif\n\nstatic void _check_header_content_type_if_html(void *data, void *arg TSRMLS_DC)\n{\n bool *is_html = static_cast(arg);\n if (*is_html)\n {\n sapi_header_struct *sapi_header = (sapi_header_struct *)data;\n static const char *suffix = \"Content-type\";\n char *header = (char *)(sapi_header->header);\n size_t header_len = strlen(header);\n size_t suffix_len = strlen(suffix);\n if (header_len > suffix_len &&\n strncmp(suffix, header, suffix_len) == 0 &&\n NULL == strstr(header, \"text\/html\"))\n {\n *is_html = false;\n }\n }\n}\n\nstatic bool _gpc_parameter_filter(const zval *param TSRMLS_DC)\n{\n if (Z_TYPE_P(param) == IS_STRING && Z_STRLEN_P(param) > OPENRASP_CONFIG(xss.min_param_length))\n {\n if (openrasp::regex_match(Z_STRVAL_P(param), OPENRASP_CONFIG(xss.filter_regex).c_str()))\n {\n return true;\n }\n }\n return false;\n}\n\nstatic int _detect_param_occur_in_html_output(const char *param, OpenRASPActionType action TSRMLS_DC)\n{\n int status = FAILURE;\n if (!PG(http_globals)[TRACK_VARS_GET] &&\n !zend_is_auto_global(\"_GET\", strlen(\"_GET\") TSRMLS_CC) &&\n Z_TYPE_P(PG(http_globals)[TRACK_VARS_GET]) != IS_ARRAY)\n {\n return FAILURE;\n }\n HashTable *ht = Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_GET]);\n int count = 0;\n for (zend_hash_internal_pointer_reset(ht);\n zend_hash_has_more_elements(ht) == SUCCESS;\n zend_hash_move_forward(ht))\n {\n zval **ele_value;\n if (zend_hash_get_current_data(ht, (void **)&ele_value) != SUCCESS)\n {\n continue;\n }\n if (_gpc_parameter_filter(*ele_value TSRMLS_CC))\n {\n if (++count > OPENRASP_CONFIG(xss.max_detection_num))\n {\n zval *attack_params = NULL;\n MAKE_STD_ZVAL(attack_params);\n array_init(attack_params);\n add_assoc_long(attack_params, \"count\", count);\n zval *plugin_message = NULL;\n MAKE_STD_ZVAL(plugin_message);\n ZVAL_STRING(plugin_message, _(\"Excessively suspected xss parameters\"), 1);\n openrasp_buildin_php_risk_handle(action, XSS_USER_INPUT, 100, attack_params, plugin_message TSRMLS_CC);\n return SUCCESS;\n }\n if (NULL != strstr(param, Z_STRVAL_PP(ele_value)))\n {\n zval *attack_params = NULL;\n MAKE_STD_ZVAL(attack_params);\n array_init(attack_params);\n add_assoc_string(attack_params, \"parameter\", Z_STRVAL_PP(ele_value), 1);\n zval *plugin_message = NULL;\n MAKE_STD_ZVAL(plugin_message);\n char *message_str = NULL;\n spprintf(&message_str, 0, _(\"Reflected XSS attack detected: using get parameter: '%s'\"), Z_STRVAL_PP(ele_value));\n ZVAL_STRING(plugin_message, message_str, 1);\n efree(message_str);\n openrasp_buildin_php_risk_handle(action, XSS_USER_INPUT, 100, attack_params, plugin_message TSRMLS_CC);\n return SUCCESS;\n }\n }\n }\n return status;\n}\n\nstatic bool _is_content_type_html(TSRMLS_D)\n{\n bool is_html = true;\n zend_llist_apply_with_argument(&SG(sapi_headers).headers, _check_header_content_type_if_html, &is_html TSRMLS_CC);\n return is_html;\n}\n\nstatic void openrasp_output_detect_init_globals(zend_openrasp_output_detect_globals *openrasp_output_detect_globals)\n{\n openrasp_output_detect_globals->output_detect = false;\n}\n\nPHP_MINIT_FUNCTION(openrasp_output_detect)\n{\n ZEND_INIT_MODULE_GLOBALS(openrasp_output_detect, openrasp_output_detect_init_globals, nullptr);\n#if (PHP_MAJOR_VERSION == 5) && (PHP_MINOR_VERSION > 3)\n php_output_handler_alias_register(ZEND_STRL(\"openrasp_ob_handler\"), openrasp_output_handler_init TSRMLS_CC);\n#endif\n return SUCCESS;\n}\n\nPHP_RINIT_FUNCTION(openrasp_output_detect)\n{\n OUTPUT_G(output_detect) = false;\n if (!openrasp_check_type_ignored(XSS_USER_INPUT TSRMLS_CC))\n {\n#if (PHP_MAJOR_VERSION == 5) && (PHP_MINOR_VERSION <= 3)\n if (php_start_ob_buffer_named(\"openrasp_ob_handler\", 0, 1 TSRMLS_CC) == FAILURE)\n {\n openrasp_error(E_WARNING, RUNTIME_ERROR, _(\"Failure start OpenRASP output buffering.\"));\n }\n#else\n openrasp_clean_output_start(ZEND_STRL(\"openrasp_ob_handler\") TSRMLS_CC);\n#endif\n }\n return SUCCESS;\n}<|endoftext|>"} {"text":"#include \"RootDirectory.h\"\n\nstd::vector RootDirectory::rootdirectories = std::vector();\n\nRootDirectory::RootDirectory(const std::string &root) {\n\trootdirectories.push_back(this);\n\tthis->id = rootdirectories.size();\n\tthis->root = (root[root.size()-1] == '\/') ? root.substr(0,root.size()-1) : root;\n\tscan(\"\");\n}\n\n\nvoid RootDirectory::scan(std::string relpath) {\n\tstruct dirent **de;\n\tstd::string fullpath(root);\n\tfullpath += \"\/\";\n\tif (relpath.size() > 0) {\n\t\tfullpath += relpath;\n\t\tfullpath += \"\/\";\n\t}\n\tint n = scandirat(AT_FDCWD, fullpath.c_str(), &de, NULL, alphasort);\n\tif (n == -1)\n\t\treturn;\n\n\twhile(n--) {\n\t\tif (!strcmp(de[n]->d_name, \"..\") || !strcmp(de[n]->d_name, \".\"))\n\t\t\tcontinue;\n\n\t\tif (de[n]->d_type == DT_DIR) {\n\t\t\t\/\/continue; \/\/XXX just testing for now don't descend the tree\n\t\t\t\/\/directory\n\t\t\tscan(de[n]->d_name); \/\/recurse\n\t\t}\n\t\tif (de[n]->d_type == DT_REG) {\n\t\t\t\/\/regular file\n\t\t\tstd::string filename(de[n]->d_name);\n\t\t\tfullpath += de[n]->d_name;\n\t\t\tFile *file = new File(root, relpath, filename);\n\t\t\tstd::cout << file->fullpath << std::endl;\n\t\t\tAddFile(file);\n\t\t}\n\t}\n\tfree(de);\n}\n\n\nvoid RootDirectory::AddFile(File *file) {\n\n\t\/\/ insert into the inode table\n\tfilesbyinode.insert(std::pair(file->inode, file));\n\n\t\/\/ insert into the size table\n\tfilesbysize.insert(std::pair(file->size, file));\n\n\t\/\/ insert into relativepath table\n\tstd::string rp;\n\tif (file->relpath.size() > 0) {\n\t\trp += file->relpath;\n\t\trp += \"\/\";\n\t}\n\trp += file->name;\n\tfilesbyrelativepath.insert(std::pair(rp, file));\n\n\t\/*\n\tif ((filesbysize.count(file->size) > 1) && (!file->hardlink)) {\n\t\tauto rp = filesbysize.equal_range(file->size); \/\/range of files with same size\n\t\tfor(auto it = rp.first; it != rp.second; it++) {\n\t\t\tif (file == it->second)\n\t\t\t\tcontinue; \/\/well, we don't want to link to ourselves\n\t\t\tif (file->equal(*it->second))\/\/ find the other identically sized file(s)\n\t\t\t\tfile->link(it->second); \/\/make a hardlink\n\t\t}\n\t}\n\t*\/\n}\n\n\nvoid RootDirectory::PrintByInode (void) {\n\tstd::cout << \"By inode:\"<< std::left << std::endl;\n\tfor (auto pf : filesbyinode) {\n\t\tFile *f = pf.second;\n\t\tif (f->hardlink)\n\t\t\tstd::cout << \"H\";\n\t\tif (f->dup)\n\t\t\tstd::cout << \"D\";\n\n\t\tstd::cout << \" \\t\";\n\t\tstd::cout<inode << std::setw(10) << f->size << std::setw(40) << f->name.substr(0,35) << \"\\t\" ;\n\t\tif (f->sha) {\n\t\t\tfor(int i = 0; i < 64 ; i++) {\n\t\t\t\tif (i==10) {\n\t\t\t\t\tstd::cout << \"...\";\n\t\t\t\t\ti+=44;\n\t\t\t\t}\n\t\t\t\tprintf(\"%02x\", f->sha[i]);\n\t\t\t}\n\t\t\tprintf(\"\\n\");\n\n\t\t} else {\n\t\t\tstd::cout << std::endl;\n\t\t}\n\t}\n\tstd::cout << std::right << std::endl;\n}\n\n\nvoid RootDirectory::PrintBySize (void) {\n\tstd::cout << std::endl << \"By size:\"<< std::left << std::endl;\n\tfor (auto pf : filesbysize) {\n\t\tauto f = pf.second;\n\t\tstd::cout<inode << std::setw(10) << f->size << std::setw(40) << f->name.substr(0,35) << \"\\t\" ;\n\t\tif (f->sha) {\n\t\t\tfor(int i = 0; i < 64 ; i++) {\n\t\t\t\tif (i==10) {\n\t\t\t\t\tstd::cout << \"...\";\n\t\t\t\t\ti+=44;\n\t\t\t\t}\n\t\t\t\tprintf(\"%02x\", f->sha[i]);\n\t\t\t}\n\t\t\tprintf(\"\\n\");\n\n\t\t} else {\n\t\t\tstd::cout << std::endl;\n\t\t}\n\t}\n\tstd::cout << std::right << std::endl;\n}\n\n\nvoid RootDirectory::PrintByRelativepath (void) {\n\tstd::cout << std::endl << \"By relative path:\"<< std::left << std::endl;\n\tfor (auto pf : filesbyrelativepath) {\n\t\tauto f = pf.second;\n\t\tstd::cout<size << std::setw(40) << f->name.substr(0,35) << \"\\t\" ;\n\t\tif (f->sha) {\n\t\t\tfor(int i = 0; i < 64 ; i++) {\n\t\t\t\tif (i==10) {\n\t\t\t\t\tstd::cout << \"...\";\n\t\t\t\t\ti+=44;\n\t\t\t\t}\n\t\t\t\tprintf(\"%02x\", f->sha[i]);\n\t\t\t}\n\t\t\tprintf(\"\\n\");\n\n\t\t} else {\n\t\t\tstd::cout << std::endl;\n\t\t}\n\t}\n\tstd::cout << std::right << std::endl;\n}\n\n\nRootDirectory::~RootDirectory() {\n\tfor (auto it = filesbysize.begin(); it != filesbysize.end(); it ++)\n\t\tdelete (*it).second;\n}\nready to find the candidates for hardlinking#include \"RootDirectory.h\"\n\nstd::vector RootDirectory::rootdirectories = std::vector();\n\nRootDirectory::RootDirectory(const std::string &root) {\n\trootdirectories.push_back(this);\n\tthis->id = rootdirectories.size();\n\tthis->root = (root[root.size()-1] == '\/') ? root.substr(0,root.size()-1) : root;\n\tscan(\"\");\n}\n\n\nvoid RootDirectory::scan(std::string relpath) {\n\tstruct dirent **de;\n\tstd::string fullpath(root);\n\tfullpath += \"\/\";\n\tif (relpath.size() > 0) {\n\t\tfullpath += relpath;\n\t\tfullpath += \"\/\";\n\t}\n\tint n = scandirat(AT_FDCWD, fullpath.c_str(), &de, NULL, alphasort);\n\tif (n == -1)\n\t\treturn;\n\n\twhile(n--) {\n\t\tif (!strcmp(de[n]->d_name, \"..\") || !strcmp(de[n]->d_name, \".\"))\n\t\t\tcontinue;\n\n\t\tif (de[n]->d_type == DT_DIR) {\n\t\t\t\/\/directory\n\t\t\tscan(de[n]->d_name); \/\/recurse\n\t\t}\n\t\tif (de[n]->d_type == DT_REG) {\n\t\t\t\/\/regular file\n\t\t\tstd::string filename(de[n]->d_name);\n\t\t\tfullpath += de[n]->d_name;\n\t\t\tFile *file = new File(root, relpath, filename);\n\t\t\tAddFile(file);\n\t\t}\n\t}\n\tfree(de);\n}\n\n\nvoid RootDirectory::AddFile(File *file) {\n\n\t\/\/ insert into the inode table\n\tfilesbyinode.insert(std::pair(file->inode, file));\n\n\t\/\/ insert into the size table\n\tfilesbysize.insert(std::pair(file->size, file));\n\n\t\/\/ insert into relativepath table\n\tstd::string rp;\n\tif (file->relpath.size() > 0) {\n\t\trp += file->relpath;\n\t\trp += \"\/\";\n\t}\n\trp += file->name;\n\tfilesbyrelativepath.insert(std::pair(rp, file));\n\n\t\/\/ find identical files (candidates for hard linking)\n\t\/*\n\tif ((filesbysize.count(file->size) > 1) && (!file->hardlink)) {\n\t\tauto rp = filesbysize.equal_range(file->size); \/\/range of files with same size\n\t\tfor(auto it = rp.first; it != rp.second; it++) {\n\t\t\tif (file == it->second)\n\t\t\t\tcontinue; \/\/well, we don't want to link to ourselves\n\t\t\tif (file->equal(*it->second))\/\/ find the other identically sized file(s)\n\t\t\t\tfile->link(it->second); \/\/make a hardlink\n\t\t}\n\t}\n\t*\/\n}\n\n\nvoid RootDirectory::PrintByInode (void) {\n\tstd::cout << \"By inode:\"<< std::left << std::endl;\n\tfor (auto pf : filesbyinode) {\n\t\tFile *f = pf.second;\n\t\tif (f->hardlink)\n\t\t\tstd::cout << \"H\";\n\t\tif (f->dup)\n\t\t\tstd::cout << \"D\";\n\n\t\tstd::cout << \" \\t\";\n\t\tstd::cout<inode << std::setw(10) << f->size << std::setw(40) << f->name.substr(0,35) << \"\\t\" ;\n\t\tif (f->sha) {\n\t\t\tfor(int i = 0; i < 64 ; i++) {\n\t\t\t\tif (i==10) {\n\t\t\t\t\tstd::cout << \"...\";\n\t\t\t\t\ti+=44;\n\t\t\t\t}\n\t\t\t\tprintf(\"%02x\", f->sha[i]);\n\t\t\t}\n\t\t\tprintf(\"\\n\");\n\n\t\t} else {\n\t\t\tstd::cout << std::endl;\n\t\t}\n\t}\n\tstd::cout << std::right << std::endl;\n}\n\n\nvoid RootDirectory::PrintBySize (void) {\n\tstd::cout << std::endl << \"By size:\"<< std::left << std::endl;\n\tfor (auto pf : filesbysize) {\n\t\tauto f = pf.second;\n\t\tstd::cout<inode << std::setw(10) << f->size << std::setw(40) << f->name.substr(0,35) << \"\\t\" ;\n\t\tif (f->sha) {\n\t\t\tfor(int i = 0; i < 64 ; i++) {\n\t\t\t\tif (i==10) {\n\t\t\t\t\tstd::cout << \"...\";\n\t\t\t\t\ti+=44;\n\t\t\t\t}\n\t\t\t\tprintf(\"%02x\", f->sha[i]);\n\t\t\t}\n\t\t\tprintf(\"\\n\");\n\n\t\t} else {\n\t\t\tstd::cout << std::endl;\n\t\t}\n\t}\n\tstd::cout << std::right << std::endl;\n}\n\n\nvoid RootDirectory::PrintByRelativepath (void) {\n\tstd::cout << std::endl << \"By relative path:\"<< std::left << std::endl;\n\tfor (auto pf : filesbyrelativepath) {\n\t\tauto f = pf.second;\n\t\tstd::cout<size << std::setw(40) << f->name.substr(0,35) << \"\\t\" ;\n\t\tif (f->sha) {\n\t\t\tfor(int i = 0; i < 64 ; i++) {\n\t\t\t\tif (i==10) {\n\t\t\t\t\tstd::cout << \"...\";\n\t\t\t\t\ti+=44;\n\t\t\t\t}\n\t\t\t\tprintf(\"%02x\", f->sha[i]);\n\t\t\t}\n\t\t\tprintf(\"\\n\");\n\n\t\t} else {\n\t\t\tstd::cout << std::endl;\n\t\t}\n\t}\n\tstd::cout << std::right << std::endl;\n}\n\n\nRootDirectory::~RootDirectory() {\n\tfor (auto it = filesbysize.begin(); it != filesbysize.end(); it ++)\n\t\tdelete (*it).second;\n}\n<|endoftext|>"} {"text":"\/\/ SimpleLayout.cpp\r\n\r\n#include \"SimpleLayout.h\"\r\n#include \"SimpleLayoutData.h\"\r\n#include \"SimpleTextRunLoop.h\"\r\n#include \"SimpleTextBlock.h\"\r\n#include \"TextLayoutArgs.h\"\r\n#include \"TextDocument.h\"\r\n#include \"TextStyleRegistry.h\"\r\n#include \"Assert.h\"\r\n#include \r\n\r\n#undef min\r\n#undef max\r\n\r\nclass DebuggableException {};\r\nclass SimpleLayoutFailed : public DebuggableException {};\r\n\r\nstatic size_t LayoutRun( SimpleTextRun run,\r\n SimpleLayoutData& layoutData,\r\n const TextLayoutArgs& args,\r\n int xStart,\r\n bool forceFit )\r\n{\r\n\tSIZE size;\r\n\tINT fit;\r\n\r\n\tint maxWidth = ( forceFit || args.maxWidth == 0 ) ? std::numeric_limits::max() : args.maxWidth;\r\n\r\n\tif ( run.textCount == 1 && args.text[run.textStart] == '\\t' && args.styleRegistry.tabSize > 0 )\r\n\t{\r\n\t\tint tabWidth = args.styleRegistry.tabSize - ( xStart % args.styleRegistry.tabSize );\r\n\t\tlayoutData.xOffsets[run.textStart - 1] = tabWidth;\r\n\t\tfit = ( tabWidth < maxWidth ? 1 : 0 );\r\n\t}\r\n\telse\r\n\t{\r\n\t\tsize_t textCount = std::min( run.textCount, 256 );\r\n\t\t\r\n\t\tSelectObject( args.hdc, args.styleRegistry.Font( run.fontid ).hfont );\r\n\t\tif ( !GetTextExtentExPoint( args.hdc,\r\n\t\t args.text.begin() + run.textStart,\r\n\t\t textCount,\r\n\t\t args.maxWidth - std::min( maxWidth, xStart ),\r\n\t\t &fit,\r\n\t\t &layoutData.xOffsets.front() + run.textStart,\r\n\t\t &size ) )\r\n\t\t{\r\n\t\t\tAssert( false );\r\n\t\t\tthrow SimpleLayoutFailed();\r\n\t\t}\r\n\t}\r\n\r\n\trun.textCount = fit;\r\n\tlayoutData.runs.push_back( run );\r\n\treturn fit;\r\n}\r\n\r\nstatic size_t WrapLine( SimpleLayoutData& layoutData,\r\n const TextLayoutArgs& args,\r\n size_t lineStart,\r\n int lineWidth )\r\n{\r\n\tSimpleTextRun lastRun = layoutData.runs.back();\r\n\r\n\t\/\/ 'lastRun' can have a textCount of 0\r\n\tsize_t estimate = args.textStart + lastRun.textStart + lastRun.textCount;\r\n\r\n\tsize_t lineEnd = args.doc.PrevSoftBreak( estimate + 1 );\r\n\r\n\tif ( lineEnd <= args.textStart + lineStart )\r\n\t\tlineEnd = args.doc.PrevWordStop( estimate + 1 );\r\n\r\n\tif ( lineEnd <= args.textStart + lineStart )\r\n\t\tlineEnd = args.doc.PrevCharStop( estimate + 1 );\r\n\r\n\tif ( lineEnd <= args.textStart + lineStart )\r\n\t\tlineEnd = estimate;\r\n\r\n\tlineEnd -= args.textStart;\r\n\r\n\tlayoutData.DiscardFrom( lineEnd );\r\n\r\n\tif ( lineStart == lineEnd )\r\n\t{\r\n\t\tlastRun.textCount = 1;\r\n\t\tLayoutRun( lastRun, layoutData, args, lineWidth, true );\r\n\t\tlineEnd++;\r\n\t}\r\n\r\n\treturn lineEnd;\r\n}\r\n\r\nTextBlockPtr SimpleLayoutParagraph( const TextLayoutArgs& args )\r\n{\r\n\tSimpleLayoutDataPtr layoutData( new SimpleLayoutData( args.text, args.endsWithNewline ) );\r\n\r\n\tint lineWidth = 0;\r\n\tsize_t lineStart = 0;\r\n\r\n\tfor ( SimpleTextRunLoop loop( args.text, args.fonts ); loop.Unfinished(); )\r\n\t{\r\n\t\tSimpleTextRun run = loop.NextRun();\r\n\t\tsize_t fit = LayoutRun( run, *layoutData, args, lineWidth, false );\r\n\r\n\t\tif ( fit == run.textCount )\r\n\t\t{\r\n\t\t\tlineWidth += layoutData->xOffsets[run.textStart + run.textCount];\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tlineStart = WrapLine( *layoutData, args, lineStart, lineWidth );\r\n\t\t\tlineWidth = 0;\r\n\r\n\t\t\tlayoutData->lines.push_back( layoutData->runs.size() );\r\n\t\t\tloop.NewLine( lineStart );\r\n\t\t}\r\n\t}\r\n\r\n\tif ( layoutData->lines.empty() || layoutData->lines.back() != layoutData->runs.size() )\r\n\t\tlayoutData->lines.push_back( layoutData->runs.size() );\r\n\r\n\treturn TextBlockPtr( new SimpleTextBlock( std::move( layoutData ), args.styleRegistry ) );\r\n}\r\nFix a maxSize bug, and an array indexing bug introduced by the last change.\/\/ SimpleLayout.cpp\r\n\r\n#include \"SimpleLayout.h\"\r\n#include \"SimpleLayoutData.h\"\r\n#include \"SimpleTextRunLoop.h\"\r\n#include \"SimpleTextBlock.h\"\r\n#include \"TextLayoutArgs.h\"\r\n#include \"TextDocument.h\"\r\n#include \"TextStyleRegistry.h\"\r\n#include \"Assert.h\"\r\n#include \r\n\r\n#undef min\r\n#undef max\r\n\r\nclass DebuggableException {};\r\nclass SimpleLayoutFailed : public DebuggableException {};\r\n\r\nstatic size_t LayoutRun( SimpleTextRun run,\r\n SimpleLayoutData& layoutData,\r\n const TextLayoutArgs& args,\r\n int xStart,\r\n bool forceFit )\r\n{\r\n\tSIZE size;\r\n\tINT fit;\r\n\r\n\tint maxWidth = ( forceFit || args.maxWidth == 0 ) ? std::numeric_limits::max() : args.maxWidth;\r\n\r\n\tif ( run.textCount == 1 && args.text[run.textStart] == '\\t' && args.styleRegistry.tabSize > 0 )\r\n\t{\r\n\t\tint tabWidth = args.styleRegistry.tabSize - ( xStart % args.styleRegistry.tabSize );\r\n\t\tlayoutData.xOffsets[run.textStart] = tabWidth;\r\n\t\tfit = ( tabWidth < maxWidth ? 1 : 0 );\r\n\t}\r\n\telse\r\n\t{\r\n\t\tsize_t textCount = std::min( run.textCount, 256 );\r\n\t\t\r\n\t\tSelectObject( args.hdc, args.styleRegistry.Font( run.fontid ).hfont );\r\n\t\tif ( !GetTextExtentExPoint( args.hdc,\r\n\t\t args.text.begin() + run.textStart,\r\n\t\t textCount,\r\n\t\t maxWidth - std::min( maxWidth, xStart ),\r\n\t\t &fit,\r\n\t\t &layoutData.xOffsets.front() + run.textStart,\r\n\t\t &size ) )\r\n\t\t{\r\n\t\t\tAssert( false );\r\n\t\t\tthrow SimpleLayoutFailed();\r\n\t\t}\r\n\t}\r\n\r\n\trun.textCount = fit;\r\n\tlayoutData.runs.push_back( run );\r\n\treturn fit;\r\n}\r\n\r\nstatic size_t WrapLine( SimpleLayoutData& layoutData,\r\n const TextLayoutArgs& args,\r\n size_t lineStart,\r\n int lineWidth )\r\n{\r\n\tSimpleTextRun lastRun = layoutData.runs.back();\r\n\r\n\t\/\/ 'lastRun' can have a textCount of 0\r\n\tsize_t estimate = args.textStart + lastRun.textStart + lastRun.textCount;\r\n\r\n\tsize_t lineEnd = args.doc.PrevSoftBreak( estimate + 1 );\r\n\r\n\tif ( lineEnd <= args.textStart + lineStart )\r\n\t\tlineEnd = args.doc.PrevWordStop( estimate + 1 );\r\n\r\n\tif ( lineEnd <= args.textStart + lineStart )\r\n\t\tlineEnd = args.doc.PrevCharStop( estimate + 1 );\r\n\r\n\tif ( lineEnd <= args.textStart + lineStart )\r\n\t\tlineEnd = estimate;\r\n\r\n\tlineEnd -= args.textStart;\r\n\r\n\tlayoutData.DiscardFrom( lineEnd );\r\n\r\n\tif ( lineStart == lineEnd )\r\n\t{\r\n\t\tlastRun.textCount = 1;\r\n\t\tLayoutRun( lastRun, layoutData, args, lineWidth, true );\r\n\t\tlineEnd++;\r\n\t}\r\n\r\n\treturn lineEnd;\r\n}\r\n\r\nTextBlockPtr SimpleLayoutParagraph( const TextLayoutArgs& args )\r\n{\r\n\tSimpleLayoutDataPtr layoutData( new SimpleLayoutData( args.text, args.endsWithNewline ) );\r\n\r\n\tint lineWidth = 0;\r\n\tsize_t lineStart = 0;\r\n\r\n\tfor ( SimpleTextRunLoop loop( args.text, args.fonts ); loop.Unfinished(); )\r\n\t{\r\n\t\tSimpleTextRun run = loop.NextRun();\r\n\t\tsize_t fit = LayoutRun( run, *layoutData, args, lineWidth, false );\r\n\r\n\t\tif ( fit == run.textCount )\r\n\t\t{\r\n\t\t\tlineWidth += layoutData->xOffsets[run.textStart + run.textCount - 1];\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tlineStart = WrapLine( *layoutData, args, lineStart, lineWidth );\r\n\t\t\tlineWidth = 0;\r\n\r\n\t\t\tlayoutData->lines.push_back( layoutData->runs.size() );\r\n\t\t\tloop.NewLine( lineStart );\r\n\t\t}\r\n\t}\r\n\r\n\tif ( layoutData->lines.empty() || layoutData->lines.back() != layoutData->runs.size() )\r\n\t\tlayoutData->lines.push_back( layoutData->runs.size() );\r\n\r\n\treturn TextBlockPtr( new SimpleTextBlock( std::move( layoutData ), args.styleRegistry ) );\r\n}\r\n<|endoftext|>"} {"text":"#include \n#include \/\/ << fixed << setprecision(xxx)\n#include \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include \n#include \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include \n#include \/\/ get(xxx)\n#include \n#include \n#include \/\/ if (M.find(key) != M.end()) { }\n#include \/\/ S.insert(M);\n\/\/ if (S.find(key) != S.end()) { }\n\/\/ for (auto it=S.begin(); it != S.end(); it++) { }\n\/\/ auto it = S.lower_bound(M);\n#include \/\/ random_device rd; mt19937 mt(rd());\n#include \n#include \n#include \n#include \n#include \/\/ atoi(xxx)\nusing namespace std;\n\n#define DEBUG 0 \/\/ change 0 -> 1 if we need debug.\n\/\/ insert #if by my emacs. #if DEBUG == 1 ... #end\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\nconst ll infty = 1000000000000000000;\n\ntypedef tuple state;\n\nint main () {\n int N;\n cin >> N;\n ll a[200010];\n for (auto i = 0; i < N; ++i) {\n cin >> a[i];\n }\n priority_queue, greater > Q;\n ll ans[200010];\n fill(ans, ans+200010, infty);\n for (auto i = 0; i < N; ++i) {\n Q.push(state(a[i], i, 0));\n }\n while(!Q.empty()) {\n ll num = get<0>(Q.top());\n ll place = get<1>(Q.top());\n ll dist = get<2>(Q.top());\n Q.pop();\n if (ans[place] == infty) {\n ans[place] = num;\n ll nplace[2] = {num + 1, num - 1};\n ll ndist = dist+1;\n ll nnum = num - dist * dist + ndist * ndist;\n for (auto j = 0; j < 2; ++j) {\n if (0 <= nplace[j] && nplace[j] < N) {\n Q.push(state(nnum, nplace[j], ndist));\n }\n }\n } \n }\n for (auto i = 0; i < N; ++i) {\n cout << a[i] << endl;\n }\n}\ntried C.cpp to 'C'#include \n#include \/\/ << fixed << setprecision(xxx)\n#include \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include \n#include \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include \n#include \/\/ get(xxx)\n#include \n#include \n#include \/\/ if (M.find(key) != M.end()) { }\n#include \/\/ S.insert(M);\n\/\/ if (S.find(key) != S.end()) { }\n\/\/ for (auto it=S.begin(); it != S.end(); it++) { }\n\/\/ auto it = S.lower_bound(M);\n#include \/\/ random_device rd; mt19937 mt(rd());\n#include \n#include \n#include \n#include \n#include \/\/ atoi(xxx)\nusing namespace std;\n\n#define DEBUG 0 \/\/ change 0 -> 1 if we need debug.\n\/\/ insert #if by my emacs. #if DEBUG == 1 ... #end\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\nconst ll infty = 1000000000000000000;\n\ntypedef tuple state;\n\nint main () {\n int N;\n cin >> N;\n ll a[200010];\n for (auto i = 0; i < N; ++i) {\n cin >> a[i];\n }\n priority_queue, greater > Q;\n ll ans[200010];\n fill(ans, ans+200010, infty);\n for (auto i = 0; i < N; ++i) {\n Q.push(state(a[i], i, 0));\n }\n while(!Q.empty()) {\n ll num = get<0>(Q.top());\n ll place = get<1>(Q.top());\n ll dist = get<2>(Q.top());\n Q.pop();\n if (ans[place] == infty) {\n ans[place] = num;\n ll nplace[2] = {place + 1, place - 1};\n ll ndist = dist+1;\n ll nnum = num - dist * dist + ndist * ndist;\n for (auto j = 0; j < 2; ++j) {\n if (0 <= nplace[j] && nplace[j] < N) {\n Q.push(state(nnum, nplace[j], ndist));\n }\n }\n } \n }\n for (auto i = 0; i < N; ++i) {\n cout << a[i] << endl;\n }\n}\n<|endoftext|>"} {"text":"\/**\n * File : D.cpp\n * Author : Kazune Takahashi\n * Created : 2018-4-7 15:32:10\n * Powered by Visual Studio Code\n *\/\n\n#include \n#include \/\/ << fixed << setprecision(xxx)\n#include \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include \n#include \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include \n#include \n#include \n#include \n#include \/\/ if (M.find(key) != M.end()) { }\n#include \n#include \/\/ random_device rd; mt19937 mt(rd());\n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\n#define DEBUG 0 \/\/ change 0 -> 1 if we need debug.\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\nconst int infty = 1000000007;\n\nint N, M, L, X;\nint a[1010];\nint DP[1010];\nint DP2[1010];\nint sum;\n\nint main()\n{\n cin >> N >> M >> L >> X;\n for (auto i = 0; i < N; i++)\n {\n cin >> a[i];\n }\n int maxi = (X - 1) * M + L;\n fill(DP, DP + M, infty);\n DP[0] = 0;\n for (auto i = 0; i < N; i++)\n {\n for (auto j = 0; j < M; j++)\n {\n DP2[j] = DP[j];\n }\n for (auto j = 0; j < M; j++)\n {\n if (DP[j] == infty)\n continue;\n sum = DP[j] + a[i];\n DP2[sum % M] = min(DP[sum % M], sum);\n }\n for (auto j = 0; j < M; j++)\n {\n DP[j] = DP2[j];\n }\n#if DEBUG == 1\n for (auto j = 0; j < M; j++)\n {\n cerr << DP[j] << \" \";\n }\n cerr << endl;\n#endif\n }\n cout << ((DP[L] <= maxi) ? \"Yes\" : \"No\") << endl;\n}tried D.cpp to 'D'\/**\n * File : D.cpp\n * Author : Kazune Takahashi\n * Created : 2018-4-7 15:32:10\n * Powered by Visual Studio Code\n *\/\n\n#include \n#include \/\/ << fixed << setprecision(xxx)\n#include \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include \n#include \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include \n#include \n#include \n#include \n#include \/\/ if (M.find(key) != M.end()) { }\n#include \n#include \/\/ random_device rd; mt19937 mt(rd());\n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\n#define DEBUG 1 \/\/ change 0 -> 1 if we need debug.\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\nconst int infty = 1000000007;\n\nint N, M, L, X;\nint a[1010];\nint DP[1010];\nint DP2[1010];\nint sum;\n\nint main()\n{\n cin >> N >> M >> L >> X;\n for (auto i = 0; i < N; i++)\n {\n cin >> a[i];\n }\n int maxi = (X - 1) * M + L;\n fill(DP, DP + M, infty);\n DP[0] = 0;\n for (auto i = 0; i < N; i++)\n {\n for (auto j = 0; j < M; j++)\n {\n if (DP[j] == infty)\n continue;\n sum = DP[j] + a[i];\n DP2[sum % M] = min(DP[sum % M], sum);\n }\n for (auto j = 0; j < M; j++)\n {\n DP[j] = DP2[j];\n }\n#if DEBUG == 1\n for (auto j = 0; j < M; j++)\n {\n cerr << DP[j] << \" \";\n }\n cerr << endl;\n#endif\n }\n cerr << ((DP[L] <= maxi) ? \"Yes\" : \"No\") << endl;\n}<|endoftext|>"} {"text":"\/*\n * bacteria-core, core for cellular automaton\n * Copyright (C) 2016 Pavel Dolgov\n *\n * See the LICENSE file for terms of use.\n *\/\n\n#ifndef CONSTANTS_HPP_\n#define CONSTANTS_HPP_\n\n\/** Default mass of bacteria *\/\nconst int DEFAULT_MASS = 5;\n\n\/** Minimum width of board *\/\nconst int MIN_WIDTH = 5;\n\n\/** Maximum width of board *\/\nconst int MAX_WIDTH = 500;\n\n\/** Minimum height of board *\/\nconst int MIN_HEIGHT = 5;\n\n\/** Maximum height of board *\/\nconst int MAX_HEIGHT = 500;\n\n\/** Indent between minimum and default width\/height *\/\nconst int INDENT = 15;\n\n#endif\nRemove constant INDENT\/*\n * bacteria-core, core for cellular automaton\n * Copyright (C) 2016 Pavel Dolgov\n *\n * See the LICENSE file for terms of use.\n *\/\n\n#ifndef CONSTANTS_HPP_\n#define CONSTANTS_HPP_\n\n\/** Default mass of bacteria *\/\nconst int DEFAULT_MASS = 5;\n\n\/** Minimum width of board *\/\nconst int MIN_WIDTH = 5;\n\n\/** Maximum width of board *\/\nconst int MAX_WIDTH = 500;\n\n\/** Minimum height of board *\/\nconst int MIN_HEIGHT = 5;\n\n\/** Maximum height of board *\/\nconst int MAX_HEIGHT = 500;\n\n#endif\n<|endoftext|>"} {"text":"#define DEBUG 1\n\n\/**\n * File : E.cpp\n * Author : Kazune Takahashi\n * Created : 2\/17\/2019, 2:03:40 PM\n * Powered by Visual Studio Code\n *\/\n\n#include \n#include \/\/ << fixed << setprecision(xxx)\n#include \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include \n#include \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include \n#include \n#include \n#include \n#include \/\/ if (M.find(key) != M.end()) { }\n#include \n#include \n#include \/\/ auto rd = bind(uniform_int_distribution(0, 9), mt19937(10101010));\n#include \/\/ std::chrono::system_clock::time_point start_time, end_time;\n\/\/ start = std::chrono::system_clock::now();\n\/\/ double elapsed = std::chrono::duration_cast(end_time-start_time).count();\n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\nconst ll MOD = 1000000007;\n\nll N, K;\nll memo[100010];\n\nll power(int x)\n{\n if (x < 0)\n {\n return 0;\n }\n assert(x < 100010);\n return memo[x];\n}\n\nll DP[5010][5010];\nll DP2[5010][5010];\n\nvoid init()\n{\n memo[0] = 1;\n for (auto i = 1; i < 100010; i++)\n {\n memo[i] = memo[i - 1] * 2;\n memo[i] %= MOD;\n }\n for (auto i = 0; i < N; i++)\n {\n DP[0][i] = power(i - (K - 1));\n }\n DP2[0][0] = DP[0][0];\n for (auto i = 1; i < N; i++)\n {\n DP2[0][i] = DP2[0][i - 1] + DP[0][i];\n DP2[0][i] %= MOD;\n }\n}\n\nvoid flush()\n{\n#if DEBUG == 1\n if (N <= 10)\n {\n for (auto i = 0; i < N; i++)\n {\n for (auto j = 0; j < N; j++)\n {\n cerr << \"DP[\" << i << \"][\" << j << \"] = \" << DP[i][j] << endl;\n }\n }\n }\n#endif\n ll ans = 0;\n for (auto i = 0; i < N; i++)\n {\n ans += DP[i][N - 1];\n ans %= MOD;\n }\n cout << ans << endl;\n}\n\nint main()\n{\n cin >> N >> K;\n init();\n for (auto i = 1; i < N; i++)\n {\n for (auto j = 0; j < N; j++)\n {\n DP[i][j] = 0;\n if (j > 0)\n {\n DP[i][j] += (DP2[i - 1][j - 1] * power(j - i - (K - 1))) % MOD;\n }\n DP[i][j] += (DP[i - 1][j] * power(j - i - (K - 2))) % MOD;\n }\n DP2[i][0] = DP[i][0];\n for (auto j = 1; j < N; j++)\n {\n DP2[i][j] = DP2[i][j - 1] + DP[i][j];\n DP2[i][j] %= MOD;\n }\n }\n flush();\n}tried E.cpp to 'E'#define DEBUG 1\n\n\/**\n * File : E.cpp\n * Author : Kazune Takahashi\n * Created : 2\/17\/2019, 2:03:40 PM\n * Powered by Visual Studio Code\n *\/\n\n#include \n#include \/\/ << fixed << setprecision(xxx)\n#include \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include \n#include \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include \n#include \n#include \n#include \n#include \/\/ if (M.find(key) != M.end()) { }\n#include \n#include \n#include \/\/ auto rd = bind(uniform_int_distribution(0, 9), mt19937(10101010));\n#include \/\/ std::chrono::system_clock::time_point start_time, end_time;\n\/\/ start = std::chrono::system_clock::now();\n\/\/ double elapsed = std::chrono::duration_cast(end_time-start_time).count();\n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\nconst ll MOD = 1000000007;\n\nll N, K;\nll memo[100010];\n\nll power(int x)\n{\n if (x < 0)\n {\n return 0;\n }\n assert(x < 100010);\n return memo[x];\n}\n\nll DP[5010][5010];\nll DP2[5010][5010];\n\nvoid init()\n{\n memo[0] = 1;\n for (auto i = 1; i < 100010; i++)\n {\n memo[i] = memo[i - 1] * 2;\n memo[i] %= MOD;\n }\n for (auto i = 0; i < N; i++)\n {\n DP[0][i] = power(i - (K - 2));\n }\n DP2[0][0] = DP[0][0];\n for (auto i = 1; i < N; i++)\n {\n DP2[0][i] = DP2[0][i - 1] + DP[0][i];\n DP2[0][i] %= MOD;\n }\n}\n\nvoid flush()\n{\n#if DEBUG == 1\n if (N <= 10)\n {\n for (auto i = 0; i < N; i++)\n {\n for (auto j = 0; j < N; j++)\n {\n cerr << \"DP[\" << i << \"][\" << j << \"] = \" << DP[i][j] << endl;\n }\n }\n }\n#endif\n cout << DP[N - 1][N - 1] << endl;\n}\n\nint main()\n{\n cin >> N >> K;\n init();\n for (auto i = 1; i < N; i++)\n {\n for (auto j = 0; j < N; j++)\n {\n DP[i][j] = 0;\n if (j > 0)\n {\n DP[i][j] += (DP2[i - 1][j - 1] * power(j - i - (K - 2))) % MOD;\n }\n DP[i][j] += (DP[i - 1][j] * power(j - i - (K - 1))) % MOD;\n }\n DP2[i][0] = DP[i][0];\n for (auto j = 1; j < N; j++)\n {\n DP2[i][j] = DP2[i][j - 1] + DP[i][j];\n DP2[i][j] %= MOD;\n }\n }\n flush();\n}<|endoftext|>"} {"text":"#include \"ledtable.h\"\n\nLEDTable::LEDTable(int pin,\n int width,\n int height,\n PixelOrder pixelorder,\n neoPixelType strip_type) : _width(width), _height(height), _pixelorder(pixelorder), strip_type(strip_type), pin(pin)\n{\n \/* determine whether the table is rotated by 90° *\/\n int x = originalWidth() - 1;\n int y = originalHeight() - 1;\n pixelOrder(&x, &y);\n _widthAndHeightAreSwitched = isOutsideTransformed(x, y);\n \/* create the strip *\/\n strip = NULL;\n#ifdef USE_SERIAL_CONNECTION\n printed_pixels = NULL;\n#endif\n}\n\nLEDTable::~LEDTable()\n{\n if (strip)\n {\n delete strip;\n }\n#ifdef USE_SERIAL_CONNECTION\n free(printed_pixels);\n#endif\n}\n\nvoid LEDTable::begin()\n{\n if (!strip)\n {\n strip = new Adafruit_NeoPixel(this->originalWidth() * this->originalHeight(), pin, strip_type);\n }\n if (strip)\n {\n strip->begin();\n }\n} \n\nvoid LEDTable::show()\n{\n if (strip)\n {\n strip->show();\n }\n} \n\nboolean LEDTable::canShow()\n{\n return strip && strip->canShow();\n}\n\nconst bool LEDTable::isOutsideTransformed(const int x, const int y) \n{\n return x < 0 || x >= originalWidth() || y < 0 || y >= originalHeight();\n}\n\nvoid LEDTable::updateColor(uint16_t index, Color color)\n{\n if (!strip || color == color_transparent) return;\n#ifdef USE_SERIAL_CONNECTION\n if (printed_pixels)\n {\n printed_pixels[index] = printed_pixels[index] || strip->getPixelColor(index) != (color & 0xffffff);\n }\n#endif \n if (!(color & 0xff000000)) \n {\n strip->setPixelColor(index, color);\n return;\n }\n \/\/ mixing different transparencies\n uint16_t transparency = ALPHA(color);\n Color color0 = strip->getPixelColor(index);\n uint16_t red = (RED(color) * (256 - transparency) + RED(color0) * transparency) >> 8;\n uint16_t green = (GREEN(color) * (256 - transparency) + GREEN(color0) * transparency) >> 8;\n uint16_t blue = (BLUE(color) * (256 - transparency) + BLUE(color0) * transparency) >> 8;\n strip->setPixelColor(index, red, green, blue);\n}\n\nvoid LEDTable::updateColorTransformed(int x, int y, Color color)\n{\n int index = stripeIndexTransformed(x, y);\n updateColor(index, color);\n}\n\nvoid LEDTable::fill(Color color) \n{\n for (int i = width() * height() - 1; i >= 0; i--) {\n updateColor(i, color);\n }\n}\n\nvoid LEDTable::fill(int x, int y, Color color) \n{\n pixelOrder(&x, &y);\n if (isOutsideTransformed(x, y)) return;\n updateColorTransformed(x, y, color);\n}\n\nvoid LEDTable::fill(int x1, int y1, int x2, int y2, Color color) \n{\n int x_min = min(x1, x2);\n int x_max = max(x1, x2);\n int y_min = min(y1, y2);\n int y_max = max(y1, y2);\n for (int x = x_min; x < x_max; x++) \n {\n for (int y = y_min; y < y_max; y++)\n {\n fill(x, y, color);\n }\n }\n}\n\nColor LEDTable::at(int x, int y)\n{\n if (!strip)\n {\n return color_default;\n }\n pixelOrder(&x, &y);\n if (isOutsideTransformed(x, y)) return color_default;\n return strip->getPixelColor(x + y * originalWidth()) & 0xffffff;\n}\n\nvoid LEDTable::ellipse(int x1, int y1, int x2, int y2, Color color)\n{\n \/\/ TODO: This can overflow if we have more that 128x128 pixel size.\n \/\/ We could use floats but that could be more overhead.\n int x_min = min(x1, x2) - 1;\n int x_max = max(x1, x2);\n int y_min = min(y1, y2) - 1;\n int y_max = max(y1, y2);\n int width = x_max - x_min;\n int height = y_max - y_min;\n int x0_2 = x_max + x_min;\n int y0_2 = y_max + y_min;\n long radius = height;\n radius *= width;\n radius *= radius; \/\/ radius = 4 * width * width * height * height\n for (int x = x_min; x < x_max; x++)\n {\n for (int y = y_min; y < y_max; y++)\n {\n long k1 = abs(x+x - x0_2);\n k1 *= height;\n long k2 = abs(y+y - y0_2);\n k2 *= width;\n if (k1*k1 + k2*k2 < radius)\n {\n fill(x, y, color);\n }\n }\n }\n}\n\nvoid LEDTable::line(int px, int py, int qx, int qy, Color color)\n{\n#define FILL(x, y) if (x_and_y_are_switched) { fill(y, x, color); } else { fill(x, y, color); };\n#define SWITCH(x, y) ;x-= y; y+= x; x = y - x;\n\n int x_direction = qx > px ? 1 : -1;\n int y_direction = qy > py ? 1 : -1;\n int dx = qx - px;\n int dy = qy - py;\n bool x_and_y_are_switched = abs(dx) < abs(dy);\n if (x_and_y_are_switched)\n {\n SWITCH(x_direction, y_direction);\n SWITCH(dx, dy);\n SWITCH(px, py);\n SWITCH(qx, qy);\n }\n \/\/ after this we know that the slope <= 45°\n if (py == qy)\n {\n for (int x = px; x != qx + x_direction; x+= x_direction)\n {\n FILL(x, py);\n }\n return;\n }\n int last_x = px;\n int last_y = py;\n long last_y_dx = long(py) * long(dx);\n while (last_x != qx || last_y != qy)\n {\n FILL(last_x, last_y);\n \/\/ compute the new positions\n int new_x = last_x + x_direction;\n int x1 = new_x;\n int y1 = last_y;\n int x2 = new_x;\n int y2 = last_y + y_direction;\n long new_y_dx = long(new_x - px) * long(dy) + long(py) * long(dx);\n int y1_dx = last_y_dx; \/\/ = y1 * dx\n int y2_dx = y2 * dx;\n last_x = new_x;\n if (abs(new_y_dx - y1_dx) < abs(new_y_dx - y2_dx))\n {\n last_y = y1;\n last_y_dx = y1_dx;\n } else {\n last_y = y2;\n last_y_dx = y2_dx;\n }\n }\n FILL(qx, qy);\n\n#undef FILL\n#undef SWITCH\n}\n\n\/\/ always use lines with number of points dividable by two to create larger lines\n\/\/ -> log memory overhead\nvoid LEDTable::line(int x1, int y1, int x2, int y2, int x3, int y3, Color color)\n{\n line(x1, y1, x2, y2, color);\n line(x3, y3, x2, y2, color);\n}\nvoid LEDTable::line(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4, Color color)\n{\n line(x1, y1, x2, y2, color);\n line(x3, y3, x2, y2, color);\n line(x3, y3, x4, y4, color);\n}\nvoid LEDTable::line(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4, int x5, int y5, Color color)\n{\n line(x1, y1, x2, y2, x3, y3, x4, y4, color);\n line(x4, y4, x5, y5, color);\n}\nvoid LEDTable::line(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4, int x5, int y5, int x6, int y6, Color color)\n{\n line(x1, y1, x2, y2, x3, y3, x4, y4, color);\n line(x4, y4, x5, y5, color);\n line(x6, y6, x5, y5, color);\n}\nvoid LEDTable::line(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4, int x5, int y5, int x6, int y6, int x7, int y7, Color color)\n{\n line(x1, y1, x2, y2, x3, y3, x4, y4, color);\n line(x4, y4, x5, y5, x6, y6, x7, y7, color);\n}\nvoid LEDTable::line(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4, int x5, int y5, int x6, int y6, int x7, int y7, int x8, int y8, Color color)\n{\n line(x1, y1, x2, y2, x3, y3, x4, y4, color);\n line(x4, y4, x5, y5, x6, y6, x7, y7, color);\n line(x7, y7, x8, y8, color);\n}\n\nvoid LEDTable::print(Text* text, int x, int y, Color text_color, Color background_color) {\n text->printOn(this, x, y, text_color, background_color);\n}\n\nconst int LEDTable::originalHeight()\n{\n return _height;\n}\n\nconst int LEDTable::originalWidth()\n{\n return _width;\n}\n\nconst int LEDTable::height()\n{\n if (_widthAndHeightAreSwitched) return _width;\n return _height;\n}\n\nconst int LEDTable::width()\n{\n if (_widthAndHeightAreSwitched) return _height;\n return _width;\n}\n\nuint8_t LEDTable::brightness()\n{\n if (!strip)\n {\n return 0;\n }\n return strip->getBrightness();\n}\nvoid LEDTable::brightness(uint8_t brightness)\n{\n if (strip)\n {\n strip->setBrightness(brightness);\n }\n}\n\nconst int LEDTable::maxX()\n{\n return width() - 1;\n}\n\nconst int LEDTable::maxY()\n{\n return height() - 1;\n}\n\nconst int LEDTable::minX()\n{\n return 0;\n}\n\nconst int LEDTable::minY()\n{\n return 0;\n}\n\nconst int LEDTable::middleX()\n{\n return width() \/ 2;\n}\n\nconst int LEDTable::middleY()\n{\n return height() \/ 2;\n}\n\nbool LEDTable::isInside(int x, int y)\n{\n return !isOutside(x, y);\n}\n\nbool LEDTable::isOutside(int x, int y)\n{\n pixelOrder(&x, &y);\n return isOutsideTransformed(x, y);\n}\n\nvoid LEDTable::pixelOrder(int* x, int*y)\n{\n _pixelorder(this, x, y);\n}\n\nint LEDTable::stripeIndex(int x, int y)\n{\n pixelOrder(&x, &y);\n return stripeIndexTransformed(x, y);\n}\n\nint LEDTable::stripeIndexTransformed(int x, int y)\n{\n return x + y * originalWidth();\n}\n\nuint8_t LEDTable::brightnessAt(int x, int y)\n{\n Color color = at(x, y);\n \/\/ http:\/\/stackoverflow.com\/questions\/15326911\/how-to-access-global-variable-when-there-is-a-local-and-global-conflict\n extern const uint8_t brightness(const Color color);\n return brightness(color);\n}\n\n\n#ifdef USE_SERIAL_CONNECTION\nvoid LEDTable::printToSerial(HardwareSerial* serial)\n{\n if (!printed_pixels)\n {\n int number_of_pixels = originalWidth() * originalHeight();\n printed_pixels = (bool*)(malloc(number_of_pixels));\n if (printed_pixels) \n {\n memset(printed_pixels, true, number_of_pixels);\n }\n serial->println();\n }\n serial->print(SERIAL_COMMAND_CHARACTER);\n serial->print(\"p \");\n serial->println(height());\n for (int y = 0; y < height(); y++)\n {\n int skipped_pixels = 0;\n for (int x = 0; x < width(); x++)\n {\n skipped_pixels++;\n const int printedPixelsIndex = stripeIndex(x, y);\n Color color = at(x, y);\n if ((!printed_pixels) || (printed_pixels[printedPixelsIndex]))\n {\n for (int i = skipped_pixels ; i > 0 ; i--)\n {\n serial->print(\"#\");\n }\n skipped_pixels = 0;\n serial->print(color & 0xffffff, HEX);\n if (printed_pixels)\n {\n printed_pixels[printedPixelsIndex] = false;\n }\n }\n }\n serial->println();\n }\n}\n\nvoid LEDTable::printPixelOrderToSerial(HardwareSerial* serial)\n{\n serial->print(SERIAL_COMMAND_CHARACTER);\n serial->print(\"o \");\n serial->println(this->originalHeight());\n for (int y = 0; y < originalHeight(); y++)\n {\n for (int x = 0; x < originalWidth(); x++)\n {\n int stripeIndex = this->stripeIndex(x, y);\n if (x != 0)\n {\n serial->print(\" \");\n }\n serial->print(stripeIndex);\n }\n serial->println();\n }\n}\n\n#endif\nfixed bug of prntg pixel order when x and y are flipped#include \"ledtable.h\"\n\nLEDTable::LEDTable(int pin,\n int width,\n int height,\n PixelOrder pixelorder,\n neoPixelType strip_type) : _width(width), _height(height), _pixelorder(pixelorder), strip_type(strip_type), pin(pin)\n{\n \/* determine whether the table is rotated by 90° *\/\n int x = originalWidth() - 1;\n int y = originalHeight() - 1;\n pixelOrder(&x, &y);\n _widthAndHeightAreSwitched = isOutsideTransformed(x, y);\n \/* create the strip *\/\n strip = NULL;\n#ifdef USE_SERIAL_CONNECTION\n printed_pixels = NULL;\n#endif\n}\n\nLEDTable::~LEDTable()\n{\n if (strip)\n {\n delete strip;\n }\n#ifdef USE_SERIAL_CONNECTION\n free(printed_pixels);\n#endif\n}\n\nvoid LEDTable::begin()\n{\n if (!strip)\n {\n strip = new Adafruit_NeoPixel(this->originalWidth() * this->originalHeight(), pin, strip_type);\n }\n if (strip)\n {\n strip->begin();\n }\n} \n\nvoid LEDTable::show()\n{\n if (strip)\n {\n strip->show();\n }\n} \n\nboolean LEDTable::canShow()\n{\n return strip && strip->canShow();\n}\n\nconst bool LEDTable::isOutsideTransformed(const int x, const int y) \n{\n return x < 0 || x >= originalWidth() || y < 0 || y >= originalHeight();\n}\n\nvoid LEDTable::updateColor(uint16_t index, Color color)\n{\n if (!strip || color == color_transparent) return;\n#ifdef USE_SERIAL_CONNECTION\n if (printed_pixels)\n {\n printed_pixels[index] = printed_pixels[index] || strip->getPixelColor(index) != (color & 0xffffff);\n }\n#endif \n if (!(color & 0xff000000)) \n {\n strip->setPixelColor(index, color);\n return;\n }\n \/\/ mixing different transparencies\n uint16_t transparency = ALPHA(color);\n Color color0 = strip->getPixelColor(index);\n uint16_t red = (RED(color) * (256 - transparency) + RED(color0) * transparency) >> 8;\n uint16_t green = (GREEN(color) * (256 - transparency) + GREEN(color0) * transparency) >> 8;\n uint16_t blue = (BLUE(color) * (256 - transparency) + BLUE(color0) * transparency) >> 8;\n strip->setPixelColor(index, red, green, blue);\n}\n\nvoid LEDTable::updateColorTransformed(int x, int y, Color color)\n{\n int index = stripeIndexTransformed(x, y);\n updateColor(index, color);\n}\n\nvoid LEDTable::fill(Color color) \n{\n for (int i = width() * height() - 1; i >= 0; i--) {\n updateColor(i, color);\n }\n}\n\nvoid LEDTable::fill(int x, int y, Color color) \n{\n pixelOrder(&x, &y);\n if (isOutsideTransformed(x, y)) return;\n updateColorTransformed(x, y, color);\n}\n\nvoid LEDTable::fill(int x1, int y1, int x2, int y2, Color color) \n{\n int x_min = min(x1, x2);\n int x_max = max(x1, x2);\n int y_min = min(y1, y2);\n int y_max = max(y1, y2);\n for (int x = x_min; x < x_max; x++) \n {\n for (int y = y_min; y < y_max; y++)\n {\n fill(x, y, color);\n }\n }\n}\n\nColor LEDTable::at(int x, int y)\n{\n if (!strip)\n {\n return color_default;\n }\n pixelOrder(&x, &y);\n if (isOutsideTransformed(x, y)) return color_default;\n return strip->getPixelColor(x + y * originalWidth()) & 0xffffff;\n}\n\nvoid LEDTable::ellipse(int x1, int y1, int x2, int y2, Color color)\n{\n \/\/ TODO: This can overflow if we have more that 128x128 pixel size.\n \/\/ We could use floats but that could be more overhead.\n int x_min = min(x1, x2) - 1;\n int x_max = max(x1, x2);\n int y_min = min(y1, y2) - 1;\n int y_max = max(y1, y2);\n int width = x_max - x_min;\n int height = y_max - y_min;\n int x0_2 = x_max + x_min;\n int y0_2 = y_max + y_min;\n long radius = height;\n radius *= width;\n radius *= radius; \/\/ radius = 4 * width * width * height * height\n for (int x = x_min; x < x_max; x++)\n {\n for (int y = y_min; y < y_max; y++)\n {\n long k1 = abs(x+x - x0_2);\n k1 *= height;\n long k2 = abs(y+y - y0_2);\n k2 *= width;\n if (k1*k1 + k2*k2 < radius)\n {\n fill(x, y, color);\n }\n }\n }\n}\n\nvoid LEDTable::line(int px, int py, int qx, int qy, Color color)\n{\n#define FILL(x, y) if (x_and_y_are_switched) { fill(y, x, color); } else { fill(x, y, color); };\n#define SWITCH(x, y) ;x-= y; y+= x; x = y - x;\n\n int x_direction = qx > px ? 1 : -1;\n int y_direction = qy > py ? 1 : -1;\n int dx = qx - px;\n int dy = qy - py;\n bool x_and_y_are_switched = abs(dx) < abs(dy);\n if (x_and_y_are_switched)\n {\n SWITCH(x_direction, y_direction);\n SWITCH(dx, dy);\n SWITCH(px, py);\n SWITCH(qx, qy);\n }\n \/\/ after this we know that the slope <= 45°\n if (py == qy)\n {\n for (int x = px; x != qx + x_direction; x+= x_direction)\n {\n FILL(x, py);\n }\n return;\n }\n int last_x = px;\n int last_y = py;\n long last_y_dx = long(py) * long(dx);\n while (last_x != qx || last_y != qy)\n {\n FILL(last_x, last_y);\n \/\/ compute the new positions\n int new_x = last_x + x_direction;\n int x1 = new_x;\n int y1 = last_y;\n int x2 = new_x;\n int y2 = last_y + y_direction;\n long new_y_dx = long(new_x - px) * long(dy) + long(py) * long(dx);\n int y1_dx = last_y_dx; \/\/ = y1 * dx\n int y2_dx = y2 * dx;\n last_x = new_x;\n if (abs(new_y_dx - y1_dx) < abs(new_y_dx - y2_dx))\n {\n last_y = y1;\n last_y_dx = y1_dx;\n } else {\n last_y = y2;\n last_y_dx = y2_dx;\n }\n }\n FILL(qx, qy);\n\n#undef FILL\n#undef SWITCH\n}\n\n\/\/ always use lines with number of points dividable by two to create larger lines\n\/\/ -> log memory overhead\nvoid LEDTable::line(int x1, int y1, int x2, int y2, int x3, int y3, Color color)\n{\n line(x1, y1, x2, y2, color);\n line(x3, y3, x2, y2, color);\n}\nvoid LEDTable::line(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4, Color color)\n{\n line(x1, y1, x2, y2, color);\n line(x3, y3, x2, y2, color);\n line(x3, y3, x4, y4, color);\n}\nvoid LEDTable::line(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4, int x5, int y5, Color color)\n{\n line(x1, y1, x2, y2, x3, y3, x4, y4, color);\n line(x4, y4, x5, y5, color);\n}\nvoid LEDTable::line(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4, int x5, int y5, int x6, int y6, Color color)\n{\n line(x1, y1, x2, y2, x3, y3, x4, y4, color);\n line(x4, y4, x5, y5, color);\n line(x6, y6, x5, y5, color);\n}\nvoid LEDTable::line(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4, int x5, int y5, int x6, int y6, int x7, int y7, Color color)\n{\n line(x1, y1, x2, y2, x3, y3, x4, y4, color);\n line(x4, y4, x5, y5, x6, y6, x7, y7, color);\n}\nvoid LEDTable::line(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4, int x5, int y5, int x6, int y6, int x7, int y7, int x8, int y8, Color color)\n{\n line(x1, y1, x2, y2, x3, y3, x4, y4, color);\n line(x4, y4, x5, y5, x6, y6, x7, y7, color);\n line(x7, y7, x8, y8, color);\n}\n\nvoid LEDTable::print(Text* text, int x, int y, Color text_color, Color background_color) {\n text->printOn(this, x, y, text_color, background_color);\n}\n\nconst int LEDTable::originalHeight()\n{\n return _height;\n}\n\nconst int LEDTable::originalWidth()\n{\n return _width;\n}\n\nconst int LEDTable::height()\n{\n if (_widthAndHeightAreSwitched) return _width;\n return _height;\n}\n\nconst int LEDTable::width()\n{\n if (_widthAndHeightAreSwitched) return _height;\n return _width;\n}\n\nuint8_t LEDTable::brightness()\n{\n if (!strip)\n {\n return 0;\n }\n return strip->getBrightness();\n}\nvoid LEDTable::brightness(uint8_t brightness)\n{\n if (strip)\n {\n strip->setBrightness(brightness);\n }\n}\n\nconst int LEDTable::maxX()\n{\n return width() - 1;\n}\n\nconst int LEDTable::maxY()\n{\n return height() - 1;\n}\n\nconst int LEDTable::minX()\n{\n return 0;\n}\n\nconst int LEDTable::minY()\n{\n return 0;\n}\n\nconst int LEDTable::middleX()\n{\n return width() \/ 2;\n}\n\nconst int LEDTable::middleY()\n{\n return height() \/ 2;\n}\n\nbool LEDTable::isInside(int x, int y)\n{\n return !isOutside(x, y);\n}\n\nbool LEDTable::isOutside(int x, int y)\n{\n pixelOrder(&x, &y);\n return isOutsideTransformed(x, y);\n}\n\nvoid LEDTable::pixelOrder(int* x, int*y)\n{\n _pixelorder(this, x, y);\n}\n\nint LEDTable::stripeIndex(int x, int y)\n{\n pixelOrder(&x, &y);\n return stripeIndexTransformed(x, y);\n}\n\nint LEDTable::stripeIndexTransformed(int x, int y)\n{\n return x + y * originalWidth();\n}\n\nuint8_t LEDTable::brightnessAt(int x, int y)\n{\n Color color = at(x, y);\n \/\/ http:\/\/stackoverflow.com\/questions\/15326911\/how-to-access-global-variable-when-there-is-a-local-and-global-conflict\n extern const uint8_t brightness(const Color color);\n return brightness(color);\n}\n\n\n#ifdef USE_SERIAL_CONNECTION\nvoid LEDTable::printToSerial(HardwareSerial* serial)\n{\n if (!printed_pixels)\n {\n int number_of_pixels = originalWidth() * originalHeight();\n printed_pixels = (bool*)(malloc(number_of_pixels));\n if (printed_pixels) \n {\n memset(printed_pixels, true, number_of_pixels);\n }\n serial->println();\n }\n serial->print(SERIAL_COMMAND_CHARACTER);\n serial->print(\"p \");\n serial->println(height());\n for (int y = 0; y < height(); y++)\n {\n int skipped_pixels = 0;\n for (int x = 0; x < width(); x++)\n {\n skipped_pixels++;\n const int printedPixelsIndex = stripeIndex(x, y);\n Color color = at(x, y);\n if ((!printed_pixels) || (printed_pixels[printedPixelsIndex]))\n {\n for (int i = skipped_pixels ; i > 0 ; i--)\n {\n serial->print(\"#\");\n }\n skipped_pixels = 0;\n serial->print(color & 0xffffff, HEX);\n if (printed_pixels)\n {\n printed_pixels[printedPixelsIndex] = false;\n }\n }\n }\n serial->println();\n }\n}\n\nvoid LEDTable::printPixelOrderToSerial(HardwareSerial* serial)\n{\n serial->print(SERIAL_COMMAND_CHARACTER);\n serial->print(\"o \");\n serial->println(this->height());\n for (int y = 0; y < height(); y++)\n {\n for (int x = 0; x < width(); x++)\n {\n int stripeIndex = this->stripeIndex(x, y);\n if (x != 0)\n {\n serial->print(\" \");\n }\n serial->print(stripeIndex);\n }\n serial->println();\n }\n}\n\n#endif\n<|endoftext|>"} {"text":"\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#include \"excelfilter.hxx\"\n\n#include \n#include \"oox\/helper\/binaryinputstream.hxx\"\n#include \"biffinputstream.hxx\"\n#include \"excelchartconverter.hxx\"\n#include \"excelvbaproject.hxx\"\n#include \"stylesbuffer.hxx\"\n#include \"themebuffer.hxx\"\n#include \"workbookfragment.hxx\"\n\nnamespace oox {\nnamespace xls {\n\n\/\/ ============================================================================\n\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::sheet;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::xml::sax;\nusing namespace ::oox::core;\n\nusing ::rtl::OUString;\nusing ::oox::drawingml::table::TableStyleListPtr;\n\n\/\/ ============================================================================\n\nExcelFilterBase::ExcelFilterBase() :\n mpBookGlob( 0 )\n{\n}\n\nExcelFilterBase::~ExcelFilterBase()\n{\n OSL_ENSURE( !mpBookGlob, \"ExcelFilterBase::~ExcelFilterBase - workbook data not cleared\" );\n}\n\nvoid ExcelFilterBase::registerWorkbookGlobals( WorkbookGlobals& rBookGlob )\n{\n mpBookGlob = &rBookGlob;\n}\n\nWorkbookGlobals& ExcelFilterBase::getWorkbookGlobals() const\n{\n OSL_ENSURE( mpBookGlob, \"ExcelFilterBase::getWorkbookGlobals - missing workbook data\" );\n return *mpBookGlob;\n}\n\nvoid ExcelFilterBase::unregisterWorkbookGlobals()\n{\n mpBookGlob = 0;\n}\n\n\/\/ ============================================================================\n\nOUString SAL_CALL ExcelFilter_getImplementationName() throw()\n{\n return OUString( \"com.sun.star.comp.oox.xls.ExcelFilter\" );\n}\n\nSequence< OUString > SAL_CALL ExcelFilter_getSupportedServiceNames() throw()\n{\n Sequence< OUString > aSeq( 2 );\n aSeq[ 0 ] = \"com.sun.star.document.ImportFilter\";\n aSeq[ 1 ] = \"com.sun.star.document.ExportFilter\";\n return aSeq;\n}\n\nReference< XInterface > SAL_CALL ExcelFilter_createInstance(\n const Reference< XComponentContext >& rxContext ) throw( Exception )\n{\n return static_cast< ::cppu::OWeakObject* >( new ExcelFilter( rxContext ) );\n}\n\n\/\/ ----------------------------------------------------------------------------\n\nExcelFilter::ExcelFilter( const Reference< XComponentContext >& rxContext ) throw( RuntimeException ) :\n XmlFilterBase( rxContext )\n{\n}\n\nExcelFilter::~ExcelFilter()\n{\n}\n\nbool ExcelFilter::importDocument() throw()\n{\n \/* To activate the XLSX\/XLSB dumper, insert the full path to the file\n file:\/\/\/\/source\/dump\/xlsbdumper.ini\n into the environment variable OOO_XLSBDUMPER and start the office with\n this variable (nonpro only). *\/\n \/\/OOX_DUMP_FILE( ::oox::dump::xlsb::Dumper );\n\n OUString aWorkbookPath = getFragmentPathFromFirstType( CREATE_OFFICEDOC_RELATION_TYPE( \"officeDocument\" ) );\n if( aWorkbookPath.isEmpty() )\n return false;\n\n \/* Construct the WorkbookGlobals object referred to by every instance of\n the class WorkbookHelper, and execute the import filter by constructing\n an instance of WorkbookFragment and loading the file. *\/\n WorkbookGlobalsRef xBookGlob = WorkbookHelper::constructGlobals( *this );\n if ( xBookGlob.get() && importFragment( new WorkbookFragment( *xBookGlob, aWorkbookPath ) ) )\n {\n importDocumentProperties();\n return true;\n }\n return false;\n}\n\nbool ExcelFilter::exportDocument() throw()\n{\n return false;\n}\n\nconst ::oox::drawingml::Theme* ExcelFilter::getCurrentTheme() const\n{\n return &WorkbookHelper( getWorkbookGlobals() ).getTheme();\n}\n\n::oox::vml::Drawing* ExcelFilter::getVmlDrawing()\n{\n return 0;\n}\n\nconst TableStyleListPtr ExcelFilter::getTableStyles()\n{\n return TableStyleListPtr();\n}\n\n::oox::drawingml::chart::ChartConverter* ExcelFilter::getChartConverter()\n{\n return WorkbookHelper( getWorkbookGlobals() ).getChartConverter();\n}\n\nGraphicHelper* ExcelFilter::implCreateGraphicHelper() const\n{\n return new ExcelGraphicHelper( getWorkbookGlobals() );\n}\n\n::oox::ole::VbaProject* ExcelFilter::implCreateVbaProject() const\n{\n return new ExcelVbaProject( getComponentContext(), Reference< XSpreadsheetDocument >( getModel(), UNO_QUERY ) );\n}\n\n\nsal_Bool SAL_CALL ExcelFilter::filter( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& rDescriptor ) throw( ::com::sun::star::uno::RuntimeException )\n{\n if ( XmlFilterBase::filter( rDescriptor ) )\n return true;\n\n if ( isExportFilter() )\n {\n Reference< XExporter > xExporter( getServiceFactory()->createInstance( \"com.sun.star.comp.oox.ExcelFilterExport\" ), UNO_QUERY );\n\n if ( xExporter.is() )\n {\n Reference< XComponent > xDocument( getModel(), UNO_QUERY );\n Reference< XFilter > xFilter( xExporter, UNO_QUERY );\n\n if ( xFilter.is() )\n {\n xExporter->setSourceDocument( xDocument );\n if ( xFilter->filter( rDescriptor ) )\n return true;\n }\n }\n }\n\n return false;\n}\n\nOUString ExcelFilter::implGetImplementationName() const\n{\n return ExcelFilter_getImplementationName();\n}\n\n} \/\/ namespace xls\n} \/\/ namespace oox\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\nwe need to catch the exception here, fdo#57451\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#include \"excelfilter.hxx\"\n\n#include \n#include \"oox\/helper\/binaryinputstream.hxx\"\n#include \"biffinputstream.hxx\"\n#include \"excelchartconverter.hxx\"\n#include \"excelvbaproject.hxx\"\n#include \"stylesbuffer.hxx\"\n#include \"themebuffer.hxx\"\n#include \"workbookfragment.hxx\"\n\nnamespace oox {\nnamespace xls {\n\n\/\/ ============================================================================\n\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::sheet;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::xml::sax;\nusing namespace ::oox::core;\n\nusing ::rtl::OUString;\nusing ::oox::drawingml::table::TableStyleListPtr;\n\n\/\/ ============================================================================\n\nExcelFilterBase::ExcelFilterBase() :\n mpBookGlob( 0 )\n{\n}\n\nExcelFilterBase::~ExcelFilterBase()\n{\n OSL_ENSURE( !mpBookGlob, \"ExcelFilterBase::~ExcelFilterBase - workbook data not cleared\" );\n}\n\nvoid ExcelFilterBase::registerWorkbookGlobals( WorkbookGlobals& rBookGlob )\n{\n mpBookGlob = &rBookGlob;\n}\n\nWorkbookGlobals& ExcelFilterBase::getWorkbookGlobals() const\n{\n OSL_ENSURE( mpBookGlob, \"ExcelFilterBase::getWorkbookGlobals - missing workbook data\" );\n return *mpBookGlob;\n}\n\nvoid ExcelFilterBase::unregisterWorkbookGlobals()\n{\n mpBookGlob = 0;\n}\n\n\/\/ ============================================================================\n\nOUString SAL_CALL ExcelFilter_getImplementationName() throw()\n{\n return OUString( \"com.sun.star.comp.oox.xls.ExcelFilter\" );\n}\n\nSequence< OUString > SAL_CALL ExcelFilter_getSupportedServiceNames() throw()\n{\n Sequence< OUString > aSeq( 2 );\n aSeq[ 0 ] = \"com.sun.star.document.ImportFilter\";\n aSeq[ 1 ] = \"com.sun.star.document.ExportFilter\";\n return aSeq;\n}\n\nReference< XInterface > SAL_CALL ExcelFilter_createInstance(\n const Reference< XComponentContext >& rxContext ) throw( Exception )\n{\n return static_cast< ::cppu::OWeakObject* >( new ExcelFilter( rxContext ) );\n}\n\n\/\/ ----------------------------------------------------------------------------\n\nExcelFilter::ExcelFilter( const Reference< XComponentContext >& rxContext ) throw( RuntimeException ) :\n XmlFilterBase( rxContext )\n{\n}\n\nExcelFilter::~ExcelFilter()\n{\n}\n\nbool ExcelFilter::importDocument() throw()\n{\n \/* To activate the XLSX\/XLSB dumper, insert the full path to the file\n file:\/\/\/\/source\/dump\/xlsbdumper.ini\n into the environment variable OOO_XLSBDUMPER and start the office with\n this variable (nonpro only). *\/\n \/\/OOX_DUMP_FILE( ::oox::dump::xlsb::Dumper );\n\n OUString aWorkbookPath = getFragmentPathFromFirstType( CREATE_OFFICEDOC_RELATION_TYPE( \"officeDocument\" ) );\n if( aWorkbookPath.isEmpty() )\n return false;\n\n \/* Construct the WorkbookGlobals object referred to by every instance of\n the class WorkbookHelper, and execute the import filter by constructing\n an instance of WorkbookFragment and loading the file. *\/\n WorkbookGlobalsRef xBookGlob = WorkbookHelper::constructGlobals( *this );\n if ( xBookGlob.get() && importFragment( new WorkbookFragment( *xBookGlob, aWorkbookPath ) ) )\n {\n try\n {\n importDocumentProperties();\n }\n catch( const Exception& e )\n {\n SAL_WARN(\"sc\", \"exception when importing document properties \" << e.Message);\n }\n return true;\n }\n return false;\n}\n\nbool ExcelFilter::exportDocument() throw()\n{\n return false;\n}\n\nconst ::oox::drawingml::Theme* ExcelFilter::getCurrentTheme() const\n{\n return &WorkbookHelper( getWorkbookGlobals() ).getTheme();\n}\n\n::oox::vml::Drawing* ExcelFilter::getVmlDrawing()\n{\n return 0;\n}\n\nconst TableStyleListPtr ExcelFilter::getTableStyles()\n{\n return TableStyleListPtr();\n}\n\n::oox::drawingml::chart::ChartConverter* ExcelFilter::getChartConverter()\n{\n return WorkbookHelper( getWorkbookGlobals() ).getChartConverter();\n}\n\nGraphicHelper* ExcelFilter::implCreateGraphicHelper() const\n{\n return new ExcelGraphicHelper( getWorkbookGlobals() );\n}\n\n::oox::ole::VbaProject* ExcelFilter::implCreateVbaProject() const\n{\n return new ExcelVbaProject( getComponentContext(), Reference< XSpreadsheetDocument >( getModel(), UNO_QUERY ) );\n}\n\n\nsal_Bool SAL_CALL ExcelFilter::filter( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& rDescriptor ) throw( ::com::sun::star::uno::RuntimeException )\n{\n if ( XmlFilterBase::filter( rDescriptor ) )\n return true;\n\n if ( isExportFilter() )\n {\n Reference< XExporter > xExporter( getServiceFactory()->createInstance( \"com.sun.star.comp.oox.ExcelFilterExport\" ), UNO_QUERY );\n\n if ( xExporter.is() )\n {\n Reference< XComponent > xDocument( getModel(), UNO_QUERY );\n Reference< XFilter > xFilter( xExporter, UNO_QUERY );\n\n if ( xFilter.is() )\n {\n xExporter->setSourceDocument( xDocument );\n if ( xFilter->filter( rDescriptor ) )\n return true;\n }\n }\n }\n\n return false;\n}\n\nOUString ExcelFilter::implGetImplementationName() const\n{\n return ExcelFilter_getImplementationName();\n}\n\n} \/\/ namespace xls\n} \/\/ namespace oox\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \"OpenCLHelper.h\"\n#include \"stringhelper.h\"\n#include \"Timer.h\"\n#include \"test\/TestArgsParser.h\"\n#include \"test\/SpeedTemplates.h\"\n\nusing namespace std;\n\n\/\/ for use in conjunction with http:\/\/www.cs.berkeley.edu\/~volkov\/volkov10-GTC.pdf\nint main( int argc, char *argv[] ) {\n OpenCLHelper *cl = OpenCLHelper::createForFirstGpuOtherwiseCpu();\n\n\/\/ int its = 10000000;\n int numFloats = 50000000;\n int workgroupSize = 512;\n bool optimizerOn = true;\n int count = 1;\n\/\/ bool enableMad = true;\n int kernelVersion = 1;\n\n TestArgsParser args( argc, argv );\n\/\/ args._arg( \"its\", &its );\n args._arg( \"n\", &numFloats );\n args._arg( \"workgroupsize\", &workgroupSize );\n args._arg( \"opt\", &optimizerOn );\n args._arg( \"count\", &count );\n args._arg( \"kernel\", &kernelVersion );\n\/\/ args._arg( \"mad\", &enableMad );\n args._go();\n cout << \"values:\" << endl;\n args._printValues();\n\n count = OpenCLHelper::getNextPower2( count );\n int thiscount = count;\n int shift = 0;\n while( thiscount > 1 ) {\n thiscount >>= 1;\n shift++;\n }\n cout << \"count: \" << count << \" shift: \" << shift << endl;\n\n\/\/ cout << \"its: \" << its << \" workgroupsize: \" << workgroupSize << \" optimizer: \" << optimizerOn << endl; \n\n string kernelSource1 = R\"DELIM(\n kernel void memcpy( global float const*src, global float *dest) {\n if( get_global_id(0) < N ) {\n float a = src[get_global_id(0)];\n dest[get_global_id(0)] = a;\n }\n }\n )DELIM\";\n\n string kernelSource2 = R\"DELIM(\n kernel void memcpy(global float const*src, global float *dest) {\n if( get_global_id(0) < N ) {\n dest[get_global_id(0)] = src[get_global_id(0)];\n }\n }\n )DELIM\";\n\n string kernelSource3 = R\"DELIM(\n kernel void memcpy(global float const*src, global float *dest) {\n dest[get_global_id(0)] = src[get_global_id(0)];\n }\n )DELIM\";\n\n string kernelSource4 = R\"DELIM(\n kernel void memcpy(global float const*src, global float *dest) {\n float a[COUNT];\n int offset = get_global_id(0) << SHIFT;\n\/\/ if( offset < N ) {\n if( get_global_id(0) < ( N >> SHIFT ) ) {\n #pragma unroll COUNT\n for( int i = 0; i < COUNT; i++ ) {\n a[i] = src[ offset + i ];\n }\n #pragma unroll COUNT\n for( int i = 0; i < COUNT; i++ ) {\n dest[ offset + i ] = a[i];\n }\n }\n }\n )DELIM\";\n \n string kernelSource5 = R\"DELIM(\n kernel void memcpy(global float const*src, global float *dest) {\n float a[{{COUNT}}];\n int offset = get_global_id(0) << {{SHIFT}};\n\/\/ if( offset < N ) {\n if( get_global_id(0) < ( {{N}} >> {{SHIFT}} ) ) {\n {% for i in range( COUNT ) %}\n a[{{i}}] = src[ offset + {{i}} ];\n {% endfor %}\n {% for i in range( COUNT ) %}\n dest[ offset + {{i}} ] = a[{{i}}];\n {% endfor %}\n }\n }\n )DELIM\";\n \n string kernelSource6 = R\"DELIM(\n #define f4(var) ( (global float4*)(var) )\n\n kernel void memcpy(global float const*src, global float *dest) {\n float4 a[COUNT];\n int offset = get_global_id(0) << SHIFT;\n if( get_global_id(0) < ( N >> SHIFT ) ) {\n #pragma unroll COUNT\n for( int i = 0; i < COUNT; i++ ) {\n a[i] = f4(src)[ offset + i ];\n }\n #pragma unroll COUNT\n for( int i = 0; i < COUNT; i++ ) {\n f4(dest)[ offset + i ] = a[i];\n }\n }\n }\n )DELIM\";\n \n string kernelSource7 = R\"DELIM(\n #define f4(var) ( (global float4*)(var) )\n\n kernel void memcpy(global float const*src, global float *dest) {\n float4 a[{{COUNT}}];\n int offset = get_global_id(0) << {{SHIFT}};\n\/\/ if( get_global_id(0) < ( {{N}} >> {{SHIFT}} ) ) {\n if( ( ( offset + {{COUNT}} - 1) << 2 ) < {{N}} ) {\n {% for i in range( COUNT ) %}\n a[{{i}}] = f4(src)[ offset + {{i}} ];\n {% endfor %}\n {% for i in range( COUNT ) %}\n f4(dest)[ offset + {{i}} ] = a[{{i}}];\n {% endfor %}\n }\n }\n )DELIM\";\n\n string kernelSource8 = R\"DELIM(\n kernel void memcpy(global float const*src, global float *dest) {\n local float a[{{COUNT}}];\n int offset = get_global_id(0) << {{SHIFT}};\n\/\/ if( get_global_id(0) < ( {{N}} >> {{SHIFT}} ) ) {\n if( ( ( offset + {{COUNT}} - 1) << 2 ) < {{N}} ) {\n {% for i in range( COUNT ) %}\n a[{{i}}] = f4(src)[ offset + {{i}} ];\n {% endfor %}\n {% for i in range( COUNT ) %}\n f4(dest)[ offset + {{i}} ] = a[{{i}}];\n {% endfor %}\n }\n }\n )DELIM\";\n\n string options = \"\";\n if( !optimizerOn ) {\n options += \" -cl-opt-disable\";\n }\n\/\/ if( enableMad ) {\n options += \" -cl-mad-enable\";\n\/\/ }\n options += \" -D COUNT=\" + toString( count );\n options += \" -D SHIFT=\" + toString( shift );\n\/\/ if( kernelVersion == 1 && count == 4 ) {\n\/\/ options += \" -D dOn\";\n\/\/ }\n options += \" -cl-single-precision-constant\";\n\/\/ options += \" -D N_ITERATIONS=\" + toString( its );\n options += \" -D N=\" + toString( numFloats );\n\/\/ options += \" -D UNROLL=\" + toString( unroll );\n \n string kernelSource = \"\";\n if( kernelVersion == 1 ) {\n kernelSource = kernelSource1;\n } else if( kernelVersion == 2 ) {\n kernelSource = kernelSource2;\n } else if( kernelVersion == 3 ) {\n kernelSource = kernelSource3;\n } else if( kernelVersion == 4 ) {\n kernelSource = kernelSource4;\n } else if( kernelVersion == 5 ) {\n SpeedTemplates::Template mytemplate( kernelSource5 );\n mytemplate.setValue( \"COUNT\", count );\n mytemplate.setValue( \"N\", numFloats );\n mytemplate.setValue( \"SHIFT\", shift );\n\/\/ mytemplate.setValue( \"unroll\", unroll );\n string renderedSource = mytemplate.render();\n cout << \"rendered source: [\" << renderedSource << \"]\" << endl;\n kernelSource = renderedSource;\n } else if( kernelVersion == 6 ) {\n kernelSource = kernelSource6;\n } else if( kernelVersion == 7 ) {\n SpeedTemplates::Template mytemplate( kernelSource7 );\n mytemplate.setValue( \"N\", numFloats );\n mytemplate.setValue( \"COUNT\", count );\n mytemplate.setValue( \"SHIFT\", shift );\n\/\/ mytemplate.setValue( \"unroll\", unroll );\n string renderedSource = mytemplate.render();\n cout << \"rendered source: [\" << renderedSource << \"]\" << endl;\n kernelSource = renderedSource;\n } else {\n throw runtime_error(\"kernel version \" + toString( kernelVersion ) + \" not implemented\");\n }\n \n\n CLKernel *kernel = cl->buildKernelFromString( kernelSource, \"memcpy\", options );\n\n float *src = new float[numFloats];\n for( int i = 0; i < numFloats; i++ ) {\n src[i] = 2.0f;\n }\n float *dest = new float[numFloats + count];\n memset( dest, 0, ( numFloats + count ) * sizeof(float) );\n\n CLWrapper *destWrapper = cl->wrap( numFloats + count, dest );\n CLWrapper *srcWrapper = cl->wrap( numFloats + count, src );\n destWrapper->createOnDevice();\n srcWrapper->copyToDevice();\n kernel->in( srcWrapper );\n kernel->out( destWrapper );\n int numWorkgroups = ( numFloats \/ count + workgroupSize - 1 ) \/ workgroupSize;\n if( kernelVersion >= 6 ) {\n numWorkgroups = ( numFloats \/ count \/ 4 + workgroupSize - 1 ) \/ workgroupSize;\n }\n cl->finish(); \/\/ just in case...\n Timer timer;\n kernel->run_1d( numWorkgroups * workgroupSize, workgroupSize );\n cl->finish();\n float kernelTime = timer.lap();\n cout << \"time: \" << kernelTime << \"ms\" << endl;\n\/\/ cout << stuff[0] << \" \" << stuff[1] << endl;\n\n float kernelTimeSeconds = kernelTime \/ 1000.0f;\n\n float throughputGbytes = numFloats * 4.0f \/ 1024 \/ 1024 \/ 1024;\n\/\/ if( kernelVersion >= 4 ) {\n\/\/ throughputGbytes *= count;\n\/\/ }\n float throughputGbytespersec = throughputGbytes \/ kernelTimeSeconds;\n\/\/ float throughputGflops = (float)its * workgroupSize \/ kernelTimeSeconds \/ 1024 \/ 1024 \/ 1024;\n\n cout << \"throughput: \" << throughputGbytespersec << \"GB\/s\" << endl;\n\n \/\/ check the memory copied...\n destWrapper->copyToHost();\n int errCount = 0;\n for( int i = 0; i < numFloats; i++ ) {\n if( dest[i] != 2.0f ) {\n if( errCount > 5 ) {\n cout << \"...\" << endl;\n break;\n }\n cout << \"DIFF: dest[\" << i << \"]=\" << dest[i] << endl;\n errCount++;\n }\n }\n for( int i = 0; i < count; i++ ) {\n if( dest[i + numFloats] != 0.0f ) {\n if( errCount > 5 ) {\n cout << \"...\" << endl;\n break;\n }\n cout << \"DIFF: dest[\" << ( i + numFloats ) << \"]=\" << dest[i + numFloats] << endl;\n errCount++;\n }\n }\n\n delete destWrapper;\n delete srcWrapper;\n delete[] src;\n delete[] dest;\n delete kernel;\n delete cl;\n\n return 0;\n}\n\nmore bugs in testmemperf...#include \n#include \n#include \n\n#include \"OpenCLHelper.h\"\n#include \"stringhelper.h\"\n#include \"Timer.h\"\n#include \"test\/TestArgsParser.h\"\n#include \"test\/SpeedTemplates.h\"\n\nusing namespace std;\n\n\/\/ for use in conjunction with http:\/\/www.cs.berkeley.edu\/~volkov\/volkov10-GTC.pdf\nint main( int argc, char *argv[] ) {\n OpenCLHelper *cl = OpenCLHelper::createForFirstGpuOtherwiseCpu();\n\n\/\/ int its = 10000000;\n int numFloats = 50000000;\n int workgroupSize = 512;\n bool optimizerOn = true;\n int count = 1;\n\/\/ bool enableMad = true;\n int kernelVersion = 1;\n\n TestArgsParser args( argc, argv );\n\/\/ args._arg( \"its\", &its );\n args._arg( \"n\", &numFloats );\n args._arg( \"workgroupsize\", &workgroupSize );\n args._arg( \"opt\", &optimizerOn );\n args._arg( \"count\", &count );\n args._arg( \"kernel\", &kernelVersion );\n\/\/ args._arg( \"mad\", &enableMad );\n args._go();\n cout << \"values:\" << endl;\n args._printValues();\n\n count = OpenCLHelper::getNextPower2( count );\n int thiscount = count;\n int shift = 0;\n while( thiscount > 1 ) {\n thiscount >>= 1;\n shift++;\n }\n cout << \"count: \" << count << \" shift: \" << shift << endl;\n\n\/\/ cout << \"its: \" << its << \" workgroupsize: \" << workgroupSize << \" optimizer: \" << optimizerOn << endl; \n\n string kernelSource1 = R\"DELIM(\n kernel void memcpy( global float const*src, global float *dest) {\n if( get_global_id(0) < N ) {\n float a = src[get_global_id(0)];\n dest[get_global_id(0)] = a;\n }\n }\n )DELIM\";\n\n string kernelSource2 = R\"DELIM(\n kernel void memcpy(global float const*src, global float *dest) {\n if( get_global_id(0) < N ) {\n dest[get_global_id(0)] = src[get_global_id(0)];\n }\n }\n )DELIM\";\n\n string kernelSource3 = R\"DELIM(\n kernel void memcpy(global float const*src, global float *dest) {\n dest[get_global_id(0)] = src[get_global_id(0)];\n }\n )DELIM\";\n\n string kernelSource4 = R\"DELIM(\n kernel void memcpy(global float const*src, global float *dest) {\n float a[COUNT];\n int offset = get_global_id(0) << SHIFT;\n\/\/ if( offset < N ) {\n if( offset + COUNT - 1 < N ) {\n #pragma unroll COUNT\n for( int i = 0; i < COUNT; i++ ) {\n a[i] = src[ offset + i ];\n }\n #pragma unroll COUNT\n for( int i = 0; i < COUNT; i++ ) {\n dest[ offset + i ] = a[i];\n }\n }\n }\n )DELIM\";\n \n string kernelSource5 = R\"DELIM(\n kernel void memcpy(global float const*src, global float *dest) {\n float a[{{COUNT}}];\n int offset = get_global_id(0) << {{SHIFT}};\n\/\/ if( offset < N ) {\n\/\/ if( get_global_id(0) < ( {{N}} >> {{SHIFT}} ) ) {\n if( offset + {{COUNT}} < {{N}} ) {\n {% for i in range( COUNT ) %}\n a[{{i}}] = src[ offset + {{i}} ];\n {% endfor %}\n {% for i in range( COUNT ) %}\n dest[ offset + {{i}} ] = a[{{i}}];\n {% endfor %}\n }\n }\n )DELIM\";\n \n string kernelSource6 = R\"DELIM(\n #define f4(var) ( (global float4*)(var) )\n\n kernel void memcpy(global float const*src, global float *dest) {\n float4 a[COUNT];\n int offset = get_global_id(0) << SHIFT;\n if( get_global_id(0) < ( N >> SHIFT ) ) {\n #pragma unroll COUNT\n for( int i = 0; i < COUNT; i++ ) {\n a[i] = f4(src)[ offset + i ];\n }\n #pragma unroll COUNT\n for( int i = 0; i < COUNT; i++ ) {\n f4(dest)[ offset + i ] = a[i];\n }\n }\n }\n )DELIM\";\n \n string kernelSource7 = R\"DELIM(\n #define f4(var) ( (global float4*)(var) )\n\n kernel void memcpy(global float const*src, global float *dest) {\n float4 a[{{COUNT}}];\n int offset = get_global_id(0) << {{SHIFT}};\n\/\/ if( get_global_id(0) < ( {{N}} >> {{SHIFT}} ) ) {\n if( ( ( offset + {{COUNT}} - 1) << 2 ) < {{N}} ) {\n {% for i in range( COUNT ) %}\n a[{{i}}] = f4(src)[ offset + {{i}} ];\n {% endfor %}\n {% for i in range( COUNT ) %}\n f4(dest)[ offset + {{i}} ] = a[{{i}}];\n {% endfor %}\n }\n }\n )DELIM\";\n\n string kernelSource8 = R\"DELIM(\n kernel void memcpy(global float const*src, global float *dest) {\n local float a[{{COUNT}}];\n int offset = get_global_id(0) << {{SHIFT}};\n\/\/ if( get_global_id(0) < ( {{N}} >> {{SHIFT}} ) ) {\n if( ( ( offset + {{COUNT}} - 1) << 2 ) < {{N}} ) {\n {% for i in range( COUNT ) %}\n a[{{i}}] = f4(src)[ offset + {{i}} ];\n {% endfor %}\n {% for i in range( COUNT ) %}\n f4(dest)[ offset + {{i}} ] = a[{{i}}];\n {% endfor %}\n }\n }\n )DELIM\";\n\n string options = \"\";\n if( !optimizerOn ) {\n options += \" -cl-opt-disable\";\n }\n\/\/ if( enableMad ) {\n options += \" -cl-mad-enable\";\n\/\/ }\n options += \" -D COUNT=\" + toString( count );\n options += \" -D SHIFT=\" + toString( shift );\n\/\/ if( kernelVersion == 1 && count == 4 ) {\n\/\/ options += \" -D dOn\";\n\/\/ }\n options += \" -cl-single-precision-constant\";\n\/\/ options += \" -D N_ITERATIONS=\" + toString( its );\n options += \" -D N=\" + toString( numFloats );\n\/\/ options += \" -D UNROLL=\" + toString( unroll );\n \n string kernelSource = \"\";\n if( kernelVersion == 1 ) {\n kernelSource = kernelSource1;\n } else if( kernelVersion == 2 ) {\n kernelSource = kernelSource2;\n } else if( kernelVersion == 3 ) {\n kernelSource = kernelSource3;\n } else if( kernelVersion == 4 ) {\n kernelSource = kernelSource4;\n } else if( kernelVersion == 5 ) {\n SpeedTemplates::Template mytemplate( kernelSource5 );\n mytemplate.setValue( \"COUNT\", count );\n mytemplate.setValue( \"N\", numFloats );\n mytemplate.setValue( \"SHIFT\", shift );\n\/\/ mytemplate.setValue( \"unroll\", unroll );\n string renderedSource = mytemplate.render();\n cout << \"rendered source: [\" << renderedSource << \"]\" << endl;\n kernelSource = renderedSource;\n } else if( kernelVersion == 6 ) {\n kernelSource = kernelSource6;\n } else if( kernelVersion == 7 ) {\n SpeedTemplates::Template mytemplate( kernelSource7 );\n mytemplate.setValue( \"N\", numFloats );\n mytemplate.setValue( \"COUNT\", count );\n mytemplate.setValue( \"SHIFT\", shift );\n\/\/ mytemplate.setValue( \"unroll\", unroll );\n string renderedSource = mytemplate.render();\n cout << \"rendered source: [\" << renderedSource << \"]\" << endl;\n kernelSource = renderedSource;\n } else {\n throw runtime_error(\"kernel version \" + toString( kernelVersion ) + \" not implemented\");\n }\n \n\n CLKernel *kernel = cl->buildKernelFromString( kernelSource, \"memcpy\", options );\n\n float *src = new float[numFloats];\n for( int i = 0; i < numFloats; i++ ) {\n src[i] = 2.0f;\n }\n float *dest = new float[numFloats + count];\n memset( dest, 0, ( numFloats + count ) * sizeof(float) );\n\n CLWrapper *destWrapper = cl->wrap( numFloats + count, dest );\n CLWrapper *srcWrapper = cl->wrap( numFloats + count, src );\n destWrapper->createOnDevice();\n srcWrapper->copyToDevice();\n kernel->in( srcWrapper );\n kernel->out( destWrapper );\n int numWorkgroups = ( numFloats \/ count + workgroupSize - 1 ) \/ workgroupSize;\n if( kernelVersion >= 6 ) {\n numWorkgroups = ( numFloats \/ count \/ 4 + workgroupSize - 1 ) \/ workgroupSize;\n }\n cl->finish(); \/\/ just in case...\n Timer timer;\n kernel->run_1d( numWorkgroups * workgroupSize, workgroupSize );\n cl->finish();\n float kernelTime = timer.lap();\n cout << \"time: \" << kernelTime << \"ms\" << endl;\n\/\/ cout << stuff[0] << \" \" << stuff[1] << endl;\n\n float kernelTimeSeconds = kernelTime \/ 1000.0f;\n\n float throughputGbytes = numFloats * 4.0f \/ 1024 \/ 1024 \/ 1024;\n\/\/ if( kernelVersion >= 4 ) {\n\/\/ throughputGbytes *= count;\n\/\/ }\n float throughputGbytespersec = throughputGbytes \/ kernelTimeSeconds;\n\/\/ float throughputGflops = (float)its * workgroupSize \/ kernelTimeSeconds \/ 1024 \/ 1024 \/ 1024;\n\n cout << \"throughput: \" << throughputGbytespersec << \"GB\/s\" << endl;\n\n \/\/ check the memory copied...\n destWrapper->copyToHost();\n int errCount = 0;\n for( int i = 0; i < numFloats; i++ ) {\n if( dest[i] != 2.0f ) {\n if( errCount > 5 ) {\n cout << \"...\" << endl;\n break;\n }\n cout << \"DIFF: dest[\" << i << \"]=\" << dest[i] << endl;\n errCount++;\n }\n }\n for( int i = 0; i < count; i++ ) {\n if( dest[i + numFloats] != 0.0f ) {\n if( errCount > 5 ) {\n cout << \"...\" << endl;\n break;\n }\n cout << \"DIFF: dest[\" << ( i + numFloats ) << \"]=\" << dest[i + numFloats] << endl;\n errCount++;\n }\n }\n\n delete destWrapper;\n delete srcWrapper;\n delete[] src;\n delete[] dest;\n delete kernel;\n delete cl;\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2009-2018 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\nCScript ParseScript(const std::string& s)\n{\n CScript result;\n\n static std::map mapOpNames;\n\n if (mapOpNames.empty())\n {\n for (unsigned int op = 0; op <= MAX_OPCODE; op++)\n {\n \/\/ Allow OP_RESERVED to get into mapOpNames\n if (op < OP_NOP && op != OP_RESERVED)\n continue;\n\n const char* name = GetOpName(static_cast(op));\n if (strcmp(name, \"OP_UNKNOWN\") == 0)\n continue;\n std::string strName(name);\n mapOpNames[strName] = static_cast(op);\n \/\/ Convenience: OP_ADD and just ADD are both recognized:\n boost::algorithm::replace_first(strName, \"OP_\", \"\");\n mapOpNames[strName] = static_cast(op);\n }\n }\n\n std::vector words;\n boost::algorithm::split(words, s, boost::algorithm::is_any_of(\" \\t\\n\"), boost::algorithm::token_compress_on);\n\n for (std::vector::const_iterator w = words.begin(); w != words.end(); ++w)\n {\n if (w->empty())\n {\n \/\/ Empty string, ignore. (boost::split given '' will return one word)\n }\n else if (std::all_of(w->begin(), w->end(), ::IsDigit) ||\n (w->front() == '-' && w->size() > 1 && std::all_of(w->begin()+1, w->end(), ::IsDigit)))\n {\n \/\/ Number\n int64_t n = atoi64(*w);\n result << n;\n }\n else if (w->substr(0,2) == \"0x\" && w->size() > 2 && IsHex(std::string(w->begin()+2, w->end())))\n {\n \/\/ Raw hex data, inserted NOT pushed onto stack:\n std::vector raw = ParseHex(std::string(w->begin()+2, w->end()));\n result.insert(result.end(), raw.begin(), raw.end());\n }\n else if (w->size() >= 2 && w->front() == '\\'' && w->back() == '\\'')\n {\n \/\/ Single-quoted string, pushed as data. NOTE: this is poor-man's\n \/\/ parsing, spaces\/tabs\/newlines in single-quoted strings won't work.\n std::vector value(w->begin()+1, w->end()-1);\n result << value;\n }\n else if (mapOpNames.count(*w))\n {\n \/\/ opcode, e.g. OP_ADD or ADD:\n result << mapOpNames[*w];\n }\n else\n {\n throw std::runtime_error(\"script parse error\");\n }\n }\n\n return result;\n}\n\n\/\/ Check that all of the input and output scripts of a transaction contains valid opcodes\nstatic bool CheckTxScriptsSanity(const CMutableTransaction& tx)\n{\n \/\/ Check input scripts for non-coinbase txs\n if (!CTransaction(tx).IsCoinBase()) {\n for (unsigned int i = 0; i < tx.vin.size(); i++) {\n if (!tx.vin[i].scriptSig.HasValidOps() || tx.vin[i].scriptSig.size() > MAX_SCRIPT_SIZE) {\n return false;\n }\n }\n }\n \/\/ Check output scripts\n for (unsigned int i = 0; i < tx.vout.size(); i++) {\n if (!tx.vout[i].scriptPubKey.HasValidOps() || tx.vout[i].scriptPubKey.size() > MAX_SCRIPT_SIZE) {\n return false;\n }\n }\n\n return true;\n}\n\nbool DecodeHexTx(CMutableTransaction& tx, const std::string& hex_tx, bool try_no_witness, bool try_witness)\n{\n if (!IsHex(hex_tx)) {\n return false;\n }\n\n std::vector txData(ParseHex(hex_tx));\n\n if (try_no_witness) {\n CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS);\n try {\n ssData >> tx;\n if (ssData.eof() && (!try_witness || CheckTxScriptsSanity(tx))) {\n return true;\n }\n } catch (const std::exception&) {\n \/\/ Fall through.\n }\n }\n\n if (try_witness) {\n CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);\n try {\n ssData >> tx;\n if (ssData.empty()) {\n return true;\n }\n } catch (const std::exception&) {\n \/\/ Fall through.\n }\n }\n\n return false;\n}\n\nbool DecodeHexBlockHeader(CBlockHeader& header, const std::string& hex_header)\n{\n if (!IsHex(hex_header)) return false;\n\n const std::vector header_data{ParseHex(hex_header)};\n CDataStream ser_header(header_data, SER_NETWORK, PROTOCOL_VERSION);\n try {\n ser_header >> header;\n } catch (const std::exception&) {\n return false;\n }\n return true;\n}\n\nbool DecodeHexBlk(CBlock& block, const std::string& strHexBlk)\n{\n if (!IsHex(strHexBlk))\n return false;\n\n std::vector blockData(ParseHex(strHexBlk));\n CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);\n try {\n ssBlock >> block;\n }\n catch (const std::exception&) {\n return false;\n }\n\n return true;\n}\n\nbool ParseHashStr(const std::string& strHex, uint256& result)\n{\n if ((strHex.size() != 64) || !IsHex(strHex))\n return false;\n\n result.SetHex(strHex);\n return true;\n}\n\nstd::vector ParseHexUV(const UniValue& v, const std::string& strName)\n{\n std::string strHex;\n if (v.isStr())\n strHex = v.getValStr();\n if (!IsHex(strHex))\n throw std::runtime_error(strName + \" must be hexadecimal string (not '\" + strHex + \"')\");\n return ParseHex(strHex);\n}\n\nint ParseSighashString(const UniValue& sighash)\n{\n int hash_type = SIGHASH_ALL;\n if (!sighash.isNull()) {\n static std::map map_sighash_values = {\n {std::string(\"ALL\"), int(SIGHASH_ALL)},\n {std::string(\"ALL|ANYONECANPAY\"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY)},\n {std::string(\"NONE\"), int(SIGHASH_NONE)},\n {std::string(\"NONE|ANYONECANPAY\"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY)},\n {std::string(\"SINGLE\"), int(SIGHASH_SINGLE)},\n {std::string(\"SINGLE|ANYONECANPAY\"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY)},\n };\n std::string strHashType = sighash.get_str();\n const auto& it = map_sighash_values.find(strHashType);\n if (it != map_sighash_values.end()) {\n hash_type = it->second;\n } else {\n throw std::runtime_error(strHashType + \" is not a valid sighash parameter.\");\n }\n }\n return hash_type;\n}\nInclude core_io.h from core_read.cpp\/\/ Copyright (c) 2009-2018 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\nCScript ParseScript(const std::string& s)\n{\n CScript result;\n\n static std::map mapOpNames;\n\n if (mapOpNames.empty())\n {\n for (unsigned int op = 0; op <= MAX_OPCODE; op++)\n {\n \/\/ Allow OP_RESERVED to get into mapOpNames\n if (op < OP_NOP && op != OP_RESERVED)\n continue;\n\n const char* name = GetOpName(static_cast(op));\n if (strcmp(name, \"OP_UNKNOWN\") == 0)\n continue;\n std::string strName(name);\n mapOpNames[strName] = static_cast(op);\n \/\/ Convenience: OP_ADD and just ADD are both recognized:\n boost::algorithm::replace_first(strName, \"OP_\", \"\");\n mapOpNames[strName] = static_cast(op);\n }\n }\n\n std::vector words;\n boost::algorithm::split(words, s, boost::algorithm::is_any_of(\" \\t\\n\"), boost::algorithm::token_compress_on);\n\n for (std::vector::const_iterator w = words.begin(); w != words.end(); ++w)\n {\n if (w->empty())\n {\n \/\/ Empty string, ignore. (boost::split given '' will return one word)\n }\n else if (std::all_of(w->begin(), w->end(), ::IsDigit) ||\n (w->front() == '-' && w->size() > 1 && std::all_of(w->begin()+1, w->end(), ::IsDigit)))\n {\n \/\/ Number\n int64_t n = atoi64(*w);\n result << n;\n }\n else if (w->substr(0,2) == \"0x\" && w->size() > 2 && IsHex(std::string(w->begin()+2, w->end())))\n {\n \/\/ Raw hex data, inserted NOT pushed onto stack:\n std::vector raw = ParseHex(std::string(w->begin()+2, w->end()));\n result.insert(result.end(), raw.begin(), raw.end());\n }\n else if (w->size() >= 2 && w->front() == '\\'' && w->back() == '\\'')\n {\n \/\/ Single-quoted string, pushed as data. NOTE: this is poor-man's\n \/\/ parsing, spaces\/tabs\/newlines in single-quoted strings won't work.\n std::vector value(w->begin()+1, w->end()-1);\n result << value;\n }\n else if (mapOpNames.count(*w))\n {\n \/\/ opcode, e.g. OP_ADD or ADD:\n result << mapOpNames[*w];\n }\n else\n {\n throw std::runtime_error(\"script parse error\");\n }\n }\n\n return result;\n}\n\n\/\/ Check that all of the input and output scripts of a transaction contains valid opcodes\nstatic bool CheckTxScriptsSanity(const CMutableTransaction& tx)\n{\n \/\/ Check input scripts for non-coinbase txs\n if (!CTransaction(tx).IsCoinBase()) {\n for (unsigned int i = 0; i < tx.vin.size(); i++) {\n if (!tx.vin[i].scriptSig.HasValidOps() || tx.vin[i].scriptSig.size() > MAX_SCRIPT_SIZE) {\n return false;\n }\n }\n }\n \/\/ Check output scripts\n for (unsigned int i = 0; i < tx.vout.size(); i++) {\n if (!tx.vout[i].scriptPubKey.HasValidOps() || tx.vout[i].scriptPubKey.size() > MAX_SCRIPT_SIZE) {\n return false;\n }\n }\n\n return true;\n}\n\nbool DecodeHexTx(CMutableTransaction& tx, const std::string& hex_tx, bool try_no_witness, bool try_witness)\n{\n if (!IsHex(hex_tx)) {\n return false;\n }\n\n std::vector txData(ParseHex(hex_tx));\n\n if (try_no_witness) {\n CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS);\n try {\n ssData >> tx;\n if (ssData.eof() && (!try_witness || CheckTxScriptsSanity(tx))) {\n return true;\n }\n } catch (const std::exception&) {\n \/\/ Fall through.\n }\n }\n\n if (try_witness) {\n CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);\n try {\n ssData >> tx;\n if (ssData.empty()) {\n return true;\n }\n } catch (const std::exception&) {\n \/\/ Fall through.\n }\n }\n\n return false;\n}\n\nbool DecodeHexBlockHeader(CBlockHeader& header, const std::string& hex_header)\n{\n if (!IsHex(hex_header)) return false;\n\n const std::vector header_data{ParseHex(hex_header)};\n CDataStream ser_header(header_data, SER_NETWORK, PROTOCOL_VERSION);\n try {\n ser_header >> header;\n } catch (const std::exception&) {\n return false;\n }\n return true;\n}\n\nbool DecodeHexBlk(CBlock& block, const std::string& strHexBlk)\n{\n if (!IsHex(strHexBlk))\n return false;\n\n std::vector blockData(ParseHex(strHexBlk));\n CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);\n try {\n ssBlock >> block;\n }\n catch (const std::exception&) {\n return false;\n }\n\n return true;\n}\n\nbool ParseHashStr(const std::string& strHex, uint256& result)\n{\n if ((strHex.size() != 64) || !IsHex(strHex))\n return false;\n\n result.SetHex(strHex);\n return true;\n}\n\nstd::vector ParseHexUV(const UniValue& v, const std::string& strName)\n{\n std::string strHex;\n if (v.isStr())\n strHex = v.getValStr();\n if (!IsHex(strHex))\n throw std::runtime_error(strName + \" must be hexadecimal string (not '\" + strHex + \"')\");\n return ParseHex(strHex);\n}\n\nint ParseSighashString(const UniValue& sighash)\n{\n int hash_type = SIGHASH_ALL;\n if (!sighash.isNull()) {\n static std::map map_sighash_values = {\n {std::string(\"ALL\"), int(SIGHASH_ALL)},\n {std::string(\"ALL|ANYONECANPAY\"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY)},\n {std::string(\"NONE\"), int(SIGHASH_NONE)},\n {std::string(\"NONE|ANYONECANPAY\"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY)},\n {std::string(\"SINGLE\"), int(SIGHASH_SINGLE)},\n {std::string(\"SINGLE|ANYONECANPAY\"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY)},\n };\n std::string strHashType = sighash.get_str();\n const auto& it = map_sighash_values.find(strHashType);\n if (it != map_sighash_values.end()) {\n hash_type = it->second;\n } else {\n throw std::runtime_error(strHashType + \" is not a valid sighash parameter.\");\n }\n }\n return hash_type;\n}\n<|endoftext|>"} {"text":"#include \"types.h\"\n#include \"amd64.h\"\n#include \"kernel.hh\"\n#include \"cpu.hh\"\n#include \"gc.hh\"\n#include \"percpu.hh\"\n#include \"spinlock.h\"\n#include \"condvar.h\"\n#include \"proc.hh\"\n#include \"uwq.hh\"\n#include \"vm.hh\"\n#include \"kalloc.hh\"\n#include \"bits.hh\"\nextern \"C\" {\n#include \"kern_c.h\"\n}\n\nbool\nuwq_trywork(void)\n{\n \/\/ Returning true means uwq added a thread to the run queue\n\n u64 i, k;\n\n \/\/ A \"random\" victim CPU\n k = rdtsc();\n for (i = 0; i < NCPU; i++) {\n u64 j = (i+k) % NCPU;\n\n if (j == mycpuid())\n continue;\n struct cpu *c = &cpus[j];\n \n \/\/ The gc_epoch is for p and uwq\n scoped_gc_epoch xgc();\n barrier();\n\n struct proc *p = c->proc;\n if (p == nullptr)\n continue;\n uwq* uwq = p->uwq;\n if (uwq == nullptr)\n continue;\n\n if (uwq->haswork()) {\n if (uwq->tryworker())\n return true;\n break;\n }\n }\n\n return false;\n}\n\nlong\nsys_wqwait(void)\n{\n uwq_worker* w = myproc()->worker;\n if (w == nullptr)\n return -1;\n\n return w->wait();\n}\n\n\/\/\n\/\/ uwq_worker\n\/\/\nuwq_worker::uwq_worker(uwq* u, proc* p)\n : uwq_(u), proc_(p), running_(false)\n{\n initlock(&lock_, \"worker_lock\", 0);\n initcondvar(&cv_, \"worker_cv\");\n}\n\nvoid\nuwq_worker::exit(void)\n{\n if (--uwq_->uref_ == 0)\n gc_delayed(uwq_);\n release(&lock_);\n delete this;\n ::exit();\n}\n\nlong\nuwq_worker::wait(void)\n{\n acquire(&lock_);\n if (!uwq_->valid())\n this->exit();\n\n running_ = false;\n cv_sleep(&cv_, &lock_);\n\n if (!uwq_->valid())\n this->exit();\n release(&lock_);\n return 0;\n}\n\n\/\/\n\/\/ uwq\n\/\/\nuwq*\nuwq::alloc(vmap* vmap, filetable *ftable)\n{\n uwq_ipcbuf* ipc;\n uwq* u;\n\n ipc = (uwq_ipcbuf*) ksalloc(slab_userwq); \n if (ipc == nullptr)\n return nullptr;\n\n ftable->incref();\n vmap->incref();\n\n u = new uwq(vmap, ftable, ipc);\n if (u == nullptr) {\n ftable->decref();\n vmap->decref();\n ksfree(slab_userwq, ipc);\n return nullptr;\n }\n\n if (mapkva(vmap->pml4, (char*)ipc, USERWQ, USERWQSIZE)) {\n ftable->decref();\n vmap->decref();\n ksfree(slab_userwq, ipc);\n u->dec();\n return nullptr;\n }\n\n return u;\n}\n\nuwq::uwq(vmap* vmap, filetable* ftable, uwq_ipcbuf* ipc) \n : rcu_freed(\"uwq\"),\n vmap_(vmap), ftable_(ftable), ipc_(ipc),\n uentry_(0), ustack_(UWQSTACK), uref_(0)\n{\n ftable_->incref();\n vmap_->incref();\n for (int i = 0; i < NCPU; i++)\n ipc_->len[i].v_ = 0;\n\n initlock(&lock_, \"uwq_lock\", 0);\n\n for (int i = 0; i < NWORKERS; i++)\n worker_[i].store(nullptr);\n}\n\nuwq::~uwq(void)\n{ \n if (ipc_ != nullptr)\n ksfree(slab_userwq, ipc_);\n vmap_->decref();\n ftable_->decref();\n}\n\nbool\nuwq::haswork(void) const\n{\n if (ipc_ == nullptr)\n return false;\n\n for (int i = 0; i < NCPU; i++) {\n if (ipc_->len[i].v_ > 0) {\n return true;\n }\n }\n return false;\n}\n\nbool\nuwq::tryworker(void)\n{\n if (!valid())\n return false;\n\n \/\/ Try to start a worker thread\n scoped_acquire lock0(&lock_);\n\n for (int i = 0; i < NWORKERS; i++) {\n if (worker_[i] == nullptr)\n continue;\n\n uwq_worker *w = worker_[i];\n if (w->running_)\n continue;\n else {\n scoped_acquire lock1(&w->lock_);\n proc* p = w->proc_;\n\n acquire(&p->lock);\n p->cpuid = mycpuid();\n release(&p->lock);\n\n w->running_ = true;\n cv_wakeup(&w->cv_);\n return true;\n }\n }\n lock0.release();\n\nagain:\n u64 uref = uref_.load();\n if (uref < ipc_->maxworkers) {\n if (!cmpxch(&uref_, uref, uref+1))\n goto again;\n \/\/ Guaranteed to have slot in worker_\n\n proc* p = allocworker();\n if (p != nullptr) {\n uwq_worker* w = new uwq_worker(this, p);\n assert(w != nullptr);\n\n ++uref_;\n p->worker = w;\n w->running_ = true;\n\n acquire(&p->lock);\n p->cpuid = mycpuid();\n addrun(p);\n release(&p->lock);\n\n for (int i = 0; i < NWORKERS; i++) {\n if (worker_[i] == nullptr)\n if (cmpxch(&worker_[i], (uwq_worker*)nullptr, w))\n return true;\n }\n panic(\"uwq::tryworker: oops\");\n }\n }\n \n return false;\n}\n\nvoid\nuwq::finish(void)\n{\n bool gcnow = true;\n\n scoped_acquire lock0(&lock_);\n for (int i = 0; i < NWORKERS; i++) {\n if (worker_[i] != nullptr) {\n uwq_worker* w = worker_[i];\n gcnow = false;\n acquire(&w->lock_);\n cv_wakeup(&w->cv_);\n release(&w->lock_);\n }\n }\n \n if (gcnow)\n gc_delayed(this);\n}\n\nvoid\nuwq::onzero() const\n{\n uwq *u = (uwq*)this;\n u->finish();\n}\n\nvoid\nuwq::setuentry(uptr uentry)\n{\n uentry_ = uentry;\n}\n\nproc*\nuwq::allocworker(void)\n{\n uptr uentry = uentry_;\n\n if (uentry == 0)\n return nullptr;\n\n proc* p = proc::alloc();\n if (p == nullptr)\n return nullptr;\n safestrcpy(p->name, \"uwq_worker\", sizeof(p->name));\n\n \/\/ finishproc will drop these refs\n vmap_->incref();\n ftable_->incref();\n \n p->vmap = vmap_;\n p->ftable = ftable_;\n \n struct vmnode *vmn;\n if ((vmn = new vmnode(USTACKPAGES)) == nullptr) {\n finishproc(p);\n return nullptr;\n }\n\n \/\/ Include a bumper page\n uptr ustack = ustack_.fetch_add((USTACKPAGES*PGSIZE)+PGSIZE);\n uptr stacktop = ustack + (USTACKPAGES*PGSIZE);\n if (vmap_->insert(vmn, ustack, 1) < 0) {\n delete vmn;\n finishproc(p);\n return nullptr;\n }\n\n p->tf->rsp = stacktop - 8;\n p->tf->rip = uentry;\n p->tf->cs = UCSEG | 0x3;\n p->tf->ds = UDSEG | 0x3;\n p->tf->ss = p->tf->ds;\n p->tf->rflags = FL_IF;\n\n return p;\n}\nOops, that wasn't right either..#include \"types.h\"\n#include \"amd64.h\"\n#include \"kernel.hh\"\n#include \"cpu.hh\"\n#include \"gc.hh\"\n#include \"percpu.hh\"\n#include \"spinlock.h\"\n#include \"condvar.h\"\n#include \"proc.hh\"\n#include \"uwq.hh\"\n#include \"vm.hh\"\n#include \"kalloc.hh\"\n#include \"bits.hh\"\nextern \"C\" {\n#include \"kern_c.h\"\n}\n\nbool\nuwq_trywork(void)\n{\n \/\/ Returning true means uwq added a thread to the run queue\n\n u64 i, k;\n\n \/\/ A \"random\" victim CPU\n k = rdtsc();\n for (i = 0; i < NCPU; i++) {\n u64 j = (i+k) % NCPU;\n\n if (j == mycpuid())\n continue;\n struct cpu *c = &cpus[j];\n \n \/\/ The gc_epoch is for p and uwq\n scoped_gc_epoch xgc();\n barrier();\n\n struct proc *p = c->proc;\n if (p == nullptr)\n continue;\n uwq* uwq = p->uwq;\n if (uwq == nullptr)\n continue;\n\n if (uwq->haswork()) {\n if (uwq->tryworker())\n return true;\n break;\n }\n }\n\n return false;\n}\n\nlong\nsys_wqwait(void)\n{\n uwq_worker* w = myproc()->worker;\n if (w == nullptr)\n return -1;\n\n return w->wait();\n}\n\n\/\/\n\/\/ uwq_worker\n\/\/\nuwq_worker::uwq_worker(uwq* u, proc* p)\n : uwq_(u), proc_(p), running_(false)\n{\n initlock(&lock_, \"worker_lock\", 0);\n initcondvar(&cv_, \"worker_cv\");\n}\n\nvoid\nuwq_worker::exit(void)\n{\n if (--uwq_->uref_ == 0)\n gc_delayed(uwq_);\n release(&lock_);\n delete this;\n ::exit();\n}\n\nlong\nuwq_worker::wait(void)\n{\n acquire(&lock_);\n if (!uwq_->valid())\n this->exit();\n\n running_ = false;\n cv_sleep(&cv_, &lock_);\n\n if (!uwq_->valid())\n this->exit();\n release(&lock_);\n return 0;\n}\n\n\/\/\n\/\/ uwq\n\/\/\nuwq*\nuwq::alloc(vmap* vmap, filetable *ftable)\n{\n uwq_ipcbuf* ipc;\n uwq* u;\n\n ipc = (uwq_ipcbuf*) ksalloc(slab_userwq); \n if (ipc == nullptr)\n return nullptr;\n\n ftable->incref();\n vmap->incref();\n\n u = new uwq(vmap, ftable, ipc);\n if (u == nullptr) {\n ftable->decref();\n vmap->decref();\n ksfree(slab_userwq, ipc);\n return nullptr;\n }\n\n if (mapkva(vmap->pml4, (char*)ipc, USERWQ, USERWQSIZE)) {\n ksfree(slab_userwq, ipc);\n u->dec();\n return nullptr;\n }\n\n return u;\n}\n\nuwq::uwq(vmap* vmap, filetable* ftable, uwq_ipcbuf* ipc) \n : rcu_freed(\"uwq\"),\n vmap_(vmap), ftable_(ftable), ipc_(ipc),\n uentry_(0), ustack_(UWQSTACK), uref_(0)\n{\n for (int i = 0; i < NCPU; i++)\n ipc_->len[i].v_ = 0;\n\n initlock(&lock_, \"uwq_lock\", 0);\n\n for (int i = 0; i < NWORKERS; i++)\n worker_[i].store(nullptr);\n}\n\nuwq::~uwq(void)\n{ \n if (ipc_ != nullptr)\n ksfree(slab_userwq, ipc_);\n vmap_->decref();\n ftable_->decref();\n}\n\nbool\nuwq::haswork(void) const\n{\n if (ipc_ == nullptr)\n return false;\n\n for (int i = 0; i < NCPU; i++) {\n if (ipc_->len[i].v_ > 0) {\n return true;\n }\n }\n return false;\n}\n\nbool\nuwq::tryworker(void)\n{\n if (!valid())\n return false;\n\n \/\/ Try to start a worker thread\n scoped_acquire lock0(&lock_);\n\n for (int i = 0; i < NWORKERS; i++) {\n if (worker_[i] == nullptr)\n continue;\n\n uwq_worker *w = worker_[i];\n if (w->running_)\n continue;\n else {\n scoped_acquire lock1(&w->lock_);\n proc* p = w->proc_;\n\n acquire(&p->lock);\n p->cpuid = mycpuid();\n release(&p->lock);\n\n w->running_ = true;\n cv_wakeup(&w->cv_);\n return true;\n }\n }\n lock0.release();\n\nagain:\n u64 uref = uref_.load();\n if (uref < ipc_->maxworkers) {\n if (!cmpxch(&uref_, uref, uref+1))\n goto again;\n \/\/ Guaranteed to have slot in worker_\n\n proc* p = allocworker();\n if (p != nullptr) {\n uwq_worker* w = new uwq_worker(this, p);\n assert(w != nullptr);\n\n ++uref_;\n p->worker = w;\n w->running_ = true;\n\n acquire(&p->lock);\n p->cpuid = mycpuid();\n addrun(p);\n release(&p->lock);\n\n for (int i = 0; i < NWORKERS; i++) {\n if (worker_[i] == nullptr)\n if (cmpxch(&worker_[i], (uwq_worker*)nullptr, w))\n return true;\n }\n panic(\"uwq::tryworker: oops\");\n }\n }\n \n return false;\n}\n\nvoid\nuwq::finish(void)\n{\n bool gcnow = true;\n\n scoped_acquire lock0(&lock_);\n for (int i = 0; i < NWORKERS; i++) {\n if (worker_[i] != nullptr) {\n uwq_worker* w = worker_[i];\n gcnow = false;\n acquire(&w->lock_);\n cv_wakeup(&w->cv_);\n release(&w->lock_);\n }\n }\n \n if (gcnow)\n gc_delayed(this);\n}\n\nvoid\nuwq::onzero() const\n{\n uwq *u = (uwq*)this;\n u->finish();\n}\n\nvoid\nuwq::setuentry(uptr uentry)\n{\n uentry_ = uentry;\n}\n\nproc*\nuwq::allocworker(void)\n{\n uptr uentry = uentry_;\n\n if (uentry == 0)\n return nullptr;\n\n proc* p = proc::alloc();\n if (p == nullptr)\n return nullptr;\n safestrcpy(p->name, \"uwq_worker\", sizeof(p->name));\n\n \/\/ finishproc will drop these refs\n vmap_->incref();\n ftable_->incref();\n \n p->vmap = vmap_;\n p->ftable = ftable_;\n \n struct vmnode *vmn;\n if ((vmn = new vmnode(USTACKPAGES)) == nullptr) {\n finishproc(p);\n return nullptr;\n }\n\n \/\/ Include a bumper page\n uptr ustack = ustack_.fetch_add((USTACKPAGES*PGSIZE)+PGSIZE);\n uptr stacktop = ustack + (USTACKPAGES*PGSIZE);\n if (vmap_->insert(vmn, ustack, 1) < 0) {\n delete vmn;\n finishproc(p);\n return nullptr;\n }\n\n p->tf->rsp = stacktop - 8;\n p->tf->rip = uentry;\n p->tf->cs = UCSEG | 0x3;\n p->tf->ds = UDSEG | 0x3;\n p->tf->ss = p->tf->ds;\n p->tf->rflags = FL_IF;\n\n return p;\n}\n<|endoftext|>"} {"text":"\/**\n * Copyright (c) 2014 Ruben Nijveld, Aaron van Geffen\n * See LICENSE for license.\n *\/\n\n#include \"..\/config.h\"\n#include \"sqlite.h\"\n#include \n#include \n#include \n\nnamespace dazeus {\nnamespace db {\n\n\/**\n * Cleanup all prepared queries and close the connection.\n *\/\nSQLiteDatabase::~SQLiteDatabase()\n{\n if (conn_) {\n sqlite3_finalize(find_property);\n sqlite3_finalize(remove_property);\n sqlite3_finalize(update_property);\n sqlite3_finalize(properties);\n sqlite3_finalize(add_permission);\n sqlite3_finalize(remove_permission);\n sqlite3_finalize(has_permission);\n int res = sqlite3_close(conn_);\n assert(res == SQLITE_OK);\n }\n}\n\nvoid SQLiteDatabase::open()\n{\n \/\/ Connect the lot!\n int fail = sqlite3_open_v2(dbc_.filename.c_str(), &conn_,\n SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,\n NULL);\n if (fail) {\n auto error = \"Can't open database (code \" + std::to_string(fail) + \"): \" +\n sqlite3_errmsg(conn_);\n throw exception(error);\n }\n upgradeDB();\n bootstrapDB();\n}\n\n\/**\n * @brief Try to create a prepared statement on the SQLite3 connection.\n *\/\nvoid SQLiteDatabase::tryPrepare(const std::string &stmt,\n sqlite3_stmt **target) const\n{\n int result = sqlite3_prepare_v2(conn_, stmt.c_str(), stmt.length(), target,\n NULL);\n if (result != SQLITE_OK) {\n throw exception(\n std::string(\"Failed to prepare SQL statement, got an error: \") +\n sqlite3_errmsg(conn_));\n }\n}\n\n\/**\n * @brief Try to bind a parameter to a prepared statement.\n *\/\nvoid SQLiteDatabase::tryBind(sqlite3_stmt *target, int param,\n const std::string &value) const\n{\n int result = sqlite3_bind_text(target, param, value.c_str(), value.length(),\n SQLITE_TRANSIENT);\n if (result != SQLITE_OK) {\n throw exception(\"Failed to bind parameter \" + std::to_string(param) +\n \" to query with error: \" + sqlite3_errmsg(conn_) +\n \" (errorcode \" + std::to_string(result) + \")\");\n }\n}\n\n\/**\n * @brief Prepare all SQL statements used by the database layer\n *\/\nvoid SQLiteDatabase::bootstrapDB()\n{\n tryPrepare(\n \"SELECT value FROM dazeus_properties \"\n \"WHERE key = ?1 \"\n \" AND network = ?2 AND receiver = ?3 AND sender = ?4\",\n &find_property);\n\n tryPrepare(\n \"DELETE FROM dazeus_properties \"\n \"WHERE key = ?1 \"\n \" AND network = ?2 AND receiver = ?3 AND sender = ?3\",\n &remove_property);\n\n tryPrepare(\n \"INSERT OR REPLACE INTO dazeus_properties \"\n \"(key, value, network, receiver, sender) \"\n \"VALUES (?1, ?2, ?3, :receiver, :sender) \",\n &update_property);\n\n tryPrepare(\n \"SELECT key FROM dazeus_properties \"\n \"WHERE key LIKE :key || '%' \"\n \" AND network = :network AND receiver = :receiver AND sender = :sender\",\n &properties);\n\n tryPrepare(\n \"INSERT OR REPLACE INTO dazeus_permissions \"\n \"(permission, network, receiver, sender) \"\n \"VALUES (:permission, :network, :receiver, :sender) \",\n &add_permission);\n\n tryPrepare(\n \"DELETE FROM dazeus_permissions \"\n \"WHERE permission = :permission \"\n \" AND network = :network AND receiver = :receiver AND sender = :sender\",\n &remove_permission);\n\n tryPrepare(\n \"SELECT * FROM dazeus_permissions \"\n \"WHERE permission = :permission \"\n \" AND network = :network AND receiver = :receiver AND sender = :sender\",\n &has_permission);\n}\n\n\/**\n * @brief Upgrade the database to the latest version.\n *\/\nvoid SQLiteDatabase::upgradeDB()\n{\n bool found = false;\n int errc = sqlite3_exec(conn_,\n \"SELECT name FROM sqlite_master WHERE type = 'table' \"\n \"AND name = 'dazeus_properties'\",\n [](void* found, int, char**, char**)\n {\n *(static_cast(found)) = true;\n return 0;\n }, static_cast(&found), NULL);\n\n if (errc != SQLITE_OK) {\n throw exception(std::string(\"Failed to retrieve database version: \") +\n sqlite3_errmsg(conn_));\n }\n\n int db_version = 0;\n if (errc == SQLITE_OK) {\n if (found) {\n \/\/ table exists, query for latest version\n errc = sqlite3_exec(conn_,\n \"SELECT value FROM dazeus_properties \"\n \"WHERE key = 'dazeus_version' LIMIT 1\",\n [](void* dbver, int columns, char** values, char**)\n {\n if (columns > 0) {\n *(static_cast(dbver)) = std::stoi(values[0]);\n }\n return 0;\n }, static_cast(&db_version), NULL);\n }\n }\n\n const char *upgrades[] = {\n \"CREATE TABLE dazeus_properties( \"\n \"key VARCHAR(255) NOT NULL, \"\n \"value TEXT NOT NULL, \"\n \"network VARCHAR(255) NOT NULL, \"\n \"receiver VARCHAR(255) NOT NULL, \"\n \"sender VARCHAR(255) NOT NULL, \"\n \"created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, \"\n \"updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, \"\n \"PRIMARY KEY(key, network, receiver, sender) \"\n \")\"\n ,\n \"CREATE TABLE dazeus_permissions( \"\n \"permission VARCHAR(255) NOT NULL, \"\n \"network VARCHAR(255) NOT NULL, \"\n \"receiver VARCHAR(255) NOT NULL, \"\n \"sender VARCHAR(255) NOT NULL, \"\n \"created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, \"\n \"updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, \"\n \"PRIMARY KEY(permission, network, receiver, sender) \"\n \")\"\n };\n\n \/\/ run any outstanding updates\n static int target_version = std::end(upgrades) - std::begin(upgrades);\n if (db_version < target_version) {\n std::cout << \"Will now upgrade database from version \" << db_version\n << \" to version \" << target_version << \".\" << std::endl;\n for (int i = db_version; i < target_version; ++i) {\n int result = sqlite3_exec(conn_, upgrades[i], NULL, NULL, NULL);\n if (result != SQLITE_OK) {\n throw exception(\"Could not run upgrade \" + std::to_string(i) +\n \", got error: \" + sqlite3_errmsg(conn_));\n }\n }\n std::cout << \"Upgrade completed. Will now update dazeus_version to \"\n << target_version << std::endl;\n errc = sqlite3_exec(conn_,\n (\"INSERT OR REPLACE INTO dazeus_properties \"\n \"(key, value, network, receiver, sender) \"\n \"VALUES ('dazeus_version', '\" + std::to_string(target_version) + \"', \"\n \" '', '', '') \").c_str(),\n NULL, NULL, NULL);\n if (errc != SQLITE_OK) {\n throw exception(\n \"Could not set dazeus_version to latest version, got error: \" +\n std::string(sqlite3_errmsg(conn_)));\n }\n }\n}\n\nstd::string SQLiteDatabase::property(const std::string &variable,\n const std::string &networkScope,\n const std::string &receiverScope,\n const std::string &senderScope)\n{\n tryBind(find_property, 1, variable);\n tryBind(find_property, 2, networkScope);\n tryBind(find_property, 3, receiverScope);\n tryBind(find_property, 4, senderScope);\n int errc = sqlite3_step(find_property);\n\n if (errc == SQLITE_ROW) {\n std::string value = reinterpret_cast(sqlite3_column_text(find_property, 0));\n sqlite3_reset(find_property);\n return value;\n } else if (errc == SQLITE_DONE) {\n \/\/ TODO: define behavior when no result is found\n sqlite3_reset(find_property);\n return \"\";\n } else {\n std::string msg = \"Got an error while executing an SQL query (code \" +\n std::to_string(errc) + \"): \" + sqlite3_errmsg(conn_);\n sqlite3_reset(find_property);\n throw exception(msg);\n }\n}\n\nvoid SQLiteDatabase::setProperty(const std::string &variable,\n const std::string &value, const std::string &networkScope,\n const std::string &receiverScope,\n const std::string &senderScope)\n{\n tryBind(update_property, 1, variable);\n tryBind(update_property, 2, value);\n tryBind(update_property, 3, networkScope);\n tryBind(update_property, 4, receiverScope);\n tryBind(update_property, 5, senderScope);\n int errc = sqlite3_step(update_property);\n\n if (errc != SQLITE_OK && errc != SQLITE_DONE) {\n std::string msg = \"Got an error while executing an SQL query (code \" +\n std::to_string(errc) + \"): \" + sqlite3_errmsg(conn_);\n sqlite3_reset(update_property);\n throw exception(msg);\n }\n\n sqlite3_reset(update_property);\n}\n\nstd::vector SQLiteDatabase::propertyKeys(const std::string &prefix,\n const std::string &networkScope,\n const std::string &receiverScope,\n const std::string &senderScope)\n{\n \/\/ Return a vector of all the property keys matching the criteria.\n std::vector keys = std::vector();\n\n tryBind(properties, 1, prefix);\n tryBind(properties, 2, networkScope);\n tryBind(properties, 3, receiverScope);\n tryBind(properties, 4, senderScope);\n\n while (true) {\n int errc = sqlite3_step(properties);\n\n if (errc == SQLITE_ROW) {\n std::string value = reinterpret_cast(sqlite3_column_text(properties, 0));\n keys.push_back(value);\n } else if (errc == SQLITE_DONE) {\n sqlite3_reset(properties);\n break;\n } else {\n std::string msg = \"Got an error while executing an SQL query (code \" +\n std::to_string(errc) + \"): \" + sqlite3_errmsg(conn_);\n sqlite3_reset(properties);\n throw exception(msg);\n }\n }\n\n return keys;\n}\n\nbool SQLiteDatabase::hasPermission(const std::string &perm_name,\n const std::string &network, const std::string &channel,\n const std::string &sender, bool defaultPermission) const\n{\n tryBind(has_permission, 1, perm_name);\n tryBind(has_permission, 2, network);\n tryBind(has_permission, 3, channel);\n tryBind(has_permission, 4, sender);\n\n int errc = sqlite3_step(has_permission);\n\n if (errc == SQLITE_ROW) {\n sqlite3_reset(has_permission);\n return true;\n } else if (errc == SQLITE_DONE) {\n sqlite3_reset(has_permission);\n return defaultPermission;\n } else {\n std::string msg = \"Got an error while executing an SQL query (code \" +\n std::to_string(errc) + \"): \" + sqlite3_errmsg(conn_);\n sqlite3_reset(has_permission);\n throw exception(msg);\n }\n}\n\nvoid SQLiteDatabase::unsetPermission(const std::string &perm_name,\n const std::string &network, const std::string &receiver,\n const std::string &sender)\n{\n tryBind(remove_permission, 1, perm_name);\n tryBind(remove_permission, 2, network);\n tryBind(remove_permission, 3, receiver);\n tryBind(remove_permission, 4, sender);\n int errc = sqlite3_step(remove_permission);\n\n if (errc != SQLITE_OK && errc != SQLITE_DONE) {\n std::string msg = \"Got an error while executing an SQL query (code \" +\n std::to_string(errc) + \"): \" + sqlite3_errmsg(conn_);\n sqlite3_reset(remove_permission);\n throw exception(msg);\n }\n\n sqlite3_reset(remove_permission);\n}\n\nvoid SQLiteDatabase::setPermission(bool permission, const std::string &perm_name,\n const std::string &network, const std::string &receiver,\n const std::string &sender)\n{\n tryBind(add_permission, 1, perm_name);\n tryBind(add_permission, 2, network);\n tryBind(add_permission, 3, receiver);\n tryBind(add_permission, 4, sender);\n int errc = sqlite3_step(add_permission);\n\n if (errc != SQLITE_OK && errc != SQLITE_DONE) {\n std::string msg = \"Got an error while executing an SQL query (code \" +\n std::to_string(errc) + \"): \" + sqlite3_errmsg(conn_);\n sqlite3_reset(add_permission);\n throw exception(msg);\n }\n\n sqlite3_reset(add_permission);\n}\n\n} \/\/ namespace db\n} \/\/ namespace dazeus\nSqlite scoping updated\/**\n * Copyright (c) 2014 Ruben Nijveld, Aaron van Geffen\n * See LICENSE for license.\n *\/\n\n#include \"..\/config.h\"\n#include \"sqlite.h\"\n#include \n#include \n#include \n\nnamespace dazeus {\nnamespace db {\n\n\/**\n * Cleanup all prepared queries and close the connection.\n *\/\nSQLiteDatabase::~SQLiteDatabase()\n{\n if (conn_) {\n sqlite3_finalize(find_property);\n sqlite3_finalize(remove_property);\n sqlite3_finalize(update_property);\n sqlite3_finalize(properties);\n sqlite3_finalize(add_permission);\n sqlite3_finalize(remove_permission);\n sqlite3_finalize(has_permission);\n int res = sqlite3_close(conn_);\n assert(res == SQLITE_OK);\n }\n}\n\nvoid SQLiteDatabase::open()\n{\n \/\/ Connect the lot!\n int fail = sqlite3_open_v2(dbc_.filename.c_str(), &conn_,\n SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,\n NULL);\n if (fail) {\n auto error = \"Can't open database (code \" + std::to_string(fail) + \"): \" +\n sqlite3_errmsg(conn_);\n throw exception(error);\n }\n upgradeDB();\n bootstrapDB();\n}\n\n\/**\n * @brief Try to create a prepared statement on the SQLite3 connection.\n *\/\nvoid SQLiteDatabase::tryPrepare(const std::string &stmt,\n sqlite3_stmt **target) const\n{\n int result = sqlite3_prepare_v2(conn_, stmt.c_str(), stmt.length(), target,\n NULL);\n if (result != SQLITE_OK) {\n throw exception(\n std::string(\"Failed to prepare SQL statement, got an error: \") +\n sqlite3_errmsg(conn_));\n }\n}\n\n\/**\n * @brief Try to bind a parameter to a prepared statement.\n *\/\nvoid SQLiteDatabase::tryBind(sqlite3_stmt *target, int param,\n const std::string &value) const\n{\n int result = sqlite3_bind_text(target, param, value.c_str(), value.length(),\n SQLITE_TRANSIENT);\n if (result != SQLITE_OK) {\n throw exception(\"Failed to bind parameter \" + std::to_string(param) +\n \" to query with error: \" + sqlite3_errmsg(conn_) +\n \" (errorcode \" + std::to_string(result) + \")\");\n }\n}\n\n\/**\n * @brief Prepare all SQL statements used by the database layer\n *\/\nvoid SQLiteDatabase::bootstrapDB()\n{\n tryPrepare(\n \"SELECT value FROM dazeus_properties \"\n \"WHERE key = ?1 \"\n \" AND (network = ?2 OR network = '') \"\n \" AND (receiver = ?3 OR receiver = '') \"\n \" AND (sender = ?4 OR sender = '') \"\n \"ORDER BY network DESC, receiver DESC, sender DESC \"\n \"LIMIT 1\",\n &find_property);\n\n tryPrepare(\n \"DELETE FROM dazeus_properties \"\n \"WHERE key = ?1 \"\n \" AND network = ?3 AND receiver = ?4 AND sender = ?5\",\n &remove_property);\n\n tryPrepare(\n \"INSERT OR REPLACE INTO dazeus_properties \"\n \"(key, value, network, receiver, sender) \"\n \"VALUES (?1, ?2, ?3, ?4, ?5) \",\n &update_property);\n\n tryPrepare(\n \"SELECT key FROM dazeus_properties \"\n \"WHERE key LIKE ?1 || '%' \"\n \" AND network = ?2 AND receiver = ?3 AND sender = ?4\",\n &properties);\n\n tryPrepare(\n \"INSERT OR REPLACE INTO dazeus_permissions \"\n \"(permission, network, receiver, sender) \"\n \"VALUES (?1, ?2, ?3, ?4) \",\n &add_permission);\n\n tryPrepare(\n \"DELETE FROM dazeus_permissions \"\n \"WHERE permission = ?1 \"\n \" AND network = ?2 AND receiver = ?3 AND sender = ?4\",\n &remove_permission);\n\n tryPrepare(\n \"SELECT * FROM dazeus_permissions \"\n \"WHERE permission = ?1 \"\n \" AND network = ?2 AND receiver = ?3 AND sender = ?4\",\n &has_permission);\n}\n\n\/**\n * @brief Upgrade the database to the latest version.\n *\/\nvoid SQLiteDatabase::upgradeDB()\n{\n bool found = false;\n int errc = sqlite3_exec(conn_,\n \"SELECT name FROM sqlite_master WHERE type = 'table' \"\n \"AND name = 'dazeus_properties'\",\n [](void* found, int, char**, char**)\n {\n *(static_cast(found)) = true;\n return 0;\n }, static_cast(&found), NULL);\n\n if (errc != SQLITE_OK) {\n throw exception(std::string(\"Failed to retrieve database version: \") +\n sqlite3_errmsg(conn_));\n }\n\n int db_version = 0;\n if (errc == SQLITE_OK) {\n if (found) {\n \/\/ table exists, query for latest version\n errc = sqlite3_exec(conn_,\n \"SELECT value FROM dazeus_properties \"\n \"WHERE key = 'dazeus_version' LIMIT 1\",\n [](void* dbver, int columns, char** values, char**)\n {\n if (columns > 0) {\n *(static_cast(dbver)) = std::stoi(values[0]);\n }\n return 0;\n }, static_cast(&db_version), NULL);\n }\n }\n\n const char *upgrades[] = {\n \"CREATE TABLE dazeus_properties( \"\n \"key VARCHAR(255) NOT NULL, \"\n \"value TEXT NOT NULL, \"\n \"network VARCHAR(255) NOT NULL, \"\n \"receiver VARCHAR(255) NOT NULL, \"\n \"sender VARCHAR(255) NOT NULL, \"\n \"created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, \"\n \"updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, \"\n \"PRIMARY KEY(key, network, receiver, sender) \"\n \")\"\n ,\n \"CREATE TABLE dazeus_permissions( \"\n \"permission VARCHAR(255) NOT NULL, \"\n \"network VARCHAR(255) NOT NULL, \"\n \"receiver VARCHAR(255) NOT NULL, \"\n \"sender VARCHAR(255) NOT NULL, \"\n \"created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, \"\n \"updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, \"\n \"PRIMARY KEY(permission, network, receiver, sender) \"\n \")\"\n };\n\n \/\/ run any outstanding updates\n static int target_version = std::end(upgrades) - std::begin(upgrades);\n if (db_version < target_version) {\n std::cout << \"Will now upgrade database from version \" << db_version\n << \" to version \" << target_version << \".\" << std::endl;\n for (int i = db_version; i < target_version; ++i) {\n int result = sqlite3_exec(conn_, upgrades[i], NULL, NULL, NULL);\n if (result != SQLITE_OK) {\n throw exception(\"Could not run upgrade \" + std::to_string(i) +\n \", got error: \" + sqlite3_errmsg(conn_));\n }\n }\n std::cout << \"Upgrade completed. Will now update dazeus_version to \"\n << target_version << std::endl;\n errc = sqlite3_exec(conn_,\n (\"INSERT OR REPLACE INTO dazeus_properties \"\n \"(key, value, network, receiver, sender) \"\n \"VALUES ('dazeus_version', '\" + std::to_string(target_version) + \"', \"\n \" '', '', '') \").c_str(),\n NULL, NULL, NULL);\n if (errc != SQLITE_OK) {\n throw exception(\n \"Could not set dazeus_version to latest version, got error: \" +\n std::string(sqlite3_errmsg(conn_)));\n }\n }\n}\n\nstd::string SQLiteDatabase::property(const std::string &variable,\n const std::string &networkScope,\n const std::string &receiverScope,\n const std::string &senderScope)\n{\n tryBind(find_property, 1, variable);\n tryBind(find_property, 2, networkScope);\n tryBind(find_property, 3, receiverScope);\n tryBind(find_property, 4, senderScope);\n int errc = sqlite3_step(find_property);\n\n if (errc == SQLITE_ROW) {\n std::string value = reinterpret_cast(sqlite3_column_text(find_property, 0));\n sqlite3_reset(find_property);\n return value;\n } else if (errc == SQLITE_DONE) {\n \/\/ TODO: define behavior when no result is found\n sqlite3_reset(find_property);\n return \"\";\n } else {\n std::string msg = \"Got an error while executing an SQL query (code \" +\n std::to_string(errc) + \"): \" + sqlite3_errmsg(conn_);\n sqlite3_reset(find_property);\n throw exception(msg);\n }\n}\n\nvoid SQLiteDatabase::setProperty(const std::string &variable,\n const std::string &value, const std::string &networkScope,\n const std::string &receiverScope,\n const std::string &senderScope)\n{\n sqlite3_stmt *stmt = value == \"\" ? remove_property : update_property;\n\n tryBind(stmt, 1, variable);\n tryBind(stmt, 2, value);\n tryBind(stmt, 3, networkScope);\n tryBind(stmt, 4, receiverScope);\n tryBind(stmt, 5, senderScope);\n int errc = sqlite3_step(stmt);\n\n if (errc != SQLITE_OK && errc != SQLITE_DONE) {\n std::string msg = \"Got an error while executing an SQL query (code \" +\n std::to_string(errc) + \"): \" + sqlite3_errmsg(conn_);\n sqlite3_reset(stmt);\n throw exception(msg);\n }\n\n sqlite3_reset(stmt);\n}\n\nstd::vector SQLiteDatabase::propertyKeys(const std::string &prefix,\n const std::string &networkScope,\n const std::string &receiverScope,\n const std::string &senderScope)\n{\n \/\/ Return a vector of all the property keys matching the criteria.\n std::vector keys = std::vector();\n\n tryBind(properties, 1, prefix);\n tryBind(properties, 2, networkScope);\n tryBind(properties, 3, receiverScope);\n tryBind(properties, 4, senderScope);\n\n while (true) {\n int errc = sqlite3_step(properties);\n\n if (errc == SQLITE_ROW) {\n std::string value = reinterpret_cast(sqlite3_column_text(properties, 0));\n keys.push_back(value);\n } else if (errc == SQLITE_DONE) {\n sqlite3_reset(properties);\n break;\n } else {\n std::string msg = \"Got an error while executing an SQL query (code \" +\n std::to_string(errc) + \"): \" + sqlite3_errmsg(conn_);\n sqlite3_reset(properties);\n throw exception(msg);\n }\n }\n\n return keys;\n}\n\nbool SQLiteDatabase::hasPermission(const std::string &perm_name,\n const std::string &network, const std::string &channel,\n const std::string &sender, bool defaultPermission) const\n{\n tryBind(has_permission, 1, perm_name);\n tryBind(has_permission, 2, network);\n tryBind(has_permission, 3, channel);\n tryBind(has_permission, 4, sender);\n\n int errc = sqlite3_step(has_permission);\n\n if (errc == SQLITE_ROW) {\n sqlite3_reset(has_permission);\n return true;\n } else if (errc == SQLITE_DONE) {\n sqlite3_reset(has_permission);\n return defaultPermission;\n } else {\n std::string msg = \"Got an error while executing an SQL query (code \" +\n std::to_string(errc) + \"): \" + sqlite3_errmsg(conn_);\n sqlite3_reset(has_permission);\n throw exception(msg);\n }\n}\n\nvoid SQLiteDatabase::unsetPermission(const std::string &perm_name,\n const std::string &network, const std::string &receiver,\n const std::string &sender)\n{\n tryBind(remove_permission, 1, perm_name);\n tryBind(remove_permission, 2, network);\n tryBind(remove_permission, 3, receiver);\n tryBind(remove_permission, 4, sender);\n int errc = sqlite3_step(remove_permission);\n\n if (errc != SQLITE_OK && errc != SQLITE_DONE) {\n std::string msg = \"Got an error while executing an SQL query (code \" +\n std::to_string(errc) + \"): \" + sqlite3_errmsg(conn_);\n sqlite3_reset(remove_permission);\n throw exception(msg);\n }\n\n sqlite3_reset(remove_permission);\n}\n\nvoid SQLiteDatabase::setPermission(bool permission, const std::string &perm_name,\n const std::string &network, const std::string &receiver,\n const std::string &sender)\n{\n tryBind(add_permission, 1, perm_name);\n tryBind(add_permission, 2, network);\n tryBind(add_permission, 3, receiver);\n tryBind(add_permission, 4, sender);\n int errc = sqlite3_step(add_permission);\n\n if (errc != SQLITE_OK && errc != SQLITE_DONE) {\n std::string msg = \"Got an error while executing an SQL query (code \" +\n std::to_string(errc) + \"): \" + sqlite3_errmsg(conn_);\n sqlite3_reset(add_permission);\n throw exception(msg);\n }\n\n sqlite3_reset(add_permission);\n}\n\n} \/\/ namespace db\n} \/\/ namespace dazeus\n<|endoftext|>"} {"text":"#include \"TChain.h\"\n#include \"TTree.h\"\n#include \"TH1F.h\"\n#include \"TF1.h\"\n#include \"TH2F.h\"\n#include \"TCanvas.h\"\n#include \"TObjArray.h\"\n#include \"TTreeStream.h\"\n\n#define NPMTs 24\n\nint MakeTrendT0( char *infile, int run) {\n\n char *outfile = \"trending.root\";\n \n if(!infile) return -1;\n if(!outfile) return -1;\n\n TFile *f = TFile::Open(infile,\"read\");\n if (!f) {\n printf(\"File %s not available\\n\", infile);\n return -1;\n }\n\n \/\/ LOAD HISTOGRAMS FROM QAresults.root \n TObjArray *fTzeroObject = (TObjArray*) f->Get(\"T0_Performance\/QAT0chists\"); \n\n TH1F* fTzeroORAplusORC =(TH1F*) ((TH1F*) fTzeroObject->FindObject(\"fTzeroORAplusORC\"))->Clone(\"A\"); \n TH1F* fResolution =(TH1F*) ((TH1F*) fTzeroObject->FindObject(\"fResolution\"))->Clone(\"B\");\n TH1F* fTzeroORA =(TH1F*) ((TH1F*) fTzeroObject->FindObject(\"fTzeroORA\"))->Clone(\"C\");\n TH1F* fTzeroORC =(TH1F*) ((TH1F*) fTzeroObject->FindObject(\"fTzeroORC\"))->Clone(\"D\");\n\n TH2F *fTimeVSAmplitude[NPMTs];\/\/counting PMTs from 0\n TH1D *fAmplitude[NPMTs];\n TH1D *fTime[NPMTs];\n \/\/-----> add new histogram here \n\n\n\n \/\/ sigma fit of resolution, mean T0A, T0C and T0C&A, mean amplitude for each PMT\n double resolutionSigma = -9999; \/\/dummy init\n double tzeroOrAPlusOrC = -9999; \/\/dummy init\n double tzeroOrA = -9999; \/\/dummy init\n double tzeroOrC = -9999; \/\/dummy init\n double meanAmplitude[NPMTs]; \/\/dummy init\n double meanTime[NPMTs]; \/\/dummy init\n double timeDelayOCDB[NPMTs]; \/\/dummy init\n \n \/\/.................................................................................\n\n for(int ipmt=1; ipmt<=NPMTs; ipmt++){ \/\/loop over all PMTs\n fTimeVSAmplitude[ipmt-1] =(TH2F*) ((TH2F*) fTzeroObject->FindObject(Form(\"fTimeVSAmplitude%d\",ipmt)))->Clone(Form(\"E%d\",ipmt));\n int nbinsX = fTimeVSAmplitude[ipmt-1]->GetNbinsX();\n int nbinsY = fTimeVSAmplitude[ipmt-1]->GetNbinsY();\n \/\/Amplitude\n fAmplitude[ipmt-1] = (TH1D*) fTimeVSAmplitude[ipmt-1]->ProjectionX(Form(\"fAmplitude%d\",ipmt), 1, nbinsY); \n meanAmplitude[ipmt-1] = -9999; \/\/dummy init \n if(fAmplitude[ipmt-1]->GetEntries()>0){\n meanAmplitude[ipmt-1] = fAmplitude[ipmt-1]->GetMean();\n }\n\n \/\/Time\n fTime[ipmt-1] = (TH1D*) fTimeVSAmplitude[ipmt-1]->ProjectionY(Form(\"fTime%d\",ipmt), 1, nbinsX); \n meanTime[ipmt-1] = -9999; \/\/dummy init \n if(fTime[ipmt-1]->GetEntries()>0){\n if(fTime[ipmt-1]->GetEntries()>20){\n meanTime[ipmt-1] = GetParameterGaus((TH1F*) fTime[ipmt-1], 1); \/\/ Mean Time\n }else if(fTime[ipmt-1]->GetEntries()>0){\n meanTime[ipmt-1] = fTime[ipmt-1]->GetMean();\n } \n }\n }\n\n\n\n if(fResolution->GetEntries()>20){\n resolutionSigma = GetParameterGaus(fResolution, 2); \/\/gaussian sigma \n }else if(fResolution->GetEntries()>0){\n resolutionSigma = fResolution->GetRMS(); \/\/gaussian sigma \n }\n\n if(fTzeroORAplusORC->GetEntries()>20){\n tzeroOrAPlusOrC = GetParameterGaus(fTzeroORAplusORC, 1); \/\/gaussian mean \n }else if(fTzeroORAplusORC->GetEntries()>0){\n tzeroOrAPlusOrC = fTzeroORAplusORC->GetMean();\n }\n\n if(fTzeroORA->GetEntries()>20){ \n tzeroOrA = GetParameterGaus(fTzeroORA, 1); \/\/gaussian mean\n }else if(fTzeroORA->GetEntries()>0){\n tzeroOrA = fTzeroORA->GetMean();\n }\n\n if(fTzeroORC->GetEntries()>20){\n tzeroOrC = GetParameterGaus(fTzeroORC, 1); \/\/gaussian mean \n }else if(fTzeroORC->GetEntries()>0){\n tzeroOrC = fTzeroORC->GetMean(); \/\/gaussian mean \n }\n\n \/\/-----> analyze the new histogram here and set mean\/sigma\n\n\n f->Close();\n\n \/\/-------------------- READ OCDB TIME DELAYS ---------------------------\n \/\/ Arguments:\n AliCDBManager* man = AliCDBManager::Instance();\n man->SetDefaultStorage(\"raw:\/\/\");\n man->SetRun(run);\n AliCDBEntry *entry = AliCDBManager::Instance()->Get(\"T0\/Calib\/TimeDelay\");\n AliT0CalibTimeEq *clb = (AliT0CalibTimeEq*)entry->GetObject(); \n for (Int_t i=0; iGetCFDvalue(i,0);\n }\n\n\n \n \/\/--------------- write walues to the output ------------ \n TTreeSRedirector* pcstream = NULL;\n pcstream = new TTreeSRedirector(outfile);\n if (!pcstream) return;\n\n\n TFile *x = pcstream->GetFile();\n x->cd();\n\n TObjString runType;\n Int_t startTimeGRP=0;\n Int_t stopTimeGRP=0;\n Int_t time=0;\n Int_t duration=0;\n\n time = (startTimeGRP+stopTimeGRP)\/2;\n duration = (stopTimeGRP-startTimeGRP);\n\n (*pcstream)<<\"t0QA\"<<\n \"run=\"< add the mean\/sigma of the new histogram here \n \n (*pcstream)<<\"t0QA\"<<\"\\n\";\n \n pcstream->Close(); \n \n delete pcstream; \n\n return;\n\n}\n\n\/\/_____________________________________________________________________________\ndouble GetParameterGaus(TH1F *histo, int whichParameter){\n\n int maxBin = histo->GetMaximumBin(); \n double max = (histo->GetBinContent(maxBin-1) + histo->GetBinContent(maxBin) + histo->GetBinContent(maxBin+1))\/3;\n double mean = histo->GetBinCenter(maxBin); \/\/mean\n double lowfwhm = histo->GetBinCenter(histo->FindFirstBinAbove(max\/2));\n double highfwhm = histo->GetBinCenter(histo->FindLastBinAbove(max\/2));\n double sigma = (highfwhm - lowfwhm)\/2.35482; \/\/estimate fwhm FWHM = 2.35482*sigma\n\n TF1 *gaussfit = new TF1(\"gaussfit\",\"gaus\", mean - 4*sigma, mean + 4*sigma); \/\/ fit in +- 4 sigma window\n gaussfit->SetParameters(max, mean, sigma); \n\n if(whichParameter==2)\n histo->Fit(gaussfit,\"RQNI\");\n else\n histo->Fit(gaussfit,\"RQN\");\n\n double parValue = gaussfit->GetParameter(whichParameter); \n\n delete gaussfit; \n \n return parValue;\n}\n\n\nmake the script working#define NPMTs 24\n\nint MakeTrendT0( char *infile, int run) {\n\n gSystem->Load(\"libANALYSIS\");\n gSystem->Load(\"libANALYSISalice\");\n gSystem->Load(\"libCORRFW\");\n gSystem->Load(\"libTENDER\");\n gSystem->Load(\"libPWGPP.so\");\n\n char *outfile = \"trending.root\";\n \n if(!infile) return -1;\n if(!outfile) return -1;\n\n TFile *f = TFile::Open(infile,\"read\");\n if (!f) {\n printf(\"File %s not available\\n\", infile);\n return -1;\n }\n\n \/\/ LOAD HISTOGRAMS FROM QAresults.root \n TObjArray *fTzeroObject = (TObjArray*) f->Get(\"T0_Performance\/QAT0chists\"); \n\n TH1F* fTzeroORAplusORC =(TH1F*) ((TH1F*) fTzeroObject->FindObject(\"fTzeroORAplusORC\"))->Clone(\"A\"); \n TH1F* fResolution =(TH1F*) ((TH1F*) fTzeroObject->FindObject(\"fResolution\"))->Clone(\"B\");\n TH1F* fTzeroORA =(TH1F*) ((TH1F*) fTzeroObject->FindObject(\"fTzeroORA\"))->Clone(\"C\");\n TH1F* fTzeroORC =(TH1F*) ((TH1F*) fTzeroObject->FindObject(\"fTzeroORC\"))->Clone(\"D\");\n\n TH2F *fTimeVSAmplitude[NPMTs];\/\/counting PMTs from 0\n TH1D *fAmplitude[NPMTs];\n TH1D *fTime[NPMTs];\n \/\/-----> add new histogram here \n\n\n\n \/\/ sigma fit of resolution, mean T0A, T0C and T0C&A, mean amplitude for each PMT\n double resolutionSigma = -9999; \/\/dummy init\n double tzeroOrAPlusOrC = -9999; \/\/dummy init\n double tzeroOrA = -9999; \/\/dummy init\n double tzeroOrC = -9999; \/\/dummy init\n double meanAmplitude[NPMTs]; \/\/dummy init\n double meanTime[NPMTs]; \/\/dummy init\n double timeDelayOCDB[NPMTs]; \/\/dummy init\n \n \/\/.................................................................................\n\n for(int ipmt=1; ipmt<=NPMTs; ipmt++){ \/\/loop over all PMTs\n fTimeVSAmplitude[ipmt-1] =(TH2F*) ((TH2F*) fTzeroObject->FindObject(Form(\"fTimeVSAmplitude%d\",ipmt)))->Clone(Form(\"E%d\",ipmt));\n int nbinsX = fTimeVSAmplitude[ipmt-1]->GetNbinsX();\n int nbinsY = fTimeVSAmplitude[ipmt-1]->GetNbinsY();\n \/\/Amplitude\n fAmplitude[ipmt-1] = (TH1D*) fTimeVSAmplitude[ipmt-1]->ProjectionX(Form(\"fAmplitude%d\",ipmt), 1, nbinsY); \n meanAmplitude[ipmt-1] = -9999; \/\/dummy init \n if(fAmplitude[ipmt-1]->GetEntries()>0){\n meanAmplitude[ipmt-1] = fAmplitude[ipmt-1]->GetMean();\n }\n\n \/\/Time\n fTime[ipmt-1] = (TH1D*) fTimeVSAmplitude[ipmt-1]->ProjectionY(Form(\"fTime%d\",ipmt), 1, nbinsX); \n meanTime[ipmt-1] = -9999; \/\/dummy init \n if(fTime[ipmt-1]->GetEntries()>0){\n if(fTime[ipmt-1]->GetEntries()>20){\n meanTime[ipmt-1] = GetParameterGaus((TH1F*) fTime[ipmt-1], 1); \/\/ Mean Time\n }else if(fTime[ipmt-1]->GetEntries()>0){\n meanTime[ipmt-1] = fTime[ipmt-1]->GetMean();\n } \n }\n }\n\n\n\n if(fResolution->GetEntries()>20){\n resolutionSigma = GetParameterGaus(fResolution, 2); \/\/gaussian sigma \n }else if(fResolution->GetEntries()>0){\n resolutionSigma = fResolution->GetRMS(); \/\/gaussian sigma \n }\n\n if(fTzeroORAplusORC->GetEntries()>20){\n tzeroOrAPlusOrC = GetParameterGaus(fTzeroORAplusORC, 1); \/\/gaussian mean \n }else if(fTzeroORAplusORC->GetEntries()>0){\n tzeroOrAPlusOrC = fTzeroORAplusORC->GetMean();\n }\n\n if(fTzeroORA->GetEntries()>20){ \n tzeroOrA = GetParameterGaus(fTzeroORA, 1); \/\/gaussian mean\n }else if(fTzeroORA->GetEntries()>0){\n tzeroOrA = fTzeroORA->GetMean();\n }\n\n if(fTzeroORC->GetEntries()>20){\n tzeroOrC = GetParameterGaus(fTzeroORC, 1); \/\/gaussian mean \n }else if(fTzeroORC->GetEntries()>0){\n tzeroOrC = fTzeroORC->GetMean(); \/\/gaussian mean \n }\n\n \/\/-----> analyze the new histogram here and set mean\/sigma\n\n\n f->Close();\n\n \/\/-------------------- READ OCDB TIME DELAYS ---------------------------\n \/\/ Arguments:\n AliCDBManager* man = AliCDBManager::Instance();\n man->SetDefaultStorage(\"raw:\/\/\");\n man->SetRun(run);\n AliCDBEntry *entry = AliCDBManager::Instance()->Get(\"T0\/Calib\/TimeDelay\");\n AliT0CalibTimeEq *clb = (AliT0CalibTimeEq*)entry->GetObject(); \n for (Int_t i=0; iGetCFDvalue(i,0);\n }\n\n\n \n \/\/--------------- write walues to the output ------------ \n TTreeSRedirector* pcstream = NULL;\n pcstream = new TTreeSRedirector(outfile);\n if (!pcstream) return;\n\n\n TFile *x = pcstream->GetFile();\n x->cd();\n\n TObjString runType;\n Int_t startTimeGRP=0;\n Int_t stopTimeGRP=0;\n Int_t time=0;\n Int_t duration=0;\n\n time = (startTimeGRP+stopTimeGRP)\/2;\n duration = (stopTimeGRP-startTimeGRP);\n\n (*pcstream)<<\"t0QA\"<<\n \"run=\"< add the mean\/sigma of the new histogram here \n \n (*pcstream)<<\"t0QA\"<<\"\\n\";\n \n pcstream->Close(); \n \n delete pcstream; \n\n return;\n\n}\n\n\/\/_____________________________________________________________________________\ndouble GetParameterGaus(TH1F *histo, int whichParameter){\n\n int maxBin = histo->GetMaximumBin(); \n double max = (histo->GetBinContent(maxBin-1) + histo->GetBinContent(maxBin) + histo->GetBinContent(maxBin+1))\/3;\n double mean = histo->GetBinCenter(maxBin); \/\/mean\n double lowfwhm = histo->GetBinCenter(histo->FindFirstBinAbove(max\/2));\n double highfwhm = histo->GetBinCenter(histo->FindLastBinAbove(max\/2));\n double sigma = (highfwhm - lowfwhm)\/2.35482; \/\/estimate fwhm FWHM = 2.35482*sigma\n\n TF1 *gaussfit = new TF1(\"gaussfit\",\"gaus\", mean - 4*sigma, mean + 4*sigma); \/\/ fit in +- 4 sigma window\n gaussfit->SetParameters(max, mean, sigma); \n\n if(whichParameter==2)\n histo->Fit(gaussfit,\"RQNI\");\n else\n histo->Fit(gaussfit,\"RQN\");\n\n double parValue = gaussfit->GetParameter(whichParameter); \n\n delete gaussfit; \n \n return parValue;\n}\n\n\n<|endoftext|>"} {"text":"#pragma once\n\n#include \"core_configuration\/core_configuration.hpp\"\n#include \"device_properties.hpp\"\n#include \"event_queue.hpp\"\n#include \"hid_keyboard_caps_lock_led_state_manager.hpp\"\n#include \"iokit_utility.hpp\"\n#include \"pressed_keys_manager.hpp\"\n#include \"types.hpp\"\n#include \n\nnamespace krbn {\nnamespace grabber {\nnamespace device_grabber_details {\nclass entry final : public pqrs::dispatcher::extra::dispatcher_client {\npublic:\n entry(device_id device_id,\n IOHIDDeviceRef device,\n std::weak_ptr core_configuration) : dispatcher_client(),\n device_id_(device_id),\n core_configuration_(core_configuration),\n hid_queue_value_monitor_async_start_called_(false),\n first_value_arrived_(false),\n grabbed_(false),\n disabled_(false),\n grabbed_time_stamp_(0),\n ungrabbed_time_stamp_(0) {\n device_properties_ = std::make_shared(device_id,\n device);\n\n pressed_keys_manager_ = std::make_shared();\n hid_queue_value_monitor_ = std::make_shared(pqrs::dispatcher::extra::get_shared_dispatcher(),\n device);\n caps_lock_led_state_manager_ = std::make_shared(device);\n device_name_ = iokit_utility::make_device_name_for_log(device_id,\n device);\n device_short_name_ = iokit_utility::make_device_name(device);\n }\n\n ~entry(void) {\n detach_from_dispatcher([this] {\n hid_queue_value_monitor_ = nullptr;\n caps_lock_led_state_manager_ = nullptr;\n });\n }\n\n device_id get_device_id(void) const {\n return device_id_;\n }\n\n void set_core_configuration(std::weak_ptr core_configuration) {\n core_configuration_ = core_configuration;\n\n control_caps_lock_led_state_manager();\n }\n\n std::shared_ptr get_device_properties(void) const {\n return device_properties_;\n }\n\n std::shared_ptr get_pressed_keys_manager(void) const {\n return pressed_keys_manager_;\n }\n\n std::shared_ptr get_hid_queue_value_monitor(void) const {\n return hid_queue_value_monitor_;\n }\n\n bool get_first_value_arrived(void) const {\n return first_value_arrived_;\n }\n\n void set_first_value_arrived(bool value) {\n first_value_arrived_ = value;\n }\n\n std::shared_ptr get_caps_lock_led_state_manager(void) const {\n return caps_lock_led_state_manager_;\n }\n\n const std::string& get_device_name(void) const {\n return device_name_;\n }\n\n const std::string& get_device_short_name(void) const {\n return device_short_name_;\n }\n\n bool get_grabbed(void) const {\n return grabbed_;\n }\n\n void set_grabbed(bool value) {\n grabbed_ = value;\n\n if (grabbed_) {\n grabbed_time_stamp_ = pqrs::osx::chrono::mach_absolute_time_point();\n } else {\n ungrabbed_time_stamp_ = pqrs::osx::chrono::mach_absolute_time_point();\n }\n\n control_caps_lock_led_state_manager();\n }\n\n bool get_disabled(void) const {\n return disabled_;\n }\n\n void set_disabled(bool value) {\n disabled_ = value;\n }\n\n bool is_ignored_device(void) const {\n if (device_properties_) {\n if (auto c = core_configuration_.lock()) {\n if (auto device_identifiers = device_properties_->get_device_identifiers()) {\n return c->get_selected_profile().get_device_ignore(\n *device_identifiers);\n }\n }\n }\n\n return false;\n }\n\n bool is_disable_built_in_keyboard_if_exists(void) const {\n if (device_properties_) {\n if (auto c = core_configuration_.lock()) {\n if (auto device_identifiers = device_properties_->get_device_identifiers()) {\n return c->get_selected_profile().get_device_disable_built_in_keyboard_if_exists(\n *device_identifiers);\n }\n }\n }\n return false;\n }\n\n void async_start_queue_value_monitor(void) {\n if (hid_queue_value_monitor_) {\n if (!hid_queue_value_monitor_async_start_called_) {\n first_value_arrived_ = false;\n hid_queue_value_monitor_async_start_called_ = true;\n }\n\n hid_queue_value_monitor_->async_start(kIOHIDOptionsTypeSeizeDevice,\n std::chrono::milliseconds(1000));\n }\n }\n\n void async_stop_queue_value_monitor(void) {\n if (hid_queue_value_monitor_) {\n hid_queue_value_monitor_async_start_called_ = false;\n\n hid_queue_value_monitor_->async_stop();\n }\n }\n\n bool is_grabbed(absolute_time_point time_stamp) {\n if (grabbed_) {\n if (grabbed_time_stamp_ <= time_stamp) {\n return true;\n }\n } else {\n \/\/\n \/\/ (grabbed_time_stamp_ <= ungrabbed_time_stamp_) when (grabbed_ == false)\n \/\/\n\n if (grabbed_time_stamp_ <= time_stamp &&\n time_stamp <= ungrabbed_time_stamp_) {\n return true;\n }\n }\n\n return false;\n }\n\nprivate:\n void control_caps_lock_led_state_manager(void) {\n if (caps_lock_led_state_manager_) {\n if (device_properties_) {\n if (auto c = core_configuration_.lock()) {\n if (auto device_identifiers = device_properties_->get_device_identifiers()) {\n if (c->get_selected_profile().get_device_manipulate_caps_lock_led(*device_identifiers)) {\n if (grabbed_) {\n caps_lock_led_state_manager_->async_start();\n return;\n }\n }\n }\n }\n }\n\n caps_lock_led_state_manager_->async_stop();\n }\n }\n\n device_id device_id_;\n std::weak_ptr core_configuration_;\n std::shared_ptr device_properties_;\n std::shared_ptr pressed_keys_manager_;\n\n std::shared_ptr hid_queue_value_monitor_;\n bool hid_queue_value_monitor_async_start_called_;\n bool first_value_arrived_;\n\n std::shared_ptr caps_lock_led_state_manager_;\n std::string device_name_;\n std::string device_short_name_;\n\n bool grabbed_;\n bool disabled_;\n\n absolute_time_point grabbed_time_stamp_;\n absolute_time_point ungrabbed_time_stamp_;\n};\n} \/\/ namespace device_grabber_details\n} \/\/ namespace grabber\n} \/\/ namespace krbn\nReturn false at is_disable_built_in_keyboard_if_exists if device is built in#pragma once\n\n#include \"core_configuration\/core_configuration.hpp\"\n#include \"device_properties.hpp\"\n#include \"event_queue.hpp\"\n#include \"hid_keyboard_caps_lock_led_state_manager.hpp\"\n#include \"iokit_utility.hpp\"\n#include \"pressed_keys_manager.hpp\"\n#include \"types.hpp\"\n#include \n\nnamespace krbn {\nnamespace grabber {\nnamespace device_grabber_details {\nclass entry final : public pqrs::dispatcher::extra::dispatcher_client {\npublic:\n entry(device_id device_id,\n IOHIDDeviceRef device,\n std::weak_ptr core_configuration) : dispatcher_client(),\n device_id_(device_id),\n core_configuration_(core_configuration),\n hid_queue_value_monitor_async_start_called_(false),\n first_value_arrived_(false),\n grabbed_(false),\n disabled_(false),\n grabbed_time_stamp_(0),\n ungrabbed_time_stamp_(0) {\n device_properties_ = std::make_shared(device_id,\n device);\n\n pressed_keys_manager_ = std::make_shared();\n hid_queue_value_monitor_ = std::make_shared(pqrs::dispatcher::extra::get_shared_dispatcher(),\n device);\n caps_lock_led_state_manager_ = std::make_shared(device);\n device_name_ = iokit_utility::make_device_name_for_log(device_id,\n device);\n device_short_name_ = iokit_utility::make_device_name(device);\n }\n\n ~entry(void) {\n detach_from_dispatcher([this] {\n hid_queue_value_monitor_ = nullptr;\n caps_lock_led_state_manager_ = nullptr;\n });\n }\n\n device_id get_device_id(void) const {\n return device_id_;\n }\n\n void set_core_configuration(std::weak_ptr core_configuration) {\n core_configuration_ = core_configuration;\n\n control_caps_lock_led_state_manager();\n }\n\n std::shared_ptr get_device_properties(void) const {\n return device_properties_;\n }\n\n std::shared_ptr get_pressed_keys_manager(void) const {\n return pressed_keys_manager_;\n }\n\n std::shared_ptr get_hid_queue_value_monitor(void) const {\n return hid_queue_value_monitor_;\n }\n\n bool get_first_value_arrived(void) const {\n return first_value_arrived_;\n }\n\n void set_first_value_arrived(bool value) {\n first_value_arrived_ = value;\n }\n\n std::shared_ptr get_caps_lock_led_state_manager(void) const {\n return caps_lock_led_state_manager_;\n }\n\n const std::string& get_device_name(void) const {\n return device_name_;\n }\n\n const std::string& get_device_short_name(void) const {\n return device_short_name_;\n }\n\n bool get_grabbed(void) const {\n return grabbed_;\n }\n\n void set_grabbed(bool value) {\n grabbed_ = value;\n\n if (grabbed_) {\n grabbed_time_stamp_ = pqrs::osx::chrono::mach_absolute_time_point();\n } else {\n ungrabbed_time_stamp_ = pqrs::osx::chrono::mach_absolute_time_point();\n }\n\n control_caps_lock_led_state_manager();\n }\n\n bool get_disabled(void) const {\n return disabled_;\n }\n\n void set_disabled(bool value) {\n disabled_ = value;\n }\n\n bool is_ignored_device(void) const {\n if (device_properties_) {\n if (auto c = core_configuration_.lock()) {\n if (auto device_identifiers = device_properties_->get_device_identifiers()) {\n return c->get_selected_profile().get_device_ignore(\n *device_identifiers);\n }\n }\n }\n\n return false;\n }\n\n bool is_disable_built_in_keyboard_if_exists(void) const {\n if (device_properties_) {\n if (device_properties_->get_is_built_in_keyboard() ||\n device_properties_->get_is_built_in_pointing_device()) {\n return false;\n }\n\n if (auto c = core_configuration_.lock()) {\n if (auto device_identifiers = device_properties_->get_device_identifiers()) {\n return c->get_selected_profile().get_device_disable_built_in_keyboard_if_exists(\n *device_identifiers);\n }\n }\n }\n return false;\n }\n\n void async_start_queue_value_monitor(void) {\n if (hid_queue_value_monitor_) {\n if (!hid_queue_value_monitor_async_start_called_) {\n first_value_arrived_ = false;\n hid_queue_value_monitor_async_start_called_ = true;\n }\n\n hid_queue_value_monitor_->async_start(kIOHIDOptionsTypeSeizeDevice,\n std::chrono::milliseconds(1000));\n }\n }\n\n void async_stop_queue_value_monitor(void) {\n if (hid_queue_value_monitor_) {\n hid_queue_value_monitor_async_start_called_ = false;\n\n hid_queue_value_monitor_->async_stop();\n }\n }\n\n bool is_grabbed(absolute_time_point time_stamp) {\n if (grabbed_) {\n if (grabbed_time_stamp_ <= time_stamp) {\n return true;\n }\n } else {\n \/\/\n \/\/ (grabbed_time_stamp_ <= ungrabbed_time_stamp_) when (grabbed_ == false)\n \/\/\n\n if (grabbed_time_stamp_ <= time_stamp &&\n time_stamp <= ungrabbed_time_stamp_) {\n return true;\n }\n }\n\n return false;\n }\n\nprivate:\n void control_caps_lock_led_state_manager(void) {\n if (caps_lock_led_state_manager_) {\n if (device_properties_) {\n if (auto c = core_configuration_.lock()) {\n if (auto device_identifiers = device_properties_->get_device_identifiers()) {\n if (c->get_selected_profile().get_device_manipulate_caps_lock_led(*device_identifiers)) {\n if (grabbed_) {\n caps_lock_led_state_manager_->async_start();\n return;\n }\n }\n }\n }\n }\n\n caps_lock_led_state_manager_->async_stop();\n }\n }\n\n device_id device_id_;\n std::weak_ptr core_configuration_;\n std::shared_ptr device_properties_;\n std::shared_ptr pressed_keys_manager_;\n\n std::shared_ptr hid_queue_value_monitor_;\n bool hid_queue_value_monitor_async_start_called_;\n bool first_value_arrived_;\n\n std::shared_ptr caps_lock_led_state_manager_;\n std::string device_name_;\n std::string device_short_name_;\n\n bool grabbed_;\n bool disabled_;\n\n absolute_time_point grabbed_time_stamp_;\n absolute_time_point ungrabbed_time_stamp_;\n};\n} \/\/ namespace device_grabber_details\n} \/\/ namespace grabber\n} \/\/ namespace krbn\n<|endoftext|>"} {"text":"\/\/\/\n\/\/\/ @file S2_easy.cpp\n\/\/\/ @brief Calculate the contribution of the clustered easy leaves\n\/\/\/ and the sparse easy leaves in parallel using OpenMP\n\/\/\/ (Deleglise-Rivat algorithm).\n\/\/\/\n\/\/\/ Copyright (C) 2016 Kim Walisch, \n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#ifdef _OPENMP\n #include \n#endif\n\nusing namespace std;\nusing namespace primecount;\nusing namespace nlohmann;\n\nnamespace {\n\ntemplate \nvoid backup(T x,\n int64_t y,\n int64_t z,\n int64_t c,\n int64_t start,\n int64_t pi_x13,\n T s2_easy,\n double percent,\n double time)\n{\n ifstream ifs(\"primecount.backup\");\n json j;\n\n if (ifs.is_open())\n {\n ifs >> j;\n ifs.close();\n }\n\n if (j.find(\"S2_easy\") != j.end())\n j.erase(j.find(\"S2_easy\"));\n\n j[\"S2_easy\"][\"x\"] = to_string(x);\n j[\"S2_easy\"][\"y\"] = y;\n j[\"S2_easy\"][\"z\"] = z;\n j[\"S2_easy\"][\"c\"] = c;\n j[\"S2_easy\"][\"start\"] = start;\n j[\"S2_easy\"][\"pi_x13\"] = pi_x13;\n j[\"S2_easy\"][\"s2_easy\"] = to_string(s2_easy);\n j[\"S2_easy\"][\"percent\"] = percent;\n j[\"S2_easy\"][\"seconds\"] = get_wtime() - time;\n\n ofstream ofs(\"primecount.backup\");\n ofs << setw(4) << j << endl;\n}\n\ntemplate \nbool resume(T x,\n int64_t y,\n int64_t z,\n int64_t c,\n int64_t& start,\n int64_t& pi_x13,\n T& s2_easy,\n double& time)\n{\n ifstream ifs(\"primecount.backup\");\n json j;\n\n if (ifs.is_open())\n {\n ifs >> j;\n ifs.close();\n }\n\n if (j.find(\"S2_easy\") != j.end() &&\n x == calculator::eval(j[\"S2_easy\"][\"x\"]) &&\n y == j[\"S2_easy\"][\"y\"] &&\n z == j[\"S2_easy\"][\"z\"] &&\n c == j[\"S2_easy\"][\"c\"])\n {\n double percent = j[\"S2_easy\"][\"percent\"];\n double seconds = j[\"S2_easy\"][\"seconds\"];\n\n start = j[\"S2_easy\"][\"start\"];\n pi_x13 = j[\"S2_easy\"][\"pi_x13\"];\n s2_easy = calculator::eval(j[\"S2_easy\"][\"s2_easy\"]);\n time = get_wtime() - seconds;\n\n if (is_print())\n {\n if (!print_variables())\n cout << endl;\n\n cout << \"=== Resuming from primecount.backup ===\" << endl;\n cout << \"start = \" << start << endl;\n cout << \"pi_x13 = \" << pi_x13 << endl;\n cout << \"s2_easy = \" << s2_easy << endl;\n cout << \"Seconds: \" << seconds << endl << endl;\n cout << \"Status: \" << fixed << setprecision(get_status_precision(x)) << percent << '%' << flush;\n }\n\n return true;\n }\n\n return false;\n}\n\n\/\/\/ Calculate the contribution of the clustered easy leaves\n\/\/\/ and the sparse easy leaves.\n\/\/\/ @param T either int64_t or uint128_t.\n\/\/\/\ntemplate \nT S2_easy_OpenMP(T x,\n int64_t y,\n int64_t z,\n int64_t c,\n Primes& primes,\n int threads,\n double& time)\n{\n T s2_easy = 0;\n int64_t start;\n int64_t pi_x13;\n double backup_time = get_wtime();\n bool is_resume = resume(x, y, z, c, start, pi_x13, s2_easy, time);\n\n if (is_resume && start >= pi_x13)\n return s2_easy;\n\n PiTable pi(y);\n S2Status status(x);\n\n int64_t pi_sqrty = pi[isqrt(y)];\n int64_t x13 = iroot<3>(x);\n int64_t max_dist = 1;\n int64_t thread_threshold = 1000;\n threads = ideal_num_threads(threads, x13, thread_threshold);\n\n if (!is_resume)\n {\n start = max(c, pi_sqrty) + 1;\n pi_x13 = pi[x13];\n }\n\n while (start <= pi_x13)\n {\n int64_t stop = min(start + max_dist * threads, pi_x13);\n\n #pragma omp parallel for schedule(dynamic) num_threads(threads) reduction(+: s2_easy)\n for (int64_t b = start; b <= stop; b++)\n {\n int64_t prime = primes[b];\n T x2 = x \/ prime;\n int64_t min_trivial = min(x2 \/ prime, y);\n int64_t min_clustered = (int64_t) isqrt(x2);\n int64_t min_sparse = z \/ prime;\n\n min_clustered = in_between(prime, min_clustered, y);\n min_sparse = in_between(prime, min_sparse, y);\n\n int64_t l = pi[min_trivial];\n int64_t pi_min_clustered = pi[min_clustered];\n int64_t pi_min_sparse = pi[min_sparse];\n\n \/\/ Find all clustered easy leaves:\n \/\/ n = primes[b] * primes[l]\n \/\/ x \/ n <= y && phi(x \/ n, b - 1) == phi(x \/ m, b - 1)\n \/\/ where phi(x \/ n, b - 1) = pi(x \/ n) - b + 2\n while (l > pi_min_clustered)\n {\n int64_t xn = (int64_t) fast_div(x2, primes[l]);\n int64_t phi_xn = pi[xn] - b + 2;\n int64_t xm = (int64_t) fast_div(x2, primes[b + phi_xn - 1]);\n int64_t l2 = pi[xm];\n s2_easy += phi_xn * (l - l2);\n l = l2;\n }\n\n \/\/ Find all sparse easy leaves:\n \/\/ n = primes[b] * primes[l]\n \/\/ x \/ n <= y && phi(x \/ n, b - 1) = pi(x \/ n) - b + 2\n for (; l > pi_min_sparse; l--)\n {\n int64_t xn = (int64_t) fast_div(x2, primes[l]);\n s2_easy += pi[xn] - b + 2;\n }\n\n if (is_print())\n status.print(b, pi_x13);\n }\n\n start = stop + 1;\n\n if (get_wtime() - backup_time < 60)\n max_dist *= 2;\n else\n {\n max_dist = ceil_div(max_dist, 2);\n double percent = status.getPercent(start, pi_x13, start, pi_x13);\n backup(x, y, z, c, start, pi_x13, s2_easy, percent, time);\n backup_time = get_wtime();\n }\n }\n\n backup(x, y, z, c, pi_x13, pi_x13, s2_easy, 100, time);\n\n return s2_easy;\n}\n\n} \/\/ namespace\n\nnamespace primecount {\n\nint64_t S2_easy(int64_t x,\n int64_t y,\n int64_t z,\n int64_t c,\n int threads)\n{\n#ifdef HAVE_MPI\n if (mpi_num_procs() > 1)\n return S2_easy_mpi(x, y, z, c, threads);\n#endif\n\n print(\"\");\n print(\"=== S2_easy(x, y) ===\");\n print(\"Computation of the easy special leaves\");\n print(x, y, c, threads);\n\n double time = get_wtime();\n auto primes = generate_primes(y);\n int64_t s2_easy = S2_easy_OpenMP((intfast64_t) x, y, z, c, primes, threads, time);\n\n print(\"S2_easy\", s2_easy, time);\n return s2_easy;\n}\n\n#ifdef HAVE_INT128_T\n\nint128_t S2_easy(int128_t x,\n int64_t y,\n int64_t z,\n int64_t c,\n int threads)\n{\n#ifdef HAVE_MPI\n if (mpi_num_procs() > 1)\n return S2_easy_mpi(x, y, z, c, threads);\n#endif\n\n print(\"\");\n print(\"=== S2_easy(x, y) ===\");\n print(\"Computation of the easy special leaves\");\n print(x, y, c, threads);\n\n int128_t s2_easy;\n double time = get_wtime();\n\n \/\/ uses less memory\n if (y <= numeric_limits::max())\n {\n auto primes = generate_primes(y);\n s2_easy = S2_easy_OpenMP((intfast128_t) x, y, z, c, primes, threads, time);\n }\n else\n {\n auto primes = generate_primes(y);\n s2_easy = S2_easy_OpenMP((intfast128_t) x, y, z, c, primes, threads, time);\n }\n\n print(\"S2_easy\", s2_easy, time);\n return s2_easy;\n}\n\n#endif\n\n} \/\/ namespace\nBackup every 5 minutes\/\/\/\n\/\/\/ @file S2_easy.cpp\n\/\/\/ @brief Calculate the contribution of the clustered easy leaves\n\/\/\/ and the sparse easy leaves in parallel using OpenMP\n\/\/\/ (Deleglise-Rivat algorithm).\n\/\/\/\n\/\/\/ Copyright (C) 2016 Kim Walisch, \n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#ifdef _OPENMP\n #include \n#endif\n\nusing namespace std;\nusing namespace primecount;\nusing namespace nlohmann;\n\nnamespace {\n\ntemplate \nvoid backup(T x,\n int64_t y,\n int64_t z,\n int64_t c,\n int64_t start,\n int64_t pi_x13,\n T s2_easy,\n double percent,\n double time)\n{\n ifstream ifs(\"primecount.backup\");\n json j;\n\n if (ifs.is_open())\n {\n ifs >> j;\n ifs.close();\n }\n\n if (j.find(\"S2_easy\") != j.end())\n j.erase(j.find(\"S2_easy\"));\n\n j[\"S2_easy\"][\"x\"] = to_string(x);\n j[\"S2_easy\"][\"y\"] = y;\n j[\"S2_easy\"][\"z\"] = z;\n j[\"S2_easy\"][\"c\"] = c;\n j[\"S2_easy\"][\"start\"] = start;\n j[\"S2_easy\"][\"pi_x13\"] = pi_x13;\n j[\"S2_easy\"][\"s2_easy\"] = to_string(s2_easy);\n j[\"S2_easy\"][\"percent\"] = percent;\n j[\"S2_easy\"][\"seconds\"] = get_wtime() - time;\n\n ofstream ofs(\"primecount.backup\");\n ofs << setw(4) << j << endl;\n}\n\ntemplate \nbool resume(T x,\n int64_t y,\n int64_t z,\n int64_t c,\n int64_t& start,\n int64_t& pi_x13,\n T& s2_easy,\n double& time)\n{\n ifstream ifs(\"primecount.backup\");\n json j;\n\n if (ifs.is_open())\n {\n ifs >> j;\n ifs.close();\n }\n\n if (j.find(\"S2_easy\") != j.end() &&\n x == calculator::eval(j[\"S2_easy\"][\"x\"]) &&\n y == j[\"S2_easy\"][\"y\"] &&\n z == j[\"S2_easy\"][\"z\"] &&\n c == j[\"S2_easy\"][\"c\"])\n {\n double percent = j[\"S2_easy\"][\"percent\"];\n double seconds = j[\"S2_easy\"][\"seconds\"];\n\n start = j[\"S2_easy\"][\"start\"];\n pi_x13 = j[\"S2_easy\"][\"pi_x13\"];\n s2_easy = calculator::eval(j[\"S2_easy\"][\"s2_easy\"]);\n time = get_wtime() - seconds;\n\n if (is_print())\n {\n if (!print_variables())\n cout << endl;\n\n cout << \"=== Resuming from primecount.backup ===\" << endl;\n cout << \"start = \" << start << endl;\n cout << \"pi_x13 = \" << pi_x13 << endl;\n cout << \"s2_easy = \" << s2_easy << endl;\n cout << \"Seconds: \" << seconds << endl << endl;\n cout << \"Status: \" << fixed << setprecision(get_status_precision(x)) << percent << '%' << flush;\n }\n\n return true;\n }\n\n return false;\n}\n\n\/\/\/ Calculate the contribution of the clustered easy leaves\n\/\/\/ and the sparse easy leaves.\n\/\/\/ @param T either int64_t or uint128_t.\n\/\/\/\ntemplate \nT S2_easy_OpenMP(T x,\n int64_t y,\n int64_t z,\n int64_t c,\n Primes& primes,\n int threads,\n double& time)\n{\n T s2_easy = 0;\n int64_t start;\n int64_t pi_x13;\n double backup_time = get_wtime();\n bool is_resume = resume(x, y, z, c, start, pi_x13, s2_easy, time);\n\n if (is_resume && start >= pi_x13)\n return s2_easy;\n\n PiTable pi(y);\n S2Status status(x);\n\n int64_t pi_sqrty = pi[isqrt(y)];\n int64_t x13 = iroot<3>(x);\n int64_t max_dist = 1;\n int64_t thread_threshold = 1000;\n threads = ideal_num_threads(threads, x13, thread_threshold);\n\n if (!is_resume)\n {\n start = max(c, pi_sqrty) + 1;\n pi_x13 = pi[x13];\n }\n\n while (start <= pi_x13)\n {\n int64_t stop = min(start + max_dist * threads, pi_x13);\n\n #pragma omp parallel for schedule(dynamic) num_threads(threads) reduction(+: s2_easy)\n for (int64_t b = start; b <= stop; b++)\n {\n int64_t prime = primes[b];\n T x2 = x \/ prime;\n int64_t min_trivial = min(x2 \/ prime, y);\n int64_t min_clustered = (int64_t) isqrt(x2);\n int64_t min_sparse = z \/ prime;\n\n min_clustered = in_between(prime, min_clustered, y);\n min_sparse = in_between(prime, min_sparse, y);\n\n int64_t l = pi[min_trivial];\n int64_t pi_min_clustered = pi[min_clustered];\n int64_t pi_min_sparse = pi[min_sparse];\n\n \/\/ Find all clustered easy leaves:\n \/\/ n = primes[b] * primes[l]\n \/\/ x \/ n <= y && phi(x \/ n, b - 1) == phi(x \/ m, b - 1)\n \/\/ where phi(x \/ n, b - 1) = pi(x \/ n) - b + 2\n while (l > pi_min_clustered)\n {\n int64_t xn = (int64_t) fast_div(x2, primes[l]);\n int64_t phi_xn = pi[xn] - b + 2;\n int64_t xm = (int64_t) fast_div(x2, primes[b + phi_xn - 1]);\n int64_t l2 = pi[xm];\n s2_easy += phi_xn * (l - l2);\n l = l2;\n }\n\n \/\/ Find all sparse easy leaves:\n \/\/ n = primes[b] * primes[l]\n \/\/ x \/ n <= y && phi(x \/ n, b - 1) = pi(x \/ n) - b + 2\n for (; l > pi_min_sparse; l--)\n {\n int64_t xn = (int64_t) fast_div(x2, primes[l]);\n s2_easy += pi[xn] - b + 2;\n }\n\n if (is_print())\n status.print(b, pi_x13);\n }\n\n start = stop + 1;\n\n if (get_wtime() - backup_time < 300)\n max_dist *= 2;\n else\n {\n max_dist = ceil_div(max_dist, 2);\n double percent = status.getPercent(start, pi_x13, start, pi_x13);\n backup(x, y, z, c, start, pi_x13, s2_easy, percent, time);\n backup_time = get_wtime();\n }\n }\n\n backup(x, y, z, c, pi_x13, pi_x13, s2_easy, 100, time);\n\n return s2_easy;\n}\n\n} \/\/ namespace\n\nnamespace primecount {\n\nint64_t S2_easy(int64_t x,\n int64_t y,\n int64_t z,\n int64_t c,\n int threads)\n{\n#ifdef HAVE_MPI\n if (mpi_num_procs() > 1)\n return S2_easy_mpi(x, y, z, c, threads);\n#endif\n\n print(\"\");\n print(\"=== S2_easy(x, y) ===\");\n print(\"Computation of the easy special leaves\");\n print(x, y, c, threads);\n\n double time = get_wtime();\n auto primes = generate_primes(y);\n int64_t s2_easy = S2_easy_OpenMP((intfast64_t) x, y, z, c, primes, threads, time);\n\n print(\"S2_easy\", s2_easy, time);\n return s2_easy;\n}\n\n#ifdef HAVE_INT128_T\n\nint128_t S2_easy(int128_t x,\n int64_t y,\n int64_t z,\n int64_t c,\n int threads)\n{\n#ifdef HAVE_MPI\n if (mpi_num_procs() > 1)\n return S2_easy_mpi(x, y, z, c, threads);\n#endif\n\n print(\"\");\n print(\"=== S2_easy(x, y) ===\");\n print(\"Computation of the easy special leaves\");\n print(x, y, c, threads);\n\n int128_t s2_easy;\n double time = get_wtime();\n\n \/\/ uses less memory\n if (y <= numeric_limits::max())\n {\n auto primes = generate_primes(y);\n s2_easy = S2_easy_OpenMP((intfast128_t) x, y, z, c, primes, threads, time);\n }\n else\n {\n auto primes = generate_primes(y);\n s2_easy = S2_easy_OpenMP((intfast128_t) x, y, z, c, primes, threads, time);\n }\n\n print(\"S2_easy\", s2_easy, time);\n return s2_easy;\n}\n\n#endif\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2011-2013 Yule Fox. All rights reserved.\n * http:\/\/www.yulefox.com\/\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace elf {\n#define WHEEL_SET_BIT0 8\n#define WHEEL_SET_BITS (WHEEL_SET_BIT0 * 4)\n#define WHEEL_SET_BIT(l) (WHEEL_SET_BIT0 * (l))\n#define WHEEL_SET_SIZE0 (1 << WHEEL_SET_BIT0)\n#define WHEEL_SET_SIZE(l) WHEEL_SET_SIZE0\n#define MAX_WHEEL_SET_SIZE (WHEEL_SET_SIZE0 * 4)\n#define MAX_CURSOR (1LL << WHEEL_SET_BITS)\n#define MAX_LIFE (MAX_CURSOR * s_mgr.interval)\n#define FRAME_DIFFER(l, r) (int)(l - r)\n\nunion cursor_t {\n struct wheel_t {\n unsigned char w0;\n unsigned char w1;\n unsigned char w2;\n unsigned char w3;\n };\n wheel_t w;\n int a;\n};\n\nstruct timer_t {\n oid_t id; \/\/ identification\n time64_t life; \/\/ life from now\n cursor_t cursor; \/\/ expired frame\n bool script;\n union cb_t {\n char script[1024]; \/\/ script function name\n callback func; \/\/ callback function\n };\n cb_t cb; \/\/ callback function\n void *args; \/\/ callback arguments\n timer_t *next; \/\/ the next node of the tail node is NULL\n timer_t *prev; \/\/ the previous node of the head node is the tail\n};\n\nstruct mgr_t {\n time64_t start_time; \/\/ start time\n time64_t end_time; \/\/ end time\n time64_t cur_time; \/\/ current frame time\n time64_t last_time; \/\/ last pause time\n time64_t interval; \/\/ frame interval time\n cursor_t cursor; \/\/ current cursor (number of escaped frames)\n int round; \/\/ current round\n int last_cursor; \/\/ last pause cursor\n int timer_total; \/\/ total number of timers\n int timer_remain; \/\/ remain timers\n int timer_passed; \/\/ total number of passed timers\n int timer_cancelled; \/\/ total number of cancelled timers\n bool pause; \/\/ suspend all timers\n timer_t *timers[MAX_WHEEL_SET_SIZE];\n};\n\ntypedef std::list handler_list;\n\nstatic handler_list s_handlers;\n\nstatic const time64_t TIMER_FRAME_INTERVAL_DEFAULT = 50; \/\/ (ms)\nstatic const time64_t TIMER_FRAME_INTERVAL_MIN = 1; \/\/ (frame)\nstatic const time64_t TIMER_FRAME_INTERVAL_MAX = 1000; \/\/ (frame)\nstatic mgr_t s_mgr;\n\n\/\/\/ calculate the number of life frames\n#define FRAME_CALC(t) ((time64_t)(t) \/ s_mgr.interval)\n\n\/\/ @{\n\/\/\/ get current bucket cursor at wheel 0\n#define CURRENT_WHEEL_CURSOR s_mgr.cursor.w.w0\n\n\/\/\/ compare given cursor with current bucket cursor at wheel @param l\n#define WHEEL_CMP(cur, l) \\\n ((int)cur.w.w##l - (int)s_mgr.cursor.w.w##l)\n\n\/\/\/ map cursor at wheel @param l\n#define BUCKET_MAP(cur, l) \\\n (cur.w.w##l + WHEEL_SET_SIZE0 * l)\n\n\/\/\/ calculate the number of frames elapsed from last cursor\n#define FRAME_BINGO (s_mgr.last_cursor + \\\n FRAME_CALC(s_mgr.cur_time - s_mgr.last_time) - s_mgr.cursor.a)\n\/\/ @}\n\n\nstatic void reset(void);\nstatic void push(timer_t *t, int bucket);\nstatic timer_t *get(const oid_t &tid, int *bucket);\nstatic void destroy(timer_t *t);\nstatic int schedule(timer_t *t);\nstatic void expire(timer_t *t);\nstatic void bingo(void);\nstatic void hash(int bucket);\nstatic void timer_min(void *args);\n\nint timer_init(void)\n{\n MODULE_IMPORT_SWITCH;\n s_mgr.interval = TIMER_FRAME_INTERVAL_DEFAULT;\n s_mgr.start_time = s_mgr.last_time = time_ms();\n s_mgr.pause = true;\n s_mgr.cursor.a = 0;\n s_mgr.round = 0;\n memset(s_mgr.timers, 0, sizeof(s_mgr.timers[0]) * MAX_WHEEL_SET_SIZE);\n timer_min(NULL);\n return 0;\n}\n\nint timer_fini(void)\n{\n MODULE_IMPORT_SWITCH;\n s_mgr.end_time = time_ms();\n for (int i = 0; i < MAX_WHEEL_SET_SIZE; ++i) {\n timer_t *head = s_mgr.timers[i];\n timer_t *t = head;\n\n while (t) {\n timer_t *n = t->next;\n\n destroy(t);\n if (n == head) break;\n t = n;\n }\n }\n return 0;\n}\n\nvoid timer_run(void)\n{\n if (s_mgr.pause || s_mgr.timer_remain <= 0) {\n return;\n }\n\n \/\/ frame may greater than 1 while CPU busying\n s_mgr.cur_time = time_ms();\n int frame = FRAME_BINGO;\n\n \/\/ time anomaly\n if (frame < 0) {\n LOG_WARN(\"timer\", \"(%u)%08X: %llu - %llu(%d).\",\n s_mgr.round, s_mgr.cursor.a,\n s_mgr.cur_time, s_mgr.last_time,\n frame);\n assert(frame >= 0);\n return;\n }\n \/\/ while processors is busy\n if (frame > 1) {\n LOG_WARN(\"timer\", \"(%u)%08X: %llu - %llu(%d).\",\n s_mgr.round, s_mgr.cursor.a,\n s_mgr.cur_time, s_mgr.last_time,\n frame);\n }\n for (int i = 1; i <= frame; ++i) { \/\/ BINGO!\n unsigned char bucket = CURRENT_WHEEL_CURSOR;\n timer_t *head = s_mgr.timers[bucket];\n timer_t *t = head;\n\n while (t) {\n timer_t *n = t->next;\n\n expire(t);\n ++s_mgr.timer_passed;\n --s_mgr.timer_remain;\n if (n == head) {\n s_mgr.timers[bucket] = NULL;\n break;\n }\n t = n;\n }\n bingo();\n }\n}\n\nvoid timer_stat(void)\n{\n LOG_INFO(\"timer\",\n \"ST: %lld RND: %u FRM: %u TMT: %u TMP: %u TMC: %u.\",\n s_mgr.start_time, s_mgr.round, s_mgr.cursor.a,\n s_mgr.timer_total, s_mgr.timer_passed, s_mgr.timer_cancelled);\n}\n\nint timer_size(void)\n{\n return s_mgr.timer_remain;\n}\n\nconst oid_t &timer_add(time64_t life, const char *func)\n{\n if (life < 0 || life >= MAX_LIFE) {\n LOG_WARN(\"timer\",\n \"Timer added FAILED: invalid timer life(%lld) [0, %lld).\",\n life, MAX_LIFE);\n return OID_NIL;\n }\n\n timer_t *t = E_NEW timer_t;\n\n memset(t, 0, sizeof(*t));\n t->id = oid_gen();\n t->life = std::max(life, s_mgr.interval);\n t->cursor.a = (FRAME_CALC(t->life) + s_mgr.cursor.a) % MAX_CURSOR;\n t->script = true;\n strcpy(t->cb.script, func);\n t->args = NULL;\n schedule(t);\n ++s_mgr.timer_total;\n ++s_mgr.timer_remain;\n return t->id;\n}\n\nconst oid_t &timer_add(time64_t life, callback func, void *args)\n{\n if (life < 0 || life >= MAX_LIFE) {\n LOG_WARN(\"timer\",\n \"Timer added FAILED: invalid timer life(%lld) [0, %lld).\",\n life, MAX_LIFE);\n return OID_NIL;\n }\n\n timer_t *t = E_NEW timer_t;\n\n memset(t, 0, sizeof(*t));\n t->id = oid_gen();\n t->life = std::max(life, s_mgr.interval);\n t->cursor.a = (FRAME_CALC(t->life) + s_mgr.cursor.a) % MAX_CURSOR;\n t->script = false;\n t->cb.func = func;\n t->args = args;\n schedule(t);\n ++s_mgr.timer_total;\n ++s_mgr.timer_remain;\n return t->id;\n}\n\nvoid timer_cycle(callback func)\n{\n s_handlers.push_back(func);\n}\n\nvoid timer_remove(const oid_t &tid)\n{\n int bucket;\n timer_t *t = get(tid, &bucket);\n\n if (t) {\n timer_t *n = t->next;\n\n if (n != t) {\n t->prev->next = n;\n n->prev = t->prev;\n } else {\n n = NULL;\n }\n if (t == s_mgr.timers[bucket]) {\n s_mgr.timers[bucket] = n;\n }\n S_FREE(t->args);\n destroy(t);\n ++s_mgr.timer_cancelled;\n --s_mgr.timer_remain;\n }\n}\n\nvoid timer_pause(void)\n{\n if (!s_mgr.pause) {\n s_mgr.pause = true;\n }\n}\n\nvoid timer_resume(void)\n{\n if (s_mgr.pause) {\n s_mgr.pause = false;\n reset();\n }\n}\n\nvoid timer_pause(const oid_t &tid)\n{\n}\n\nvoid timer_resume(const oid_t &tid)\n{\n}\n\nvoid timer_interval(time64_t t)\n{\n ELF_ASSERT(t >= TIMER_FRAME_INTERVAL_MIN && t <= TIMER_FRAME_INTERVAL_MAX);\n s_mgr.interval = t;\n reset();\n}\n\nvoid timer_bucket(unsigned char no, int l)\n{\n switch (l) {\n case 0:\n s_mgr.cursor.w.w0 = no;\n break;\n case 1:\n s_mgr.cursor.w.w1 = no;\n break;\n case 2:\n s_mgr.cursor.w.w2 = no;\n break;\n case 3:\n s_mgr.cursor.w.w3 = no;\n break;\n }\n reset();\n}\n\nstatic void reset(void)\n{\n s_mgr.last_time = time_ms();\n s_mgr.last_cursor = s_mgr.cursor.a;\n}\n\nstatic void push(timer_t *t, int bucket)\n{\n timer_t *head = s_mgr.timers[bucket];\n\n if (head) {\n head->prev->next = t;\n t->prev = head->prev;\n } else {\n head = s_mgr.timers[bucket] = t;\n }\n head->prev = t;\n t->next = head;\n}\n\nstatic timer_t *get(const oid_t &tid, int *bucket)\n{\n timer_t *head = NULL;\n timer_t *t = NULL;\n\n for (int i = 0; i < MAX_WHEEL_SET_SIZE; ++i) {\n head = t = s_mgr.timers[i];\n while (t) {\n if (tid == t->id) {\n *bucket = i;\n return t;\n }\n if ((t = t->next) == head) break;\n }\n }\n *bucket = 0;\n return NULL;\n}\n\nstatic void destroy(timer_t *t)\n{\n if (t) {\n S_DELETE(t);\n }\n}\n\nstatic int schedule(timer_t *t)\n{\n int frame = FRAME_DIFFER(t->cursor.a, s_mgr.cursor.a);\n int bucket = 0;\n\n if (frame < WHEEL_SET_SIZE0) { \/\/ hash into wheel 0\n bucket = BUCKET_MAP(t->cursor, 0);\n } else if (WHEEL_CMP(t->cursor, 3)) { \/\/ hash into wheel 3\n bucket = BUCKET_MAP(t->cursor, 3);\n } else if (WHEEL_CMP(t->cursor, 2)) { \/\/ hash into wheel 2\n bucket = BUCKET_MAP(t->cursor, 2);\n } else if (WHEEL_CMP(t->cursor, 1)) { \/\/ hash into wheel 1\n bucket = BUCKET_MAP(t->cursor, 1);\n }\n push(t, bucket);\n return bucket;\n}\n\nstatic void expire(timer_t *t)\n{\n ELF_ASSERT(t);\n if (t->script) {\n \/\/ script_func_exec(t->cb.script, 0);\n } else {\n t->cb.func(t->args);\n }\n destroy(t);\n}\n\nstatic void bingo(void)\n{\n int bucket = 0;\n cursor_t next_cursor = s_mgr.cursor;\n\n ++next_cursor.a;\n if (WHEEL_CMP(next_cursor, 3)) {\n bucket = BUCKET_MAP(next_cursor, 3);\n } else if (WHEEL_CMP(next_cursor, 2)) {\n bucket = BUCKET_MAP(next_cursor, 2);\n } else if (WHEEL_CMP(next_cursor, 1)) {\n bucket = BUCKET_MAP(next_cursor, 1);\n }\n if (++s_mgr.cursor.a == 0) {\n ++s_mgr.round;\n }\n if (bucket > 0) { \/\/ hash to more precisely wheel\n hash(bucket);\n }\n}\n\nstatic void hash(int bucket)\n{\n timer_t *head = s_mgr.timers[bucket];\n timer_t *t = head;\n\n while (t) {\n timer_t *n = t->next;\n\n schedule(t);\n if (n == head) {\n s_mgr.timers[bucket] = NULL;\n break;\n }\n t = n;\n }\n}\nstatic void timer_min(void *args)\n{\n LOG_TRACE(\"timer\", \"%s\", \"BINGO: MIN.\");\n\n time_t cur = elf::time_s();\n elf::time64_t tm_timer;\n struct tm tm_cur;\n\n localtime_r(&cur, &tm_cur);\n tm_timer = (60 - tm_cur.tm_sec) * 1000llu;\n timer_add(tm_timer, timer_min, NULL);\n\n handler_list::const_iterator itr = s_handlers.begin();\n\n for (; itr != s_handlers.end(); ++itr) {\n (*itr)(&cur);\n }\n}\n} \/\/ namespace elf\n\n[FIX] mimute timer.\/*\n * Copyright (C) 2011-2013 Yule Fox. All rights reserved.\n * http:\/\/www.yulefox.com\/\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace elf {\n#define WHEEL_SET_BIT0 8\n#define WHEEL_SET_BITS (WHEEL_SET_BIT0 * 4)\n#define WHEEL_SET_BIT(l) (WHEEL_SET_BIT0 * (l))\n#define WHEEL_SET_SIZE0 (1 << WHEEL_SET_BIT0)\n#define WHEEL_SET_SIZE(l) WHEEL_SET_SIZE0\n#define MAX_WHEEL_SET_SIZE (WHEEL_SET_SIZE0 * 4)\n#define MAX_CURSOR (1LL << WHEEL_SET_BITS)\n#define MAX_LIFE (MAX_CURSOR * s_mgr.interval)\n#define FRAME_DIFFER(l, r) (int)(l - r)\n\nunion cursor_t {\n struct wheel_t {\n unsigned char w0;\n unsigned char w1;\n unsigned char w2;\n unsigned char w3;\n };\n wheel_t w;\n int a;\n};\n\nstruct timer_t {\n oid_t id; \/\/ identification\n time64_t life; \/\/ life from now\n cursor_t cursor; \/\/ expired frame\n bool script;\n union cb_t {\n char script[1024]; \/\/ script function name\n callback func; \/\/ callback function\n };\n cb_t cb; \/\/ callback function\n void *args; \/\/ callback arguments\n timer_t *next; \/\/ the next node of the tail node is NULL\n timer_t *prev; \/\/ the previous node of the head node is the tail\n};\n\nstruct mgr_t {\n time64_t start_time; \/\/ start time\n time64_t end_time; \/\/ end time\n time64_t cur_time; \/\/ current frame time\n time64_t last_time; \/\/ last pause time\n time64_t interval; \/\/ frame interval time\n cursor_t cursor; \/\/ current cursor (number of escaped frames)\n int round; \/\/ current round\n int last_cursor; \/\/ last pause cursor\n int timer_total; \/\/ total number of timers\n int timer_remain; \/\/ remain timers\n int timer_passed; \/\/ total number of passed timers\n int timer_cancelled; \/\/ total number of cancelled timers\n bool pause; \/\/ suspend all timers\n timer_t *timers[MAX_WHEEL_SET_SIZE];\n};\n\ntypedef std::list handler_list;\n\nstatic handler_list s_handlers;\n\nstatic const time64_t TIMER_FRAME_INTERVAL_DEFAULT = 50; \/\/ (ms)\nstatic const time64_t TIMER_FRAME_INTERVAL_MIN = 1; \/\/ (frame)\nstatic const time64_t TIMER_FRAME_INTERVAL_MAX = 1000; \/\/ (frame)\nstatic mgr_t s_mgr;\n\n\/\/\/ calculate the number of life frames\n#define FRAME_CALC(t) ((time64_t)(t) \/ s_mgr.interval)\n\n\/\/ @{\n\/\/\/ get current bucket cursor at wheel 0\n#define CURRENT_WHEEL_CURSOR s_mgr.cursor.w.w0\n\n\/\/\/ compare given cursor with current bucket cursor at wheel @param l\n#define WHEEL_CMP(cur, l) \\\n ((int)cur.w.w##l - (int)s_mgr.cursor.w.w##l)\n\n\/\/\/ map cursor at wheel @param l\n#define BUCKET_MAP(cur, l) \\\n (cur.w.w##l + WHEEL_SET_SIZE0 * l)\n\n\/\/\/ calculate the number of frames elapsed from last cursor\n#define FRAME_BINGO (s_mgr.last_cursor + \\\n FRAME_CALC(s_mgr.cur_time - s_mgr.last_time) - s_mgr.cursor.a)\n\/\/ @}\n\n\nstatic void reset(void);\nstatic void push(timer_t *t, int bucket);\nstatic timer_t *get(const oid_t &tid, int *bucket);\nstatic void destroy(timer_t *t);\nstatic int schedule(timer_t *t);\nstatic void expire(timer_t *t);\nstatic void bingo(void);\nstatic void hash(int bucket);\nstatic void timer_min(void *args);\n\nint timer_init(void)\n{\n MODULE_IMPORT_SWITCH;\n s_mgr.interval = TIMER_FRAME_INTERVAL_DEFAULT;\n s_mgr.start_time = s_mgr.last_time = time_ms();\n s_mgr.pause = true;\n s_mgr.cursor.a = 0;\n s_mgr.round = 0;\n memset(s_mgr.timers, 0, sizeof(s_mgr.timers[0]) * MAX_WHEEL_SET_SIZE);\n\n time_t ms = elf::time_ms() % 1000;\n time_t cur = elf::time_s();\n elf::time64_t tm_timer;\n struct tm tm_cur;\n\n localtime_r(&cur, &tm_cur);\n tm_timer = (60 - tm_cur.tm_sec) * 1000llu - ms;\n\n timer_add(tm_timer, timer_min, NULL);\n return 0;\n}\n\nint timer_fini(void)\n{\n MODULE_IMPORT_SWITCH;\n s_mgr.end_time = time_ms();\n for (int i = 0; i < MAX_WHEEL_SET_SIZE; ++i) {\n timer_t *head = s_mgr.timers[i];\n timer_t *t = head;\n\n while (t) {\n timer_t *n = t->next;\n\n destroy(t);\n if (n == head) break;\n t = n;\n }\n }\n return 0;\n}\n\nvoid timer_run(void)\n{\n if (s_mgr.pause || s_mgr.timer_remain <= 0) {\n return;\n }\n\n \/\/ frame may greater than 1 while CPU busying\n s_mgr.cur_time = time_ms();\n int frame = FRAME_BINGO;\n\n \/\/ time anomaly\n if (frame < 0) {\n LOG_WARN(\"timer\", \"(%u)%08X: %llu - %llu(%d).\",\n s_mgr.round, s_mgr.cursor.a,\n s_mgr.cur_time, s_mgr.last_time,\n frame);\n assert(frame >= 0);\n return;\n }\n \/\/ while processors is busy\n if (frame > 1) {\n LOG_WARN(\"timer\", \"(%u)%08X: %llu - %llu(%d).\",\n s_mgr.round, s_mgr.cursor.a,\n s_mgr.cur_time, s_mgr.last_time,\n frame);\n }\n for (int i = 1; i <= frame; ++i) { \/\/ BINGO!\n unsigned char bucket = CURRENT_WHEEL_CURSOR;\n timer_t *head = s_mgr.timers[bucket];\n timer_t *t = head;\n\n while (t) {\n timer_t *n = t->next;\n\n expire(t);\n ++s_mgr.timer_passed;\n --s_mgr.timer_remain;\n if (n == head) {\n s_mgr.timers[bucket] = NULL;\n break;\n }\n t = n;\n }\n bingo();\n }\n}\n\nvoid timer_stat(void)\n{\n LOG_INFO(\"timer\",\n \"ST: %lld RND: %u FRM: %u TMT: %u TMP: %u TMC: %u.\",\n s_mgr.start_time, s_mgr.round, s_mgr.cursor.a,\n s_mgr.timer_total, s_mgr.timer_passed, s_mgr.timer_cancelled);\n}\n\nint timer_size(void)\n{\n return s_mgr.timer_remain;\n}\n\nconst oid_t &timer_add(time64_t life, const char *func)\n{\n if (life < 0 || life >= MAX_LIFE) {\n LOG_WARN(\"timer\",\n \"Timer added FAILED: invalid timer life(%lld) [0, %lld).\",\n life, MAX_LIFE);\n return OID_NIL;\n }\n\n timer_t *t = E_NEW timer_t;\n\n memset(t, 0, sizeof(*t));\n t->id = oid_gen();\n t->life = std::max(life, s_mgr.interval);\n t->cursor.a = (FRAME_CALC(t->life) + s_mgr.cursor.a) % MAX_CURSOR;\n t->script = true;\n strcpy(t->cb.script, func);\n t->args = NULL;\n schedule(t);\n ++s_mgr.timer_total;\n ++s_mgr.timer_remain;\n return t->id;\n}\n\nconst oid_t &timer_add(time64_t life, callback func, void *args)\n{\n if (life < 0 || life >= MAX_LIFE) {\n LOG_WARN(\"timer\",\n \"Timer added FAILED: invalid timer life(%lld) [0, %lld).\",\n life, MAX_LIFE);\n return OID_NIL;\n }\n\n timer_t *t = E_NEW timer_t;\n\n memset(t, 0, sizeof(*t));\n t->id = oid_gen();\n t->life = std::max(life, s_mgr.interval);\n t->cursor.a = (FRAME_CALC(t->life) + s_mgr.cursor.a) % MAX_CURSOR;\n t->script = false;\n t->cb.func = func;\n t->args = args;\n schedule(t);\n ++s_mgr.timer_total;\n ++s_mgr.timer_remain;\n return t->id;\n}\n\nvoid timer_cycle(callback func)\n{\n s_handlers.push_back(func);\n}\n\nvoid timer_remove(const oid_t &tid)\n{\n int bucket;\n timer_t *t = get(tid, &bucket);\n\n if (t) {\n timer_t *n = t->next;\n\n if (n != t) {\n t->prev->next = n;\n n->prev = t->prev;\n } else {\n n = NULL;\n }\n if (t == s_mgr.timers[bucket]) {\n s_mgr.timers[bucket] = n;\n }\n S_FREE(t->args);\n destroy(t);\n ++s_mgr.timer_cancelled;\n --s_mgr.timer_remain;\n }\n}\n\nvoid timer_pause(void)\n{\n if (!s_mgr.pause) {\n s_mgr.pause = true;\n }\n}\n\nvoid timer_resume(void)\n{\n if (s_mgr.pause) {\n s_mgr.pause = false;\n reset();\n }\n}\n\nvoid timer_pause(const oid_t &tid)\n{\n}\n\nvoid timer_resume(const oid_t &tid)\n{\n}\n\nvoid timer_interval(time64_t t)\n{\n ELF_ASSERT(t >= TIMER_FRAME_INTERVAL_MIN && t <= TIMER_FRAME_INTERVAL_MAX);\n s_mgr.interval = t;\n reset();\n}\n\nvoid timer_bucket(unsigned char no, int l)\n{\n switch (l) {\n case 0:\n s_mgr.cursor.w.w0 = no;\n break;\n case 1:\n s_mgr.cursor.w.w1 = no;\n break;\n case 2:\n s_mgr.cursor.w.w2 = no;\n break;\n case 3:\n s_mgr.cursor.w.w3 = no;\n break;\n }\n reset();\n}\n\nstatic void reset(void)\n{\n s_mgr.last_time = time_ms();\n s_mgr.last_cursor = s_mgr.cursor.a;\n}\n\nstatic void push(timer_t *t, int bucket)\n{\n timer_t *head = s_mgr.timers[bucket];\n\n if (head) {\n head->prev->next = t;\n t->prev = head->prev;\n } else {\n head = s_mgr.timers[bucket] = t;\n }\n head->prev = t;\n t->next = head;\n}\n\nstatic timer_t *get(const oid_t &tid, int *bucket)\n{\n timer_t *head = NULL;\n timer_t *t = NULL;\n\n for (int i = 0; i < MAX_WHEEL_SET_SIZE; ++i) {\n head = t = s_mgr.timers[i];\n while (t) {\n if (tid == t->id) {\n *bucket = i;\n return t;\n }\n if ((t = t->next) == head) break;\n }\n }\n *bucket = 0;\n return NULL;\n}\n\nstatic void destroy(timer_t *t)\n{\n if (t) {\n S_DELETE(t);\n }\n}\n\nstatic int schedule(timer_t *t)\n{\n int frame = FRAME_DIFFER(t->cursor.a, s_mgr.cursor.a);\n int bucket = 0;\n\n if (frame < WHEEL_SET_SIZE0) { \/\/ hash into wheel 0\n bucket = BUCKET_MAP(t->cursor, 0);\n } else if (WHEEL_CMP(t->cursor, 3)) { \/\/ hash into wheel 3\n bucket = BUCKET_MAP(t->cursor, 3);\n } else if (WHEEL_CMP(t->cursor, 2)) { \/\/ hash into wheel 2\n bucket = BUCKET_MAP(t->cursor, 2);\n } else if (WHEEL_CMP(t->cursor, 1)) { \/\/ hash into wheel 1\n bucket = BUCKET_MAP(t->cursor, 1);\n }\n push(t, bucket);\n return bucket;\n}\n\nstatic void expire(timer_t *t)\n{\n ELF_ASSERT(t);\n if (t->script) {\n \/\/ script_func_exec(t->cb.script, 0);\n } else {\n t->cb.func(t->args);\n }\n destroy(t);\n}\n\nstatic void bingo(void)\n{\n int bucket = 0;\n cursor_t next_cursor = s_mgr.cursor;\n\n ++next_cursor.a;\n if (WHEEL_CMP(next_cursor, 3)) {\n bucket = BUCKET_MAP(next_cursor, 3);\n } else if (WHEEL_CMP(next_cursor, 2)) {\n bucket = BUCKET_MAP(next_cursor, 2);\n } else if (WHEEL_CMP(next_cursor, 1)) {\n bucket = BUCKET_MAP(next_cursor, 1);\n }\n if (++s_mgr.cursor.a == 0) {\n ++s_mgr.round;\n }\n if (bucket > 0) { \/\/ hash to more precisely wheel\n hash(bucket);\n }\n}\n\nstatic void hash(int bucket)\n{\n timer_t *head = s_mgr.timers[bucket];\n timer_t *t = head;\n\n while (t) {\n timer_t *n = t->next;\n\n schedule(t);\n if (n == head) {\n s_mgr.timers[bucket] = NULL;\n break;\n }\n t = n;\n }\n}\nstatic void timer_min(void *args)\n{\n LOG_TRACE(\"timer\", \"%s\", \"BINGO: MIN.\");\n\n time_t cur = elf::time_s();\n elf::time64_t tm_timer;\n struct tm tm_cur;\n\n localtime_r(&cur, &tm_cur);\n tm_timer = (60 - tm_cur.tm_sec) * 1000llu;\n timer_add(tm_timer, timer_min, NULL);\n\n handler_list::const_iterator itr = s_handlers.begin();\n\n for (; itr != s_handlers.end(); ++itr) {\n (*itr)(&cur);\n }\n}\n} \/\/ namespace elf\n\n<|endoftext|>"} {"text":"\/\/ Copyright 2016, Alex Dunyak\n\n#include \"drake\/solvers\/MosekLP.h\"\n\nextern \"C\" {\n #include \n}\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"drake\/solvers\/Constraint.h\"\n\n\nnamespace drake {\nnamespace solvers {\n\nMosekLP::MosekLP(int num_variables, int num_constraints,\n std::vector equationScalars,\n Eigen::MatrixXd cons,\n std::vector mosek_constraint_bounds,\n std::vector upper_constraint_bounds,\n std::vector lower_constraint_bounds,\n std::vector mosek_variable_bounds,\n std::vector upper_variable_bounds,\n std::vector lower_variable_bounds) {\n numvar_ = num_variables;\n numcon_ = num_constraints;\n env_ = NULL;\n task_ = NULL;\n solutions_.clear();\n r_ = MSK_makeenv(&env_, NULL);\n if (r_ == MSK_RES_OK) {\n \/\/ Creates optimization task\n r_ = MSK_maketask(env_, numcon_, numvar_, &task_);\n \/\/ Append numcon_ empty constraints\n if (r_ == MSK_RES_OK)\n r_ = MSK_appendcons(task_, numcon_);\n\n \/\/ Append numvar_ variables, initially fixed at zero\n if (r_ == MSK_RES_OK)\n r_ = MSK_appendvars(task_, numvar_);\n }\n \/\/ add the equation to maximize to the environment.\n int j = 0;\n for (j = 0; j < numvar_ && r_ == MSK_RES_OK; j++) {\n if (r_ == MSK_RES_OK)\n r_ = MSK_putcj(task_, j, equationScalars[j]);\n }\n AddVariableBounds(mosek_variable_bounds, upper_variable_bounds,\n lower_variable_bounds);\n AddLinearConstraintMatrix(cons);\n AddLinearConstraintBounds(mosek_constraint_bounds, upper_constraint_bounds,\n lower_constraint_bounds);\n}\n\nvoid MosekLP::AddLinearConstraintMatrix(const Eigen::MatrixXd& cons) {\n Eigen::SparseMatrix sparsecons = cons.sparseView();\n \/\/ Send the sparse matrix rep into addLinearConstraintSparseColumnMatrix(),\n \/\/ which will handle setting the mosek constraints\n MosekLP::AddLinearConstraintSparseColumnMatrix(sparsecons);\n}\n\nvoid MosekLP::AddLinearConstraintSparseColumnMatrix(\n const Eigen::SparseMatrix& sparsecons) {\n int j = 0; \/\/ iterator\n \/\/ Define sparse matrix representation to be the same size as the desired\n \/\/ constraints\n std::vector aptrb;\n std::vector aptre;\n std::vector asub;\n std::vector aval;\n\n for (j = 0; j < sparsecons.cols(); j++)\n aptrb.push_back((MSKint32t) sparsecons.outerIndexPtr()[j]);\n for (j = 0; j < sparsecons.cols(); j++)\n aptre.push_back((MSKint32t) sparsecons.outerIndexPtr()[j+1]);\n for (j = 0; j < sparsecons.nonZeros(); j++)\n asub.push_back((MSKint32t) sparsecons.innerIndexPtr()[j]);\n for (j = 0; j < sparsecons.nonZeros(); j++)\n aval.push_back(sparsecons.valuePtr()[j]);\n\n \/\/ following code adapted from http:\/\/docs.mosek.com\/7.1\/capi\/Linear_optimization.html\n \/\/ check if still working in valid environment\n for (j = 0; j < numvar_ && r_ == MSK_RES_OK; j++) {\n r_ = MSK_putacol(task_,\n j,\n aptre[j] - aptrb[j], \/\/ Number of nonzeros in column i\n &asub[0] + aptrb[j], \/\/ Pointer to row indexes of column i\n &aval[0] + aptrb[j]); \/\/ pointer to values of column i\n }\n}\n\nvoid MosekLP::AddLinearConstraintBounds(\n const std::vector& mosek_bounds_,\n const std::vector& upper_bounds_,\n const std::vector& lower_bounds_) {\n int i = 0;\n for (; i < numcon_ && r_ == MSK_RES_OK; i++) {\n r_ = MSK_putconbound(task_, i, mosek_bounds_[i],\n lower_bounds_[i], upper_bounds_[i]);\n }\n}\n\nvoid MosekLP::AddVariableBounds(const std::vector& mosek_bounds_,\n const std::vector& upper_bounds_,\n const std::vector& lower_bounds_) {\n int j = 0;\n for (; j < numvar_ && r_ == MSK_RES_OK; j++) {\n r_ = MSK_putvarbound(task_, j, mosek_bounds_[j], lower_bounds_[j],\n upper_bounds_[j]);\n }\n}\n\nstd::vector MosekLP::FindMosekBounds(\n const std::vector& upper_bounds_,\n const std::vector& lower_bounds_) const {\n assert(upper_bounds_.size() == lower_bounds_.size());\n std::vector mosek_bounds_;\n unsigned int i = 0;\n for (i = 0; i != upper_bounds_.size(); i++) {\n if (upper_bounds_[i] == +MSK_INFINITY) {\n if (lower_bounds_[i] == -MSK_INFINITY) {\n mosek_bounds_.push_back(MSK_BK_FR);\n } else {\n mosek_bounds_.push_back(MSK_BK_LO);\n }\n } else {\n if (upper_bounds_[i] == lower_bounds_[i]) {\n mosek_bounds_.push_back(MSK_BK_FX);\n } else if (lower_bounds_[i] == -MSK_INFINITY) {\n mosek_bounds_.push_back(MSK_BK_UP);\n } else {\n mosek_bounds_.push_back(MSK_BK_RA);\n }\n }\n }\n return mosek_bounds_;\n}\n\n\nSolutionResult MosekLP::Solve(OptimizationProblem &prog) const {\n \/\/ construct an object that calls all the previous work so I can salvage\n \/\/ something at least.\n \/\/ assume that the problem type is linear currently.\n \/\/ TODO(adunyak): Add support for quadratic objective and constraints\n if (!prog.GetSolverOptionsStr(\"Mosek\").empty()) {\n if (prog.GetSolverOptionsStr(\"Mosek\").at(\"problemtype\").find(\"linear\")\n == std::string::npos) {\n return kUnknownError; \/\/ Not a linear optimization\n }\n } else {\n return kUnknownError;\n }\n int totalconnum = 0, i = 0;\n for (auto&& con_ : prog.GetAllLinearConstraints()) {\n \/\/ check to see if the constraint references a single variable,\n \/\/ which is handles as a variable bound by mosek\n for (i = 0; i < (con_.constraint())->A().rows(); ++i) {\n auto row = (con_.constraint())->A().row(i);\n if (row.nonZeros() != 1)\n totalconnum++;\n }\n }\n Eigen::MatrixXd linear_cons(totalconnum, prog.num_vars());\n std::vector upper_constraint_bounds(totalconnum);\n std::vector lower_constraint_bounds(totalconnum);\n std::vector mosek_constraint_bounds(totalconnum);\n std::vector mosek_variable_bounds(prog.num_vars());\n std::vector upper_variable_bounds(numvar_);\n std::vector lower_variable_bounds(numvar_);\n linear_cons.setZero(totalconnum, prog.num_vars());\n\n \/\/ Expect only one boundingbox constraint or no such constraint.\n if (!(prog.bounding_box_constraints().empty())) {\n assert(&(prog.bounding_box_constraints().front()) ==\n &(prog.bounding_box_constraints().back()));\n auto bbox = *(prog.bounding_box_constraints().front().constraint());\n std::vector lower_variable_bounds(bbox.lower_bound().data(),\n bbox.lower_bound().data() +\n bbox.lower_bound().rows() * bbox.lower_bound().cols());\n std::vector upper_variable_bounds(bbox.upper_bound().data(),\n bbox.upper_bound().data() +\n bbox.upper_bound().rows() * bbox.upper_bound().cols());\n for (auto& b : lower_variable_bounds) {\n if (b == -std::numeric_limits::infinity())\n b = -MSK_INFINITY;\n }\n for (auto& b : upper_variable_bounds) {\n if (b == +std::numeric_limits::infinity())\n b = MSK_INFINITY;\n }\n mosek_variable_bounds = FindMosekBounds(upper_variable_bounds,\n lower_variable_bounds);\n } else {\n \/\/ No bounding box constraint\n for (i = 0; i < numvar_; i++) {\n upper_variable_bounds[i] = +MSK_INFINITY;\n lower_variable_bounds[i] = -MSK_INFINITY;\n }\n mosek_variable_bounds = FindMosekBounds(upper_variable_bounds,\n lower_variable_bounds);\n }\n int connum = 0;\n i = 0;\n \/\/ TODO(alexdunyak): Allow constraints to affect specific variables\n for (const auto& con : prog.GetAllLinearConstraints()) {\n \/\/ con can call functions of Binding, but the actual\n \/\/ type is const std::list>::const_iterator&\n \/\/ Address the constraint matrix directly, translating back to our original\n \/\/ variable space\n for (int i = 0; static_cast(i) <\n con.constraint()->num_constraints(); i++) {\n for (int j = 0; j < (con.constraint())->A().cols(); j++) {\n linear_cons(connum, j) = (con.constraint()->A())(i, j);\n }\n \/\/ lower bounds first\n lower_constraint_bounds[connum] =\n (con.constraint())->lower_bound()(i);\n if (lower_constraint_bounds[connum] ==\n -std::numeric_limits::infinity())\n lower_constraint_bounds[connum] = -MSK_INFINITY;\n \/\/ upper bound\n upper_constraint_bounds[connum] =\n (con.constraint())->upper_bound()(i);\n if (upper_constraint_bounds[connum] ==\n +std::numeric_limits::infinity())\n upper_constraint_bounds[connum] = +MSK_INFINITY;\n connum++;\n }\n }\n mosek_constraint_bounds = FindMosekBounds(upper_constraint_bounds,\n lower_constraint_bounds);\n \/\/ find the linear objective here\n LinearConstraint *obj_ = static_cast(\n &(*(prog.generic_costs().front().constraint())));\n std::vector linobj_((*obj_).A().data(),\n (*obj_).A().data() + (*obj_).A().rows() * (*obj_).A().cols());\n MosekLP opt(prog.num_vars(),\n totalconnum,\n linobj_,\n linear_cons,\n mosek_constraint_bounds,\n upper_constraint_bounds,\n lower_constraint_bounds,\n mosek_variable_bounds,\n upper_variable_bounds,\n lower_variable_bounds);\n std::string mom = prog.GetSolverOptionsStr(\"Mosek\").at(\"maxormin\");\n std::string ptype = prog.GetSolverOptionsStr(\"Mosek\").at(\"problemtype\");\n SolutionResult s = opt.OptimizeTask(mom, ptype);\n prog.SetDecisionVariableValues(opt.GetEigenVectorSolutions());\n return s;\n}\n\nSolutionResult MosekLP::OptimizeTask(const std::string& maxormin,\n const std::string& ptype) {\n solutions_.clear();\n MSKsoltypee problemtype = MSK_SOL_BAS;\n if (ptype.find(\"quad\") != std::string::npos)\n problemtype = MSK_SOL_ITR;\n else if (ptype.find(\"linear\") != std::string::npos)\n problemtype = MSK_SOL_BAS;\n else\n return kUnknownError;\n if (r_ == MSK_RES_OK && maxormin == \"max\")\n r_ = MSK_putobjsense(task_, MSK_OBJECTIVE_SENSE_MAXIMIZE);\n else if (r_ == MSK_RES_OK && maxormin == \"min\")\n r_ = MSK_putobjsense(task_, MSK_OBJECTIVE_SENSE_MINIMIZE);\n if (r_ == MSK_RES_OK) {\n MSKrescodee trmcode;\n\n r_ = MSK_optimizetrm(task_, &trmcode);\n if (r_ == MSK_RES_OK) {\n MSKsolstae solsta;\n if (r_ == MSK_RES_OK) {\n r_ = MSK_getsolsta(task_, problemtype, &solsta);\n\n switch (solsta) {\n case MSK_SOL_STA_OPTIMAL:\n case MSK_SOL_STA_NEAR_OPTIMAL: {\n std::unique_ptr xx(new double[numvar_]);\n if (xx) {\n \/* Request the basic solution. *\/\n MSK_getxx(task_, problemtype, xx.get());\n for (int j = 0; j < numvar_; ++j) {\n solutions_.push_back(xx[j]);\n }\n return kSolutionFound;\n } else {\n r_ = MSK_RES_ERR_SPACE;\n return kUnknownError;\n }\n break;\n }\n case MSK_SOL_STA_DUAL_INFEAS_CER:\n case MSK_SOL_STA_PRIM_INFEAS_CER:\n case MSK_SOL_STA_NEAR_DUAL_INFEAS_CER:\n case MSK_SOL_STA_NEAR_PRIM_INFEAS_CER:\n printf(\"Primal or dual infeasibility certificate found.\\n\");\n return kInfeasibleConstraints;\n break;\n case MSK_SOL_STA_UNKNOWN: {\n char symname[MSK_MAX_STR_LEN];\n char desc[MSK_MAX_STR_LEN];\n\n \/* If the solutions status is unknown, print the termination code\n indicating why the optimizer terminated prematurely. *\/\n MSK_getcodedesc(trmcode, symname, desc);\n printf(\"The solution status is unknown.\\n\");\n printf(\"The optimizer terminitated with code: %s\\n\", symname);\n break;\n }\n default:\n printf(\"Other solution status.\\n\");\n break;\n }\n }\n }\n }\n return kUnknownError;\n}\n\nEigen::VectorXd MosekLP::GetEigenVectorSolutions() const {\n Eigen::VectorXd soln(numvar_);\n if (solutions_.empty())\n return soln;\n unsigned int i = 0;\n for (i = 0; i < solutions_.size(); ++i) {\n soln(i) = solutions_[i];\n }\n return soln.transpose();\n}\n\n} \/\/ namespace solvers\n} \/\/ namespace drake\nchanged a static_cast using a reference-dereference to simply use the get() function of std::unique_ptr.\/\/ Copyright 2016, Alex Dunyak\n\n#include \"drake\/solvers\/MosekLP.h\"\n\nextern \"C\" {\n #include \n}\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"drake\/solvers\/Constraint.h\"\n\n\nnamespace drake {\nnamespace solvers {\n\nMosekLP::MosekLP(int num_variables, int num_constraints,\n std::vector equationScalars,\n Eigen::MatrixXd cons,\n std::vector mosek_constraint_bounds,\n std::vector upper_constraint_bounds,\n std::vector lower_constraint_bounds,\n std::vector mosek_variable_bounds,\n std::vector upper_variable_bounds,\n std::vector lower_variable_bounds) {\n numvar_ = num_variables;\n numcon_ = num_constraints;\n env_ = NULL;\n task_ = NULL;\n solutions_.clear();\n r_ = MSK_makeenv(&env_, NULL);\n if (r_ == MSK_RES_OK) {\n \/\/ Creates optimization task\n r_ = MSK_maketask(env_, numcon_, numvar_, &task_);\n \/\/ Append numcon_ empty constraints\n if (r_ == MSK_RES_OK)\n r_ = MSK_appendcons(task_, numcon_);\n\n \/\/ Append numvar_ variables, initially fixed at zero\n if (r_ == MSK_RES_OK)\n r_ = MSK_appendvars(task_, numvar_);\n }\n \/\/ add the equation to maximize to the environment.\n int j = 0;\n for (j = 0; j < numvar_ && r_ == MSK_RES_OK; j++) {\n if (r_ == MSK_RES_OK)\n r_ = MSK_putcj(task_, j, equationScalars[j]);\n }\n AddVariableBounds(mosek_variable_bounds, upper_variable_bounds,\n lower_variable_bounds);\n AddLinearConstraintMatrix(cons);\n AddLinearConstraintBounds(mosek_constraint_bounds, upper_constraint_bounds,\n lower_constraint_bounds);\n}\n\nvoid MosekLP::AddLinearConstraintMatrix(const Eigen::MatrixXd& cons) {\n Eigen::SparseMatrix sparsecons = cons.sparseView();\n \/\/ Send the sparse matrix rep into addLinearConstraintSparseColumnMatrix(),\n \/\/ which will handle setting the mosek constraints\n MosekLP::AddLinearConstraintSparseColumnMatrix(sparsecons);\n}\n\nvoid MosekLP::AddLinearConstraintSparseColumnMatrix(\n const Eigen::SparseMatrix& sparsecons) {\n int j = 0; \/\/ iterator\n \/\/ Define sparse matrix representation to be the same size as the desired\n \/\/ constraints\n std::vector aptrb;\n std::vector aptre;\n std::vector asub;\n std::vector aval;\n\n for (j = 0; j < sparsecons.cols(); j++)\n aptrb.push_back((MSKint32t) sparsecons.outerIndexPtr()[j]);\n for (j = 0; j < sparsecons.cols(); j++)\n aptre.push_back((MSKint32t) sparsecons.outerIndexPtr()[j+1]);\n for (j = 0; j < sparsecons.nonZeros(); j++)\n asub.push_back((MSKint32t) sparsecons.innerIndexPtr()[j]);\n for (j = 0; j < sparsecons.nonZeros(); j++)\n aval.push_back(sparsecons.valuePtr()[j]);\n\n \/\/ following code adapted from http:\/\/docs.mosek.com\/7.1\/capi\/Linear_optimization.html\n \/\/ check if still working in valid environment\n for (j = 0; j < numvar_ && r_ == MSK_RES_OK; j++) {\n r_ = MSK_putacol(task_,\n j,\n aptre[j] - aptrb[j], \/\/ Number of nonzeros in column i\n &asub[0] + aptrb[j], \/\/ Pointer to row indexes of column i\n &aval[0] + aptrb[j]); \/\/ pointer to values of column i\n }\n}\n\nvoid MosekLP::AddLinearConstraintBounds(\n const std::vector& mosek_bounds_,\n const std::vector& upper_bounds_,\n const std::vector& lower_bounds_) {\n int i = 0;\n for (; i < numcon_ && r_ == MSK_RES_OK; i++) {\n r_ = MSK_putconbound(task_, i, mosek_bounds_[i],\n lower_bounds_[i], upper_bounds_[i]);\n }\n}\n\nvoid MosekLP::AddVariableBounds(const std::vector& mosek_bounds_,\n const std::vector& upper_bounds_,\n const std::vector& lower_bounds_) {\n int j = 0;\n for (; j < numvar_ && r_ == MSK_RES_OK; j++) {\n r_ = MSK_putvarbound(task_, j, mosek_bounds_[j], lower_bounds_[j],\n upper_bounds_[j]);\n }\n}\n\nstd::vector MosekLP::FindMosekBounds(\n const std::vector& upper_bounds_,\n const std::vector& lower_bounds_) const {\n assert(upper_bounds_.size() == lower_bounds_.size());\n std::vector mosek_bounds_;\n unsigned int i = 0;\n for (i = 0; i != upper_bounds_.size(); i++) {\n if (upper_bounds_[i] == +MSK_INFINITY) {\n if (lower_bounds_[i] == -MSK_INFINITY) {\n mosek_bounds_.push_back(MSK_BK_FR);\n } else {\n mosek_bounds_.push_back(MSK_BK_LO);\n }\n } else {\n if (upper_bounds_[i] == lower_bounds_[i]) {\n mosek_bounds_.push_back(MSK_BK_FX);\n } else if (lower_bounds_[i] == -MSK_INFINITY) {\n mosek_bounds_.push_back(MSK_BK_UP);\n } else {\n mosek_bounds_.push_back(MSK_BK_RA);\n }\n }\n }\n return mosek_bounds_;\n}\n\n\nSolutionResult MosekLP::Solve(OptimizationProblem &prog) const {\n \/\/ construct an object that calls all the previous work so I can salvage\n \/\/ something at least.\n \/\/ assume that the problem type is linear currently.\n \/\/ TODO(adunyak): Add support for quadratic objective and constraints\n if (!prog.GetSolverOptionsStr(\"Mosek\").empty()) {\n if (prog.GetSolverOptionsStr(\"Mosek\").at(\"problemtype\").find(\"linear\")\n == std::string::npos) {\n return kUnknownError; \/\/ Not a linear optimization\n }\n } else {\n return kUnknownError;\n }\n int totalconnum = 0, i = 0;\n for (auto&& con_ : prog.GetAllLinearConstraints()) {\n \/\/ check to see if the constraint references a single variable,\n \/\/ which is handles as a variable bound by mosek\n for (i = 0; i < (con_.constraint())->A().rows(); ++i) {\n auto row = (con_.constraint())->A().row(i);\n if (row.nonZeros() != 1)\n totalconnum++;\n }\n }\n Eigen::MatrixXd linear_cons(totalconnum, prog.num_vars());\n std::vector upper_constraint_bounds(totalconnum);\n std::vector lower_constraint_bounds(totalconnum);\n std::vector mosek_constraint_bounds(totalconnum);\n std::vector mosek_variable_bounds(prog.num_vars());\n std::vector upper_variable_bounds(numvar_);\n std::vector lower_variable_bounds(numvar_);\n linear_cons.setZero(totalconnum, prog.num_vars());\n\n \/\/ Expect only one boundingbox constraint or no such constraint.\n if (!(prog.bounding_box_constraints().empty())) {\n assert(&(prog.bounding_box_constraints().front()) ==\n &(prog.bounding_box_constraints().back()));\n auto bbox = *(prog.bounding_box_constraints().front().constraint());\n std::vector lower_variable_bounds(bbox.lower_bound().data(),\n bbox.lower_bound().data() +\n bbox.lower_bound().rows() * bbox.lower_bound().cols());\n std::vector upper_variable_bounds(bbox.upper_bound().data(),\n bbox.upper_bound().data() +\n bbox.upper_bound().rows() * bbox.upper_bound().cols());\n for (auto& b : lower_variable_bounds) {\n if (b == -std::numeric_limits::infinity())\n b = -MSK_INFINITY;\n }\n for (auto& b : upper_variable_bounds) {\n if (b == +std::numeric_limits::infinity())\n b = MSK_INFINITY;\n }\n mosek_variable_bounds = FindMosekBounds(upper_variable_bounds,\n lower_variable_bounds);\n } else {\n \/\/ No bounding box constraint\n for (i = 0; i < numvar_; i++) {\n upper_variable_bounds[i] = +MSK_INFINITY;\n lower_variable_bounds[i] = -MSK_INFINITY;\n }\n mosek_variable_bounds = FindMosekBounds(upper_variable_bounds,\n lower_variable_bounds);\n }\n int connum = 0;\n i = 0;\n \/\/ TODO(alexdunyak): Allow constraints to affect specific variables\n for (const auto& con : prog.GetAllLinearConstraints()) {\n \/\/ con can call functions of Binding, but the actual\n \/\/ type is const std::list>::const_iterator&\n \/\/ Address the constraint matrix directly, translating back to our original\n \/\/ variable space\n for (int i = 0; static_cast(i) <\n con.constraint()->num_constraints(); i++) {\n for (int j = 0; j < (con.constraint())->A().cols(); j++) {\n linear_cons(connum, j) = (con.constraint()->A())(i, j);\n }\n \/\/ lower bounds first\n lower_constraint_bounds[connum] =\n (con.constraint())->lower_bound()(i);\n if (lower_constraint_bounds[connum] ==\n -std::numeric_limits::infinity())\n lower_constraint_bounds[connum] = -MSK_INFINITY;\n \/\/ upper bound\n upper_constraint_bounds[connum] =\n (con.constraint())->upper_bound()(i);\n if (upper_constraint_bounds[connum] ==\n +std::numeric_limits::infinity())\n upper_constraint_bounds[connum] = +MSK_INFINITY;\n connum++;\n }\n }\n mosek_constraint_bounds = FindMosekBounds(upper_constraint_bounds,\n lower_constraint_bounds);\n \/\/ find the linear objective here\n LinearConstraint *obj_ = static_cast(\n (prog.generic_costs().front().constraint()).get());\n std::vector linobj_((*obj_).A().data(),\n (*obj_).A().data() + (*obj_).A().rows() * (*obj_).A().cols());\n MosekLP opt(prog.num_vars(),\n totalconnum,\n linobj_,\n linear_cons,\n mosek_constraint_bounds,\n upper_constraint_bounds,\n lower_constraint_bounds,\n mosek_variable_bounds,\n upper_variable_bounds,\n lower_variable_bounds);\n std::string mom = prog.GetSolverOptionsStr(\"Mosek\").at(\"maxormin\");\n std::string ptype = prog.GetSolverOptionsStr(\"Mosek\").at(\"problemtype\");\n SolutionResult s = opt.OptimizeTask(mom, ptype);\n prog.SetDecisionVariableValues(opt.GetEigenVectorSolutions());\n return s;\n}\n\nSolutionResult MosekLP::OptimizeTask(const std::string& maxormin,\n const std::string& ptype) {\n solutions_.clear();\n MSKsoltypee problemtype = MSK_SOL_BAS;\n if (ptype.find(\"quad\") != std::string::npos)\n problemtype = MSK_SOL_ITR;\n else if (ptype.find(\"linear\") != std::string::npos)\n problemtype = MSK_SOL_BAS;\n else\n return kUnknownError;\n if (r_ == MSK_RES_OK && maxormin == \"max\")\n r_ = MSK_putobjsense(task_, MSK_OBJECTIVE_SENSE_MAXIMIZE);\n else if (r_ == MSK_RES_OK && maxormin == \"min\")\n r_ = MSK_putobjsense(task_, MSK_OBJECTIVE_SENSE_MINIMIZE);\n if (r_ == MSK_RES_OK) {\n MSKrescodee trmcode;\n\n r_ = MSK_optimizetrm(task_, &trmcode);\n if (r_ == MSK_RES_OK) {\n MSKsolstae solsta;\n if (r_ == MSK_RES_OK) {\n r_ = MSK_getsolsta(task_, problemtype, &solsta);\n\n switch (solsta) {\n case MSK_SOL_STA_OPTIMAL:\n case MSK_SOL_STA_NEAR_OPTIMAL: {\n std::unique_ptr xx(new double[numvar_]);\n if (xx) {\n \/* Request the basic solution. *\/\n MSK_getxx(task_, problemtype, xx.get());\n for (int j = 0; j < numvar_; ++j) {\n solutions_.push_back(xx[j]);\n }\n return kSolutionFound;\n } else {\n r_ = MSK_RES_ERR_SPACE;\n return kUnknownError;\n }\n break;\n }\n case MSK_SOL_STA_DUAL_INFEAS_CER:\n case MSK_SOL_STA_PRIM_INFEAS_CER:\n case MSK_SOL_STA_NEAR_DUAL_INFEAS_CER:\n case MSK_SOL_STA_NEAR_PRIM_INFEAS_CER:\n printf(\"Primal or dual infeasibility certificate found.\\n\");\n return kInfeasibleConstraints;\n break;\n case MSK_SOL_STA_UNKNOWN: {\n char symname[MSK_MAX_STR_LEN];\n char desc[MSK_MAX_STR_LEN];\n\n \/* If the solutions status is unknown, print the termination code\n indicating why the optimizer terminated prematurely. *\/\n MSK_getcodedesc(trmcode, symname, desc);\n printf(\"The solution status is unknown.\\n\");\n printf(\"The optimizer terminitated with code: %s\\n\", symname);\n break;\n }\n default:\n printf(\"Other solution status.\\n\");\n break;\n }\n }\n }\n }\n return kUnknownError;\n}\n\nEigen::VectorXd MosekLP::GetEigenVectorSolutions() const {\n Eigen::VectorXd soln(numvar_);\n if (solutions_.empty())\n return soln;\n unsigned int i = 0;\n for (i = 0; i < solutions_.size(); ++i) {\n soln(i) = solutions_[i];\n }\n return soln.transpose();\n}\n\n} \/\/ namespace solvers\n} \/\/ namespace drake\n<|endoftext|>"} {"text":"#include \"mainwindow.hpp\"\n\n#include \"drape_surface.hpp\"\n\n#include \n\nMainWindow::MainWindow(QWidget *parent)\n : QMainWindow(parent)\n , m_surface(NULL)\n{\n resize(1200, 800);\n DrapeSurface * surface = new DrapeSurface();\n m_surface = QWidget::createWindowContainer(surface, this);\n setCentralWidget(m_surface);\n}\n\nMainWindow::~MainWindow()\n{\n ASSERT(m_surface == NULL, ());\n}\n\nvoid MainWindow::closeEvent(QCloseEvent * closeEvent)\n{\n delete m_surface;\n m_surface = NULL;\n}\n[drape] request depth buffer for drawable surface#include \"mainwindow.hpp\"\n\n#include \"drape_surface.hpp\"\n\n#include \n\nMainWindow::MainWindow(QWidget *parent)\n : QMainWindow(parent)\n , m_surface(NULL)\n{\n resize(1200, 800);\n\n DrapeSurface * surface = new DrapeSurface();\n QSurfaceFormat format = surface->requestedFormat();\n format.setDepthBufferSize(16);\n surface->setFormat(format);\n m_surface = QWidget::createWindowContainer(surface, this);\n setCentralWidget(m_surface);\n}\n\nMainWindow::~MainWindow()\n{\n ASSERT(m_surface == NULL, ());\n}\n\nvoid MainWindow::closeEvent(QCloseEvent * closeEvent)\n{\n delete m_surface;\n m_surface = NULL;\n}\n<|endoftext|>"} {"text":"\/** @file\n @brief Implementation\n\n @date 2015\n\n @author\n Sensics, Inc.\n \n*\/\n\n\/\/ Copyright 2015 Sensics, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Internal Includes\n#include \"VideoIMUFusionDevice.h\"\n#include \n#include \n#include \n#include \n#include \n\n\/\/ Generated JSON header file\n#include \"org_osvr_filter_videoimufusion_json.h\"\n\n\/\/ Library\/third-party includes\n\/\/ - none\n\n\/\/ Standard includes\n#include \n#include \n\nstatic const OSVR_ChannelCount FUSED_SENSOR_ID = 0;\nstatic const OSVR_ChannelCount TRANSFORMED_VIDEO_SENSOR_ID = 1;\n\nVideoIMUFusionDevice::VideoIMUFusionDevice(OSVR_PluginRegContext ctx,\n std::string const &name,\n std::string const &imuPath,\n std::string const &videoPath,\n VideoIMUFusionParams const ¶ms)\n : m_fusion(params) {\n \/\/\/ Create the initialization options\n OSVR_DeviceInitOptions opts = osvrDeviceCreateInitOptions(ctx);\n\n osvrDeviceTrackerConfigure(opts, &m_trackerOut);\n\n \/\/\/ Create the device token with the options\n OSVR_DeviceToken dev;\n if (OSVR_RETURN_FAILURE ==\n osvrAnalysisSyncInit(ctx, name.c_str(), opts, &dev, &m_clientCtx)) {\n throw std::runtime_error(\"Could not initialize analysis plugin!\");\n }\n m_dev = osvr::pluginkit::DeviceToken(dev);\n\n \/\/\/ Send JSON descriptor\n m_dev.sendJsonDescriptor(org_osvr_filter_videoimufusion_json);\n\n \/\/\/ Register update callback\n m_dev.registerUpdateCallback(this);\n\n \/\/\/ Set up to receive our input.\n osvrClientGetInterface(m_clientCtx, imuPath.c_str(), &m_imu);\n osvrRegisterOrientationCallback(\n m_imu, &VideoIMUFusionDevice::s_handleIMUData, this);\n osvrRegisterAngularVelocityCallback(\n m_imu, &VideoIMUFusionDevice::s_handleIMUVelocity, this);\n\n osvrClientGetInterface(m_clientCtx, videoPath.c_str(), &m_videoTracker);\n\n osvrRegisterPoseCallback(\n m_videoTracker, &VideoIMUFusionDevice::s_handleVideoTrackerData, this);\n}\n\nVideoIMUFusionDevice::~VideoIMUFusionDevice() {\n \/\/\/ free the interfaces before the pointed-to function objects\n \/\/\/ disappear.\n if (m_imu) {\n osvrClientFreeInterface(m_clientCtx, m_imu);\n m_imu = nullptr;\n }\n if (m_videoTracker) {\n osvrClientFreeInterface(m_clientCtx, m_videoTracker);\n m_imu = nullptr;\n }\n}\n\nvoid VideoIMUFusionDevice::s_handleIMUData(\n void *userdata, const OSVR_TimeValue *timestamp,\n const OSVR_OrientationReport *report) {\n static_cast(userdata)\n ->handleIMUData(*timestamp, *report);\n}\nvoid VideoIMUFusionDevice::s_handleIMUVelocity(\n void *userdata, const OSVR_TimeValue *timestamp,\n const OSVR_AngularVelocityReport *report) {\n static_cast(userdata)\n ->handleIMUVelocity(*timestamp, *report);\n}\nvoid VideoIMUFusionDevice::s_handleVideoTrackerData(\n void *userdata, const OSVR_TimeValue *timestamp,\n const OSVR_PoseReport *report) {\n static_cast(userdata)\n ->handleVideoTrackerData(*timestamp, *report);\n}\n\nvoid VideoIMUFusionDevice::handleIMUData(const OSVR_TimeValue ×tamp,\n const OSVR_OrientationReport &report) {\n m_fusion.handleIMUData(timestamp, report);\n if (m_fusion.running()) {\n sendMainPoseReport();\n }\n}\nvoid VideoIMUFusionDevice::handleIMUVelocity(\n const OSVR_TimeValue ×tamp, const OSVR_AngularVelocityReport &report) {\n\n using namespace osvr::util::eigen_interop;\n Eigen::Quaterniond q = map(report.state.incrementalRotation);\n Eigen::Vector3d rot;\n if (q.w() >= 1. || q.vec().isZero(1e-10)) {\n rot = Eigen::Vector3d::Zero();\n } else {\n auto magnitude = q.vec().blueNorm();\n rot = (q.vec() \/ magnitude * (2. * std::atan2(magnitude, q.w()))) \/\n report.state.dt;\n \/\/\/ @todo without transformations being applied to vel quats, this\n \/\/\/ is needed.\n \/\/ std::swap(rot[0], rot[1]);\n rot[1] *= -1.;\n rot[2] *= -1.;\n }\n\n m_fusion.handleIMUVelocity(timestamp, rot);\n if (m_fusion.running()) {\n sendMainPoseReport();\n }\n}\nvoid VideoIMUFusionDevice::handleVideoTrackerData(\n const OSVR_TimeValue ×tamp, const OSVR_PoseReport &report) {\n if (!m_fusion.running()) {\n auto ts = OSVR_TimeValue{};\n auto oriState = OSVR_OrientationState{};\n auto ret = osvrGetOrientationState(m_imu, &ts, &oriState);\n if (ret != OSVR_RETURN_SUCCESS) {\n std::cout << \"Got a video report before an IMU report, ignoring it\"\n << std::endl;\n return;\n }\n m_fusion.handleVideoTrackerDataDuringStartup(timestamp, report,\n oriState);\n return;\n }\n m_fusion.handleVideoTrackerDataWhileRunning(timestamp, report);\n sendMainPoseReport();\n osvrDeviceTrackerSendPoseTimestamped(\n m_dev, m_trackerOut, &m_fusion.getLatestReorientedVideoPose(),\n TRANSFORMED_VIDEO_SENSOR_ID, ×tamp);\n}\n\nvoid VideoIMUFusionDevice::sendMainPoseReport() {\n osvrDeviceTrackerSendPoseTimestamped(\n m_dev, m_trackerOut, &m_fusion.getLatestFusedPose(), FUSED_SENSOR_ID,\n &m_fusion.getLatestFusedTime());\n}\nAlternate method of getting the angular velocity vector out of that incremental quat.\/** @file\n @brief Implementation\n\n @date 2015\n\n @author\n Sensics, Inc.\n \n*\/\n\n\/\/ Copyright 2015 Sensics, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Internal Includes\n#include \"VideoIMUFusionDevice.h\"\n#include \n#include \n#include \n#include \n#include \n\n\/\/ Generated JSON header file\n#include \"org_osvr_filter_videoimufusion_json.h\"\n\n\/\/ Library\/third-party includes\n\/\/ - none\n\n\/\/ Standard includes\n#include \n#include \n\nstatic const OSVR_ChannelCount FUSED_SENSOR_ID = 0;\nstatic const OSVR_ChannelCount TRANSFORMED_VIDEO_SENSOR_ID = 1;\n\nVideoIMUFusionDevice::VideoIMUFusionDevice(OSVR_PluginRegContext ctx,\n std::string const &name,\n std::string const &imuPath,\n std::string const &videoPath,\n VideoIMUFusionParams const ¶ms)\n : m_fusion(params) {\n \/\/\/ Create the initialization options\n OSVR_DeviceInitOptions opts = osvrDeviceCreateInitOptions(ctx);\n\n osvrDeviceTrackerConfigure(opts, &m_trackerOut);\n\n \/\/\/ Create the device token with the options\n OSVR_DeviceToken dev;\n if (OSVR_RETURN_FAILURE ==\n osvrAnalysisSyncInit(ctx, name.c_str(), opts, &dev, &m_clientCtx)) {\n throw std::runtime_error(\"Could not initialize analysis plugin!\");\n }\n m_dev = osvr::pluginkit::DeviceToken(dev);\n\n \/\/\/ Send JSON descriptor\n m_dev.sendJsonDescriptor(org_osvr_filter_videoimufusion_json);\n\n \/\/\/ Register update callback\n m_dev.registerUpdateCallback(this);\n\n \/\/\/ Set up to receive our input.\n osvrClientGetInterface(m_clientCtx, imuPath.c_str(), &m_imu);\n osvrRegisterOrientationCallback(\n m_imu, &VideoIMUFusionDevice::s_handleIMUData, this);\n osvrRegisterAngularVelocityCallback(\n m_imu, &VideoIMUFusionDevice::s_handleIMUVelocity, this);\n\n osvrClientGetInterface(m_clientCtx, videoPath.c_str(), &m_videoTracker);\n\n osvrRegisterPoseCallback(\n m_videoTracker, &VideoIMUFusionDevice::s_handleVideoTrackerData, this);\n}\n\nVideoIMUFusionDevice::~VideoIMUFusionDevice() {\n \/\/\/ free the interfaces before the pointed-to function objects\n \/\/\/ disappear.\n if (m_imu) {\n osvrClientFreeInterface(m_clientCtx, m_imu);\n m_imu = nullptr;\n }\n if (m_videoTracker) {\n osvrClientFreeInterface(m_clientCtx, m_videoTracker);\n m_imu = nullptr;\n }\n}\n\nvoid VideoIMUFusionDevice::s_handleIMUData(\n void *userdata, const OSVR_TimeValue *timestamp,\n const OSVR_OrientationReport *report) {\n static_cast(userdata)\n ->handleIMUData(*timestamp, *report);\n}\nvoid VideoIMUFusionDevice::s_handleIMUVelocity(\n void *userdata, const OSVR_TimeValue *timestamp,\n const OSVR_AngularVelocityReport *report) {\n static_cast(userdata)\n ->handleIMUVelocity(*timestamp, *report);\n}\nvoid VideoIMUFusionDevice::s_handleVideoTrackerData(\n void *userdata, const OSVR_TimeValue *timestamp,\n const OSVR_PoseReport *report) {\n static_cast(userdata)\n ->handleVideoTrackerData(*timestamp, *report);\n}\n\nvoid VideoIMUFusionDevice::handleIMUData(const OSVR_TimeValue ×tamp,\n const OSVR_OrientationReport &report) {\n m_fusion.handleIMUData(timestamp, report);\n if (m_fusion.running()) {\n sendMainPoseReport();\n }\n}\nvoid VideoIMUFusionDevice::handleIMUVelocity(\n const OSVR_TimeValue ×tamp, const OSVR_AngularVelocityReport &report) {\n\n using namespace osvr::util::eigen_interop;\n Eigen::Quaterniond q = map(report.state.incrementalRotation);\n Eigen::Vector3d rot;\n if (q.w() >= 1. || q.vec().isZero(1e-10)) {\n rot = Eigen::Vector3d::Zero();\n } else {\n#if 0\n auto magnitude = q.vec().blueNorm();\n rot = (q.vec() \/ magnitude * (2. * std::atan2(magnitude, q.w()))) \/\n report.state.dt;\n \/\/\/ @todo without transformations being applied to vel quats, this\n \/\/\/ is needed.\n \/\/ std::swap(rot[0], rot[1]);\n rot[1] *= -1.;\n rot[2] *= -1.;\n#else\n auto angle = std::acos(q.w());\n rot = q.vec().normalized() * angle * 2 \/ report.state.dt;\n\n \/\/\/ @todo without transformations being applied to vel quats, this\n \/\/\/ is needed.\n rot[1] *= -1.;\n rot[2] *= -1.;\n#endif\n }\n\n m_fusion.handleIMUVelocity(timestamp, rot);\n if (m_fusion.running()) {\n sendMainPoseReport();\n }\n}\nvoid VideoIMUFusionDevice::handleVideoTrackerData(\n const OSVR_TimeValue ×tamp, const OSVR_PoseReport &report) {\n if (!m_fusion.running()) {\n auto ts = OSVR_TimeValue{};\n auto oriState = OSVR_OrientationState{};\n auto ret = osvrGetOrientationState(m_imu, &ts, &oriState);\n if (ret != OSVR_RETURN_SUCCESS) {\n std::cout << \"Got a video report before an IMU report, ignoring it\"\n << std::endl;\n return;\n }\n m_fusion.handleVideoTrackerDataDuringStartup(timestamp, report,\n oriState);\n return;\n }\n m_fusion.handleVideoTrackerDataWhileRunning(timestamp, report);\n sendMainPoseReport();\n osvrDeviceTrackerSendPoseTimestamped(\n m_dev, m_trackerOut, &m_fusion.getLatestReorientedVideoPose(),\n TRANSFORMED_VIDEO_SENSOR_ID, ×tamp);\n}\n\nvoid VideoIMUFusionDevice::sendMainPoseReport() {\n osvrDeviceTrackerSendPoseTimestamped(\n m_dev, m_trackerOut, &m_fusion.getLatestFusedPose(), FUSED_SENSOR_ID,\n &m_fusion.getLatestFusedTime());\n}\n<|endoftext|>"} {"text":"\/\/ [WriteFile Name=ConfigureSubnetworkTrace, Category=Analysis]\n\/\/ [Legal]\n\/\/ Copyright 2020 Esri.\n\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/ [Legal]\n\n#ifdef PCH_BUILD\n#include \"pch.hpp\"\n#endif \/\/ PCH_BUILD\n\n#include \"ConfigureSubnetworkTrace.h\"\n\n#include \"CodedValueDomain.h\"\n#include \"TaskWatcher.h\"\n#include \"UtilityAssetGroup.h\"\n#include \"UtilityAssetType.h\"\n#include \"UtilityCategory.h\"\n#include \"UtilityCategoryComparison.h\"\n#include \"UtilityDomainNetwork.h\"\n#include \"UtilityElement.h\"\n#include \"UtilityElementTraceResult.h\"\n#include \"UtilityNetwork.h\"\n#include \"UtilityNetworkDefinition.h\"\n#include \"UtilityNetworkSource.h\"\n#include \"UtilityNetworkTypes.h\"\n#include \"UtilityTerminal.h\"\n#include \"UtilityTerminalConfiguration.h\"\n#include \"UtilityTier.h\"\n#include \"UtilityTraceAndCondition.h\"\n#include \"UtilityTraceConfiguration.h\"\n#include \"UtilityTraceOrCondition.h\"\n#include \"UtilityTraceParameters.h\"\n#include \"UtilityTraceResultListModel.h\"\n#include \"UtilityTraversability.h\"\n\n#include \n#include \n\nusing namespace Esri::ArcGISRuntime;\n\nConfigureSubnetworkTrace::ConfigureSubnetworkTrace(QObject* parent \/* = nullptr *\/):\n QObject(parent)\n{\n m_utilityNetwork = new UtilityNetwork(m_featureLayerUrl, this);\n\n connect(m_utilityNetwork, &UtilityNetwork::doneLoading, this, &ConfigureSubnetworkTrace::onUtilityNetworkLoaded);\n\n connect(m_utilityNetwork, &UtilityNetwork::traceCompleted, this, &ConfigureSubnetworkTrace::onTraceCompleted);\n\n m_utilityNetwork->load();\n}\n\nQString ConfigureSubnetworkTrace::expressionToString(UtilityTraceConditionalExpression* expression)\n{\n switch (expression->traceConditionType())\n {\n case UtilityTraceConditionType::UtilityNetworkAttributeComparison:\n {\n const UtilityNetworkAttributeComparison* attributeExpression = static_cast(expression);\n const UtilityNetworkAttribute* networkAttribute = attributeExpression->networkAttribute();\n const UtilityNetworkAttribute* otherNetworkAttribute = attributeExpression->otherNetworkAttribute();\n const Domain networkDomain = networkAttribute->domain();\n const QString operatorAsString = comparisonOperatorToString(attributeExpression->comparisonOperator());\n\n \/\/ check if attribute domain is a coded value domain.\n if (!networkDomain.isEmpty() && (networkDomain.domainType() == DomainType::CodedValueDomain))\n {\n const CodedValueDomain codedValueDomain = static_cast(networkDomain);\n const QList codedValues = codedValueDomain.codedValues();\n\n \/\/ get the coded value using the value as the index for the list of coded values\n const QString codedValueName = codedValues[attributeExpression->value().toInt()].name();\n\n return QString(\"`%1` %2 `%3`\").arg(networkAttribute->name(), operatorAsString, codedValueName);\n }\n else\n {\n if (otherNetworkAttribute)\n {\n return QString(\"`%1` %2 `%3`\").arg(networkAttribute->name(), operatorAsString, otherNetworkAttribute->name());\n }\n return QString(\"`%1` %2 `%3`\").arg(networkAttribute->name(), operatorAsString, attributeExpression->value().toString());\n }\n }\n case UtilityTraceConditionType::UtilityCategoryComparison:\n {\n const UtilityCategoryComparison* comparisonExpression = static_cast(expression);\n\n return QString(\"`%1` %2\").arg(comparisonExpression->category()->name(), (comparisonExpression->comparisonOperator() == UtilityCategoryComparisonOperator::Exists) ? \"Exists\" : \"DoesNotExist\");\n }\n case UtilityTraceConditionType::UtilityTraceAndCondition:\n {\n const UtilityTraceAndCondition* andExpression = static_cast(expression);\n\n return QString(\"(%1) AND\\n (%2)\").arg(expressionToString(andExpression->leftExpression()), expressionToString(andExpression->rightExpression()));\n }\n case UtilityTraceConditionType::UtilityTraceOrCondition:\n {\n const UtilityTraceOrCondition* orExpression = static_cast(expression);\n return QString(\"(%1) OR\\n (%2)\").arg(expressionToString(orExpression->leftExpression()), expressionToString(orExpression->rightExpression()));\n }\n default:\n return QString(\"Unknown trace conditional expression\");\n }\n}\n\nQString ConfigureSubnetworkTrace::comparisonOperatorToString(const UtilityAttributeComparisonOperator& comparisonOperator)\n{\n switch (comparisonOperator)\n {\n case UtilityAttributeComparisonOperator::Equal:\n return QString(\"Equal\");\n case UtilityAttributeComparisonOperator::NotEqual:\n return QString(\"NotEqual\");\n case UtilityAttributeComparisonOperator::GreaterThan:\n return QString(\"GreaterThan\");\n case UtilityAttributeComparisonOperator::GreaterThanEqual:\n return QString(\"GreaterThanEqual\");\n case UtilityAttributeComparisonOperator::LessThan:\n return QString(\"LessThan\");\n case UtilityAttributeComparisonOperator::LessThanEqual:\n return QString(\"LessThanEqual\");\n case UtilityAttributeComparisonOperator::IncludesTheValues:\n return QString(\"IncludesTheValues\");\n case UtilityAttributeComparisonOperator::DoesNotIncludeTheValues:\n return QString(\"DoesNotIncludeTheValues\");\n case UtilityAttributeComparisonOperator::IncludesAny:\n return QString(\"IncludesAny\");\n case UtilityAttributeComparisonOperator::DoesNotIncludeAny:\n return QString(\"DoesNotIncludeAny\");\n default:\n return QString(\"Unknown comparison operator\");\n }\n}\n\nQVariant ConfigureSubnetworkTrace::convertToDataType(const QVariant& value, const Esri::ArcGISRuntime::UtilityNetworkAttributeDataType& dataType)\n{\n switch (dataType)\n {\n case UtilityNetworkAttributeDataType::Integer:\n {\n \/\/ inconsistent results when using QVariant.toInt() on a\n \/\/ QString that doesn't contain an Integer dataType.\n \/\/ e.g. QVariant(QString(\"123.321\")).toInt();\n return static_cast(value.toDouble());\n }\n case UtilityNetworkAttributeDataType::Float:\n {\n return value.toFloat();\n }\n case UtilityNetworkAttributeDataType::Double:\n {\n return value.toDouble();\n }\n case UtilityNetworkAttributeDataType::Boolean:\n {\n return value.toBool();\n }\n default:\n return QVariant();\n }\n}\n\nvoid ConfigureSubnetworkTrace::codedValueOrInputText(const QString& currentText)\n{\n \/\/ Update the UI to show the correct value entry for the attribute.\n if (m_networkDefinition)\n {\n const Domain domain = m_networkDefinition->networkAttribute(currentText)->domain();\n if (!domain.isEmpty() && (domain.domainType() == DomainType::CodedValueDomain))\n {\n m_valueSelectionListModel.clear();\n const CodedValueDomain codedValueDomain = static_cast(domain);\n\n for (CodedValue codedValue: codedValueDomain.codedValues())\n m_valueSelectionListModel.append(codedValue.name());\n\n m_textFieldVisible = false;\n }\n else\n {\n m_textFieldVisible = true;\n }\n emit valueSelectionListModelChanged();\n emit textFieldVisibleChanged();\n }\n}\n\nvoid ConfigureSubnetworkTrace::addCondition(const QString& selectedAttribute, int selectedOperator, const QVariant& selectedValue)\n{\n \/\/ NOTE: You may also create a UtilityCategoryComparison with UtilityNetworkDefinition.Categories and UtilityCategoryComparisonOperator.\n\n UtilityNetworkAttribute* selectedNetworkAttribute = m_networkDefinition->networkAttribute(selectedAttribute);\n const QVariant convertedSelectedValue = convertToDataType(selectedValue, selectedNetworkAttribute->dataType());\n\n if (convertedSelectedValue.isNull())\n {\n m_dialogText = \"Unknow network attribute data type\";\n emit dialogTextChanged();\n emit showDialog();\n return;\n }\n\n const UtilityAttributeComparisonOperator selectedOperatorEnum = static_cast(selectedOperator);\n\n \/\/ NOTE: You may also create a UtilityNetworkAttributeComparison with another NetworkAttribute.\n UtilityTraceConditionalExpression* expression = new UtilityNetworkAttributeComparison(selectedNetworkAttribute, selectedOperatorEnum, convertedSelectedValue, this);\n\n UtilityTraceConditionalExpression* otherExpression = static_cast(m_traceConfiguration->traversability()->barriers());\n\n \/\/ NOTE: You may also combine expressions with UtilityTraceAndCondition\n UtilityTraceConditionalExpression* combineExpressions = new UtilityTraceOrCondition(otherExpression, expression, this);\n\n m_expressionBuilder = expressionToString(combineExpressions);\n emit expressionBuilderChanged();\n\n m_traceConfiguration->traversability()->setBarriers(combineExpressions);\n}\n\nvoid ConfigureSubnetworkTrace::changeIncludeBarriersState(bool includeBarriers)\n{\n m_traceConfiguration->setIncludeBarriers(includeBarriers);\n}\n\nvoid ConfigureSubnetworkTrace::changeIncludeContainersState(bool includeContainers)\n{\n m_traceConfiguration->setIncludeContainers(includeContainers);\n}\n\nvoid ConfigureSubnetworkTrace::reset()\n{\n \/\/ Reset the barrier condition to the initial value.\n m_traceConfiguration->traversability()->setBarriers(m_initialExpression);\n m_expressionBuilder.clear();\n m_expressionBuilder = expressionToString(static_cast(m_initialExpression));\n emit expressionBuilderChanged();\n}\n\nvoid ConfigureSubnetworkTrace::trace()\n{\n if (!m_utilityNetwork || !m_utilityElementStartingLocation)\n {\n return;\n }\n\n m_busy = true;\n emit busyChanged();\n const QList startingLocations {m_utilityElementStartingLocation};\n \/\/ Create utility trace parameters for the starting location.\n m_traceParams = new UtilityTraceParameters(UtilityTraceType::Subnetwork, startingLocations, this);\n m_traceParams->setTraceConfiguration(m_traceConfiguration);\n\n \/\/ trace the network\n m_utilityNetwork->trace(m_traceParams);\n}\n\nvoid ConfigureSubnetworkTrace::onTraceCompleted()\n{\n if (m_utilityNetwork->traceResult()->isEmpty())\n {\n m_dialogText = \"No results returned\";\n emit dialogTextChanged();\n emit showDialog();\n }\n \/\/ Get the first result.\n UtilityTraceResult* result = m_utilityNetwork->traceResult()->at(0);\n\n const QList elements = static_cast(result)->elements(this);\n\n \/\/ Display the number of elements found by the trace.\n m_dialogText = QString(\"%1 elements found.\").arg(elements.length());\n m_busy = false;\n emit dialogTextChanged();\n emit showDialog();\n emit busyChanged();\n}\n\nvoid ConfigureSubnetworkTrace::onUtilityNetworkLoaded(const Error& e)\n{\n if (!e.isEmpty())\n {\n m_dialogText = QString(\"%1 - %2\").arg(e.message(), e.additionalMessage());\n m_busy = false;\n emit dialogTextChanged();\n emit showDialog();\n emit busyChanged();\n return;\n }\n\n m_busy = false;\n emit busyChanged();\n m_networkDefinition = m_utilityNetwork->definition();\n\n \/\/ Build the choice lists for network attribute comparison.\n for (UtilityNetworkAttribute* networkAttribute : m_networkDefinition->networkAttributes())\n {\n if (!networkAttribute->isSystemDefined())\n m_attributeListModel.append(networkAttribute->name());\n }\n emit attributeListModelChanged();\n\n \/\/ Create a default starting location.\n const UtilityNetworkSource* networkSource = m_networkDefinition->networkSource(m_deviceTableName);\n const UtilityAssetGroup* assetGroup = networkSource->assetGroup(m_assetGroupName);\n UtilityAssetType* assetType = assetGroup->assetType(m_assetTypeName);\n m_utilityElementStartingLocation = m_utilityNetwork->createElementWithAssetType(assetType, m_gloabId);\n\n QList terminals = m_utilityElementStartingLocation->assetType()->terminalConfiguration()->terminals();\n\n \/\/ Set the terminal for this location. (For our case, we use the 'Load' terminal.)\n auto terminal = std::find_if(terminals.begin(), terminals.end(), [](UtilityTerminal* terminal)\n {\n return terminal->name() == \"Load\";\n });\n\n m_utilityElementStartingLocation->setTerminal(static_cast(*terminal));\n\n \/\/ Get a default trace configuration from a tier to update the UI.\n const UtilityDomainNetwork* domainNetwork = m_networkDefinition->domainNetwork(m_domainNetworkName);\n const UtilityTier* utilityTierSource = domainNetwork->tier(m_tierName);\n\n \/\/ Set the trace configuration.\n m_traceConfiguration = utilityTierSource->traceConfiguration();\n\n m_initialExpression = m_traceConfiguration->traversability()->barriers();\n\n if (m_initialExpression)\n {\n m_expressionBuilder = expressionToString(static_cast(m_initialExpression));\n emit expressionBuilderChanged();\n }\n\n \/\/ Set the traversability scope.\n utilityTierSource->traceConfiguration()->traversability()->setScope(UtilityTraversabilityScope::Junctions);\n}\n\nConfigureSubnetworkTrace::~ConfigureSubnetworkTrace() = default;\n\nvoid ConfigureSubnetworkTrace::init()\n{\n qmlRegisterType(\"Esri.Samples\", 1, 0, \"ConfigureSubnetworkTraceSample\");\n}\nadding checks and return\/\/ [WriteFile Name=ConfigureSubnetworkTrace, Category=Analysis]\n\/\/ [Legal]\n\/\/ Copyright 2020 Esri.\n\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/ [Legal]\n\n#ifdef PCH_BUILD\n#include \"pch.hpp\"\n#endif \/\/ PCH_BUILD\n\n#include \"ConfigureSubnetworkTrace.h\"\n\n#include \"CodedValueDomain.h\"\n#include \"TaskWatcher.h\"\n#include \"UtilityAssetGroup.h\"\n#include \"UtilityAssetType.h\"\n#include \"UtilityCategory.h\"\n#include \"UtilityCategoryComparison.h\"\n#include \"UtilityDomainNetwork.h\"\n#include \"UtilityElement.h\"\n#include \"UtilityElementTraceResult.h\"\n#include \"UtilityNetwork.h\"\n#include \"UtilityNetworkDefinition.h\"\n#include \"UtilityNetworkSource.h\"\n#include \"UtilityNetworkTypes.h\"\n#include \"UtilityTerminal.h\"\n#include \"UtilityTerminalConfiguration.h\"\n#include \"UtilityTier.h\"\n#include \"UtilityTraceAndCondition.h\"\n#include \"UtilityTraceConfiguration.h\"\n#include \"UtilityTraceOrCondition.h\"\n#include \"UtilityTraceParameters.h\"\n#include \"UtilityTraceResultListModel.h\"\n#include \"UtilityTraversability.h\"\n\n#include \n#include \n\nusing namespace Esri::ArcGISRuntime;\n\nConfigureSubnetworkTrace::ConfigureSubnetworkTrace(QObject* parent \/* = nullptr *\/):\n QObject(parent)\n{\n m_utilityNetwork = new UtilityNetwork(m_featureLayerUrl, this);\n\n connect(m_utilityNetwork, &UtilityNetwork::doneLoading, this, &ConfigureSubnetworkTrace::onUtilityNetworkLoaded);\n\n connect(m_utilityNetwork, &UtilityNetwork::traceCompleted, this, &ConfigureSubnetworkTrace::onTraceCompleted);\n\n m_utilityNetwork->load();\n}\n\nQString ConfigureSubnetworkTrace::expressionToString(UtilityTraceConditionalExpression* expression)\n{\n switch (expression->traceConditionType())\n {\n case UtilityTraceConditionType::UtilityNetworkAttributeComparison:\n {\n const UtilityNetworkAttributeComparison* attributeExpression = static_cast(expression);\n const UtilityNetworkAttribute* networkAttribute = attributeExpression->networkAttribute();\n const UtilityNetworkAttribute* otherNetworkAttribute = attributeExpression->otherNetworkAttribute();\n const Domain networkDomain = networkAttribute->domain();\n const QString operatorAsString = comparisonOperatorToString(attributeExpression->comparisonOperator());\n\n \/\/ check if attribute domain is a coded value domain.\n if (!networkDomain.isEmpty() && (networkDomain.domainType() == DomainType::CodedValueDomain))\n {\n const CodedValueDomain codedValueDomain = static_cast(networkDomain);\n const QList codedValues = codedValueDomain.codedValues();\n\n \/\/ get the coded value using the value as the index for the list of coded values\n const QString codedValueName = codedValues[attributeExpression->value().toInt()].name();\n\n return QString(\"`%1` %2 `%3`\").arg(networkAttribute->name(), operatorAsString, codedValueName);\n }\n else\n {\n if (otherNetworkAttribute)\n {\n return QString(\"`%1` %2 `%3`\").arg(networkAttribute->name(), operatorAsString, otherNetworkAttribute->name());\n }\n return QString(\"`%1` %2 `%3`\").arg(networkAttribute->name(), operatorAsString, attributeExpression->value().toString());\n }\n }\n case UtilityTraceConditionType::UtilityCategoryComparison:\n {\n const UtilityCategoryComparison* comparisonExpression = static_cast(expression);\n\n return QString(\"`%1` %2\").arg(comparisonExpression->category()->name(), (comparisonExpression->comparisonOperator() == UtilityCategoryComparisonOperator::Exists) ? \"Exists\" : \"DoesNotExist\");\n }\n case UtilityTraceConditionType::UtilityTraceAndCondition:\n {\n const UtilityTraceAndCondition* andExpression = static_cast(expression);\n\n return QString(\"(%1) AND\\n (%2)\").arg(expressionToString(andExpression->leftExpression()), expressionToString(andExpression->rightExpression()));\n }\n case UtilityTraceConditionType::UtilityTraceOrCondition:\n {\n const UtilityTraceOrCondition* orExpression = static_cast(expression);\n return QString(\"(%1) OR\\n (%2)\").arg(expressionToString(orExpression->leftExpression()), expressionToString(orExpression->rightExpression()));\n }\n default:\n return QString(\"Unknown trace conditional expression\");\n }\n}\n\nQString ConfigureSubnetworkTrace::comparisonOperatorToString(const UtilityAttributeComparisonOperator& comparisonOperator)\n{\n switch (comparisonOperator)\n {\n case UtilityAttributeComparisonOperator::Equal:\n return QString(\"Equal\");\n case UtilityAttributeComparisonOperator::NotEqual:\n return QString(\"NotEqual\");\n case UtilityAttributeComparisonOperator::GreaterThan:\n return QString(\"GreaterThan\");\n case UtilityAttributeComparisonOperator::GreaterThanEqual:\n return QString(\"GreaterThanEqual\");\n case UtilityAttributeComparisonOperator::LessThan:\n return QString(\"LessThan\");\n case UtilityAttributeComparisonOperator::LessThanEqual:\n return QString(\"LessThanEqual\");\n case UtilityAttributeComparisonOperator::IncludesTheValues:\n return QString(\"IncludesTheValues\");\n case UtilityAttributeComparisonOperator::DoesNotIncludeTheValues:\n return QString(\"DoesNotIncludeTheValues\");\n case UtilityAttributeComparisonOperator::IncludesAny:\n return QString(\"IncludesAny\");\n case UtilityAttributeComparisonOperator::DoesNotIncludeAny:\n return QString(\"DoesNotIncludeAny\");\n default:\n return QString(\"Unknown comparison operator\");\n }\n}\n\nQVariant ConfigureSubnetworkTrace::convertToDataType(const QVariant& value, const Esri::ArcGISRuntime::UtilityNetworkAttributeDataType& dataType)\n{\n switch (dataType)\n {\n case UtilityNetworkAttributeDataType::Integer:\n {\n \/\/ inconsistent results when using QVariant.toInt() on a\n \/\/ QString that doesn't contain an Integer dataType.\n \/\/ e.g. QVariant(QString(\"123.321\")).toInt();\n return static_cast(value.toDouble());\n }\n case UtilityNetworkAttributeDataType::Float:\n {\n return value.toFloat();\n }\n case UtilityNetworkAttributeDataType::Double:\n {\n return value.toDouble();\n }\n case UtilityNetworkAttributeDataType::Boolean:\n {\n return value.toBool();\n }\n default:\n return QVariant();\n }\n}\n\nvoid ConfigureSubnetworkTrace::codedValueOrInputText(const QString& currentText)\n{\n \/\/ Update the UI to show the correct value entry for the attribute.\n if (m_networkDefinition)\n {\n const Domain domain = m_networkDefinition->networkAttribute(currentText)->domain();\n if (!domain.isEmpty() && (domain.domainType() == DomainType::CodedValueDomain))\n {\n m_valueSelectionListModel.clear();\n const CodedValueDomain codedValueDomain = static_cast(domain);\n\n for (CodedValue codedValue: codedValueDomain.codedValues())\n m_valueSelectionListModel.append(codedValue.name());\n\n m_textFieldVisible = false;\n }\n else\n {\n m_textFieldVisible = true;\n }\n emit valueSelectionListModelChanged();\n emit textFieldVisibleChanged();\n }\n}\n\nvoid ConfigureSubnetworkTrace::addCondition(const QString& selectedAttribute, int selectedOperator, const QVariant& selectedValue)\n{\n \/\/ NOTE: You may also create a UtilityCategoryComparison with UtilityNetworkDefinition.Categories and UtilityCategoryComparisonOperator.\n\n UtilityNetworkAttribute* selectedNetworkAttribute = m_networkDefinition->networkAttribute(selectedAttribute);\n const QVariant convertedSelectedValue = convertToDataType(selectedValue, selectedNetworkAttribute->dataType());\n\n if (convertedSelectedValue.isNull())\n {\n m_dialogText = \"Unknow network attribute data type\";\n emit dialogTextChanged();\n emit showDialog();\n return;\n }\n\n const UtilityAttributeComparisonOperator selectedOperatorEnum = static_cast(selectedOperator);\n\n \/\/ NOTE: You may also create a UtilityNetworkAttributeComparison with another NetworkAttribute.\n UtilityTraceConditionalExpression* expression = new UtilityNetworkAttributeComparison(selectedNetworkAttribute, selectedOperatorEnum, convertedSelectedValue, this);\n\n UtilityTraceConditionalExpression* otherExpression = static_cast(m_traceConfiguration->traversability()->barriers());\n\n \/\/ NOTE: You may also combine expressions with UtilityTraceAndCondition\n UtilityTraceConditionalExpression* combineExpressions = new UtilityTraceOrCondition(otherExpression, expression, this);\n\n m_expressionBuilder = expressionToString(combineExpressions);\n emit expressionBuilderChanged();\n\n if (m_traceConfiguration)\n m_traceConfiguration->traversability()->setBarriers(combineExpressions);\n}\n\nvoid ConfigureSubnetworkTrace::changeIncludeBarriersState(bool includeBarriers)\n{\n if (m_traceConfiguration)\n m_traceConfiguration->setIncludeBarriers(includeBarriers);\n}\n\nvoid ConfigureSubnetworkTrace::changeIncludeContainersState(bool includeContainers)\n{\n if (m_traceConfiguration)\n m_traceConfiguration->setIncludeContainers(includeContainers);\n}\n\nvoid ConfigureSubnetworkTrace::reset()\n{\n \/\/ Reset the barrier condition to the initial value.\n m_traceConfiguration->traversability()->setBarriers(m_initialExpression);\n m_expressionBuilder.clear();\n m_expressionBuilder = expressionToString(static_cast(m_initialExpression));\n emit expressionBuilderChanged();\n}\n\nvoid ConfigureSubnetworkTrace::trace()\n{\n if (!m_utilityNetwork || !m_utilityElementStartingLocation)\n {\n return;\n }\n\n m_busy = true;\n emit busyChanged();\n const QList startingLocations {m_utilityElementStartingLocation};\n \/\/ Create utility trace parameters for the starting location.\n m_traceParams = new UtilityTraceParameters(UtilityTraceType::Subnetwork, startingLocations, this);\n m_traceParams->setTraceConfiguration(m_traceConfiguration);\n\n \/\/ trace the network\n m_utilityNetwork->trace(m_traceParams);\n}\n\nvoid ConfigureSubnetworkTrace::onTraceCompleted()\n{\n if (m_utilityNetwork->traceResult()->isEmpty())\n {\n m_dialogText = \"No results returned\";\n emit dialogTextChanged();\n emit showDialog();\n return;\n }\n \/\/ Get the first result.\n UtilityTraceResult* result = m_utilityNetwork->traceResult()->at(0);\n\n const QList elements = static_cast(result)->elements(this);\n\n \/\/ Display the number of elements found by the trace.\n m_dialogText = QString(\"%1 elements found.\").arg(elements.length());\n m_busy = false;\n emit dialogTextChanged();\n emit showDialog();\n emit busyChanged();\n}\n\nvoid ConfigureSubnetworkTrace::onUtilityNetworkLoaded(const Error& e)\n{\n if (!e.isEmpty())\n {\n m_dialogText = QString(\"%1 - %2\").arg(e.message(), e.additionalMessage());\n m_busy = false;\n emit dialogTextChanged();\n emit showDialog();\n emit busyChanged();\n return;\n }\n\n m_busy = false;\n emit busyChanged();\n m_networkDefinition = m_utilityNetwork->definition();\n\n \/\/ Build the choice lists for network attribute comparison.\n for (UtilityNetworkAttribute* networkAttribute : m_networkDefinition->networkAttributes())\n {\n if (!networkAttribute->isSystemDefined())\n m_attributeListModel.append(networkAttribute->name());\n }\n emit attributeListModelChanged();\n\n \/\/ Create a default starting location.\n const UtilityNetworkSource* networkSource = m_networkDefinition->networkSource(m_deviceTableName);\n const UtilityAssetGroup* assetGroup = networkSource->assetGroup(m_assetGroupName);\n UtilityAssetType* assetType = assetGroup->assetType(m_assetTypeName);\n m_utilityElementStartingLocation = m_utilityNetwork->createElementWithAssetType(assetType, m_gloabId);\n\n QList terminals = m_utilityElementStartingLocation->assetType()->terminalConfiguration()->terminals();\n\n \/\/ Set the terminal for this location. (For our case, we use the 'Load' terminal.)\n auto terminal = std::find_if(terminals.begin(), terminals.end(), [](UtilityTerminal* terminal)\n {\n return terminal->name() == \"Load\";\n });\n\n m_utilityElementStartingLocation->setTerminal(static_cast(*terminal));\n\n \/\/ Get a default trace configuration from a tier to update the UI.\n const UtilityDomainNetwork* domainNetwork = m_networkDefinition->domainNetwork(m_domainNetworkName);\n const UtilityTier* utilityTierSource = domainNetwork->tier(m_tierName);\n\n \/\/ Set the trace configuration.\n m_traceConfiguration = utilityTierSource->traceConfiguration();\n\n m_initialExpression = m_traceConfiguration->traversability()->barriers();\n\n if (m_initialExpression)\n {\n m_expressionBuilder = expressionToString(static_cast(m_initialExpression));\n emit expressionBuilderChanged();\n }\n\n \/\/ Set the traversability scope.\n utilityTierSource->traceConfiguration()->traversability()->setScope(UtilityTraversabilityScope::Junctions);\n}\n\nConfigureSubnetworkTrace::~ConfigureSubnetworkTrace() = default;\n\nvoid ConfigureSubnetworkTrace::init()\n{\n qmlRegisterType(\"Esri.Samples\", 1, 0, \"ConfigureSubnetworkTraceSample\");\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n E12 - Etat de l'analyseur\n -------------------\n début : 8 mars 2016 10:43:21\n copyright : (C) 2016 par H4112\n*************************************************************************\/\n\n\/\/---------- Réalisation de la classe (fichier E12.cpp) --\n\n\/\/---------------------------------------------------------------- INCLUDE\n\n\/\/-------------------------------------------------------- Include système\n#include \nusing namespace std;\n\n\/\/------------------------------------------------------ Include personnel\n#include \"E12.h\"\n\n\/\/------------------------------------------------------------- Constantes\n\n\/\/---------------------------------------------------- Variables de classe\n\n\/\/----------------------------------------------------------- Types privés\n\n\n\/\/----------------------------------------------------------------- PUBLIC\n\/\/-------------------------------------------------------- Fonctions amies\n\n\/\/----------------------------------------------------- Méthodes publiques\nvoid E12::Print ( ) const \n{\n\tcout << \"E12\" << endl;\n}\n\nbool E12::Transition ( Automate & automate, Symbole * s )\n{\n\tswitch(*s)\n\t{\n\t\tcase VIRGULE:\n\t\tcase POINT_VIRGULE:\n\t\t{\n\t\t\tSymbole * id = automate.PopSymbole();\n\n\t\t\tSymbole * nouveauSymbole;\n\t\t\t\/\/TODO remplir cette variable pour réduire R6\n\t\t\tautomate.Reduction(nouveauSymbole, 1);\n\t\t\treturn true;\n\t\t}\n\t}\n\t\n\treturn false;\n}\n\n\/\/------------------------------------------------- Surcharge d'opérateurs\n\n\/\/-------------------------------------------- Constructeurs - destructeur\nE12::E12 ( const E12 & unE12 )\n\t: Etat ( unE12 )\n{\n#ifdef MAP\n cout << \"Appel au constructeur de copie de \" << endl;\n#endif\n} \/\/----- Fin de E12 (constructeur de copie)\n\n\nE12::E12 ( )\n\t: Etat ( )\n{\n#ifdef MAP\n cout << \"Appel au constructeur de \" << endl;\n#endif\n} \/\/----- Fin de E12\n\n\nE12::~E12 ( )\n{\n#ifdef MAP\n cout << \"Appel au destructeur de \" << endl;\n#endif\n} \/\/----- Fin de ~E12\n\n\n\/\/------------------------------------------------------------------ PRIVE\n\n\/\/----------------------------------------------------- Méthodes protégées\n\n\/\/------------------------------------------------------- Méthodes privées\nÉtat E12\/*************************************************************************\n E12 - Etat de l'analyseur\n -------------------\n début : 8 mars 2016 10:43:21\n copyright : (C) 2016 par H4112\n*************************************************************************\/\n\n\/\/---------- Réalisation de la classe (fichier E12.cpp) --\n\n\/\/---------------------------------------------------------------- INCLUDE\n\n\/\/-------------------------------------------------------- Include système\n#include \nusing namespace std;\n\n\/\/------------------------------------------------------ Include personnel\n#include \"E12.h\"\n\n#include \"..\/symboles\/ListeIdentifiants.h\"\n#include \"..\/symboles\/Identifiant.h\"\n\n\/\/------------------------------------------------------------- Constantes\n\n\/\/---------------------------------------------------- Variables de classe\n\n\/\/----------------------------------------------------------- Types privés\n\n\n\/\/----------------------------------------------------------------- PUBLIC\n\/\/-------------------------------------------------------- Fonctions amies\n\n\/\/----------------------------------------------------- Méthodes publiques\nvoid E12::Print ( ) const \n{\n\tcout << \"E12\" << endl;\n}\n\nbool E12::Transition ( Automate & automate, Symbole * s )\n{\n\tswitch(*s)\n\t{\n\t\tcase VIRGULE:\n\t\tcase POINT_VIRGULE:\n\t\t{\n\t\t\tIdentifiant * id = (Identifiant *) automate.PopSymbole();\n\n\t\t\tListeIdentifiants * lid = new ListeIdentifiants();\n\t\t\tlid->AjouterVariable(id);\n\t\t\t\n\t\t\tdelete id;\n\t\t\t\n\t\t\t\/\/réduire R6\n\t\t\tautomate.Reduction(lid, 1);\n\t\t\treturn true;\n\t\t}\n\t}\n\t\n\treturn false;\n}\n\n\/\/------------------------------------------------- Surcharge d'opérateurs\n\n\/\/-------------------------------------------- Constructeurs - destructeur\nE12::E12 ( const E12 & unE12 )\n\t: Etat ( unE12 )\n{\n#ifdef MAP\n cout << \"Appel au constructeur de copie de \" << endl;\n#endif\n} \/\/----- Fin de E12 (constructeur de copie)\n\n\nE12::E12 ( )\n\t: Etat ( )\n{\n#ifdef MAP\n cout << \"Appel au constructeur de \" << endl;\n#endif\n} \/\/----- Fin de E12\n\n\nE12::~E12 ( )\n{\n#ifdef MAP\n cout << \"Appel au destructeur de \" << endl;\n#endif\n} \/\/----- Fin de ~E12\n\n\n\/\/------------------------------------------------------------------ PRIVE\n\n\/\/----------------------------------------------------- Méthodes protégées\n\n\/\/------------------------------------------------------- Méthodes privées\n<|endoftext|>"} {"text":"\/*\n * yosys -- Yosys Open SYnthesis Suite\n *\n * Copyright (C) 2012 Clifford Wolf \n * \n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \"kernel\/register.h\"\n#include \"kernel\/celltypes.h\"\n#include \"kernel\/rtlil.h\"\n#include \"kernel\/log.h\"\n\nUSING_YOSYS_NAMESPACE\nPRIVATE_NAMESPACE_BEGIN\n\nbool check_label(bool &active, std::string run_from, std::string run_to, std::string label)\n{\n\tif (!run_from.empty() && run_from == run_to) {\n\t\tactive = (label == run_from);\n\t} else {\n\t\tif (label == run_from)\n\t\t\tactive = true;\n\t\tif (label == run_to)\n\t\t\tactive = false;\n\t}\n\treturn active;\n}\n\nstruct SynthPass : public Pass {\n\tSynthPass() : Pass(\"synth\", \"generic synthesis script\") { }\n\tvirtual void help()\n\t{\n\t\t\/\/ |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n\t\tlog(\"\\n\");\n\t\tlog(\" synth [options]\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"This command runs the default synthesis script. This command does not operate\\n\");\n\t\tlog(\"on partly selected designs.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -top \\n\");\n\t\tlog(\" use the specified module as top module (default='top')\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -encfile \\n\");\n\t\tlog(\" passed to 'fsm_recode' via 'fsm'\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -noabc\\n\");\n\t\tlog(\" do not run abc (as if yosys was compiled without ABC support)\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -run [:]\\n\");\n\t\tlog(\" only run the commands between the labels (see below). an empty\\n\");\n\t\tlog(\" from label is synonymous to 'begin', and empty to label is\\n\");\n\t\tlog(\" synonymous to the end of the command list.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"The following commands are executed by this synthesis command:\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" begin:\\n\");\n\t\tlog(\" hierarchy -check [-top ]\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" coarse:\\n\");\n\t\tlog(\" proc\\n\");\n\t\tlog(\" opt_clean\\n\");\n\t\tlog(\" check\\n\");\n\t\tlog(\" opt\\n\");\n\t\tlog(\" wreduce\\n\");\n\t\tlog(\" alumacc\\n\");\n\t\tlog(\" share\\n\");\n\t\tlog(\" opt\\n\");\n\t\tlog(\" fsm\\n\");\n\t\tlog(\" opt -fast\\n\");\n\t\tlog(\" memory -nomap\\n\");\n\t\tlog(\" opt_clean\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" fine:\\n\");\n\t\tlog(\" opt -fast -full\\n\");\n\t\tlog(\" memory_map\\n\");\n\t\tlog(\" opt -full\\n\");\n\t\tlog(\" techmap\\n\");\n\t\tlog(\" opt -fast\\n\");\n\t#ifdef YOSYS_ENABLE_ABC\n\t\tlog(\" abc -fast\\n\");\n\t\tlog(\" opt -fast\\n\");\n\t#endif\n\t\tlog(\"\\n\");\n\t\tlog(\" check:\\n\");\n\t\tlog(\" hierarchy -check\\n\");\n\t\tlog(\" stat\\n\");\n\t\tlog(\" check\\n\");\n\t\tlog(\"\\n\");\n\t}\n\tvirtual void execute(std::vector args, RTLIL::Design *design)\n\t{\n\t\tstd::string top_module, fsm_opts;\n\t\tstd::string run_from, run_to;\n\t\tbool noabc = false;\n\n\t\tsize_t argidx;\n\t\tfor (argidx = 1; argidx < args.size(); argidx++)\n\t\t{\n\t\t\tif (args[argidx] == \"-top\" && argidx+1 < args.size()) {\n\t\t\t\ttop_module = args[++argidx];\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-encfile\" && argidx+1 < args.size()) {\n\t\t\t\tfsm_opts = \" -encfile \" + args[++argidx];\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-run\" && argidx+1 < args.size()) {\n\t\t\t\tsize_t pos = args[argidx+1].find(':');\n\t\t\t\tif (pos == std::string::npos) {\n\t\t\t\t\trun_from = args[++argidx];\n\t\t\t\t\trun_to = args[argidx];\n\t\t\t\t} else {\n\t\t\t\t\trun_from = args[++argidx].substr(0, pos);\n\t\t\t\t\trun_to = args[argidx].substr(pos+1);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-noabc\") {\n\t\t\t\tnoabc = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\textra_args(args, argidx, design);\n\n\t\tif (!design->full_selection())\n\t\t\tlog_cmd_error(\"This comannd only operates on fully selected designs!\\n\");\n\n\t\tbool active = run_from.empty();\n\n\t\tlog_header(\"Executing SYNTH pass.\\n\");\n\t\tlog_push();\n\n\t\tif (check_label(active, run_from, run_to, \"begin\"))\n\t\t{\n\t\t\tif (top_module.empty())\n\t\t\t\tPass::call(design, stringf(\"hierarchy -check\"));\n\t\t\telse\n\t\t\t\tPass::call(design, stringf(\"hierarchy -check -top %s\", top_module.c_str()));\n\t\t}\n\n\t\tif (check_label(active, run_from, run_to, \"coarse\"))\n\t\t{\n\t\t\tPass::call(design, \"proc\");\n\t\t\tPass::call(design, \"opt_clean\");\n\t\t\tPass::call(design, \"check\");\n\t\t\tPass::call(design, \"opt\");\n\t\t\tPass::call(design, \"wreduce\");\n\t\t\tPass::call(design, \"alumacc\");\n\t\t\tPass::call(design, \"share\");\n\t\t\tPass::call(design, \"opt\");\n\t\t\tPass::call(design, \"fsm\" + fsm_opts);\n\t\t\tPass::call(design, \"opt -fast\");\n\t\t\tPass::call(design, \"memory -nomap\");\n\t\t\tPass::call(design, \"opt_clean\");\n\t\t}\n\n\t\tif (check_label(active, run_from, run_to, \"fine\"))\n\t\t{\n\t\t\tPass::call(design, \"opt -fast -full\");\n\t\t\tPass::call(design, \"memory_map\");\n\t\t\tPass::call(design, \"opt -full\");\n\t\t\tPass::call(design, \"techmap\");\n\t\t\tPass::call(design, \"opt -fast\");\n\n\t\t\tif (!noabc) {\n\t\t#ifdef YOSYS_ENABLE_ABC\n\t\t\t\tPass::call(design, \"abc -fast\");\n\t\t\t\tPass::call(design, \"opt -fast\");\n\t\t#endif\n\t\t\t}\n\t\t}\n\n\t\tif (check_label(active, run_from, run_to, \"check\"))\n\t\t{\n\t\t\tPass::call(design, \"hierarchy -check\");\n\t\t\tPass::call(design, \"stat\");\n\t\t\tPass::call(design, \"check\");\n\t\t}\n\n\t\tlog_pop();\n\t}\n} SynthPass;\n \nPRIVATE_NAMESPACE_END\nAdded \"synth -nordff -noalumacc\"\/*\n * yosys -- Yosys Open SYnthesis Suite\n *\n * Copyright (C) 2012 Clifford Wolf \n * \n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \"kernel\/register.h\"\n#include \"kernel\/celltypes.h\"\n#include \"kernel\/rtlil.h\"\n#include \"kernel\/log.h\"\n\nUSING_YOSYS_NAMESPACE\nPRIVATE_NAMESPACE_BEGIN\n\nbool check_label(bool &active, std::string run_from, std::string run_to, std::string label)\n{\n\tif (!run_from.empty() && run_from == run_to) {\n\t\tactive = (label == run_from);\n\t} else {\n\t\tif (label == run_from)\n\t\t\tactive = true;\n\t\tif (label == run_to)\n\t\t\tactive = false;\n\t}\n\treturn active;\n}\n\nstruct SynthPass : public Pass {\n\tSynthPass() : Pass(\"synth\", \"generic synthesis script\") { }\n\tvirtual void help()\n\t{\n\t\t\/\/ |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n\t\tlog(\"\\n\");\n\t\tlog(\" synth [options]\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"This command runs the default synthesis script. This command does not operate\\n\");\n\t\tlog(\"on partly selected designs.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -top \\n\");\n\t\tlog(\" use the specified module as top module (default='top')\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -encfile \\n\");\n\t\tlog(\" passed to 'fsm_recode' via 'fsm'\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -noabc\\n\");\n\t\tlog(\" do not run abc (as if yosys was compiled without ABC support)\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -noalumacc\\n\");\n\t\tlog(\" do not run 'alumacc' pass. i.e. keep arithmetic operators in\\n\");\n\t\tlog(\" their direct form ($add, $sub, etc.).\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -nordff\\n\");\n\t\tlog(\" passed to 'memory'. prohibits merging of FFs into memory read ports\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -run [:]\\n\");\n\t\tlog(\" only run the commands between the labels (see below). an empty\\n\");\n\t\tlog(\" from label is synonymous to 'begin', and empty to label is\\n\");\n\t\tlog(\" synonymous to the end of the command list.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"The following commands are executed by this synthesis command:\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" begin:\\n\");\n\t\tlog(\" hierarchy -check [-top ]\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" coarse:\\n\");\n\t\tlog(\" proc\\n\");\n\t\tlog(\" opt_clean\\n\");\n\t\tlog(\" check\\n\");\n\t\tlog(\" opt\\n\");\n\t\tlog(\" wreduce\\n\");\n\t\tlog(\" alumacc\\n\");\n\t\tlog(\" share\\n\");\n\t\tlog(\" opt\\n\");\n\t\tlog(\" fsm\\n\");\n\t\tlog(\" opt -fast\\n\");\n\t\tlog(\" memory -nomap\\n\");\n\t\tlog(\" opt_clean\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" fine:\\n\");\n\t\tlog(\" opt -fast -full\\n\");\n\t\tlog(\" memory_map\\n\");\n\t\tlog(\" opt -full\\n\");\n\t\tlog(\" techmap\\n\");\n\t\tlog(\" opt -fast\\n\");\n\t#ifdef YOSYS_ENABLE_ABC\n\t\tlog(\" abc -fast\\n\");\n\t\tlog(\" opt -fast\\n\");\n\t#endif\n\t\tlog(\"\\n\");\n\t\tlog(\" check:\\n\");\n\t\tlog(\" hierarchy -check\\n\");\n\t\tlog(\" stat\\n\");\n\t\tlog(\" check\\n\");\n\t\tlog(\"\\n\");\n\t}\n\tvirtual void execute(std::vector args, RTLIL::Design *design)\n\t{\n\t\tstd::string top_module, fsm_opts, memory_opts;\n\t\tstd::string run_from, run_to;\n\t\tbool noalumacc = false;\n\t\tbool noabc = false;\n\n\t\tsize_t argidx;\n\t\tfor (argidx = 1; argidx < args.size(); argidx++)\n\t\t{\n\t\t\tif (args[argidx] == \"-top\" && argidx+1 < args.size()) {\n\t\t\t\ttop_module = args[++argidx];\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-encfile\" && argidx+1 < args.size()) {\n\t\t\t\tfsm_opts = \" -encfile \" + args[++argidx];\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-run\" && argidx+1 < args.size()) {\n\t\t\t\tsize_t pos = args[argidx+1].find(':');\n\t\t\t\tif (pos == std::string::npos) {\n\t\t\t\t\trun_from = args[++argidx];\n\t\t\t\t\trun_to = args[argidx];\n\t\t\t\t} else {\n\t\t\t\t\trun_from = args[++argidx].substr(0, pos);\n\t\t\t\t\trun_to = args[argidx].substr(pos+1);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-noabc\") {\n\t\t\t\tnoabc = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-noalumacc\") {\n\t\t\t\tnoalumacc = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-nordff\") {\n\t\t\t\tmemory_opts += \" -nordff\";\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\textra_args(args, argidx, design);\n\n\t\tif (!design->full_selection())\n\t\t\tlog_cmd_error(\"This comannd only operates on fully selected designs!\\n\");\n\n\t\tbool active = run_from.empty();\n\n\t\tlog_header(\"Executing SYNTH pass.\\n\");\n\t\tlog_push();\n\n\t\tif (check_label(active, run_from, run_to, \"begin\"))\n\t\t{\n\t\t\tif (top_module.empty())\n\t\t\t\tPass::call(design, stringf(\"hierarchy -check\"));\n\t\t\telse\n\t\t\t\tPass::call(design, stringf(\"hierarchy -check -top %s\", top_module.c_str()));\n\t\t}\n\n\t\tif (check_label(active, run_from, run_to, \"coarse\"))\n\t\t{\n\t\t\tPass::call(design, \"proc\");\n\t\t\tPass::call(design, \"opt_clean\");\n\t\t\tPass::call(design, \"check\");\n\t\t\tPass::call(design, \"opt\");\n\t\t\tPass::call(design, \"wreduce\");\n\t\t\tif (!noalumacc)\n\t\t\t\tPass::call(design, \"alumacc\");\n\t\t\tPass::call(design, \"share\");\n\t\t\tPass::call(design, \"opt\");\n\t\t\tPass::call(design, \"fsm\" + fsm_opts);\n\t\t\tPass::call(design, \"opt -fast\");\n\t\t\tPass::call(design, \"memory -nomap\" + memory_opts);\n\t\t\tPass::call(design, \"opt_clean\");\n\t\t}\n\n\t\tif (check_label(active, run_from, run_to, \"fine\"))\n\t\t{\n\t\t\tPass::call(design, \"opt -fast -full\");\n\t\t\tPass::call(design, \"memory_map\");\n\t\t\tPass::call(design, \"opt -full\");\n\t\t\tPass::call(design, \"techmap\");\n\t\t\tPass::call(design, \"opt -fast\");\n\n\t\t\tif (!noabc) {\n\t\t#ifdef YOSYS_ENABLE_ABC\n\t\t\t\tPass::call(design, \"abc -fast\");\n\t\t\t\tPass::call(design, \"opt -fast\");\n\t\t#endif\n\t\t\t}\n\t\t}\n\n\t\tif (check_label(active, run_from, run_to, \"check\"))\n\t\t{\n\t\t\tPass::call(design, \"hierarchy -check\");\n\t\t\tPass::call(design, \"stat\");\n\t\t\tPass::call(design, \"check\");\n\t\t}\n\n\t\tlog_pop();\n\t}\n} SynthPass;\n \nPRIVATE_NAMESPACE_END\n<|endoftext|>"} {"text":"#include \"command.h\"\n\n#include \n\n#include \"engine\/util.h\"\n\n\nCommand::Command(Player *player, QObject *parent) :\n QObject(parent),\n m_player(player) {\n\n Q_ASSERT(m_player);\n}\n\nCommand::~Command() {\n}\n\nvoid Command::setDescription(const QString &description) {\n\n m_description = description;\n}\n\nvoid Command::setCommand(const QString &_command) {\n\n QRegExp whitespace(\"\\\\s+\");\n QString command = _command.trimmed();\n\n m_words = command.split(whitespace);\n if (m_player->isAdmin()) {\n if (m_words[0] == \"exec-script\") {\n m_words.clear();\n m_words << command.section(whitespace, 0, 0);\n m_words << command.section(whitespace, 1);\n return;\n }\n if (m_words[0] == \"get-trigger\" || m_words[0] == \"set-trigger\") {\n m_words.clear();\n m_words << command.section(whitespace, 0, 0);\n m_words << command.section(whitespace, 1, 1);\n m_words << command.section(whitespace, 2, 2);\n if (m_words.last().toInt() > 0) {\n m_words << command.section(whitespace, 3, 3);\n m_words << command.section(whitespace, 4);\n } else {\n m_words << command.section(whitespace, 3);\n }\n return;\n }\n if (m_words[0] == \"set-prop\" &&\n m_words.length() >= 3 && m_words[2] == \"description\") {\n return;\n }\n }\n\n for (int i = 0; i < m_words.length(); i++) {\n QString word = m_words[i];\n if (word.startsWith(\"\\\"\")) {\n while (i < m_words.length() - 1 && !word.endsWith(\"\\\"\")) {\n word += \" \" + m_words[i + 1];\n m_words.removeAt(i);\n }\n if (word.endsWith(\"\\\"\")) {\n m_words[i] = word.mid(1, word.length() - 2);\n } else {\n m_words[i] = word.mid(1);\n }\n }\n }\n}\n\nvoid Command::prependWord(const QString &word) {\n\n m_words.prepend(word);\n}\n\nvoid Command::appendWord(const QString &word) {\n\n m_words.append(word);\n}\n\nbool Command::assertWordsLeft(const QString &noneLeftText) {\n\n if (!hasWordsLeft()) {\n m_player->send(noneLeftText);\n return false;\n } else {\n return true;\n }\n}\n\nQString Command::takeWord(Options options) {\n\n if (m_words.length() > 0) {\n if (options & IfNotLast && m_words.length() == 1) {\n return QString();\n }\n return m_words.takeFirst();\n }\n\n return QString();\n}\n\nQString Command::takeWord(const char *pattern, Options options) {\n\n return takeWord(QRegExp(QString(pattern)), options);\n}\n\nQString Command::takeWord(const QRegExp &pattern, Options options) {\n\n if (m_words.length() > 0) {\n if (options & IfNotLast && m_words.length() == 1) {\n return QString();\n }\n if (pattern.exactMatch(m_words[0])) {\n return m_words.takeFirst();\n }\n }\n\n return QString();\n}\n\nGameObjectPtr Command::takeObject(const GameObjectPtrList &pool) {\n\n QPair description = takeObjectsDescription();\n if (!description.first.isEmpty()) {\n GameObjectPtrList objects = objectsByDescription(description, pool);\n if (objects.length() > 0) {\n return objects[0];\n }\n }\n\n return GameObjectPtr();\n}\n\nGameObjectPtrList Command::takeObjects(const GameObjectPtrList &pool) {\n\n QPair description = takeObjectsDescription();\n if (!description.first.isEmpty()) {\n return objectsByDescription(description, pool);\n }\n\n return GameObjectPtrList();\n}\n\nQPair Command::takeObjectsDescription() {\n\n QPair description;\n if (m_words.length() > 0) {\n description.first = m_words.takeFirst().toLower();\n if (m_words.length() > 0) {\n description.second = m_words.first().toInt();\n if (description.second > 0) {\n m_words.removeFirst();\n }\n }\n }\n return description;\n}\n\nQString Command::takeRest() {\n\n QString rest = m_words.join(\" \");\n m_words.clear();\n return rest;\n}\n\nGameObjectPtrList Command::objectsByDescription(const QPair &description,\n const GameObjectPtrList &pool) {\n\n GameObjectPtrList objects;\n if (description.first == \"all\") {\n objects = pool;\n } else {\n for (const GameObjectPtr &object : pool) {\n QString loweredName = object->name().toLower();\n if (loweredName == description.first) {\n objects.clear();\n objects << object;\n break;\n }\n for (const QString &word : loweredName.split(' ')) {\n if (word.startsWith(description.first)) {\n objects << object;\n break;\n }\n }\n }\n }\n if (description.second > 0) {\n if (description.second <= (uint) objects.length()) {\n GameObjectPtr selected = objects[description.second - 1];\n objects.clear();\n objects << selected;\n } else {\n objects.clear();\n }\n }\n return objects;\n}\n\nbool Command::requireSome(const GameObjectPtr &object, const QString &tooFewText) {\n\n if (object.isNull()) {\n m_player->send(tooFewText);\n return false;\n } else {\n return true;\n }\n}\n\nbool Command::requireSome(const GameObjectPtrList &objects,\n const QString &tooFewText) {\n\n if (objects.length() == 0) {\n m_player->send(tooFewText);\n return false;\n } else {\n return true;\n }\n}\n\nbool Command::requireUnique(const GameObjectPtrList &objects,\n const QString &tooFewText,\n const QString &tooManyText) {\n\n if (objects.length() == 0) {\n m_player->send(tooFewText);\n return false;\n } else if (objects.length() > 1) {\n m_player->send(tooManyText);\n return false;\n } else {\n return true;\n }\n}\nDon't be an ass when there are multiple exits with the same name.#include \"command.h\"\n\n#include \n\n#include \"engine\/util.h\"\n\n\nCommand::Command(Player *player, QObject *parent) :\n QObject(parent),\n m_player(player) {\n\n Q_ASSERT(m_player);\n}\n\nCommand::~Command() {\n}\n\nvoid Command::setDescription(const QString &description) {\n\n m_description = description;\n}\n\nvoid Command::setCommand(const QString &_command) {\n\n QRegExp whitespace(\"\\\\s+\");\n QString command = _command.trimmed();\n\n m_words = command.split(whitespace);\n if (m_player->isAdmin()) {\n if (m_words[0] == \"exec-script\") {\n m_words.clear();\n m_words << command.section(whitespace, 0, 0);\n m_words << command.section(whitespace, 1);\n return;\n }\n if (m_words[0] == \"get-trigger\" || m_words[0] == \"set-trigger\") {\n m_words.clear();\n m_words << command.section(whitespace, 0, 0);\n m_words << command.section(whitespace, 1, 1);\n m_words << command.section(whitespace, 2, 2);\n if (m_words.last().toInt() > 0) {\n m_words << command.section(whitespace, 3, 3);\n m_words << command.section(whitespace, 4);\n } else {\n m_words << command.section(whitespace, 3);\n }\n return;\n }\n if (m_words[0] == \"set-prop\" &&\n m_words.length() >= 3 && m_words[2] == \"description\") {\n return;\n }\n }\n\n for (int i = 0; i < m_words.length(); i++) {\n QString word = m_words[i];\n if (word.startsWith(\"\\\"\")) {\n while (i < m_words.length() - 1 && !word.endsWith(\"\\\"\")) {\n word += \" \" + m_words[i + 1];\n m_words.removeAt(i);\n }\n if (word.endsWith(\"\\\"\")) {\n m_words[i] = word.mid(1, word.length() - 2);\n } else {\n m_words[i] = word.mid(1);\n }\n }\n }\n}\n\nvoid Command::prependWord(const QString &word) {\n\n m_words.prepend(word);\n}\n\nvoid Command::appendWord(const QString &word) {\n\n m_words.append(word);\n}\n\nbool Command::assertWordsLeft(const QString &noneLeftText) {\n\n if (!hasWordsLeft()) {\n m_player->send(noneLeftText);\n return false;\n } else {\n return true;\n }\n}\n\nQString Command::takeWord(Options options) {\n\n if (m_words.length() > 0) {\n if (options & IfNotLast && m_words.length() == 1) {\n return QString();\n }\n return m_words.takeFirst();\n }\n\n return QString();\n}\n\nQString Command::takeWord(const char *pattern, Options options) {\n\n return takeWord(QRegExp(QString(pattern)), options);\n}\n\nQString Command::takeWord(const QRegExp &pattern, Options options) {\n\n if (m_words.length() > 0) {\n if (options & IfNotLast && m_words.length() == 1) {\n return QString();\n }\n if (pattern.exactMatch(m_words[0])) {\n return m_words.takeFirst();\n }\n }\n\n return QString();\n}\n\nGameObjectPtr Command::takeObject(const GameObjectPtrList &pool) {\n\n QPair description = takeObjectsDescription();\n if (!description.first.isEmpty()) {\n GameObjectPtrList objects = objectsByDescription(description, pool);\n if (objects.length() > 0) {\n return objects[0];\n }\n }\n\n return GameObjectPtr();\n}\n\nGameObjectPtrList Command::takeObjects(const GameObjectPtrList &pool) {\n\n QPair description = takeObjectsDescription();\n if (!description.first.isEmpty()) {\n return objectsByDescription(description, pool);\n }\n\n return GameObjectPtrList();\n}\n\nQPair Command::takeObjectsDescription() {\n\n QPair description;\n if (m_words.length() > 0) {\n description.first = m_words.takeFirst().toLower();\n if (m_words.length() > 0) {\n description.second = m_words.first().toInt();\n if (description.second > 0) {\n m_words.removeFirst();\n }\n }\n }\n return description;\n}\n\nQString Command::takeRest() {\n\n QString rest = m_words.join(\" \");\n m_words.clear();\n return rest;\n}\n\nGameObjectPtrList Command::objectsByDescription(const QPair &description,\n const GameObjectPtrList &pool) {\n\n GameObjectPtrList objects;\n if (description.first == \"all\") {\n objects = pool;\n } else {\n for (const GameObjectPtr &object : pool) {\n QString loweredName = object->name().toLower();\n for (const QString &word : loweredName.split(' ')) {\n if (word.startsWith(description.first)) {\n objects << object;\n break;\n }\n }\n }\n }\n if (description.second > 0) {\n if (description.second <= (uint) objects.length()) {\n GameObjectPtr selected = objects[description.second - 1];\n objects.clear();\n objects << selected;\n } else {\n objects.clear();\n }\n }\n return objects;\n}\n\nbool Command::requireSome(const GameObjectPtr &object, const QString &tooFewText) {\n\n if (object.isNull()) {\n m_player->send(tooFewText);\n return false;\n } else {\n return true;\n }\n}\n\nbool Command::requireSome(const GameObjectPtrList &objects,\n const QString &tooFewText) {\n\n if (objects.length() == 0) {\n m_player->send(tooFewText);\n return false;\n } else {\n return true;\n }\n}\n\nbool Command::requireUnique(const GameObjectPtrList &objects,\n const QString &tooFewText,\n const QString &tooManyText) {\n\n if (objects.length() == 0) {\n m_player->send(tooFewText);\n return false;\n } else if (objects.length() > 1) {\n m_player->send(tooManyText);\n return false;\n } else {\n return true;\n }\n}\n<|endoftext|>"} {"text":"\/**\n * Copyright (c) 2016 zScale Technology GmbH \n * Authors:\n * - Paul Asmuth \n * - Laura Schlimmer \n *\n * This program is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License (\"the license\") as\n * published by the Free Software Foundation, either version 3 of the License,\n * or any later version.\n *\n * In accordance with Section 7(e) of the license, the licensing of the Program\n * under the license does not imply a trademark license. Therefore any rights,\n * title and interest in our trademarks remain entirely with us.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the license for more details.\n *\n * You can be released from the requirements of the license by purchasing a\n * commercial license. Buying such a license is mandatory as soon as you develop\n * commercial activities involving this program without disclosing the source\n * code of your own applications\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"eventql\/util\/thread\/FixedSizeThreadPool.h\"\n#include \"eventql\/util\/util\/SimpleRateLimit.h\"\n#include \n#include \n\nusing namespace eventql;\n\nstruct UploadShard {\n Buffer data;\n size_t nrows;\n};\n\nvoid run(const cli::FlagParser& flags) {\n auto source_table = flags.getString(\"source_table\");\n auto destination_table = flags.getString(\"destination_table\");\n auto shard_size = flags.getInt(\"shard_size\");\n auto num_upload_threads = flags.getInt(\"upload_threads\");\n auto mysql_addr = flags.getString(\"mysql\");\n auto host = flags.getString(\"host\");\n auto port = flags.getInt(\"port\");\n auto db = flags.getString(\"database\");\n\n logInfo(\"mysql2evql\", \"Connecting to MySQL Server...\");\n\n util::mysql::mysqlInit();\n auto mysql_conn = util::mysql::MySQLConnection::openConnection(URI(mysql_addr));\n\n logInfo(\n \"mysql2evql\",\n \"Analyzing the input table. This might take a few minutes...\");\n\n auto schema = mysql_conn->getTableSchema(source_table);\n logDebug(\"mysql2evql\", \"Table Schema:\\n$0\", schema->toString());\n Vector column_names;\n for (const auto& field : schema->fields()) {\n column_names.emplace_back(field.name);\n }\n\n \/* status line *\/\n std::atomic num_rows_uploaded(0);\n util::SimpleRateLimitedFn status_line(kMicrosPerSecond, [&] () {\n logInfo(\n \"mysql2evql\",\n \"Uploading... $0 rows\",\n num_rows_uploaded.load());\n });\n\n \/* start upload threads *\/\n http::HTTPMessage::HeaderList auth_headers;\n if (flags.isSet(\"auth_token\")) {\n auth_headers.emplace_back(\n \"Authorization\",\n StringUtil::format(\"Token $0\", flags.getString(\"auth_token\")));\n \/\/} else if (!cfg_.getPassword().isEmpty()) {\n \/\/ auth_headers.emplace_back(\n \/\/ \"Authorization\",\n \/\/ StringUtil::format(\"Basic $0\",\n \/\/ util::Base64::encode(\n \/\/ cfg_.getUser() + \":\" + cfg_.getPassword().get())));\n }\n\n bool upload_done = false;\n thread::Queue upload_queue(1);\n Vector upload_threads(num_upload_threads);\n for (size_t i = 0; i < num_upload_threads; ++i) {\n upload_threads[i] = std::thread([&] {\n while (!upload_done) {\n auto shard = upload_queue.interruptiblePop();\n if (shard.isEmpty()) {\n continue;\n }\n\n logDebug(\n \"mysql2evql\",\n \"Uploading batch; target=$0:$1 size=$2MB\",\n host,\n port,\n shard.get().data.size() \/ 1000000.0);\n\n try {\n auto insert_uri = StringUtil::format(\n \"http:\/\/$0:$1\/api\/v1\/tables\/insert\",\n host,\n port);\n\n http::HTTPClient http_client;\n auto upload_res = http_client.executeRequest(\n http::HTTPRequest::mkPost(\n insert_uri,\n \"[\" + shard.get().data.toString() + \"]\",\n auth_headers));\n\n if (upload_res.statusCode() != 201) {\n logError(\n \"mysql2evql\", \"[FATAL ERROR]: HTTP Status Code $0 $1\",\n upload_res.statusCode(),\n upload_res.body().toString());\n RAISE(kRuntimeError, upload_res.body().toString());\n }\n\n num_rows_uploaded += shard.get().nrows;\n status_line.runMaybe();\n } catch (const std::exception& e) {\n logError(\"mysql2evql\", e, \"error while uploading table data\");\n }\n }\n });\n }\n\n \/* fetch rows from mysql *\/\n UploadShard shard;\n shard.nrows = 0;\n json::JSONOutputStream json(BufferOutputStream::fromBuffer(&shard.data));\n\n String where_expr;\n if (flags.isSet(\"filter\")) {\n where_expr = \"WHERE \" + flags.getString(\"filter\");\n }\n\n auto get_rows_qry = StringUtil::format(\n \"SELECT * FROM `$0` $1;\",\n source_table,\n where_expr);\n\n mysql_conn->executeQuery(\n get_rows_qry,\n [&] (const Vector& column_values) -> bool {\n ++shard.nrows;\n\n if (shard.nrows > 1) {\n json.addComma();\n }\n\n json.beginObject();\n json.addObjectEntry(\"database\");\n json.addString(db);\n json.addComma();\n json.addObjectEntry(\"table\");\n json.addString(destination_table);\n json.addComma();\n json.addObjectEntry(\"data\");\n json.beginObject();\n\n for (size_t i = 0; i < column_names.size() && i < column_values.size(); ++i) {\n if (i > 0 ){\n json.addComma();\n }\n\n json.addObjectEntry(column_names[i]);\n json.addString(column_values[i]);\n }\n\n json.endObject();\n json.endObject();\n\n if (shard.nrows == shard_size) {\n upload_queue.insert(shard, true);\n shard.data.clear();\n shard.nrows = 0;\n }\n\n status_line.runMaybe();\n return true;\n });\n\n if (shard.nrows > 0) {\n upload_queue.insert(shard, true);\n }\n\n upload_queue.waitUntilEmpty();\n upload_done = true;\n upload_queue.wakeup();\n for (auto& t : upload_threads) {\n t.join();\n }\n\n status_line.runForce();\n logInfo(\"mysql2evql\", \"Upload finished successfully :)\");\n}\n\nint main(int argc, const char** argv) {\n Application::init();\n Application::logToStderr(\"mysql2evql\");\n\n cli::FlagParser flags;\n\n flags.defineFlag(\n \"loglevel\",\n cli::FlagParser::T_STRING,\n false,\n NULL,\n \"INFO\",\n \"loglevel\",\n \"\");\n\n flags.defineFlag(\n \"source_table\",\n cli::FlagParser::T_STRING,\n true,\n \"t\",\n NULL,\n \"table name\",\n \"\");\n\n flags.defineFlag(\n \"destination_table\",\n cli::FlagParser::T_STRING,\n true,\n \"t\",\n NULL,\n \"table name\",\n \"\");\n\n flags.defineFlag(\n \"host\",\n cli::FlagParser::T_STRING,\n true,\n \"h\",\n NULL,\n \"eventql server hostname\",\n \"\");\n\n flags.defineFlag(\n \"port\",\n cli::FlagParser::T_INTEGER,\n true,\n \"p\",\n NULL,\n \"eventql server port\",\n \"\");\n\n flags.defineFlag(\n \"database\",\n cli::FlagParser::T_STRING,\n true,\n \"db\",\n \"\",\n \"eventql database\",\n \"\");\n\n flags.defineFlag(\n \"auth_token\",\n cli::FlagParser::T_STRING,\n false,\n NULL,\n NULL,\n \"auth token\",\n \"\");\n\n flags.defineFlag(\n \"mysql\",\n cli::FlagParser::T_STRING,\n true,\n \"x\",\n \"mysql:\/\/localhost:3306\/mydb?user=root\",\n \"MySQL connection string\",\n \"\");\n\n flags.defineFlag(\n \"filter\",\n cli::FlagParser::T_STRING,\n false,\n NULL,\n NULL,\n \"boolean sql expression\",\n \"\");\n\n\n flags.defineFlag(\n \"shard_size\",\n cli::FlagParser::T_INTEGER,\n false,\n NULL,\n \"128\",\n \"shard size\",\n \"\");\n\n flags.defineFlag(\n \"upload_threads\",\n cli::FlagParser::T_INTEGER,\n false,\n NULL,\n \"8\",\n \"concurrent uploads\",\n \"\");\n\n try {\n flags.parseArgv(argc, argv);\n } catch (const StandardException& e) {\n logError(\"mysql2evql\", \"$0\", e.what());\n auto stdout_os = OutputStream::getStdout();\n flags.printUsage(stdout_os.get());\n return 0;\n }\n\n Logger::get()->setMinimumLogLevel(\n strToLogLevel(flags.getString(\"loglevel\")));\n\n try {\n run(flags);\n return 0;\n } catch (const StandardException& e) {\n return 1;\n }\n}\nproper return code\/**\n * Copyright (c) 2016 zScale Technology GmbH \n * Authors:\n * - Paul Asmuth \n * - Laura Schlimmer \n *\n * This program is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License (\"the license\") as\n * published by the Free Software Foundation, either version 3 of the License,\n * or any later version.\n *\n * In accordance with Section 7(e) of the license, the licensing of the Program\n * under the license does not imply a trademark license. Therefore any rights,\n * title and interest in our trademarks remain entirely with us.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the license for more details.\n *\n * You can be released from the requirements of the license by purchasing a\n * commercial license. Buying such a license is mandatory as soon as you develop\n * commercial activities involving this program without disclosing the source\n * code of your own applications\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"eventql\/util\/thread\/FixedSizeThreadPool.h\"\n#include \"eventql\/util\/util\/SimpleRateLimit.h\"\n#include \n#include \n\nusing namespace eventql;\n\nstruct UploadShard {\n Buffer data;\n size_t nrows;\n};\n\nbool run(const cli::FlagParser& flags) {\n auto source_table = flags.getString(\"source_table\");\n auto destination_table = flags.getString(\"destination_table\");\n auto shard_size = flags.getInt(\"shard_size\");\n auto num_upload_threads = flags.getInt(\"upload_threads\");\n auto mysql_addr = flags.getString(\"mysql\");\n auto host = flags.getString(\"host\");\n auto port = flags.getInt(\"port\");\n auto db = flags.getString(\"database\");\n\n logInfo(\"mysql2evql\", \"Connecting to MySQL Server...\");\n\n util::mysql::mysqlInit();\n auto mysql_conn = util::mysql::MySQLConnection::openConnection(URI(mysql_addr));\n\n logInfo(\n \"mysql2evql\",\n \"Analyzing the input table. This might take a few minutes...\");\n\n auto schema = mysql_conn->getTableSchema(source_table);\n logDebug(\"mysql2evql\", \"Table Schema:\\n$0\", schema->toString());\n Vector column_names;\n for (const auto& field : schema->fields()) {\n column_names.emplace_back(field.name);\n }\n\n \/* status line *\/\n std::atomic num_rows_uploaded(0);\n util::SimpleRateLimitedFn status_line(kMicrosPerSecond, [&] () {\n logInfo(\n \"mysql2evql\",\n \"Uploading... $0 rows\",\n num_rows_uploaded.load());\n });\n\n \/* start upload threads *\/\n http::HTTPMessage::HeaderList auth_headers;\n if (flags.isSet(\"auth_token\")) {\n auth_headers.emplace_back(\n \"Authorization\",\n StringUtil::format(\"Token $0\", flags.getString(\"auth_token\")));\n \/\/} else if (!cfg_.getPassword().isEmpty()) {\n \/\/ auth_headers.emplace_back(\n \/\/ \"Authorization\",\n \/\/ StringUtil::format(\"Basic $0\",\n \/\/ util::Base64::encode(\n \/\/ cfg_.getUser() + \":\" + cfg_.getPassword().get())));\n }\n\n bool upload_done = false;\n bool upload_error = false;\n thread::Queue upload_queue(1);\n Vector upload_threads(num_upload_threads);\n for (size_t i = 0; i < num_upload_threads; ++i) {\n upload_threads[i] = std::thread([&] {\n while (!upload_done) {\n auto shard = upload_queue.interruptiblePop();\n if (shard.isEmpty()) {\n continue;\n }\n\n logDebug(\n \"mysql2evql\",\n \"Uploading batch; target=$0:$1 size=$2MB\",\n host,\n port,\n shard.get().data.size() \/ 1000000.0);\n\n try {\n auto insert_uri = StringUtil::format(\n \"http:\/\/$0:$1\/api\/v1\/tables\/insert\",\n host,\n port);\n\n http::HTTPClient http_client;\n auto upload_res = http_client.executeRequest(\n http::HTTPRequest::mkPost(\n insert_uri,\n \"[\" + shard.get().data.toString() + \"]\",\n auth_headers));\n\n if (upload_res.statusCode() != 201) {\n logError(\n \"mysql2evql\", \"[FATAL ERROR]: HTTP Status Code $0 $1\",\n upload_res.statusCode(),\n upload_res.body().toString());\n RAISE(kRuntimeError, upload_res.body().toString());\n }\n\n num_rows_uploaded += shard.get().nrows;\n status_line.runMaybe();\n } catch (const std::exception& e) {\n upload_error = true;\n logError(\"mysql2evql\", e, \"error while uploading table data\");\n }\n }\n });\n }\n\n \/* fetch rows from mysql *\/\n UploadShard shard;\n shard.nrows = 0;\n json::JSONOutputStream json(BufferOutputStream::fromBuffer(&shard.data));\n\n String where_expr;\n if (flags.isSet(\"filter\")) {\n where_expr = \"WHERE \" + flags.getString(\"filter\");\n }\n\n auto get_rows_qry = StringUtil::format(\n \"SELECT * FROM `$0` $1;\",\n source_table,\n where_expr);\n\n mysql_conn->executeQuery(\n get_rows_qry,\n [&] (const Vector& column_values) -> bool {\n ++shard.nrows;\n\n if (shard.nrows > 1) {\n json.addComma();\n }\n\n json.beginObject();\n json.addObjectEntry(\"database\");\n json.addString(db);\n json.addComma();\n json.addObjectEntry(\"table\");\n json.addString(destination_table);\n json.addComma();\n json.addObjectEntry(\"data\");\n json.beginObject();\n\n for (size_t i = 0; i < column_names.size() && i < column_values.size(); ++i) {\n if (i > 0 ){\n json.addComma();\n }\n\n json.addObjectEntry(column_names[i]);\n json.addString(column_values[i]);\n }\n\n json.endObject();\n json.endObject();\n\n if (shard.nrows == shard_size) {\n upload_queue.insert(shard, true);\n shard.data.clear();\n shard.nrows = 0;\n }\n\n status_line.runMaybe();\n return true;\n });\n\n if (shard.nrows > 0) {\n upload_queue.insert(shard, true);\n }\n\n upload_queue.waitUntilEmpty();\n upload_done = true;\n upload_queue.wakeup();\n for (auto& t : upload_threads) {\n t.join();\n }\n\n status_line.runForce();\n\n if (upload_error) {\n logInfo(\"mysql2evql\", \"Upload finished with errors\");\n return false;\n } else {\n logInfo(\"mysql2evql\", \"Upload finished successfully :)\");\n return true;\n }\n}\n\nint main(int argc, const char** argv) {\n Application::init();\n Application::logToStderr(\"mysql2evql\");\n\n cli::FlagParser flags;\n\n flags.defineFlag(\n \"loglevel\",\n cli::FlagParser::T_STRING,\n false,\n NULL,\n \"INFO\",\n \"loglevel\",\n \"\");\n\n flags.defineFlag(\n \"source_table\",\n cli::FlagParser::T_STRING,\n true,\n \"t\",\n NULL,\n \"table name\",\n \"\");\n\n flags.defineFlag(\n \"destination_table\",\n cli::FlagParser::T_STRING,\n true,\n \"t\",\n NULL,\n \"table name\",\n \"\");\n\n flags.defineFlag(\n \"host\",\n cli::FlagParser::T_STRING,\n true,\n \"h\",\n NULL,\n \"eventql server hostname\",\n \"\");\n\n flags.defineFlag(\n \"port\",\n cli::FlagParser::T_INTEGER,\n true,\n \"p\",\n NULL,\n \"eventql server port\",\n \"\");\n\n flags.defineFlag(\n \"database\",\n cli::FlagParser::T_STRING,\n true,\n \"db\",\n \"\",\n \"eventql database\",\n \"\");\n\n flags.defineFlag(\n \"auth_token\",\n cli::FlagParser::T_STRING,\n false,\n NULL,\n NULL,\n \"auth token\",\n \"\");\n\n flags.defineFlag(\n \"mysql\",\n cli::FlagParser::T_STRING,\n true,\n \"x\",\n \"mysql:\/\/localhost:3306\/mydb?user=root\",\n \"MySQL connection string\",\n \"\");\n\n flags.defineFlag(\n \"filter\",\n cli::FlagParser::T_STRING,\n false,\n NULL,\n NULL,\n \"boolean sql expression\",\n \"\");\n\n\n flags.defineFlag(\n \"shard_size\",\n cli::FlagParser::T_INTEGER,\n false,\n NULL,\n \"128\",\n \"shard size\",\n \"\");\n\n flags.defineFlag(\n \"upload_threads\",\n cli::FlagParser::T_INTEGER,\n false,\n NULL,\n \"8\",\n \"concurrent uploads\",\n \"\");\n\n try {\n flags.parseArgv(argc, argv);\n } catch (const StandardException& e) {\n logError(\"mysql2evql\", \"$0\", e.what());\n auto stdout_os = OutputStream::getStdout();\n flags.printUsage(stdout_os.get());\n return 0;\n }\n\n Logger::get()->setMinimumLogLevel(\n strToLogLevel(flags.getString(\"loglevel\")));\n\n try {\n if (run(flags)) {\n return 0;\n } else {\n return 1;\n }\n } catch (const StandardException& e) {\n logFatal(\"mysql2evql\", \"$0\", e.what());\n return 1;\n }\n}\n<|endoftext|>"} {"text":"\/*\n\nCopyright (c) 2006, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \n#include \n#include \"libtorrent\/pch.hpp\"\n#include \"libtorrent\/assert.hpp\"\n#include \"libtorrent\/file_pool.hpp\"\n#include \"libtorrent\/error_code.hpp\"\n\nnamespace libtorrent\n{\n\tboost::shared_ptr file_pool::open_file(void* st, std::string const& p\n\t\t, int m, error_code& ec)\n\t{\n\t\tTORRENT_ASSERT(st != 0);\n\t\tTORRENT_ASSERT(is_complete(p));\n\t\tTORRENT_ASSERT((m & file::rw_mask) == file::read_only\n\t\t\t|| (m & file::rw_mask) == file::read_write);\n\t\tmutex::scoped_lock l(m_mutex);\n\t\tfile_set::iterator i = m_files.find(p);\n\t\tif (i != m_files.end())\n\t\t{\n\t\t\tlru_file_entry& e = i->second;\n\t\t\te.last_use = time_now();\n\n\t\t\tif (e.key != st && ((e.mode & file::rw_mask) != file::read_only\n\t\t\t\t|| (m & file::rw_mask) != file::read_only))\n\t\t\t{\n\t\t\t\t\/\/ this means that another instance of the storage\n\t\t\t\t\/\/ is using the exact same file.\n#if BOOST_VERSION >= 103500\n\t\t\t\tec = errors::file_collision;\n#endif\n\t\t\t\treturn boost::shared_ptr();\n\t\t\t}\n\n\t\t\te.key = st;\n\t\t\t\/\/ if we asked for a file in write mode,\n\t\t\t\/\/ and the cached file is is not opened in\n\t\t\t\/\/ write mode, re-open it\n\t\t\tif (((e.mode & file::rw_mask) != file::read_write)\n\t\t\t\t&& ((m & file::rw_mask) == file::read_write))\n\t\t\t{\n\t\t\t\t\/\/ close the file before we open it with\n\t\t\t\t\/\/ the new read\/write privilages\n\t\t\t\tTORRENT_ASSERT(e.file_ptr.unique());\n\t\t\t\te.file_ptr->close();\n\t\t\t\tif (!e.file_ptr->open(p, m, ec))\n\t\t\t\t{\n\t\t\t\t\tm_files.erase(i);\n\t\t\t\t\treturn boost::shared_ptr();\n\t\t\t\t}\n#ifdef TORRENT_WINDOWS\n\t\t\t\tif (m_low_prio_io)\n\t\t\t\t{\n\t\t\t\t\tFILE_IO_PRIORITY_HINT_INFO priorityHint;\n\t\t\t\t\tpriorityHint.PriorityHint = IoPriorityHintLow;\n\t\t\t\t\tresult = SetFileInformationByHandle(e.file_ptr->native_handle(),\n\t\t\t\t\t\tFileIoPriorityHintInfo, &priorityHint, sizeof(PriorityHint));\n\t\t\t\t}\n#endif\n\t\t\t\tTORRENT_ASSERT(e.file_ptr->is_open());\n\t\t\t\te.mode = m;\n\t\t\t}\n\t\t\tTORRENT_ASSERT((e.mode & file::no_buffer) == (m & file::no_buffer));\n\t\t\treturn e.file_ptr;\n\t\t}\n\t\t\/\/ the file is not in our cache\n\t\tif ((int)m_files.size() >= m_size)\n\t\t{\n\t\t\t\/\/ the file cache is at its maximum size, close\n\t\t\t\/\/ the least recently used (lru) file from it\n\t\t\tremove_oldest();\n\t\t}\n\t\tlru_file_entry e;\n\t\te.file_ptr.reset(new (std::nothrow)file);\n\t\tif (!e.file_ptr)\n\t\t{\n\t\t\tec = error_code(ENOMEM, get_posix_category());\n\t\t\treturn e.file_ptr;\n\t\t}\n\t\tif (!e.file_ptr->open(p, m, ec))\n\t\t\treturn boost::shared_ptr();\n\t\te.mode = m;\n\t\te.key = st;\n\t\tm_files.insert(std::make_pair(p, e));\n\t\tTORRENT_ASSERT(e.file_ptr->is_open());\n\t\treturn e.file_ptr;\n\t}\n\n\tvoid file_pool::remove_oldest()\n\t{\n\t\tfile_set::iterator i = std::min_element(m_files.begin(), m_files.end()\n\t\t\t, boost::bind(&lru_file_entry::last_use, boost::bind(&file_set::value_type::second, _1))\n\t\t\t\t< boost::bind(&lru_file_entry::last_use, boost::bind(&file_set::value_type::second, _2)));\n\t\tif (i == m_files.end()) return;\n\t\tm_files.erase(i);\n\t}\n\n\tvoid file_pool::release(std::string const& p)\n\t{\n\t\tmutex::scoped_lock l(m_mutex);\n\n\t\tfile_set::iterator i = m_files.find(p);\n\t\tif (i != m_files.end()) m_files.erase(i);\n\t}\n\n\t\/\/ closes files belonging to the specified\n\t\/\/ storage. If 0 is passed, all files are closed\n\tvoid file_pool::release(void* st)\n\t{\n\t\tmutex::scoped_lock l(m_mutex);\n\t\tif (st == 0)\n\t\t{\n\t\t\tm_files.clear();\n\t\t\treturn;\n\t\t}\n\n\t\tfor (file_set::iterator i = m_files.begin();\n\t\t\ti != m_files.end();)\n\t\t{\n\t\t\tif (i->second.key == st)\n\t\t\t\tm_files.erase(i++);\n\t\t\telse\n\t\t\t\t++i;\n\t\t}\n\t}\n\n\tvoid file_pool::resize(int size)\n\t{\n\t\tTORRENT_ASSERT(size > 0);\n\t\tif (size == m_size) return;\n\t\tmutex::scoped_lock l(m_mutex);\n\t\tm_size = size;\n\t\tif (int(m_files.size()) <= m_size) return;\n\n\t\t\/\/ close the least recently used files\n\t\twhile (int(m_files.size()) > m_size)\n\t\t\tremove_oldest();\n\t}\n\n}\nfixed windows unit tests\/*\n\nCopyright (c) 2006, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \n#include \n#include \"libtorrent\/pch.hpp\"\n#include \"libtorrent\/assert.hpp\"\n#include \"libtorrent\/file_pool.hpp\"\n#include \"libtorrent\/error_code.hpp\"\n\nnamespace libtorrent\n{\n\tboost::shared_ptr file_pool::open_file(void* st, std::string const& p\n\t\t, int m, error_code& ec)\n\t{\n\t\tTORRENT_ASSERT(st != 0);\n\t\tTORRENT_ASSERT(is_complete(p));\n\t\tTORRENT_ASSERT((m & file::rw_mask) == file::read_only\n\t\t\t|| (m & file::rw_mask) == file::read_write);\n\t\tmutex::scoped_lock l(m_mutex);\n\t\tfile_set::iterator i = m_files.find(p);\n\t\tif (i != m_files.end())\n\t\t{\n\t\t\tlru_file_entry& e = i->second;\n\t\t\te.last_use = time_now();\n\n\t\t\tif (e.key != st && ((e.mode & file::rw_mask) != file::read_only\n\t\t\t\t|| (m & file::rw_mask) != file::read_only))\n\t\t\t{\n\t\t\t\t\/\/ this means that another instance of the storage\n\t\t\t\t\/\/ is using the exact same file.\n#if BOOST_VERSION >= 103500\n\t\t\t\tec = errors::file_collision;\n#endif\n\t\t\t\treturn boost::shared_ptr();\n\t\t\t}\n\n\t\t\te.key = st;\n\t\t\t\/\/ if we asked for a file in write mode,\n\t\t\t\/\/ and the cached file is is not opened in\n\t\t\t\/\/ write mode, re-open it\n\t\t\tif (((e.mode & file::rw_mask) != file::read_write)\n\t\t\t\t&& ((m & file::rw_mask) == file::read_write))\n\t\t\t{\n\t\t\t\t\/\/ close the file before we open it with\n\t\t\t\t\/\/ the new read\/write privilages\n\t\t\t\tTORRENT_ASSERT(e.file_ptr.unique());\n\t\t\t\te.file_ptr->close();\n\t\t\t\tif (!e.file_ptr->open(p, m, ec))\n\t\t\t\t{\n\t\t\t\t\tm_files.erase(i);\n\t\t\t\t\treturn boost::shared_ptr();\n\t\t\t\t}\n#ifdef TORRENT_WINDOWS\n\/\/ file prio is supported on vista and up\n#if _WIN32_WINNT >= 0x0600\n\t\t\t\tif (m_low_prio_io)\n\t\t\t\t{\n\t\t\t\t\tFILE_IO_PRIORITY_HINT_INFO priorityHint;\n\t\t\t\t\tpriorityHint.PriorityHint = IoPriorityHintLow;\n\t\t\t\t\tresult = SetFileInformationByHandle(e.file_ptr->native_handle(),\n\t\t\t\t\t\tFileIoPriorityHintInfo, &priorityHint, sizeof(PriorityHint));\n\t\t\t\t}\n#endif\n#endif\n\t\t\t\tTORRENT_ASSERT(e.file_ptr->is_open());\n\t\t\t\te.mode = m;\n\t\t\t}\n\t\t\tTORRENT_ASSERT((e.mode & file::no_buffer) == (m & file::no_buffer));\n\t\t\treturn e.file_ptr;\n\t\t}\n\t\t\/\/ the file is not in our cache\n\t\tif ((int)m_files.size() >= m_size)\n\t\t{\n\t\t\t\/\/ the file cache is at its maximum size, close\n\t\t\t\/\/ the least recently used (lru) file from it\n\t\t\tremove_oldest();\n\t\t}\n\t\tlru_file_entry e;\n\t\te.file_ptr.reset(new (std::nothrow)file);\n\t\tif (!e.file_ptr)\n\t\t{\n\t\t\tec = error_code(ENOMEM, get_posix_category());\n\t\t\treturn e.file_ptr;\n\t\t}\n\t\tif (!e.file_ptr->open(p, m, ec))\n\t\t\treturn boost::shared_ptr();\n\t\te.mode = m;\n\t\te.key = st;\n\t\tm_files.insert(std::make_pair(p, e));\n\t\tTORRENT_ASSERT(e.file_ptr->is_open());\n\t\treturn e.file_ptr;\n\t}\n\n\tvoid file_pool::remove_oldest()\n\t{\n\t\tfile_set::iterator i = std::min_element(m_files.begin(), m_files.end()\n\t\t\t, boost::bind(&lru_file_entry::last_use, boost::bind(&file_set::value_type::second, _1))\n\t\t\t\t< boost::bind(&lru_file_entry::last_use, boost::bind(&file_set::value_type::second, _2)));\n\t\tif (i == m_files.end()) return;\n\t\tm_files.erase(i);\n\t}\n\n\tvoid file_pool::release(std::string const& p)\n\t{\n\t\tmutex::scoped_lock l(m_mutex);\n\n\t\tfile_set::iterator i = m_files.find(p);\n\t\tif (i != m_files.end()) m_files.erase(i);\n\t}\n\n\t\/\/ closes files belonging to the specified\n\t\/\/ storage. If 0 is passed, all files are closed\n\tvoid file_pool::release(void* st)\n\t{\n\t\tmutex::scoped_lock l(m_mutex);\n\t\tif (st == 0)\n\t\t{\n\t\t\tm_files.clear();\n\t\t\treturn;\n\t\t}\n\n\t\tfor (file_set::iterator i = m_files.begin();\n\t\t\ti != m_files.end();)\n\t\t{\n\t\t\tif (i->second.key == st)\n\t\t\t\tm_files.erase(i++);\n\t\t\telse\n\t\t\t\t++i;\n\t\t}\n\t}\n\n\tvoid file_pool::resize(int size)\n\t{\n\t\tTORRENT_ASSERT(size > 0);\n\t\tif (size == m_size) return;\n\t\tmutex::scoped_lock l(m_mutex);\n\t\tm_size = size;\n\t\tif (int(m_files.size()) <= m_size) return;\n\n\t\t\/\/ close the least recently used files\n\t\twhile (int(m_files.size()) > m_size)\n\t\t\tremove_oldest();\n\t}\n\n}\n<|endoftext|>"} {"text":"\/\/\/ \\file src\/fmm_method.cc\n\/\/\/ \\brief Implementation of FMM Method\n\n#include \"include\/fmm_method.h\"\n\nnamespace dashmm {\n\nvoid FMM::generate(SourceNode &curr, const ExpansionRef expand) const {\n int n_digits = expand.accuracy(); \n curr.set_expansion(expand.get_new_expansion(curr.center(), n_digits));\n ExpansionRef currexp = curr.expansion(); \n SourceRef sources = curr.parts(); \n double scale = 1.0 \/ curr.size(); \n currexp.S_to_M(curr.center(), sources, scale); \n}\n\nvoid FMM::aggregate(SourceNode &curr, const ExpansionRef expand) const {\n int n_digits = expand.accuracy(); \n curr.set_expansion(expand.get_new_expansion(curr.center(), n_digits)); \n ExpansionRef currexp = curr.expansion(); \n\n for (size_t i = 0; i < 8; ++i) {\n SourceNode kid = curr.child(i); \n if (kid.is_valid()) {\n ExpansionRef kexp = kid.expansion(); \n currexp.M_to_M(kexp, i, kid.size());\n }\n }\n}\n\nvoid FMM::inherit(TargetNode &curr, const ExpansionRef expand, \n size_t which_child) const {\n int n_digits = expand.accuracy(); \n curr.set_expansion(expand.get_new_expansion(curr.center(), n_digits)); \n ExpansionRef currexp = curr.expansion(); \n\n if (curr.parent().is_valid()) {\n ExpansionRef pexp = curr.parent().expansion(); \n currexp.L_to_L(pexp, which_child, curr.size()); \n } else {\n curr.set_expansion(expand.get_new_expansion(curr.center(), n_digits));\n } \n}\n\nvoid FMM::process(TargetNode &curr, std::vector &consider, \n bool curr_is_leaf) const {\n ExpansionRef currexp = curr.expansion(); \n double scale = 1.0 \/ curr.size(); \n TargetRef targets = curr.parts(); \n Index t_index = curr.index(); \n\n if (curr_is_leaf) {\n for (auto S = consider.begin(); S != consider.end(); ++S) {\n if (S->level() < curr.level()) {\n if (well_sep_test_asymmetric(t_index, S->index())) {\n SourceRef sources = S->parts(); \n currexp.S_to_L(curr.center(), sources, scale); \n } else {\n SourceRef sources = S->parts(); \n ExpansionRef expand = S->expansion(); \n expand.S_to_T(sources, targets);\n }\n } else {\n if (well_sep_test(S->index(), curr.index())) {\n ExpansionRef expand = S->expansion(); \n double s_size = S->size(); \n Index s_index = S->index(); \n currexp.M_to_L(expand, s_index, s_size, t_index); \n } else {\n proc_coll_recur(curr, *S); \n }\n }\n }\n\n currexp.L_to_T(targets, scale); \n } else {\n std::vector newcons{}; \n \n for (auto S = consider.begin(); S != consider.end(); ++S) {\n if (S->level() < curr.level()) {\n if (well_sep_test_asymmetric(t_index, S->index())) {\n SourceRef sources = S->parts(); \n currexp.S_to_L(curr.center(), sources, scale); \n } else {\n \/\/ a 1; add it to newcons\n newcons.push_back(*S); \n }\n } else {\n if (well_sep_test(S->index(), curr.index())) {\n ExpansionRef expand = S->expansion(); \n double s_size = S->size(); \n Index s_index = S->index(); \n currexp.M_to_L(expand, s_index, s_size, t_index); \n } else {\n bool S_is_leaf = true; \n for (size_t i = 0; i < 8; ++i) {\n SourceNode child = S->child(i); \n if (child.is_valid()) {\n newcons.push_back(child); \n S_is_leaf = false;\n }\n }\n\n if (S_is_leaf) \n newcons.push_back(*S);\n }\n }\n }\n\n consider = std::move(newcons); \n }\n\n}\n\nbool FMM::refine_test(bool same_sources_and_targets, const TargetNode &curr,\n const std::vector &consider) const {\n if (same_sources_and_targets) {\n return true;\n }\n\n for (auto i = consider.begin(); i != consider.end(); ++i) {\n if (i->level() == curr.level()) {\n if (!well_sep_test(i->index(), curr.index()) && !i->is_leaf()) {\n return true;\n }\n }\n }\n\n return false;\n}\n\nbool FMM::well_sep_test_asymmetric(Index smaller, Index larger) const {\n int delta = smaller.level() - larger.level();\n int shift = (1 << delta) - 1;\n Index l_mod{larger.x() << delta, larger.y() << delta,\n larger.z() << delta, smaller.level()};\n Index l_mod_top{l_mod.x() + shift, l_mod.y() + shift, l_mod.z() + shift,\n l_mod.level()};\n\n \/\/in the asymmetric case, we need to check both sides of the larger box\n \/\/ to make sure there is a gap of one of the smaller boxes\n if (abs(smaller.x() - l_mod.x()) > 1\n && abs(smaller.x() - l_mod_top.x()) > 1) return true;\n if (abs(smaller.y() - l_mod.y()) > 1\n && abs(smaller.y() - l_mod_top.y()) > 1) return true;\n if (abs(smaller.z() - l_mod.z()) > 1\n && abs(smaller.z() - l_mod_top.z()) > 1) return true;\n return false;\n}\n\nbool FMM::well_sep_test(Index source, Index target) const {\n \/\/When the nodes are the same level, we just need to have at least one\n \/\/ index that is different by +\/- 2 or more.\n if (abs(source.x() - target.x()) > 1) return true;\n if (abs(source.y() - target.y()) > 1) return true;\n if (abs(source.z() - target.z()) > 1) return true;\n return false;\n}\n\nvoid FMM::proc_coll_recur(TargetNode &T, SourceNode &S) const {\n if (well_sep_test_asymmetric(S.index(), T.index())) {\n ExpansionRef expand = S.expansion(); \n TargetRef targets = T.parts(); \n double scale = 1.0 \/ T.size(); \n expand.M_to_T(targets, scale); \n } else {\n if (S.is_leaf()) {\n ExpansionRef expand = S.expansion(); \n TargetRef targets = T.parts(); \n SourceRef sources = S.parts(); \n expand.S_to_T(sources, targets); \n } else {\n for (size_t i = 0; i < 8; ++i) {\n SourceNode child = S.child(i); \n if (child.is_valid()) \n proc_coll_recur(T, child);\n }\n }\n }\n}\n\n\n} \/\/ namespace dashmm\nfix typo that passes a wrong scaling factor to M_to_T\/\/\/ \\file src\/fmm_method.cc\n\/\/\/ \\brief Implementation of FMM Method\n\n#include \"include\/fmm_method.h\"\n\nnamespace dashmm {\n\nvoid FMM::generate(SourceNode &curr, const ExpansionRef expand) const {\n int n_digits = expand.accuracy(); \n curr.set_expansion(expand.get_new_expansion(curr.center(), n_digits));\n ExpansionRef currexp = curr.expansion(); \n SourceRef sources = curr.parts(); \n double scale = 1.0 \/ curr.size(); \n currexp.S_to_M(curr.center(), sources, scale); \n}\n\nvoid FMM::aggregate(SourceNode &curr, const ExpansionRef expand) const {\n int n_digits = expand.accuracy(); \n curr.set_expansion(expand.get_new_expansion(curr.center(), n_digits)); \n ExpansionRef currexp = curr.expansion(); \n\n for (size_t i = 0; i < 8; ++i) {\n SourceNode kid = curr.child(i); \n if (kid.is_valid()) {\n ExpansionRef kexp = kid.expansion(); \n currexp.M_to_M(kexp, i, kid.size());\n }\n }\n}\n\nvoid FMM::inherit(TargetNode &curr, const ExpansionRef expand, \n size_t which_child) const {\n int n_digits = expand.accuracy(); \n curr.set_expansion(expand.get_new_expansion(curr.center(), n_digits)); \n ExpansionRef currexp = curr.expansion(); \n\n if (curr.parent().is_valid()) {\n ExpansionRef pexp = curr.parent().expansion(); \n currexp.L_to_L(pexp, which_child, curr.size()); \n } else {\n curr.set_expansion(expand.get_new_expansion(curr.center(), n_digits));\n } \n}\n\nvoid FMM::process(TargetNode &curr, std::vector &consider, \n bool curr_is_leaf) const {\n ExpansionRef currexp = curr.expansion(); \n double scale = 1.0 \/ curr.size(); \n TargetRef targets = curr.parts(); \n Index t_index = curr.index(); \n\n if (curr_is_leaf) {\n for (auto S = consider.begin(); S != consider.end(); ++S) {\n if (S->level() < curr.level()) {\n if (well_sep_test_asymmetric(t_index, S->index())) {\n SourceRef sources = S->parts(); \n currexp.S_to_L(curr.center(), sources, scale); \n } else {\n SourceRef sources = S->parts(); \n ExpansionRef expand = S->expansion(); \n expand.S_to_T(sources, targets);\n }\n } else {\n if (well_sep_test(S->index(), curr.index())) {\n ExpansionRef expand = S->expansion(); \n double s_size = S->size(); \n Index s_index = S->index(); \n currexp.M_to_L(expand, s_index, s_size, t_index); \n } else {\n proc_coll_recur(curr, *S); \n }\n }\n }\n\n currexp.L_to_T(targets, scale); \n } else {\n std::vector newcons{}; \n \n for (auto S = consider.begin(); S != consider.end(); ++S) {\n if (S->level() < curr.level()) {\n if (well_sep_test_asymmetric(t_index, S->index())) {\n SourceRef sources = S->parts(); \n currexp.S_to_L(curr.center(), sources, scale); \n } else {\n \/\/ a 1; add it to newcons\n newcons.push_back(*S); \n }\n } else {\n if (well_sep_test(S->index(), curr.index())) {\n ExpansionRef expand = S->expansion(); \n double s_size = S->size(); \n Index s_index = S->index(); \n currexp.M_to_L(expand, s_index, s_size, t_index); \n } else {\n bool S_is_leaf = true; \n for (size_t i = 0; i < 8; ++i) {\n SourceNode child = S->child(i); \n if (child.is_valid()) {\n newcons.push_back(child); \n S_is_leaf = false;\n }\n }\n\n if (S_is_leaf) \n newcons.push_back(*S);\n }\n }\n }\n\n consider = std::move(newcons); \n }\n\n}\n\nbool FMM::refine_test(bool same_sources_and_targets, const TargetNode &curr,\n const std::vector &consider) const {\n if (same_sources_and_targets) {\n return true;\n }\n\n for (auto i = consider.begin(); i != consider.end(); ++i) {\n if (i->level() == curr.level()) {\n if (!well_sep_test(i->index(), curr.index()) && !i->is_leaf()) {\n return true;\n }\n }\n }\n\n return false;\n}\n\nbool FMM::well_sep_test_asymmetric(Index smaller, Index larger) const {\n int delta = smaller.level() - larger.level();\n int shift = (1 << delta) - 1;\n Index l_mod{larger.x() << delta, larger.y() << delta,\n larger.z() << delta, smaller.level()};\n Index l_mod_top{l_mod.x() + shift, l_mod.y() + shift, l_mod.z() + shift,\n l_mod.level()};\n\n \/\/in the asymmetric case, we need to check both sides of the larger box\n \/\/ to make sure there is a gap of one of the smaller boxes\n if (abs(smaller.x() - l_mod.x()) > 1\n && abs(smaller.x() - l_mod_top.x()) > 1) return true;\n if (abs(smaller.y() - l_mod.y()) > 1\n && abs(smaller.y() - l_mod_top.y()) > 1) return true;\n if (abs(smaller.z() - l_mod.z()) > 1\n && abs(smaller.z() - l_mod_top.z()) > 1) return true;\n return false;\n}\n\nbool FMM::well_sep_test(Index source, Index target) const {\n \/\/When the nodes are the same level, we just need to have at least one\n \/\/ index that is different by +\/- 2 or more.\n if (abs(source.x() - target.x()) > 1) return true;\n if (abs(source.y() - target.y()) > 1) return true;\n if (abs(source.z() - target.z()) > 1) return true;\n return false;\n}\n\nvoid FMM::proc_coll_recur(TargetNode &T, SourceNode &S) const {\n if (well_sep_test_asymmetric(S.index(), T.index())) {\n ExpansionRef expand = S.expansion(); \n TargetRef targets = T.parts(); \n double scale = 1.0 \/ S.size(); \n expand.M_to_T(targets, scale); \n } else {\n if (S.is_leaf()) {\n ExpansionRef expand = S.expansion(); \n TargetRef targets = T.parts(); \n SourceRef sources = S.parts(); \n expand.S_to_T(sources, targets); \n } else {\n for (size_t i = 0; i < 8; ++i) {\n SourceNode child = S.child(i); \n if (child.is_valid()) \n proc_coll_recur(T, child);\n }\n }\n }\n}\n\n\n} \/\/ namespace dashmm\n<|endoftext|>"} {"text":"\/*\n * Copyright © 2014 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\/\n\n\/**\n * \\file opt_rebalance_tree.cpp\n *\n * Rebalances a reduction expression tree.\n *\n * For reduction operations (e.g., x + y + z + w) we generate an expression\n * tree like\n *\n * +\n * \/ \\\n * + w\n * \/ \\\n * + z\n * \/ \\\n * x y\n *\n * which we can rebalance into\n *\n * +\n * \/ \\\n * \/ \\\n * + +\n * \/ \\ \/ \\\n * x y z w\n *\n * to get a better instruction scheduling.\n *\n * See \"Tree Rebalancing in Optimal Editor Time and Space\" by Quentin F. Stout\n * and Bette L. Warren.\n *\n * Also see http:\/\/penguin.ewu.edu\/~trolfe\/DSWpaper\/ for a very readable\n * explanation of the of the tree_to_vine() (rightward rotation) and\n * vine_to_tree() (leftward rotation) algorithms.\n *\/\n\n#include \"ir.h\"\n#include \"ir_visitor.h\"\n#include \"ir_rvalue_visitor.h\"\n#include \"ir_optimization.h\"\n#include \"main\/macros.h\" \/* for MAX2 *\/\n\n\/* The DSW algorithm generates a degenerate tree (really, a linked list) in\n * tree_to_vine(). We'd rather not leave a binary expression with only one\n * operand, so trivial modifications (the ternary operators below) are needed\n * to ensure that we only rotate around the ir_expression nodes of the tree.\n *\/\nstatic unsigned\ntree_to_vine(ir_expression *root)\n{\n unsigned size = 0;\n ir_rvalue *vine_tail = root;\n ir_rvalue *remainder = root->operands[1];\n\n while (remainder != NULL) {\n ir_expression *remainder_temp = remainder->as_expression();\n ir_expression *remainder_left = remainder_temp ?\n remainder_temp->operands[0]->as_expression() : NULL;\n\n if (remainder_left == NULL) {\n \/* move vine_tail down one *\/\n vine_tail = remainder;\n remainder = remainder->as_expression() ?\n ((ir_expression *)remainder)->operands[1] : NULL;\n size++;\n } else {\n \/* rotate *\/\n ir_expression *tempptr = remainder_left;\n ((ir_expression *)remainder)->operands[0] = tempptr->operands[1];\n tempptr->operands[1] = remainder;\n remainder = tempptr;\n ((ir_expression *)vine_tail)->operands[1] = tempptr;\n }\n }\n\n return size;\n}\n\nstatic void\ncompression(ir_expression *root, unsigned count)\n{\n ir_expression *scanner = root;\n\n for (unsigned i = 0; i < count; i++) {\n ir_expression *child = (ir_expression *)scanner->operands[1];\n scanner->operands[1] = child->operands[1];\n scanner = (ir_expression *)scanner->operands[1];\n child->operands[1] = scanner->operands[0];\n scanner->operands[0] = child;\n }\n}\n\nstatic void\nvine_to_tree(ir_expression *root, unsigned size)\n{\n int n = size - 1;\n for (int m = n \/ 2; m > 0; m = n \/ 2) {\n compression(root, m);\n n -= m + 1;\n }\n}\n\nnamespace {\n\nclass ir_rebalance_visitor : public ir_rvalue_enter_visitor {\npublic:\n ir_rebalance_visitor()\n {\n progress = false;\n }\n\n void handle_rvalue(ir_rvalue **rvalue);\n\n bool progress;\n};\n\nstruct is_reduction_data {\n ir_expression_operation operation;\n const glsl_type *type;\n unsigned num_expr;\n bool is_reduction;\n bool contains_constant;\n};\n\n} \/* anonymous namespace *\/\n\nstatic bool\nis_reduction_operation(ir_expression_operation operation)\n{\n switch (operation) {\n case ir_binop_add:\n case ir_binop_mul:\n case ir_binop_bit_and:\n case ir_binop_bit_xor:\n case ir_binop_bit_or:\n case ir_binop_logic_and:\n case ir_binop_logic_xor:\n case ir_binop_logic_or:\n case ir_binop_min:\n case ir_binop_max:\n return true;\n default:\n return false;\n }\n}\n\n\/* Note that this function does not attempt to recognize that reduction trees\n * are already balanced.\n *\n * We return false from this function for a number of reasons other than an\n * expression tree not being a mathematical reduction. Namely,\n *\n * - if the tree contains multiple constants that we may be able to combine.\n * - if the tree contains matrices:\n * - they might contain vec4's with many constant components that we can\n * simplify after splitting.\n * - applying the matrix chain ordering optimization is more than just\n * balancing an expression tree.\n * - if the tree contains operations on multiple types.\n * - if the tree contains ir_dereference_{array,record}, since foo[a+b] + c\n * would trick the visiting pass.\n *\/\nstatic void\nis_reduction(ir_instruction *ir, void *data)\n{\n struct is_reduction_data *ird = (struct is_reduction_data *)data;\n if (!ird->is_reduction)\n return;\n\n \/* We don't want to balance a tree that contains multiple constants, since\n * we'll be able to constant fold them if they're not in separate subtrees.\n *\/\n if (ir->as_constant()) {\n if (ird->contains_constant) {\n ird->is_reduction = false;\n }\n ird->contains_constant = true;\n return;\n }\n\n \/* Array\/record dereferences have subtrees that are not part of the expr\n * tree we're balancing. Skip trees containing them.\n *\/\n if (ir->ir_type == ir_type_dereference_array ||\n ir->ir_type == ir_type_dereference_record) {\n ird->is_reduction = false;\n return;\n }\n\n ir_expression *expr = ir->as_expression();\n if (!expr)\n return;\n\n \/* Non-constant matrices might still contain constant vec4 that we can\n * constant fold once split up. Handling matrices will need some more\n * work.\n *\/\n if (expr->type->is_matrix() ||\n expr->operands[0]->type->is_matrix() ||\n (expr->operands[1] && expr->operands[1]->type->is_matrix())) {\n ird->is_reduction = false;\n return;\n }\n\n if (ird->type != NULL && ird->type != expr->type) {\n ird->is_reduction = false;\n return;\n }\n ird->type = expr->type;\n\n ird->num_expr++;\n if (is_reduction_operation(expr->operation)) {\n if (ird->operation != 0 && ird->operation != expr->operation)\n ird->is_reduction = false;\n ird->operation = expr->operation;\n } else {\n ird->is_reduction = false;\n }\n}\n\nstatic ir_rvalue *\nhandle_expression(ir_expression *expr)\n{\n struct is_reduction_data ird;\n ird.operation = (ir_expression_operation)0;\n ird.type = NULL;\n ird.num_expr = 0;\n ird.is_reduction = true;\n ird.contains_constant = false;\n\n visit_tree(expr, is_reduction, (void *)&ird);\n\n if (ird.is_reduction && ird.num_expr > 2) {\n ir_constant z = ir_constant(0.0f);\n ir_expression pseudo_root = ir_expression(ir_binop_add, &z, expr);\n\n unsigned size = tree_to_vine(&pseudo_root);\n vine_to_tree(&pseudo_root, size);\n\n expr = (ir_expression *)pseudo_root.operands[1];\n }\n return expr;\n}\n\nstatic void\nupdate_types(ir_instruction *ir, void *)\n{\n ir_expression *expr = ir->as_expression();\n if (!expr)\n return;\n\n const glsl_type *const new_type =\n glsl_type::get_instance(expr->type->base_type,\n MAX2(expr->operands[0]->type->components(),\n expr->operands[1]->type->components()),\n 1);\n assert(new_type != glsl_type::error_type);\n expr->type = new_type;\n}\n\nvoid\nir_rebalance_visitor::handle_rvalue(ir_rvalue **rvalue)\n{\n if (!*rvalue)\n return;\n\n ir_expression *expr = (*rvalue)->as_expression();\n if (!expr || !is_reduction_operation(expr->operation))\n return;\n\n ir_rvalue *new_rvalue = handle_expression(expr);\n\n \/* If we failed to rebalance the tree (e.g., because it wasn't a reduction,\n * or some other set of cases) new_rvalue will point to the same root as\n * before.\n *\n * Similarly, if the tree rooted at *rvalue was a reduction and was already\n * balanced, the algorithm will rearrange the tree but will ultimately\n * return an identical tree, so this check will handle that as well and\n * will not set progress = true.\n *\/\n if (new_rvalue == *rvalue)\n return;\n\n visit_tree(new_rvalue, NULL, NULL, update_types);\n\n *rvalue = new_rvalue;\n this->progress = true;\n}\n\nbool\ndo_rebalance_tree(exec_list *instructions)\n{\n ir_rebalance_visitor v;\n\n v.run(instructions);\n\n return v.progress;\n}\nglsl: Make the tree rebalancer use vector_elements, not components().\/*\n * Copyright © 2014 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\/\n\n\/**\n * \\file opt_rebalance_tree.cpp\n *\n * Rebalances a reduction expression tree.\n *\n * For reduction operations (e.g., x + y + z + w) we generate an expression\n * tree like\n *\n * +\n * \/ \\\n * + w\n * \/ \\\n * + z\n * \/ \\\n * x y\n *\n * which we can rebalance into\n *\n * +\n * \/ \\\n * \/ \\\n * + +\n * \/ \\ \/ \\\n * x y z w\n *\n * to get a better instruction scheduling.\n *\n * See \"Tree Rebalancing in Optimal Editor Time and Space\" by Quentin F. Stout\n * and Bette L. Warren.\n *\n * Also see http:\/\/penguin.ewu.edu\/~trolfe\/DSWpaper\/ for a very readable\n * explanation of the of the tree_to_vine() (rightward rotation) and\n * vine_to_tree() (leftward rotation) algorithms.\n *\/\n\n#include \"ir.h\"\n#include \"ir_visitor.h\"\n#include \"ir_rvalue_visitor.h\"\n#include \"ir_optimization.h\"\n#include \"main\/macros.h\" \/* for MAX2 *\/\n\n\/* The DSW algorithm generates a degenerate tree (really, a linked list) in\n * tree_to_vine(). We'd rather not leave a binary expression with only one\n * operand, so trivial modifications (the ternary operators below) are needed\n * to ensure that we only rotate around the ir_expression nodes of the tree.\n *\/\nstatic unsigned\ntree_to_vine(ir_expression *root)\n{\n unsigned size = 0;\n ir_rvalue *vine_tail = root;\n ir_rvalue *remainder = root->operands[1];\n\n while (remainder != NULL) {\n ir_expression *remainder_temp = remainder->as_expression();\n ir_expression *remainder_left = remainder_temp ?\n remainder_temp->operands[0]->as_expression() : NULL;\n\n if (remainder_left == NULL) {\n \/* move vine_tail down one *\/\n vine_tail = remainder;\n remainder = remainder->as_expression() ?\n ((ir_expression *)remainder)->operands[1] : NULL;\n size++;\n } else {\n \/* rotate *\/\n ir_expression *tempptr = remainder_left;\n ((ir_expression *)remainder)->operands[0] = tempptr->operands[1];\n tempptr->operands[1] = remainder;\n remainder = tempptr;\n ((ir_expression *)vine_tail)->operands[1] = tempptr;\n }\n }\n\n return size;\n}\n\nstatic void\ncompression(ir_expression *root, unsigned count)\n{\n ir_expression *scanner = root;\n\n for (unsigned i = 0; i < count; i++) {\n ir_expression *child = (ir_expression *)scanner->operands[1];\n scanner->operands[1] = child->operands[1];\n scanner = (ir_expression *)scanner->operands[1];\n child->operands[1] = scanner->operands[0];\n scanner->operands[0] = child;\n }\n}\n\nstatic void\nvine_to_tree(ir_expression *root, unsigned size)\n{\n int n = size - 1;\n for (int m = n \/ 2; m > 0; m = n \/ 2) {\n compression(root, m);\n n -= m + 1;\n }\n}\n\nnamespace {\n\nclass ir_rebalance_visitor : public ir_rvalue_enter_visitor {\npublic:\n ir_rebalance_visitor()\n {\n progress = false;\n }\n\n void handle_rvalue(ir_rvalue **rvalue);\n\n bool progress;\n};\n\nstruct is_reduction_data {\n ir_expression_operation operation;\n const glsl_type *type;\n unsigned num_expr;\n bool is_reduction;\n bool contains_constant;\n};\n\n} \/* anonymous namespace *\/\n\nstatic bool\nis_reduction_operation(ir_expression_operation operation)\n{\n switch (operation) {\n case ir_binop_add:\n case ir_binop_mul:\n case ir_binop_bit_and:\n case ir_binop_bit_xor:\n case ir_binop_bit_or:\n case ir_binop_logic_and:\n case ir_binop_logic_xor:\n case ir_binop_logic_or:\n case ir_binop_min:\n case ir_binop_max:\n return true;\n default:\n return false;\n }\n}\n\n\/* Note that this function does not attempt to recognize that reduction trees\n * are already balanced.\n *\n * We return false from this function for a number of reasons other than an\n * expression tree not being a mathematical reduction. Namely,\n *\n * - if the tree contains multiple constants that we may be able to combine.\n * - if the tree contains matrices:\n * - they might contain vec4's with many constant components that we can\n * simplify after splitting.\n * - applying the matrix chain ordering optimization is more than just\n * balancing an expression tree.\n * - if the tree contains operations on multiple types.\n * - if the tree contains ir_dereference_{array,record}, since foo[a+b] + c\n * would trick the visiting pass.\n *\/\nstatic void\nis_reduction(ir_instruction *ir, void *data)\n{\n struct is_reduction_data *ird = (struct is_reduction_data *)data;\n if (!ird->is_reduction)\n return;\n\n \/* We don't want to balance a tree that contains multiple constants, since\n * we'll be able to constant fold them if they're not in separate subtrees.\n *\/\n if (ir->as_constant()) {\n if (ird->contains_constant) {\n ird->is_reduction = false;\n }\n ird->contains_constant = true;\n return;\n }\n\n \/* Array\/record dereferences have subtrees that are not part of the expr\n * tree we're balancing. Skip trees containing them.\n *\/\n if (ir->ir_type == ir_type_dereference_array ||\n ir->ir_type == ir_type_dereference_record) {\n ird->is_reduction = false;\n return;\n }\n\n ir_expression *expr = ir->as_expression();\n if (!expr)\n return;\n\n \/* Non-constant matrices might still contain constant vec4 that we can\n * constant fold once split up. Handling matrices will need some more\n * work.\n *\/\n if (expr->type->is_matrix() ||\n expr->operands[0]->type->is_matrix() ||\n (expr->operands[1] && expr->operands[1]->type->is_matrix())) {\n ird->is_reduction = false;\n return;\n }\n\n if (ird->type != NULL && ird->type != expr->type) {\n ird->is_reduction = false;\n return;\n }\n ird->type = expr->type;\n\n ird->num_expr++;\n if (is_reduction_operation(expr->operation)) {\n if (ird->operation != 0 && ird->operation != expr->operation)\n ird->is_reduction = false;\n ird->operation = expr->operation;\n } else {\n ird->is_reduction = false;\n }\n}\n\nstatic ir_rvalue *\nhandle_expression(ir_expression *expr)\n{\n struct is_reduction_data ird;\n ird.operation = (ir_expression_operation)0;\n ird.type = NULL;\n ird.num_expr = 0;\n ird.is_reduction = true;\n ird.contains_constant = false;\n\n visit_tree(expr, is_reduction, (void *)&ird);\n\n if (ird.is_reduction && ird.num_expr > 2) {\n ir_constant z = ir_constant(0.0f);\n ir_expression pseudo_root = ir_expression(ir_binop_add, &z, expr);\n\n unsigned size = tree_to_vine(&pseudo_root);\n vine_to_tree(&pseudo_root, size);\n\n expr = (ir_expression *)pseudo_root.operands[1];\n }\n return expr;\n}\n\nstatic void\nupdate_types(ir_instruction *ir, void *)\n{\n ir_expression *expr = ir->as_expression();\n if (!expr)\n return;\n\n const glsl_type *const new_type =\n glsl_type::get_instance(expr->type->base_type,\n MAX2(expr->operands[0]->type->vector_elements,\n expr->operands[1]->type->vector_elements),\n 1);\n assert(new_type != glsl_type::error_type);\n expr->type = new_type;\n}\n\nvoid\nir_rebalance_visitor::handle_rvalue(ir_rvalue **rvalue)\n{\n if (!*rvalue)\n return;\n\n ir_expression *expr = (*rvalue)->as_expression();\n if (!expr || !is_reduction_operation(expr->operation))\n return;\n\n ir_rvalue *new_rvalue = handle_expression(expr);\n\n \/* If we failed to rebalance the tree (e.g., because it wasn't a reduction,\n * or some other set of cases) new_rvalue will point to the same root as\n * before.\n *\n * Similarly, if the tree rooted at *rvalue was a reduction and was already\n * balanced, the algorithm will rearrange the tree but will ultimately\n * return an identical tree, so this check will handle that as well and\n * will not set progress = true.\n *\/\n if (new_rvalue == *rvalue)\n return;\n\n visit_tree(new_rvalue, NULL, NULL, update_types);\n\n *rvalue = new_rvalue;\n this->progress = true;\n}\n\nbool\ndo_rebalance_tree(exec_list *instructions)\n{\n ir_rebalance_visitor v;\n\n v.run(instructions);\n\n return v.progress;\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ libavg - Media Playback Engine. \n\/\/ Copyright (C) 2003-2006 Ulrich von Zadow\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ Current versions can be found at www.libavg.de\n\/\/\n\n#include \"FilterHighpass.h\"\n#include \"Filterfill.h\"\n#include \"Pixel8.h\"\n#include \"Bitmap.h\"\n\n#include \n#include \n\nusing namespace std;\n\nnamespace avg {\n \nFilterHighpass::FilterHighpass()\n{\n}\n\nFilterHighpass::~FilterHighpass()\n{\n}\n\nBitmapPtr FilterHighpass::apply(BitmapPtr pBmpSrc)\n{\n assert(pBmpSrc->getPixelFormat() == I8);\n BitmapPtr pBmpDest = BitmapPtr(new Bitmap(pBmpSrc->getSize(), I8,\n pBmpSrc->getName()));\n int SrcStride = pBmpSrc->getStride();\n int DestStride = pBmpDest->getStride();\n unsigned char * pSrcLine = pBmpSrc->getPixels()+3*SrcStride;\n unsigned char * pDestLine = pBmpDest->getPixels()+3*DestStride;\n IntPoint size = pBmpDest->getSize();\n for (int y = 3; ygetPixels(), 128, DestStride*3);\n memset(pBmpDest->getPixels()+DestStride*(size.y-3), 128, DestStride*3);\n return pBmpDest;\n}\n\n}\nPartial overflow bugfix in FilterHighpass.\/\/\n\/\/ libavg - Media Playback Engine. \n\/\/ Copyright (C) 2003-2006 Ulrich von Zadow\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ Current versions can be found at www.libavg.de\n\/\/\n\n#include \"FilterHighpass.h\"\n#include \"Filterfill.h\"\n#include \"Pixel8.h\"\n#include \"Bitmap.h\"\n\n#include \n#include \n\nusing namespace std;\n\nnamespace avg {\n \nFilterHighpass::FilterHighpass()\n{\n}\n\nFilterHighpass::~FilterHighpass()\n{\n}\n\nBitmapPtr FilterHighpass::apply(BitmapPtr pBmpSrc)\n{\n assert(pBmpSrc->getPixelFormat() == I8);\n BitmapPtr pBmpDest = BitmapPtr(new Bitmap(pBmpSrc->getSize(), I8,\n pBmpSrc->getName()));\n int SrcStride = pBmpSrc->getStride();\n int DestStride = pBmpDest->getStride();\n unsigned char * pSrcLine = pBmpSrc->getPixels()+3*SrcStride;\n unsigned char * pDestLine = pBmpDest->getPixels()+3*DestStride;\n IntPoint size = pBmpDest->getSize();\n for (int y = 3; ygetPixels(), 128, DestStride*3);\n memset(pBmpDest->getPixels()+DestStride*(size.y-3), 128, DestStride*3);\n return pBmpDest;\n}\n\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright © 2008, 2009 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\/\n#include \n#include \n#include \n\n#include \"ast.h\"\n#include \"glsl_parser_extras.h\"\n#include \"glsl_parser.h\"\n#include \"ir_optimization.h\"\n#include \"ir_print_visitor.h\"\n#include \"program.h\"\n#include \"loop_analysis.h\"\n\nextern \"C\" struct gl_shader *\n_mesa_new_shader(struct gl_context *ctx, GLuint name, GLenum type);\n\nextern \"C\" void\n_mesa_reference_shader(struct gl_context *ctx, struct gl_shader **ptr,\n struct gl_shader *sh);\n\n\/* Copied from shader_api.c for the stand-alone compiler.\n *\/\nvoid\n_mesa_reference_shader(struct gl_context *ctx, struct gl_shader **ptr,\n struct gl_shader *sh)\n{\n *ptr = sh;\n}\n\nstruct gl_shader *\n_mesa_new_shader(struct gl_context *ctx, GLuint name, GLenum type)\n{\n struct gl_shader *shader;\n\n (void) ctx;\n\n assert(type == GL_FRAGMENT_SHADER || type == GL_VERTEX_SHADER);\n shader = talloc_zero(NULL, struct gl_shader);\n if (shader) {\n shader->Type = type;\n shader->Name = name;\n shader->RefCount = 1;\n }\n return shader;\n}\n\nstatic void\ninitialize_context(struct gl_context *ctx, gl_api api)\n{\n memset(ctx, 0, sizeof(*ctx));\n\n ctx->API = api;\n\n ctx->Extensions.ARB_draw_buffers = GL_TRUE;\n ctx->Extensions.ARB_fragment_coord_conventions = GL_TRUE;\n ctx->Extensions.EXT_texture_array = GL_TRUE;\n ctx->Extensions.NV_texture_rectangle = GL_TRUE;\n\n \/* 1.10 minimums. *\/\n ctx->Const.MaxLights = 8;\n ctx->Const.MaxClipPlanes = 8;\n ctx->Const.MaxTextureUnits = 2;\n\n \/* More than the 1.10 minimum to appease parser tests taken from\n * apps that (hopefully) already checked the number of coords.\n *\/\n ctx->Const.MaxTextureCoordUnits = 4;\n\n ctx->Const.VertexProgram.MaxAttribs = 16;\n ctx->Const.VertexProgram.MaxUniformComponents = 512;\n ctx->Const.MaxVarying = 8;\n ctx->Const.MaxVertexTextureImageUnits = 0;\n ctx->Const.MaxCombinedTextureImageUnits = 2;\n ctx->Const.MaxTextureImageUnits = 2;\n ctx->Const.FragmentProgram.MaxUniformComponents = 64;\n\n ctx->Const.MaxDrawBuffers = 2;\n\n ctx->Driver.NewShader = _mesa_new_shader;\n}\n\n\/* Returned string will have 'ctx' as its talloc owner. *\/\nstatic char *\nload_text_file(void *ctx, const char *file_name)\n{\n\tchar *text = NULL;\n\tsize_t size;\n\tsize_t total_read = 0;\n\tFILE *fp = fopen(file_name, \"rb\");\n\n\tif (!fp) {\n\t\treturn NULL;\n\t}\n\n\tfseek(fp, 0L, SEEK_END);\n\tsize = ftell(fp);\n\tfseek(fp, 0L, SEEK_SET);\n\n\ttext = (char *) talloc_size(ctx, size + 1);\n\tif (text != NULL) {\n\t\tdo {\n\t\t\tsize_t bytes = fread(text + total_read,\n\t\t\t\t\t 1, size - total_read, fp);\n\t\t\tif (bytes < size - total_read) {\n\t\t\t\tfree(text);\n\t\t\t\ttext = NULL;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (bytes == 0) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\ttotal_read += bytes;\n\t\t} while (total_read < size);\n\n\t\ttext[total_read] = '\\0';\n\t}\n\n\tfclose(fp);\n\n\treturn text;\n}\n\nint glsl_es = 0;\nint dump_ast = 0;\nint dump_hir = 0;\nint dump_lir = 0;\nint do_link = 0;\n\nconst struct option compiler_opts[] = {\n { \"glsl-es\", 0, &glsl_es, 1 },\n { \"dump-ast\", 0, &dump_ast, 1 },\n { \"dump-hir\", 0, &dump_hir, 1 },\n { \"dump-lir\", 0, &dump_lir, 1 },\n { \"link\", 0, &do_link, 1 },\n { NULL, 0, NULL, 0 }\n};\n\n\/**\n * \\brief Print proper usage and exit with failure.\n *\/\nvoid\nusage_fail(const char *name)\n{\n\n const char *header =\n \"usage: %s [options] \\n\"\n \"\\n\"\n \"Possible options are:\\n\";\n printf(header, name, name);\n for (const struct option *o = compiler_opts; o->name != 0; ++o) {\n printf(\" --%s\\n\", o->name);\n }\n exit(EXIT_FAILURE);\n}\n\n\nvoid\ncompile_shader(struct gl_context *ctx, struct gl_shader *shader)\n{\n struct _mesa_glsl_parse_state *state =\n new(shader) _mesa_glsl_parse_state(ctx, shader->Type, shader);\n\n const char *source = shader->Source;\n state->error = preprocess(state, &source, &state->info_log,\n\t\t\t state->extensions, ctx->API);\n\n if (!state->error) {\n _mesa_glsl_lexer_ctor(state, source);\n _mesa_glsl_parse(state);\n _mesa_glsl_lexer_dtor(state);\n }\n\n if (dump_ast) {\n foreach_list_const(n, &state->translation_unit) {\n\t ast_node *ast = exec_node_data(ast_node, n, link);\n\t ast->print();\n }\n printf(\"\\n\\n\");\n }\n\n shader->ir = new(shader) exec_list;\n if (!state->error && !state->translation_unit.is_empty())\n _mesa_ast_to_hir(shader->ir, state);\n\n \/* Print out the unoptimized IR. *\/\n if (!state->error && dump_hir) {\n validate_ir_tree(shader->ir);\n _mesa_print_ir(shader->ir, state);\n }\n\n \/* Optimization passes *\/\n if (!state->error && !shader->ir->is_empty()) {\n bool progress;\n do {\n\t progress = do_common_optimization(shader->ir, false, 32);\n } while (progress);\n\n validate_ir_tree(shader->ir);\n }\n\n\n \/* Print out the resulting IR *\/\n if (!state->error && dump_lir) {\n _mesa_print_ir(shader->ir, state);\n }\n\n shader->symbols = state->symbols;\n shader->CompileStatus = !state->error;\n shader->Version = state->language_version;\n memcpy(shader->builtins_to_link, state->builtins_to_link,\n\t sizeof(shader->builtins_to_link[0]) * state->num_builtins_to_link);\n shader->num_builtins_to_link = state->num_builtins_to_link;\n\n if (shader->InfoLog)\n talloc_free(shader->InfoLog);\n\n shader->InfoLog = state->info_log;\n\n \/* Retain any live IR, but trash the rest. *\/\n reparent_ir(shader->ir, shader);\n\n talloc_free(state);\n\n return;\n}\n\nint\nmain(int argc, char **argv)\n{\n int status = EXIT_SUCCESS;\n struct gl_context local_ctx;\n struct gl_context *ctx = &local_ctx;\n\n int c;\n int idx = 0;\n while ((c = getopt_long(argc, argv, \"\", compiler_opts, &idx)) != -1)\n \/* empty *\/ ;\n\n\n if (argc <= optind)\n usage_fail(argv[0]);\n\n initialize_context(ctx, (glsl_es) ? API_OPENGLES2 : API_OPENGL);\n\n struct gl_shader_program *whole_program;\n\n whole_program = talloc_zero (NULL, struct gl_shader_program);\n assert(whole_program != NULL);\n\n for (\/* empty *\/; argc > optind; optind++) {\n whole_program->Shaders = (struct gl_shader **)\n\t talloc_realloc(whole_program, whole_program->Shaders,\n\t\t\tstruct gl_shader *, whole_program->NumShaders + 1);\n assert(whole_program->Shaders != NULL);\n\n struct gl_shader *shader = talloc_zero(whole_program, gl_shader);\n\n whole_program->Shaders[whole_program->NumShaders] = shader;\n whole_program->NumShaders++;\n\n const unsigned len = strlen(argv[optind]);\n if (len < 6)\n\t usage_fail(argv[0]);\n\n const char *const ext = & argv[optind][len - 5];\n if (strncmp(\".vert\", ext, 5) == 0)\n\t shader->Type = GL_VERTEX_SHADER;\n else if (strncmp(\".geom\", ext, 5) == 0)\n\t shader->Type = GL_GEOMETRY_SHADER;\n else if (strncmp(\".frag\", ext, 5) == 0)\n\t shader->Type = GL_FRAGMENT_SHADER;\n else\n\t usage_fail(argv[0]);\n\n shader->Source = load_text_file(whole_program, argv[optind]);\n if (shader->Source == NULL) {\n\t printf(\"File \\\"%s\\\" does not exist.\\n\", argv[optind]);\n\t exit(EXIT_FAILURE);\n }\n\n compile_shader(ctx, shader);\n\n if (!shader->CompileStatus) {\n\t printf(\"Info log for %s:\\n%s\\n\", argv[optind], shader->InfoLog);\n\t status = EXIT_FAILURE;\n\t break;\n }\n }\n\n if ((status == EXIT_SUCCESS) && do_link) {\n link_shaders(ctx, whole_program);\n status = (whole_program->LinkStatus) ? EXIT_SUCCESS : EXIT_FAILURE;\n\n if (strlen(whole_program->InfoLog) > 0)\n\t printf(\"Info log for linking:\\n%s\\n\", whole_program->InfoLog);\n }\n\n for (unsigned i = 0; i < MESA_SHADER_TYPES; i++)\n talloc_free(whole_program->_LinkedShaders[i]);\n\n talloc_free(whole_program);\n _mesa_glsl_release_types();\n _mesa_glsl_release_functions();\n\n return status;\n}\nglsl: fix implicit int to bool warning\/*\n * Copyright © 2008, 2009 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\/\n#include \n#include \n#include \n\n#include \"ast.h\"\n#include \"glsl_parser_extras.h\"\n#include \"glsl_parser.h\"\n#include \"ir_optimization.h\"\n#include \"ir_print_visitor.h\"\n#include \"program.h\"\n#include \"loop_analysis.h\"\n\nextern \"C\" struct gl_shader *\n_mesa_new_shader(struct gl_context *ctx, GLuint name, GLenum type);\n\nextern \"C\" void\n_mesa_reference_shader(struct gl_context *ctx, struct gl_shader **ptr,\n struct gl_shader *sh);\n\n\/* Copied from shader_api.c for the stand-alone compiler.\n *\/\nvoid\n_mesa_reference_shader(struct gl_context *ctx, struct gl_shader **ptr,\n struct gl_shader *sh)\n{\n *ptr = sh;\n}\n\nstruct gl_shader *\n_mesa_new_shader(struct gl_context *ctx, GLuint name, GLenum type)\n{\n struct gl_shader *shader;\n\n (void) ctx;\n\n assert(type == GL_FRAGMENT_SHADER || type == GL_VERTEX_SHADER);\n shader = talloc_zero(NULL, struct gl_shader);\n if (shader) {\n shader->Type = type;\n shader->Name = name;\n shader->RefCount = 1;\n }\n return shader;\n}\n\nstatic void\ninitialize_context(struct gl_context *ctx, gl_api api)\n{\n memset(ctx, 0, sizeof(*ctx));\n\n ctx->API = api;\n\n ctx->Extensions.ARB_draw_buffers = GL_TRUE;\n ctx->Extensions.ARB_fragment_coord_conventions = GL_TRUE;\n ctx->Extensions.EXT_texture_array = GL_TRUE;\n ctx->Extensions.NV_texture_rectangle = GL_TRUE;\n\n \/* 1.10 minimums. *\/\n ctx->Const.MaxLights = 8;\n ctx->Const.MaxClipPlanes = 8;\n ctx->Const.MaxTextureUnits = 2;\n\n \/* More than the 1.10 minimum to appease parser tests taken from\n * apps that (hopefully) already checked the number of coords.\n *\/\n ctx->Const.MaxTextureCoordUnits = 4;\n\n ctx->Const.VertexProgram.MaxAttribs = 16;\n ctx->Const.VertexProgram.MaxUniformComponents = 512;\n ctx->Const.MaxVarying = 8;\n ctx->Const.MaxVertexTextureImageUnits = 0;\n ctx->Const.MaxCombinedTextureImageUnits = 2;\n ctx->Const.MaxTextureImageUnits = 2;\n ctx->Const.FragmentProgram.MaxUniformComponents = 64;\n\n ctx->Const.MaxDrawBuffers = 2;\n\n ctx->Driver.NewShader = _mesa_new_shader;\n}\n\n\/* Returned string will have 'ctx' as its talloc owner. *\/\nstatic char *\nload_text_file(void *ctx, const char *file_name)\n{\n\tchar *text = NULL;\n\tsize_t size;\n\tsize_t total_read = 0;\n\tFILE *fp = fopen(file_name, \"rb\");\n\n\tif (!fp) {\n\t\treturn NULL;\n\t}\n\n\tfseek(fp, 0L, SEEK_END);\n\tsize = ftell(fp);\n\tfseek(fp, 0L, SEEK_SET);\n\n\ttext = (char *) talloc_size(ctx, size + 1);\n\tif (text != NULL) {\n\t\tdo {\n\t\t\tsize_t bytes = fread(text + total_read,\n\t\t\t\t\t 1, size - total_read, fp);\n\t\t\tif (bytes < size - total_read) {\n\t\t\t\tfree(text);\n\t\t\t\ttext = NULL;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (bytes == 0) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\ttotal_read += bytes;\n\t\t} while (total_read < size);\n\n\t\ttext[total_read] = '\\0';\n\t}\n\n\tfclose(fp);\n\n\treturn text;\n}\n\nint glsl_es = 0;\nint dump_ast = 0;\nint dump_hir = 0;\nint dump_lir = 0;\nint do_link = 0;\n\nconst struct option compiler_opts[] = {\n { \"glsl-es\", 0, &glsl_es, 1 },\n { \"dump-ast\", 0, &dump_ast, 1 },\n { \"dump-hir\", 0, &dump_hir, 1 },\n { \"dump-lir\", 0, &dump_lir, 1 },\n { \"link\", 0, &do_link, 1 },\n { NULL, 0, NULL, 0 }\n};\n\n\/**\n * \\brief Print proper usage and exit with failure.\n *\/\nvoid\nusage_fail(const char *name)\n{\n\n const char *header =\n \"usage: %s [options] \\n\"\n \"\\n\"\n \"Possible options are:\\n\";\n printf(header, name, name);\n for (const struct option *o = compiler_opts; o->name != 0; ++o) {\n printf(\" --%s\\n\", o->name);\n }\n exit(EXIT_FAILURE);\n}\n\n\nvoid\ncompile_shader(struct gl_context *ctx, struct gl_shader *shader)\n{\n struct _mesa_glsl_parse_state *state =\n new(shader) _mesa_glsl_parse_state(ctx, shader->Type, shader);\n\n const char *source = shader->Source;\n state->error = preprocess(state, &source, &state->info_log,\n\t\t\t state->extensions, ctx->API) != 0;\n\n if (!state->error) {\n _mesa_glsl_lexer_ctor(state, source);\n _mesa_glsl_parse(state);\n _mesa_glsl_lexer_dtor(state);\n }\n\n if (dump_ast) {\n foreach_list_const(n, &state->translation_unit) {\n\t ast_node *ast = exec_node_data(ast_node, n, link);\n\t ast->print();\n }\n printf(\"\\n\\n\");\n }\n\n shader->ir = new(shader) exec_list;\n if (!state->error && !state->translation_unit.is_empty())\n _mesa_ast_to_hir(shader->ir, state);\n\n \/* Print out the unoptimized IR. *\/\n if (!state->error && dump_hir) {\n validate_ir_tree(shader->ir);\n _mesa_print_ir(shader->ir, state);\n }\n\n \/* Optimization passes *\/\n if (!state->error && !shader->ir->is_empty()) {\n bool progress;\n do {\n\t progress = do_common_optimization(shader->ir, false, 32);\n } while (progress);\n\n validate_ir_tree(shader->ir);\n }\n\n\n \/* Print out the resulting IR *\/\n if (!state->error && dump_lir) {\n _mesa_print_ir(shader->ir, state);\n }\n\n shader->symbols = state->symbols;\n shader->CompileStatus = !state->error;\n shader->Version = state->language_version;\n memcpy(shader->builtins_to_link, state->builtins_to_link,\n\t sizeof(shader->builtins_to_link[0]) * state->num_builtins_to_link);\n shader->num_builtins_to_link = state->num_builtins_to_link;\n\n if (shader->InfoLog)\n talloc_free(shader->InfoLog);\n\n shader->InfoLog = state->info_log;\n\n \/* Retain any live IR, but trash the rest. *\/\n reparent_ir(shader->ir, shader);\n\n talloc_free(state);\n\n return;\n}\n\nint\nmain(int argc, char **argv)\n{\n int status = EXIT_SUCCESS;\n struct gl_context local_ctx;\n struct gl_context *ctx = &local_ctx;\n\n int c;\n int idx = 0;\n while ((c = getopt_long(argc, argv, \"\", compiler_opts, &idx)) != -1)\n \/* empty *\/ ;\n\n\n if (argc <= optind)\n usage_fail(argv[0]);\n\n initialize_context(ctx, (glsl_es) ? API_OPENGLES2 : API_OPENGL);\n\n struct gl_shader_program *whole_program;\n\n whole_program = talloc_zero (NULL, struct gl_shader_program);\n assert(whole_program != NULL);\n\n for (\/* empty *\/; argc > optind; optind++) {\n whole_program->Shaders = (struct gl_shader **)\n\t talloc_realloc(whole_program, whole_program->Shaders,\n\t\t\tstruct gl_shader *, whole_program->NumShaders + 1);\n assert(whole_program->Shaders != NULL);\n\n struct gl_shader *shader = talloc_zero(whole_program, gl_shader);\n\n whole_program->Shaders[whole_program->NumShaders] = shader;\n whole_program->NumShaders++;\n\n const unsigned len = strlen(argv[optind]);\n if (len < 6)\n\t usage_fail(argv[0]);\n\n const char *const ext = & argv[optind][len - 5];\n if (strncmp(\".vert\", ext, 5) == 0)\n\t shader->Type = GL_VERTEX_SHADER;\n else if (strncmp(\".geom\", ext, 5) == 0)\n\t shader->Type = GL_GEOMETRY_SHADER;\n else if (strncmp(\".frag\", ext, 5) == 0)\n\t shader->Type = GL_FRAGMENT_SHADER;\n else\n\t usage_fail(argv[0]);\n\n shader->Source = load_text_file(whole_program, argv[optind]);\n if (shader->Source == NULL) {\n\t printf(\"File \\\"%s\\\" does not exist.\\n\", argv[optind]);\n\t exit(EXIT_FAILURE);\n }\n\n compile_shader(ctx, shader);\n\n if (!shader->CompileStatus) {\n\t printf(\"Info log for %s:\\n%s\\n\", argv[optind], shader->InfoLog);\n\t status = EXIT_FAILURE;\n\t break;\n }\n }\n\n if ((status == EXIT_SUCCESS) && do_link) {\n link_shaders(ctx, whole_program);\n status = (whole_program->LinkStatus) ? EXIT_SUCCESS : EXIT_FAILURE;\n\n if (strlen(whole_program->InfoLog) > 0)\n\t printf(\"Info log for linking:\\n%s\\n\", whole_program->InfoLog);\n }\n\n for (unsigned i = 0; i < MESA_SHADER_TYPES; i++)\n talloc_free(whole_program->_LinkedShaders[i]);\n\n talloc_free(whole_program);\n _mesa_glsl_release_types();\n _mesa_glsl_release_functions();\n\n return status;\n}\n<|endoftext|>"} {"text":"\/\/ Check that we transparently fallback to llvm-gcc for i386 kexts, we don't\n\/\/ support the ABI they use (yet).\n\n\/\/ RUN: %clang -target i386-apple-darwin10 \\\n\/\/ RUN: -fapple-kext -### -fsyntax-only %s 2> %t\n\/\/ RUN: FileCheck --check-prefix=CHECK < %t %s\n\n\/\/ CHECK: cc1plus\"\n\/\/ CHECK: \"-fapple-kext\"\n\n\/\/ RUN: %clang -target i386-apple-darwin10 \\\n\/\/ RUN: -mkernel -### -fsyntax-only %s 2> %t\n\/\/ RUN: FileCheck --check-prefix=CHECK-MKERNEL < %t %s\n\n\/\/ CHECK-MKERNEL: cc1plus\"\n\/\/ CHECK-MKERNEL: \"-mkernel\"\n\n\/\/ RUN: %clang -target i386-apple-darwin10 \\\n\/\/ RUN: -Wno-self-assign -Wc++11-extensions -Wno-microsoft -Wmicrosoft -Wvla \\\n\/\/ RUN: -faltivec -mthumb -mcpu=G4 -mlongcall -mno-longcall -msoft-float \\\n\/\/ RUN: -fapple-kext -### -fsyntax-only %s 2> %t\n\/\/ RUN: FileCheck --check-prefix=CHECK-UNSUPPORTED < %t %s\n\n\/\/ CHECK-UNSUPPORTED: cc1plus\"\n\/\/ CHECK-UNSUPPORTED-NOT: \"-Wno-self-assign\"\n\/\/ CHECK-UNSUPPORTED-NOT: \"-Wc++11-extensions\"\n\/\/ CHECK-UNSUPPORTED-NOT: \"-Wno-microsoft\"\n\/\/ CHECK-UNSUPPORTED-NOT: \"-Wmicrosoft\"\n\/\/ CHECK-UNSUPPORTED-NOT: \"-Wvla\"\n\/\/ CHECK-UNSUPPORTED-NOT: \"-faltivec\"\n\/\/ CHECK-UNSUPPORTED-NOT: \"-mthumb\"\n\/\/ CHECK-UNSUPPORTED-NOT: \"-mlongcall\"\n\/\/ CHECK-UNSUPPORTED: \"-mno-longcall\"\n\/\/ CHECK-UNSUPPORTED: \"-msoft-float\"\n\n\/\/ RUN: %clang -target i386-apple-darwin10 \\\n\/\/ RUN: -Wconstant-logical-operand -save-temps \\\n\/\/ RUN: -fapple-kext -### -fsyntax-only %s 2> %t\n\/\/ RUN: FileCheck --check-prefix=CHECK-UNSUPPORTED2 < %t %s\n\n\/\/ CHECK-UNSUPPORTED2: cc1plus\"\n\/\/ CHECK-UNSUPPORTED2-NOT: \"-Wconstant-logical-operand\"\n\n\/\/ Check that --serialize-diagnostics does not cause an \"argument unused\" error.\n\/\/ RUN: %clang -target i386-apple-darwin10 \\\n\/\/ RUN: -Werror -Wall -Wno-comment -fapple-kext \\\n\/\/ RUN: --serialize-diagnostics %t.dia -c %s\nDon't actually execute gcc during testing.\/\/ Check that we transparently fallback to llvm-gcc for i386 kexts, we don't\n\/\/ support the ABI they use (yet).\n\n\/\/ RUN: %clang -target i386-apple-darwin10 \\\n\/\/ RUN: -fapple-kext -### -fsyntax-only %s 2> %t\n\/\/ RUN: FileCheck --check-prefix=CHECK < %t %s\n\n\/\/ CHECK: cc1plus\"\n\/\/ CHECK: \"-fapple-kext\"\n\n\/\/ RUN: %clang -target i386-apple-darwin10 \\\n\/\/ RUN: -mkernel -### -fsyntax-only %s 2> %t\n\/\/ RUN: FileCheck --check-prefix=CHECK-MKERNEL < %t %s\n\n\/\/ CHECK-MKERNEL: cc1plus\"\n\/\/ CHECK-MKERNEL: \"-mkernel\"\n\n\/\/ RUN: %clang -target i386-apple-darwin10 \\\n\/\/ RUN: -Wno-self-assign -Wc++11-extensions -Wno-microsoft -Wmicrosoft -Wvla \\\n\/\/ RUN: -faltivec -mthumb -mcpu=G4 -mlongcall -mno-longcall -msoft-float \\\n\/\/ RUN: -fapple-kext -### -fsyntax-only %s 2> %t\n\/\/ RUN: FileCheck --check-prefix=CHECK-UNSUPPORTED < %t %s\n\n\/\/ CHECK-UNSUPPORTED: cc1plus\"\n\/\/ CHECK-UNSUPPORTED-NOT: \"-Wno-self-assign\"\n\/\/ CHECK-UNSUPPORTED-NOT: \"-Wc++11-extensions\"\n\/\/ CHECK-UNSUPPORTED-NOT: \"-Wno-microsoft\"\n\/\/ CHECK-UNSUPPORTED-NOT: \"-Wmicrosoft\"\n\/\/ CHECK-UNSUPPORTED-NOT: \"-Wvla\"\n\/\/ CHECK-UNSUPPORTED-NOT: \"-faltivec\"\n\/\/ CHECK-UNSUPPORTED-NOT: \"-mthumb\"\n\/\/ CHECK-UNSUPPORTED-NOT: \"-mlongcall\"\n\/\/ CHECK-UNSUPPORTED: \"-mno-longcall\"\n\/\/ CHECK-UNSUPPORTED: \"-msoft-float\"\n\n\/\/ RUN: %clang -target i386-apple-darwin10 \\\n\/\/ RUN: -Wconstant-logical-operand -save-temps \\\n\/\/ RUN: -fapple-kext -### -fsyntax-only %s 2> %t\n\/\/ RUN: FileCheck --check-prefix=CHECK-UNSUPPORTED2 < %t %s\n\n\/\/ CHECK-UNSUPPORTED2: cc1plus\"\n\/\/ CHECK-UNSUPPORTED2-NOT: \"-Wconstant-logical-operand\"\n\n\/\/ Check that --serialize-diagnostics does not cause an \"argument unused\" error.\n\/\/ RUN: %clang -target i386-apple-darwin10 \\\n\/\/ RUN: -Werror -Wall -Wno-comment -fapple-kext -### \\\n\/\/ RUN: --serialize-diagnostics %t.dia -c %s 2>&1 | \\\n\/\/ RUN: FileCheck --check-prefix=CHECK-UNUSED %s\n\n\/\/ CHECK-UNUSED-NOT: argument unused\n\/\/ CHECK-UNUSED: cc1plus\n<|endoftext|>"} {"text":"#include \"ieventdispatcher.h\"\n\n#include \"iconnection.h\"\n\n#include \n\n#define IEVENTDISPATCHER_DEBUG\n\nusing namespace std;\n\nIEventDispatcher::~IEventDispatcher()\n{\n map::iterator it = m_connections.begin();\n for ( ; it != m_connections.end(); it = m_connections.begin() ) {\n it->second->setEventDispatcher(0);\n }\n}\n\nbool IEventDispatcher::addConnection(IConnection *conn)\n{\n pair::iterator, bool> insertResult;\n insertResult = m_connections.insert(make_pair(conn->fileDescriptor(), conn));\n return insertResult.second;\n}\n\nbool IEventDispatcher::removeConnection(IConnection *conn)\n{\n return m_connections.erase(conn->fileDescriptor());\n}\n\nvoid IEventDispatcher::notifyConnectionForReading(FileDescriptor fd)\n{\n std::map::iterator it = m_connections.find(fd);\n if (it != m_connections.end()) {\n it->second->notifyRead();\n } else {\n#ifdef IEVENTDISPATCHER_DEBUG\n \/\/ while interesting for debugging, this is not an error if a connection was in the epoll\n \/\/ set and disconnected in its notifyRead() or notifyWrite() implementation\n printf(\"IEventDispatcher::notifyRead(): unhandled file descriptor %d.\\n\", fd);\n#endif\n }\n}\n\nvoid IEventDispatcher::notifyConnectionForWriting(FileDescriptor fd)\n{\n std::map::iterator it = m_connections.find(fd);\n if (it != m_connections.end()) {\n it->second->notifyRead();\n } else {\n#ifdef IEVENTDISPATCHER_DEBUG\n \/\/ while interesting for debugging, this is not an error if a connection was in the epoll\n \/\/ set and disconnected in its notifyRead() or notifyWrite() implementation\n printf(\"IEventDispatcher::notifyWrite(): unhandled file descriptor %d.\\n\", fd);\n#endif\n }\n}\nIn notifyConnectionForWriting(), call notifyWrite(), not notifyRead().#include \"ieventdispatcher.h\"\n\n#include \"iconnection.h\"\n\n#include \n\n#define IEVENTDISPATCHER_DEBUG\n\nusing namespace std;\n\nIEventDispatcher::~IEventDispatcher()\n{\n map::iterator it = m_connections.begin();\n for ( ; it != m_connections.end(); it = m_connections.begin() ) {\n it->second->setEventDispatcher(0);\n }\n}\n\nbool IEventDispatcher::addConnection(IConnection *conn)\n{\n pair::iterator, bool> insertResult;\n insertResult = m_connections.insert(make_pair(conn->fileDescriptor(), conn));\n return insertResult.second;\n}\n\nbool IEventDispatcher::removeConnection(IConnection *conn)\n{\n return m_connections.erase(conn->fileDescriptor());\n}\n\nvoid IEventDispatcher::notifyConnectionForReading(FileDescriptor fd)\n{\n std::map::iterator it = m_connections.find(fd);\n if (it != m_connections.end()) {\n it->second->notifyRead();\n } else {\n#ifdef IEVENTDISPATCHER_DEBUG\n \/\/ while interesting for debugging, this is not an error if a connection was in the epoll\n \/\/ set and disconnected in its notifyRead() or notifyWrite() implementation\n printf(\"IEventDispatcher::notifyRead(): unhandled file descriptor %d.\\n\", fd);\n#endif\n }\n}\n\nvoid IEventDispatcher::notifyConnectionForWriting(FileDescriptor fd)\n{\n std::map::iterator it = m_connections.find(fd);\n if (it != m_connections.end()) {\n it->second->notifyWrite();\n } else {\n#ifdef IEVENTDISPATCHER_DEBUG\n \/\/ while interesting for debugging, this is not an error if a connection was in the epoll\n \/\/ set and disconnected in its notifyRead() or notifyWrite() implementation\n printf(\"IEventDispatcher::notifyWrite(): unhandled file descriptor %d.\\n\", fd);\n#endif\n }\n}\n<|endoftext|>"} {"text":"\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2010 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef STREAM_HELPER_HXX_INCLUDED\n#define STREAM_HELPER_HXX_INCLUDED\n\n#include \"internal\/types.hxx\"\n\nclass IStream;\n\nclass BufferStream : public StreamInterface\n{\npublic:\n BufferStream(IStream *str);\n ~BufferStream();\n unsigned long sread (unsigned char *vuf, unsigned long size);\n long stell ();\n long sseek (unsigned long offset, int origin);\nprivate:\n IStream *stream;\n};\n\nclass FileStream : public StreamInterface\n{\npublic:\n FileStream(const char *filename);\n ~FileStream();\n unsigned long sread (unsigned char *buf, unsigned long size);\n long stell ();\n long sseek (unsigned long offset, int origin);\nprivate:\n FILE *file;\n};\n\n#endif\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\nWaE: C4099: type name first seen using struct now using class\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2010 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef STREAM_HELPER_HXX_INCLUDED\n#define STREAM_HELPER_HXX_INCLUDED\n\n#include \"internal\/types.hxx\"\n\nstruct IStream;\n\nclass BufferStream : public StreamInterface\n{\npublic:\n BufferStream(IStream *str);\n ~BufferStream();\n unsigned long sread (unsigned char *vuf, unsigned long size);\n long stell ();\n long sseek (unsigned long offset, int origin);\nprivate:\n IStream *stream;\n};\n\nclass FileStream : public StreamInterface\n{\npublic:\n FileStream(const char *filename);\n ~FileStream();\n unsigned long sread (unsigned char *buf, unsigned long size);\n long stell ();\n long sseek (unsigned long offset, int origin);\nprivate:\n FILE *file;\n};\n\n#endif\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"\n\n#include \"histoBook.h\"\n#include \"TKey.h\"\n#include \"TObject.h\"\n\n\/\/ constructor sets the name of the file for saving\nhistoBook::histoBook( string name, string input, string inDir ){\n\n\tif (name.find( \".root\") != std::string::npos){\n\t\tfilename = name;\t\n\t} else\n\t\tfilename = name + \".root\";\n\n\tcurrentDir = \"\/\";\n\n\tfile = new TFile( filename.c_str(), \"recreate\" );\n\tfile->cd();\n\n\t\n\t\/\/ make the legend and draw it once to apply styles etc. \n\t\/\/ for some reason needed to make styling work on the first draw\n\tlegend = new TLegend( 0.65, 0.65, 0.9, 0.9);\n\tlegend->SetFillColor( kWhite );\n\tlegend->Draw();\n\tlegend->Clear();\n\n\tglobalStyle();\n\n\t\/\/ if an input was given merge it into the live record\n\tif ( input.length() >= 5 ){\n\t\tTFile * fin = new TFile( input.c_str() );\n\t\tcd ( inDir );\n\t\tfin->cd( inDir.c_str() );\n\t\tloadRootDir( gDirectory, inDir );\n\t}\n\n\n\n}\n\/\/ destructor\nhistoBook::~histoBook(){\n\n\tdelete legend;\n\n\tsave();\n\tfile->Close();\n}\nvoid histoBook::save() {\n\n\tfile->Write();\n}\n\nvoid histoBook::loadRootDir( TDirectory* tDir, string path ){\n\n\t\/\/cout << \"histoBook.loadRootDir] Path : \" << path << endl;\n\n\tTList* list;\n\n\tif ( tDir ){\n\t\tlist = tDir->GetListOfKeys(); \n\t} else {\n\t\tcout << \"[histoBook.loadRootDir] Bad Directory Given \" << endl;\n\t\treturn;\n\t}\n\n\tTIter next(list); \n\tTKey* key; \n\tTObject* obj; \n\t\n\twhile ( (key = (TKey*)next()) ) { \n\t\t\n\t\tobj = key->ReadObj() ; \n\t\t\n\t\tif ( 0 == strcmp(obj->IsA()->GetName(),\"TDirectoryFile\") ){\n\t\t\tTDirectoryFile* dir = (TDirectoryFile*)obj;\n\t\t\t\n\t\t\tstring nPath = path + dir->GetName();\n\t\t\tif ( path == (string) \"\" )\n\t\t\t\tnPath = path + dir->GetName();\n\t\t\telse \n\t\t\t\tnPath = path + \"\/\" + dir->GetName();\n\n\t\t\tcd( nPath );\n\t\t\tloadRootDir( dir, nPath );\n\t\t} else if ( obj ){\n\t\t\tif ( (strcmp(obj->IsA()->GetName(),\"TProfile\")!=0) && (!obj->InheritsFrom(\"TH2\") && (!obj->InheritsFrom(\"TH1\"))) ) { \n\t\t\t\t\/\/ not a 1d or 2d histogram\n\t\t\t} else {\n\t\t\t\t\/\/ add it to the book\n\t\t\t\t\/\/cout << \"Adding : \" << obj->GetName() << endl;\n\t\t\t\tadd( obj->GetName(), (TH1*)obj->Clone( obj->GetName() ) );\n\t\t\t} \n\t\t\t\n\t\t}\n\t}\t\n\n}\n\n\nvoid histoBook::add( string name, TH1* h ){\n\n\tstring oName = name;\n\tif ( name.length() <= 1 || !h )\n\t\treturn;\n\n\tname = currentDir + name;\n\t\n\t\/\/ dont allow duplicated name overites\n\tif ( book[ name ] ){\n\t\tcout << \"[histoBook.add] Duplicate histogram name in this directory \" << currentDir << \" \/ \" << oName << endl;\n\t\treturn;\n\t}\n\n\t\/\/ save the histo to the map\n\tbook[ name ] = h;\n\n}\n\/*\n*\n* TODO:: add support for full subdirectory trees\n*\/\nstring histoBook::cd( string sdir ){\n\n\tstring old = currentDir;\n\n\tchar* csdir = (char*)sdir.c_str();\n\tfile->cd();\n\n\tif ( file->GetDirectory( csdir ) ){\n\t\tfile->cd( csdir );\n\t} else {\n\t\tcout << \"[histoBook.cd] creating directory \" << sdir << endl;\n\t\tfile->mkdir( csdir );\n\t\tfile->cd( csdir );\n\t}\n\n\tcurrentDir = sdir;\n\n\treturn old;\n}\n\nvoid histoBook::make( xmlConfig * config, string nodeName ){\n\n\tif ( config && config->nodeExists( nodeName ) ){\n\t\t\n\t\tstring hName = config->tagName( nodeName );\n\t\tif ( \"\" == hName )\n\t\t\thName = nodeName;\n\n\t\tstring type = config->getString( nodeName + \":type\", \"1D\" );\n\n\t\tif ( \"1D\" == type ){\n\t\t\tmake1D( hName, config->getString( nodeName + \":title\", hName ), \n\t\t\t\t\tconfig->getInt( nodeName + \":nBinsX\", 1 ), config->getDouble( nodeName + \":x1\", 0 ),\n\t\t\t\t\tconfig->getDouble( nodeName + \":x2\", 1 ) );\n\n\t\t} else if ( \"2D\" == type ){\n\t\t\tmake2D( hName, config->getString( nodeName + \":title\", hName ), \n\t\t\t\t\tconfig->getInt( nodeName + \":nBinsX\", 1 ), config->getDouble( nodeName + \":x1\", 0 ),\n\t\t\t\t\tconfig->getDouble( nodeName + \":x2\", 1 ),\n\t\t\t\t\tconfig->getInt( nodeName + \":nBinsY\", 1 ), config->getDouble( nodeName + \":y1\", 0 ),\n\t\t\t\t\tconfig->getDouble( nodeName + \":y2\", 1 ) );\n\t\n\t}\n\n}\n\nvoid histoBook::make1F( string name, string title, uint nBins, double low, double hi ){\n\n\tTH1F* h;\n\th = new TH1F( name.c_str(), title.c_str(), nBins, low, hi );\n\n\tthis->add( name, h );\n}\n\n\nvoid histoBook::make1D( string name, string title, uint nBins, double low, double hi ){\n\n\tTH1D* h;\n\th = new TH1D( name.c_str(), title.c_str(), nBins, low, hi );\n\n\tthis->add( name, h );\n}\n\nvoid histoBook::make1D( string name, string title, uint nBins, const Double_t* bins ){\n\n\tTH1D* h;\n\th = new TH1D( name.c_str(), title.c_str(), nBins, bins );\n\n\tthis->add( name, h );\n}\n\nvoid histoBook::make2D( string name, string title, uint nBinsX, double lowX, double hiX, uint nBinsY, double lowY, double hiY ){\n\n\tTH2D* h;\n\n\th = new TH2D( name.c_str(), title.c_str(), nBinsX, lowX, hiX, nBinsY, lowY, hiY );\n\n\tthis->add( name, h );\n}\nvoid histoBook::make2D( string name, string title, uint nBinsX, const Double_t* xBins, uint nBinsY, double lowY, double hiY ){\n\n\tTH2D* h;\n\th = new TH2D( name.c_str(), title.c_str(), nBinsX, xBins, nBinsY, lowY, hiY );\n\n\tthis->add( name, h );\n}\n\n\nTH1* histoBook::get( string name, string sdir ){\n\tif ( sdir.compare(\"\") == 0)\n\t\tsdir = currentDir;\n\treturn book[ ( sdir + name ) ];\n}\nTH2* histoBook::get2D( string name, string sdir ){\n\tif ( sdir.compare(\"\") == 0)\n\t\tsdir = currentDir;\n\treturn (TH2*)book[ ( sdir + name ) ];\n}\n\nvoid histoBook::fill( string name, double bin, double weight ){ \n\tif ( get( name ) != 0)\n\t\tget( name )->Fill( bin, weight );\n}\n\n\nvoid histoBook::globalStyle(){\n\n\tgStyle->SetCanvasColor(kWhite); \/\/ background is no longer mouse-dropping white\n \tgStyle->SetPalette(1,0); \/\/ blue to red false color palette. Use 9 for b\/w\n \tgStyle->SetCanvasBorderMode(0); \/\/ turn off canvas borders\n \tgStyle->SetPadBorderMode(0);\n \tgStyle->SetPaintTextFormat(\"5.2f\"); \/\/ What precision to put numbers if plotted with \"TEXT\"\n\n\n \t\/\/ For publishing:\n \tgStyle->SetLineWidth(2.);\n \tgStyle->SetTextSize(0.7);\n \tgStyle->SetLabelSize(0.05,\"xy\");\n \tgStyle->SetTitleSize(0.05,\"xy\");\n \tgStyle->SetTitleOffset(1.0,\"x\");\n \tgStyle->SetTitleOffset(1.5,\"y\");\n \tgStyle->SetPadTopMargin(0.1);\n \tgStyle->SetPadRightMargin(0.1);\n \tgStyle->SetPadBottomMargin(0.16);\n \tgStyle->SetPadLeftMargin(0.2);\n\n \tgStyle->SetFillColor(-1); \n\tgStyle->SetFillStyle(4000); \n\n\n\t\n}\n\n\nhistoBook* histoBook::style( string histName ){\n\tstyling = histName;\n\treturn this;\n}\n\nhistoBook* histoBook::set( string param, string p1, string p2, string p3, string p4 ){\n\t\n\t\/\/ force the param name to lowercase\n\ttransform(param.begin(), param.end(), param.begin(), ::tolower);\n\n TH1* h = get( styling );\n if ( h ){\n\n\t if ( \"title\" == param ){\n\t \th->SetTitle( p1.c_str() );\n\t } else if ( \"x\" == param ){\n\t \th->GetXaxis()->SetTitle( p1.c_str() );\n\t } else if ( \"y\" == param ){\n\t \th->GetYaxis()->SetTitle( p1.c_str() );\n\t } else if ( \"legend\" == param ){\n\t \tif ( p2 == \"\")\n\t \t\tp2=\"lpf\";\n\t \tlegend->AddEntry( h, p1.c_str(), p2.c_str() );\n\t\t\tlegend->Draw();\n\t } else if ( \"draw\" == param ){\n\t \tdrawOption = p1;\n\t }\n\t}\n\n\treturn this;\n}\n\nhistoBook* histoBook::set( string param, double p1, double p2, double p3, double p4 ){\n\n\n\ttransform(param.begin(), param.end(), param.begin(), ::tolower);\n\n TH1* h = get( styling );\n if ( h ){\n\n\t if ( \"linecolor\" == param ){\n\n\t \th->SetLineColor( (int) p1 );\n\t } else if ( \"domain\" == param ){\n\t \tdouble min = p1;\n\t \tdouble max = p2;\n\t\t h->GetXaxis()->SetRangeUser( min, max );\n\t } else if ( \"dynamicdomain\" == param ){\n\t \tdouble thresh = p1;\n\t \tint min = (int)p2;\n\t \tint max = (int)p3;\n\t \tint axis = (int)p4;\t\t\/\/ 1 = x, 2 = y\n\n\t \tif ( 1 != axis && 2 != axis )\n\t \t\taxis = 1;\n\t \t\n\t \tif ( thresh >= 0) {\n\t \t\tif ( -1 >= min )\n\t \t\t\tmin = h->FindFirstBinAbove( thresh, axis );\n\t \t\tif ( -1 >= max )\n\t \t\t\tmax = h->FindLastBinAbove( thresh, axis );\n\t \t}\n\t \t\n\t \tif ( 1 == axis )\n\t\t \t h->GetXaxis()->SetRange( min, max );\n\t\t \telse if ( 2 == axis )\n\t\t \t\th->GetYaxis()->SetRange( min, max );\n\n\t } else if ( \"range\" == param ){\n\n\t \tdouble min = p1;\n\t \tdouble max = p2;\n\t \t\n\t \th->GetYaxis()->SetRangeUser( min, max );\n\t } else if ( \"markercolor\" == param ) {\n\t \th->SetMarkerColor( (int)p1 );\n\t } else if ( \"markerstyle\" == param ) {\n\t \th->SetMarkerStyle( (int)p1 );\n\t } else if ( \"legend\" == param ){\n\t \t\/\/ p1 - alignmentX\n\t \t\/\/ p2 - alignmentY\n\t \t\/\/ p3 - width\n\t \t\/\/ p4 - height\n\n\t \t\/\/ make sure option is valid\n\t \tif ( !(legendAlignment::center == p1 || legendAlignment::left == p1 || legendAlignment::right == p1) )\n\t \t\tp1 = legendAlignment::best;\n\t \tif ( !(legendAlignment::center == p2 || legendAlignment::top == p2 || legendAlignment::bottom == p2) )\n\t \t\tp2 = legendAlignment::best;\n\t \tplaceLegend( p1, p2, p3, p4 );\n\t } else if ( \"numberofticks\" == param ){\n\t \t\/\/ p1 - # of primary divisions\n\t \t\/\/ p2 - # of secondary divisions\n\t \t\/\/ p3 - axis : 0 or 1 = x, 2 = y\n\t \t\n\t \tif ( p2 == -1 )\n\t \t\tp2 = 0;\n\n\t\t if ( 2 == (int)p3 )\n\t\t \th->GetYaxis()->SetNdivisions( (int) p1, (int) p2, 0, true );\n\t\t else \n\t\t \th->GetXaxis()->SetNdivisions( (int) p1, (int) p2, 0, true );\n\t }\n\n }\n \n \n \n\n\n\treturn this;\n}\n\n\nhistoBook* histoBook::draw(string name, Option_t* opt ){\n\n\t\/\/ no parameters\n\tif ( name == \"\"){\n\t\tTH1* h = get( styling );\n\t\tif ( h ){\n\t\t\t\/\/ use the draw option set in its styling\n\t\t\th->Draw( drawOption.c_str() );\n\t\t\tdrawOption = \"\";\n\t\t}\t\n\t} else {\n\t\tTH1* h = get( name );\n\t\tif ( h ){\n\t\t\th->Draw( opt );\n\t\t}\n\t}\n\t\n\treturn this;\n}\n\n\nhistoBook* histoBook::placeLegend( int alignmentX, int alignmentY, double width, double height ){\n\n\tdouble mR = 1 - gPad->GetRightMargin();\n\tdouble mL = gPad->GetLeftMargin();\n\tdouble mT = 1- gPad->GetTopMargin();\n\tdouble mB = gPad->GetBottomMargin();\n\n\tdouble x1, x2, y1, y2;\n\n\tif ( width <= 0 || width > 1 )\n\t\twidth = .2;\n\tif ( height <= 0 || height > 1 )\n\t\theight = .2;\n\n\t\/\/ alignment best needs a current histo\n\tif ( !(get( styling )) ){\n\t\tif ( legendAlignment::best == alignmentX )\n\t\t\talignmentX = legendAlignment::right;\n\t\tif ( legendAlignment::best == alignmentY )\n\t\t\talignmentY = legendAlignment::top;\n\t} else {\n\n\t\t\/\/TODO\n\n\t}\n\n\n\tif ( \tlegendAlignment::left == alignmentX ){\n\t\tx1 = mL ;\n\t\tx2 = mL + width;\n\t}\n\tif ( \tlegendAlignment::right == alignmentX ){\n\t\tx1 = mR - width;\n\t\tx2 = mR ;\n\t}\n\tif ( \tlegendAlignment::center == alignmentX ){\n\t\tx1 = 0.55 - width\/2.0;\n\t\tx2 = 0.55 + width\/2.0;\n\t}\n\tif ( \tlegendAlignment::top == alignmentY ){\n\t\ty1 = mT - height;\n\t\ty2 = mT ;\n\t}\n\tif ( \tlegendAlignment::bottom == alignmentY ){\n\t\ty1 = mB ;\n\t\ty2 = mB + height;\n\t}\n\tif ( \tlegendAlignment::center == alignmentY ){\n\t\ty1 = 0.55 - height\/2.0;\n\t\ty2 = 0.55 + height\/2.0;\n\t}\n\tlegend->SetX1NDC( x1 );\n\tlegend->SetX2NDC( x2 );\n\tlegend->SetY1NDC( y1 );\n\tlegend->SetY2NDC( y2 );\n\n\treturn this;\n}test upstream\n\n#include \"histoBook.h\"\n#include \"TKey.h\"\n#include \"TObject.h\"\n\n\/\/ constructor sets the name of the file for saving\nhistoBook::histoBook( string name, string input, string inDir ){\n\n\tif (name.find( \".root\") != std::string::npos){\n\t\tfilename = name;\t\n\t} else\n\t\tfilename = name + \".root\";\n\n\tcurrentDir = \"\/\";\n\n\tfile = new TFile( filename.c_str(), \"recreate\" );\n\tfile->cd();\n\n\t\n\t\/\/ make the legend and draw it once to apply styles etc. \n\t\/\/ for some reason needed to make styling work on the first draw\n\tlegend = new TLegend( 0.65, 0.65, 0.9, 0.9);\n\tlegend->SetFillColor( kWhite );\n\tlegend->Draw();\n\tlegend->Clear();\n\n\tglobalStyle();\n\n\t\/\/ if an input was given merge it into the live record\n\tif ( input.length() >= 5 ){\n\t\tTFile * fin = new TFile( input.c_str() );\n\t\tcd ( inDir );\n\t\tfin->cd( inDir.c_str() );\n\t\tloadRootDir( gDirectory, inDir );\n\t}\n\n\n\n}\n\/\/ destructor\nhistoBook::~histoBook(){\n\n\tdelete legend;\n\n\tsave();\n\tfile->Close();\n}\nvoid histoBook::save() {\n\n\tfile->Write();\n}\n\nvoid histoBook::loadRootDir( TDirectory* tDir, string path ){\n\n\t\/\/cout << \"histoBook.loadRootDir] Path : \" << path << endl;\n\n\tTList* list;\n\n\tif ( tDir ){\n\t\tlist = tDir->GetListOfKeys(); \n\t} else {\n\t\tcout << \"[histoBook.loadRootDir] Bad Directory Given \" << endl;\n\t\treturn;\n\t}\n\n\tTIter next(list); \n\tTKey* key; \n\tTObject* obj; \n\t\n\twhile ( (key = (TKey*)next()) ) { \n\t\t\n\t\tobj = key->ReadObj() ; \n\t\t\n\t\tif ( 0 == strcmp(obj->IsA()->GetName(),\"TDirectoryFile\") ){\n\t\t\tTDirectoryFile* dir = (TDirectoryFile*)obj;\n\t\t\t\n\t\t\tstring nPath = path + dir->GetName();\n\t\t\tif ( path == (string) \"\" )\n\t\t\t\tnPath = path + dir->GetName();\n\t\t\telse \n\t\t\t\tnPath = path + \"\/\" + dir->GetName();\n\n\t\t\tcd( nPath );\n\t\t\tloadRootDir( dir, nPath );\n\t\t} else if ( obj ){\n\t\t\tif ( (strcmp(obj->IsA()->GetName(),\"TProfile\")!=0) && (!obj->InheritsFrom(\"TH2\") && (!obj->InheritsFrom(\"TH1\"))) ) { \n\t\t\t\t\/\/ not a 1d or 2d histogram\n\t\t\t} else {\n\t\t\t\t\/\/ add it to the book\n\t\t\t\t\/\/cout << \"Adding : \" << obj->GetName() << endl;\n\t\t\t\tadd( obj->GetName(), (TH1*)obj->Clone( obj->GetName() ) );\n\t\t\t} \n\t\t\t\n\t\t}\n\t}\t\n\n}\n\n\nvoid histoBook::add( string name, TH1* h ){\n\n\tstring oName = name;\n\tif ( name.length() <= 1 || !h )\n\t\treturn;\n\n\tname = currentDir + name;\n\t\n\t\/\/ dont allow duplicated name overites\n\tif ( book[ name ] ){\n\t\tcout << \"[histoBook.add] Duplicate histogram name in this directory \" << currentDir << \" \/ \" << oName << endl;\n\t\treturn;\n\t}\n\n\t\/\/ save the histo to the map\n\tbook[ name ] = h;\n\n}\n\/*\n*\n* TODO:: add support for full subdirectory trees\n*\/\nstring histoBook::cd( string sdir ){\n\n\tstring old = currentDir;\n\n\tchar* csdir = (char*)sdir.c_str();\n\tfile->cd();\n\n\tif ( file->GetDirectory( csdir ) ){\n\t\tfile->cd( csdir );\n\t} else {\n\t\tcout << \"[histoBook.cd] creating directory \" << sdir << endl;\n\t\tfile->mkdir( csdir );\n\t\tfile->cd( csdir );\n\t}\n\n\tcurrentDir = sdir;\n\n\treturn old;\n}\n\nvoid histoBook::make( xmlConfig * config, string nodeName ){\n\n\tif ( config && config->nodeExists( nodeName ) ){\n\t\t\n\t\tstring hName = config->tagName( nodeName );\n\t\tif ( \"\" == hName )\n\t\t\thName = nodeName;\n\n\t\tstring type = config->getString( nodeName + \":type\", \"1D\" );\n\n\t\tif ( \"1D\" == type ){\n\t\t\tmake1D( hName, config->getString( nodeName + \":title\", hName ), \n\t\t\t\t\tconfig->getInt( nodeName + \":nBinsX\", 1 ), config->getDouble( nodeName + \":x1\", 0 ),\n\t\t\t\t\tconfig->getDouble( nodeName + \":x2\", 1 ) );\n\n\t\t} else if ( \"2D\" == type ){\n\t\t\tmake2D( hName, config->getString( nodeName + \":title\", hName ), \n\t\t\t\t\tconfig->getInt( nodeName + \":nBinsX\", 1 ), config->getDouble( nodeName + \":x1\", 0 ),\n\t\t\t\t\tconfig->getDouble( nodeName + \":x2\", 1 ),\n\t\t\t\t\tconfig->getInt( nodeName + \":nBinsY\", 1 ), config->getDouble( nodeName + \":y1\", 0 ),\n\t\t\t\t\tconfig->getDouble( nodeName + \":y2\", 1 ) );\n\t\t}\n\t\n\t}\n\n}\n\nvoid histoBook::make1F( string name, string title, uint nBins, double low, double hi ){\n\n\tTH1F* h;\n\th = new TH1F( name.c_str(), title.c_str(), nBins, low, hi );\n\n\tthis->add( name, h );\n}\n\n\nvoid histoBook::make1D( string name, string title, uint nBins, double low, double hi ){\n\n\tTH1D* h;\n\th = new TH1D( name.c_str(), title.c_str(), nBins, low, hi );\n\n\tthis->add( name, h );\n}\n\nvoid histoBook::make1D( string name, string title, uint nBins, const Double_t* bins ){\n\n\tTH1D* h;\n\th = new TH1D( name.c_str(), title.c_str(), nBins, bins );\n\n\tthis->add( name, h );\n}\n\nvoid histoBook::make2D( string name, string title, uint nBinsX, double lowX, double hiX, uint nBinsY, double lowY, double hiY ){\n\n\tTH2D* h;\n\n\th = new TH2D( name.c_str(), title.c_str(), nBinsX, lowX, hiX, nBinsY, lowY, hiY );\n\n\tthis->add( name, h );\n}\nvoid histoBook::make2D( string name, string title, uint nBinsX, const Double_t* xBins, uint nBinsY, double lowY, double hiY ){\n\n\tTH2D* h;\n\th = new TH2D( name.c_str(), title.c_str(), nBinsX, xBins, nBinsY, lowY, hiY );\n\n\tthis->add( name, h );\n}\n\n\nTH1* histoBook::get( string name, string sdir ){\n\tif ( sdir.compare(\"\") == 0)\n\t\tsdir = currentDir;\n\treturn book[ ( sdir + name ) ];\n}\nTH2* histoBook::get2D( string name, string sdir ){\n\tif ( sdir.compare(\"\") == 0)\n\t\tsdir = currentDir;\n\treturn (TH2*)book[ ( sdir + name ) ];\n}\n\nvoid histoBook::fill( string name, double bin, double weight ){ \n\tif ( get( name ) != 0)\n\t\tget( name )->Fill( bin, weight );\n}\n\n\nvoid histoBook::globalStyle(){\n\n\tgStyle->SetCanvasColor(kWhite); \/\/ background is no longer mouse-dropping white\n \tgStyle->SetPalette(1,0); \/\/ blue to red false color palette. Use 9 for b\/w\n \tgStyle->SetCanvasBorderMode(0); \/\/ turn off canvas borders\n \tgStyle->SetPadBorderMode(0);\n \tgStyle->SetPaintTextFormat(\"5.2f\"); \/\/ What precision to put numbers if plotted with \"TEXT\"\n\n\n \t\/\/ For publishing:\n \tgStyle->SetLineWidth(2.);\n \tgStyle->SetTextSize(0.7);\n \tgStyle->SetLabelSize(0.05,\"xy\");\n \tgStyle->SetTitleSize(0.05,\"xy\");\n \tgStyle->SetTitleOffset(1.0,\"x\");\n \tgStyle->SetTitleOffset(1.5,\"y\");\n \tgStyle->SetPadTopMargin(0.1);\n \tgStyle->SetPadRightMargin(0.1);\n \tgStyle->SetPadBottomMargin(0.16);\n \tgStyle->SetPadLeftMargin(0.2);\n\n \tgStyle->SetFillColor(-1); \n\tgStyle->SetFillStyle(4000); \n\n\n\t\n}\n\n\nhistoBook* histoBook::style( string histName ){\n\tstyling = histName;\n\treturn this;\n}\n\nhistoBook* histoBook::set( string param, string p1, string p2, string p3, string p4 ){\n\t\n\t\/\/ force the param name to lowercase\n\ttransform(param.begin(), param.end(), param.begin(), ::tolower);\n\n TH1* h = get( styling );\n if ( h ){\n\n\t if ( \"title\" == param ){\n\t \th->SetTitle( p1.c_str() );\n\t } else if ( \"x\" == param ){\n\t \th->GetXaxis()->SetTitle( p1.c_str() );\n\t } else if ( \"y\" == param ){\n\t \th->GetYaxis()->SetTitle( p1.c_str() );\n\t } else if ( \"legend\" == param ){\n\t \tif ( p2 == \"\")\n\t \t\tp2=\"lpf\";\n\t \tlegend->AddEntry( h, p1.c_str(), p2.c_str() );\n\t\t\tlegend->Draw();\n\t } else if ( \"draw\" == param ){\n\t \tdrawOption = p1;\n\t }\n\t}\n\n\treturn this;\n}\n\nhistoBook* histoBook::set( string param, double p1, double p2, double p3, double p4 ){\n\n\n\ttransform(param.begin(), param.end(), param.begin(), ::tolower);\n\n TH1* h = get( styling );\n if ( h ){\n\n\t if ( \"linecolor\" == param ){\n\n\t \th->SetLineColor( (int) p1 );\n\t } else if ( \"domain\" == param ){\n\t \tdouble min = p1;\n\t \tdouble max = p2;\n\t\t h->GetXaxis()->SetRangeUser( min, max );\n\t } else if ( \"dynamicdomain\" == param ){\n\t \tdouble thresh = p1;\n\t \tint min = (int)p2;\n\t \tint max = (int)p3;\n\t \tint axis = (int)p4;\t\t\/\/ 1 = x, 2 = y\n\n\t \tif ( 1 != axis && 2 != axis )\n\t \t\taxis = 1;\n\t \t\n\t \tif ( thresh >= 0) {\n\t \t\tif ( -1 >= min )\n\t \t\t\tmin = h->FindFirstBinAbove( thresh, axis );\n\t \t\tif ( -1 >= max )\n\t \t\t\tmax = h->FindLastBinAbove( thresh, axis );\n\t \t}\n\t \t\n\t \tif ( 1 == axis )\n\t\t \t h->GetXaxis()->SetRange( min, max );\n\t\t \telse if ( 2 == axis )\n\t\t \t\th->GetYaxis()->SetRange( min, max );\n\n\t } else if ( \"range\" == param ){\n\n\t \tdouble min = p1;\n\t \tdouble max = p2;\n\t \t\n\t \th->GetYaxis()->SetRangeUser( min, max );\n\t } else if ( \"markercolor\" == param ) {\n\t \th->SetMarkerColor( (int)p1 );\n\t } else if ( \"markerstyle\" == param ) {\n\t \th->SetMarkerStyle( (int)p1 );\n\t } else if ( \"legend\" == param ){\n\t \t\/\/ p1 - alignmentX\n\t \t\/\/ p2 - alignmentY\n\t \t\/\/ p3 - width\n\t \t\/\/ p4 - height\n\n\t \t\/\/ make sure option is valid\n\t \tif ( !(legendAlignment::center == p1 || legendAlignment::left == p1 || legendAlignment::right == p1) )\n\t \t\tp1 = legendAlignment::best;\n\t \tif ( !(legendAlignment::center == p2 || legendAlignment::top == p2 || legendAlignment::bottom == p2) )\n\t \t\tp2 = legendAlignment::best;\n\t \tplaceLegend( p1, p2, p3, p4 );\n\t } else if ( \"numberofticks\" == param ){\n\t \t\/\/ p1 - # of primary divisions\n\t \t\/\/ p2 - # of secondary divisions\n\t \t\/\/ p3 - axis : 0 or 1 = x, 2 = y\n\t \t\n\t \tif ( p2 == -1 )\n\t \t\tp2 = 0;\n\n\t\t if ( 2 == (int)p3 )\n\t\t \th->GetYaxis()->SetNdivisions( (int) p1, (int) p2, 0, true );\n\t\t else \n\t\t \th->GetXaxis()->SetNdivisions( (int) p1, (int) p2, 0, true );\n\t }\n\n }\n \n \n \n\n\n\treturn this;\n}\n\n\nhistoBook* histoBook::draw(string name, Option_t* opt ){\n\n\t\/\/ no parameters\n\tif ( name == \"\"){\n\t\tTH1* h = get( styling );\n\t\tif ( h ){\n\t\t\t\/\/ use the draw option set in its styling\n\t\t\th->Draw( drawOption.c_str() );\n\t\t\tdrawOption = \"\";\n\t\t}\t\n\t} else {\n\t\tTH1* h = get( name );\n\t\tif ( h ){\n\t\t\th->Draw( opt );\n\t\t}\n\t}\n\t\n\treturn this;\n}\n\n\nhistoBook* histoBook::placeLegend( int alignmentX, int alignmentY, double width, double height ){\n\n\tdouble mR = 1 - gPad->GetRightMargin();\n\tdouble mL = gPad->GetLeftMargin();\n\tdouble mT = 1- gPad->GetTopMargin();\n\tdouble mB = gPad->GetBottomMargin();\n\n\tdouble x1, x2, y1, y2;\n\n\tif ( width <= 0 || width > 1 )\n\t\twidth = .2;\n\tif ( height <= 0 || height > 1 )\n\t\theight = .2;\n\n\t\/\/ alignment best needs a current histo\n\tif ( !(get( styling )) ){\n\t\tif ( legendAlignment::best == alignmentX )\n\t\t\talignmentX = legendAlignment::right;\n\t\tif ( legendAlignment::best == alignmentY )\n\t\t\talignmentY = legendAlignment::top;\n\t} else {\n\n\t\t\/\/TODO\n\n\t}\n\n\n\tif ( \tlegendAlignment::left == alignmentX ){\n\t\tx1 = mL ;\n\t\tx2 = mL + width;\n\t}\n\tif ( \tlegendAlignment::right == alignmentX ){\n\t\tx1 = mR - width;\n\t\tx2 = mR ;\n\t}\n\tif ( \tlegendAlignment::center == alignmentX ){\n\t\tx1 = 0.55 - width\/2.0;\n\t\tx2 = 0.55 + width\/2.0;\n\t}\n\tif ( \tlegendAlignment::top == alignmentY ){\n\t\ty1 = mT - height;\n\t\ty2 = mT ;\n\t}\n\tif ( \tlegendAlignment::bottom == alignmentY ){\n\t\ty1 = mB ;\n\t\ty2 = mB + height;\n\t}\n\tif ( \tlegendAlignment::center == alignmentY ){\n\t\ty1 = 0.55 - height\/2.0;\n\t\ty2 = 0.55 + height\/2.0;\n\t}\n\tlegend->SetX1NDC( x1 );\n\tlegend->SetX2NDC( x2 );\n\tlegend->SetY1NDC( y1 );\n\tlegend->SetY2NDC( y2 );\n\n\treturn this;\n}<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \"opencv2\/core.hpp\"\nusing namespace cv;\n\n#include \"math.hpp\"\n\nfloat median(std::vector& v)\n{\n\tconst int n = v.size();\n\tassert(n > 0);\n\tif (n == 1) return v[0];\n\n\tstd::sort(v.begin(), v.end());\n\treturn v[n \/ 2];\n}\n\nfloat mean(std::vector& v)\n{\n\tconst int n = v.size();\n\tif (n == 0) return 0.f;\n\n\tfloat sum = std::accumulate(std::begin(v), std::end(v), 0.0);\n\treturn sum \/ n;\n}\n\nfloat var(std::vector& v)\n{\n\tconst int n = v.size();\n\tif (n == 0) return 0.f;\n\n\tfloat _mean = mean(v);\n\treturn sqrt(std::accumulate(std::begin(v), std::end(v), 0.f,\n\t\t[&](const float b, const float e) {\n\t\t\tfloat diff = e - _mean;\n\t\t\treturn b + diff * diff;\n\t\t}) \/ n);\n}\n\n\nfloat randInt(const float min, const float max)\n{\n\treturn roundf(rand() \/ (float)RAND_MAX * (max - min) + min);\n}\n\n\nRect randomCrop(const Mat& img, const float w2hrat)\n{\n\tint h = img.rows,\n\t w = img.cols,\n\t minh = 8,\n\t minw = 8;\n\n\tint x0, y0, dx, dy;\n\twhile (1)\n\t{\n\t\tx0 = randInt(0, w - minw);\n\t\ty0 = randInt(0, h - minh);\n\t\tdy = randInt(minh, h - 1 - y0);\n\t\tif (w2hrat > 1e-5) \/\/ Valid aspect ratio\n\t\t{\n\t\t\tdx = roundf((float) dy * w2hrat);\n\t\t\tif (dx < minw || x0 + dx + 1 > w) continue;\n\t\t}\n\t\telse\n\t\t\tdx = randInt(minw, w - 1 - x0);\n\n\t\treturn Rect(x0, y0, dx, dy);\n\t}\n}\n\n\nRect randomCrop(const Mat& img, const Rect good_crop, const float thresh)\n{\n\tRect crop = randomCrop(img);\n\twhile (cropOverlap(good_crop, crop) > thresh)\n\t\tcrop = randomCrop(img);\n\treturn crop;\n}\n\n\nfloat cropOverlap(const Rect crop1, const Rect crop2)\n{\n\tint x1a = crop1.x,\n\t y1a = crop1.y,\n\t x1b = crop1.x + crop1.width,\n\t y1b = crop1.y + crop1.height,\n\t x2a = crop2.x,\n\t y2a = crop2.y,\n\t x2b = crop2.x + crop2.width,\n\t y2b = crop2.y + crop2.height;\n\n\tint ow = max(0, min(x1b, x2b) - max(x1a, x2a)),\n\t oh = max(0, min(y1b, y2b) - max(y1a, y2a));\n\n\tint oA = ow * oh;\n\tif (oA == 0) return 0;\n\n\tint A1 = crop1.width * crop1.height,\n\t A2 = crop2.width * crop2.height;\n\n\treturn oA \/ (float) (A1 + A2 - oA);\n}\n\nChange minh, minw in randomCrop#include \n#include \n#include \n\n#include \"opencv2\/core.hpp\"\nusing namespace cv;\n\n#include \"math.hpp\"\n\nfloat median(std::vector& v)\n{\n\tconst int n = v.size();\n\tassert(n > 0);\n\tif (n == 1) return v[0];\n\n\tstd::sort(v.begin(), v.end());\n\treturn v[n \/ 2];\n}\n\nfloat mean(std::vector& v)\n{\n\tconst int n = v.size();\n\tif (n == 0) return 0.f;\n\n\tfloat sum = std::accumulate(std::begin(v), std::end(v), 0.0);\n\treturn sum \/ n;\n}\n\nfloat var(std::vector& v)\n{\n\tconst int n = v.size();\n\tif (n == 0) return 0.f;\n\n\tfloat _mean = mean(v);\n\treturn sqrt(std::accumulate(std::begin(v), std::end(v), 0.f,\n\t\t[&](const float b, const float e) {\n\t\t\tfloat diff = e - _mean;\n\t\t\treturn b + diff * diff;\n\t\t}) \/ n);\n}\n\n\nfloat randInt(const float min, const float max)\n{\n\treturn roundf(rand() \/ (float)RAND_MAX * (max - min) + min);\n}\n\n\nRect randomCrop(const Mat& img, const float w2hrat)\n{\n\tint h = img.rows,\n\t w = img.cols,\n\t minh = max(32, h \/ 8),\n\t minw = max(32, w \/ 8);\n\n\tint x0, y0, dx, dy;\n\twhile (1)\n\t{\n\t\tx0 = randInt(0, w - minw);\n\t\ty0 = randInt(0, h - minh);\n\t\tdy = randInt(minh, h - 1 - y0);\n\t\tif (w2hrat > 1e-5) \/\/ Valid aspect ratio\n\t\t{\n\t\t\tdx = roundf((float) dy * w2hrat);\n\t\t\tif (dx < minw || x0 + dx + 1 > w) continue;\n\t\t}\n\t\telse\n\t\t\tdx = randInt(minw, w - 1 - x0);\n\n\t\treturn Rect(x0, y0, dx, dy);\n\t}\n}\n\n\nRect randomCrop(const Mat& img, const Rect good_crop, const float thresh)\n{\n\tRect crop = randomCrop(img);\n\twhile (cropOverlap(good_crop, crop) > thresh)\n\t\tcrop = randomCrop(img);\n\treturn crop;\n}\n\n\nfloat cropOverlap(const Rect crop1, const Rect crop2)\n{\n\tint x1a = crop1.x,\n\t y1a = crop1.y,\n\t x1b = crop1.x + crop1.width,\n\t y1b = crop1.y + crop1.height,\n\t x2a = crop2.x,\n\t y2a = crop2.y,\n\t x2b = crop2.x + crop2.width,\n\t y2b = crop2.y + crop2.height;\n\n\tint ow = max(0, min(x1b, x2b) - max(x1a, x2a)),\n\t oh = max(0, min(y1b, y2b) - max(y1a, y2a));\n\n\tint oA = ow * oh;\n\tif (oA == 0) return 0;\n\n\tint A1 = crop1.width * crop1.height,\n\t A2 = crop2.width * crop2.height;\n\n\treturn oA \/ (float) (A1 + A2 - oA);\n}\n\n<|endoftext|>"} {"text":"{% extends '0key_output.cpp' %}\n\n{% block templateargs %}\n{{state_type}}, counter, &{{update_func}}, &get_count\n{% endblock %}\n\n{% block output %}\n{{output_tuple_type}} {{output_tuple_name}};\n{{output_tuple_set_func}}({{output_tuple_name}}_tmp);\n{% endblock %}\n\nremove newlines in template{% extends '0key_output.cpp' %}\n\n{% block templateargs %}{{state_type}}, counter, &{{update_func}}, &get_count{% endblock %}\n\n{% block output %}\n{{output_tuple_type}} {{output_tuple_name}};\n{{output_tuple_set_func}}({{output_tuple_name}}_tmp);\n{% endblock %}\n\n<|endoftext|>"} {"text":"#include \"vast\/index.h\"\n\n#include \n#include \"vast\/bitmap_index.h\"\n#include \"vast\/segment.h\"\n#include \"vast\/expression.h\"\n#include \"vast\/partition.h\"\n#include \"vast\/uuid.h\"\n#include \"vast\/io\/serialization.h\"\n\nusing namespace cppa;\n\nnamespace vast {\n\nindex_actor::index_actor(path directory, size_t batch_size)\n : dir_{std::move(directory)},\n batch_size_{batch_size}\n{\n}\n\nchar const* index_actor::description() const\n{\n return \"index\";\n}\n\nvoid index_actor::act()\n{\n chaining(false);\n trap_exit(true);\n\n traverse(\n dir_,\n [&](path const& p) -> bool\n {\n if (! exists(p \/ \"coverage\"))\n {\n \/\/ If the meta data of a partition does not exist, we have a file\n \/\/ system inconsistency and ignore the partition.\n VAST_LOG_ACTOR_WARN(\"couldn't find meta data for partition \" << p);\n }\n else\n {\n auto part = spawn(p, batch_size_);\n partitions_.emplace(p.basename(), part);\n }\n\n return true;\n });\n\n if (! partitions_.empty())\n {\n auto active = partitions_.rbegin();\n VAST_LOG_ACTOR_INFO(\"sets existing partition as active: \" << active->first);\n active_ = active->second;\n }\n\n become(\n on(atom(\"EXIT\"), arg_match) >> [=](uint32_t reason)\n {\n if (partitions_.empty())\n quit(reason);\n else\n for (auto& p : partitions_)\n send_exit(p.second, reason);\n },\n on(atom(\"DOWN\"), arg_match) >> [=](uint32_t reason)\n {\n VAST_LOG_ACTOR_DEBUG(\"got DOWN from \" << VAST_ACTOR_ID(last_sender()));\n\n for (auto i = partitions_.begin(); i != partitions_.end(); ++i)\n if (i->second == last_sender())\n {\n partitions_.erase(i);\n break;\n }\n\n if (reason == exit::stop)\n {\n if (partitions_.empty())\n quit(exit::stop);\n }\n else\n {\n if (reason != exit::error)\n VAST_LOG_ACTOR_WARN(\n \"terminates with unknown exit code from \" <<\n VAST_ACTOR_ID(last_sender()) << \": \" << reason);\n\n quit(exit::error);\n }\n },\n on(atom(\"partition\"), arg_match) >> [=](std::string const& part)\n {\n auto part_dir = path{part};\n\n if (exists(dir_ \/ part_dir))\n VAST_LOG_ACTOR_INFO(\"appends to existing partition \" << part);\n else\n VAST_LOG_ACTOR_INFO(\"creates new partition \" << part);\n\n if (! partitions_.count(part_dir))\n {\n auto d = dir_ \/ part_dir;\n auto a = spawn(d, batch_size_);\n partitions_.emplace(part_dir, a);\n }\n\n VAST_LOG_ACTOR_INFO(\"sets active partition to \" << part_dir);\n active_ = partitions_[part_dir];\n assert(active_);\n },\n on_arg_match >> [=](expr::ast const& ast)\n {\n if (partitions_.empty())\n {\n VAST_LOG_ACTOR_WARN(\"has no partitions to answer: \" << ast);\n return;\n }\n\n for (auto i = partitions_.rbegin(); i != partitions_.rend(); ++i)\n {\n send(i->second, ast, last_sender());\n VAST_LOG_ACTOR_DEBUG(\"sent predicate \" << ast <<\n \" to partition \" << VAST_ACTOR_ID(i->second));\n }\n },\n on_arg_match >> [=](segment const& s)\n {\n if (partitions_.empty())\n {\n auto id = uuid::random();\n VAST_LOG_ACTOR_INFO(\"creates new random partition \" << id);\n auto part_dir = dir_ \/ to(id);\n assert(! exists(part_dir));\n auto p = spawn(part_dir, batch_size_);\n active_ = p;\n partitions_.emplace(part_dir.basename(), std::move(p));\n }\n\n forward_to(active_);\n return make_any_tuple(atom(\"segment\"), atom(\"ack\"), s.id());\n },\n on(atom(\"delete\")) >> [=]\n {\n if (partitions_.empty())\n {\n VAST_LOG_ACTOR_WARN(\"ignores request to delete empty index\");\n return;\n }\n\n become(\n keep_behavior,\n on(atom(\"DOWN\"), arg_match) >> [=](uint32_t reason)\n {\n if (reason != exit::kill)\n VAST_LOG_ACTOR_WARN(\n \"got DOWN from \" << VAST_ACTOR_ID(last_sender()) <<\n \" with unexpected exit code \" << reason);\n\n for (auto i = partitions_.begin(); i != partitions_.end(); ++i)\n if (i->second == last_sender())\n {\n partitions_.erase(i);\n break;\n }\n\n if (partitions_.empty())\n {\n if (! rm(dir_))\n {\n VAST_LOG_ACTOR_ERROR(\"failed to delete index directory: \" <<\n dir_);\n quit(exit::error);\n return;\n }\n\n VAST_LOG_ACTOR_INFO(\"deleted index: \" << dir_);\n unbecome();\n }\n }\n );\n\n for (auto& p : partitions_)\n send_exit(p.second, exit::kill);\n });\n}\n\n} \/\/ namespace vast\nConsider \"done\" as normal exit status.#include \"vast\/index.h\"\n\n#include \n#include \"vast\/bitmap_index.h\"\n#include \"vast\/segment.h\"\n#include \"vast\/expression.h\"\n#include \"vast\/partition.h\"\n#include \"vast\/uuid.h\"\n#include \"vast\/io\/serialization.h\"\n\nusing namespace cppa;\n\nnamespace vast {\n\nindex_actor::index_actor(path directory, size_t batch_size)\n : dir_{std::move(directory)},\n batch_size_{batch_size}\n{\n}\n\nchar const* index_actor::description() const\n{\n return \"index\";\n}\n\nvoid index_actor::act()\n{\n chaining(false);\n trap_exit(true);\n\n traverse(\n dir_,\n [&](path const& p) -> bool\n {\n if (! exists(p \/ \"coverage\"))\n {\n \/\/ If the meta data of a partition does not exist, we have a file\n \/\/ system inconsistency and ignore the partition.\n VAST_LOG_ACTOR_WARN(\"couldn't find meta data for partition \" << p);\n }\n else\n {\n auto part = spawn(p, batch_size_);\n partitions_.emplace(p.basename(), part);\n }\n\n return true;\n });\n\n if (! partitions_.empty())\n {\n auto active = partitions_.rbegin();\n VAST_LOG_ACTOR_INFO(\"sets existing partition as active: \" << active->first);\n active_ = active->second;\n }\n\n become(\n on(atom(\"EXIT\"), arg_match) >> [=](uint32_t reason)\n {\n if (partitions_.empty())\n quit(reason);\n else\n for (auto& p : partitions_)\n send_exit(p.second, reason);\n },\n on(atom(\"DOWN\"), arg_match) >> [=](uint32_t reason)\n {\n VAST_LOG_ACTOR_DEBUG(\"got DOWN from \" << VAST_ACTOR_ID(last_sender()));\n\n for (auto i = partitions_.begin(); i != partitions_.end(); ++i)\n if (i->second == last_sender())\n {\n partitions_.erase(i);\n break;\n }\n\n if (reason == exit::stop || reason == exit::done)\n {\n if (partitions_.empty())\n quit(reason);\n }\n else\n {\n if (reason != exit::error)\n VAST_LOG_ACTOR_WARN(\n \"terminates with unknown exit code from \" <<\n VAST_ACTOR_ID(last_sender()) << \": \" << reason);\n\n quit(exit::error);\n }\n },\n on(atom(\"partition\"), arg_match) >> [=](std::string const& part)\n {\n auto part_dir = path{part};\n\n if (exists(dir_ \/ part_dir))\n VAST_LOG_ACTOR_INFO(\"appends to existing partition \" << part);\n else\n VAST_LOG_ACTOR_INFO(\"creates new partition \" << part);\n\n if (! partitions_.count(part_dir))\n {\n auto d = dir_ \/ part_dir;\n auto a = spawn(d, batch_size_);\n partitions_.emplace(part_dir, a);\n }\n\n VAST_LOG_ACTOR_INFO(\"sets active partition to \" << part_dir);\n active_ = partitions_[part_dir];\n assert(active_);\n },\n on_arg_match >> [=](expr::ast const& ast)\n {\n if (partitions_.empty())\n {\n VAST_LOG_ACTOR_WARN(\"has no partitions to answer: \" << ast);\n return;\n }\n\n for (auto i = partitions_.rbegin(); i != partitions_.rend(); ++i)\n {\n send(i->second, ast, last_sender());\n VAST_LOG_ACTOR_DEBUG(\"sent predicate \" << ast <<\n \" to partition \" << VAST_ACTOR_ID(i->second));\n }\n },\n on_arg_match >> [=](segment const& s)\n {\n if (partitions_.empty())\n {\n auto id = uuid::random();\n VAST_LOG_ACTOR_INFO(\"creates new random partition \" << id);\n auto part_dir = dir_ \/ to(id);\n assert(! exists(part_dir));\n auto p = spawn(part_dir, batch_size_);\n active_ = p;\n partitions_.emplace(part_dir.basename(), std::move(p));\n }\n\n forward_to(active_);\n return make_any_tuple(atom(\"segment\"), atom(\"ack\"), s.id());\n },\n on(atom(\"delete\")) >> [=]\n {\n if (partitions_.empty())\n {\n VAST_LOG_ACTOR_WARN(\"ignores request to delete empty index\");\n return;\n }\n\n become(\n keep_behavior,\n on(atom(\"DOWN\"), arg_match) >> [=](uint32_t reason)\n {\n if (reason != exit::kill)\n VAST_LOG_ACTOR_WARN(\n \"got DOWN from \" << VAST_ACTOR_ID(last_sender()) <<\n \" with unexpected exit code \" << reason);\n\n for (auto i = partitions_.begin(); i != partitions_.end(); ++i)\n if (i->second == last_sender())\n {\n partitions_.erase(i);\n break;\n }\n\n if (partitions_.empty())\n {\n if (! rm(dir_))\n {\n VAST_LOG_ACTOR_ERROR(\"failed to delete index directory: \" <<\n dir_);\n quit(exit::error);\n return;\n }\n\n VAST_LOG_ACTOR_INFO(\"deleted index: \" << dir_);\n unbecome();\n }\n }\n );\n\n for (auto& p : partitions_)\n send_exit(p.second, exit::kill);\n });\n}\n\n} \/\/ namespace vast\n<|endoftext|>"} {"text":"#ifndef LUACPP_REGISTER_ANY_FUNCTION_HPP\n#define LUACPP_REGISTER_ANY_FUNCTION_HPP\n\n#include \"luacpp\/stack.hpp\"\n#include \"luacpp\/register_closure.hpp\"\n#include \"luacpp\/from_lua_cast.hpp\"\n#include \"luacpp\/coroutine.hpp\"\n#include \n\nnamespace lua\n{\n\tnamespace detail\n\t{\n\t\tstruct call_environment\n\t\t{\n\t\t\tlua_State &L;\n\t\t\tbool *suspend_requested;\n\t\t};\n\n\t\ttemplate \n\t\tstruct argument_converter\n\t\t{\n\t\t\tT operator()(call_environment const &env, int address) const\n\t\t\t{\n\t\t\t\treturn from_lua_cast(env.L, address);\n\t\t\t}\n\t\t};\n\n\t\ttemplate \n\t\tstruct argument_converter : argument_converter\n\t\t{\n\t\t};\n\n\t\ttemplate <>\n\t\tstruct argument_converter\n\t\t{\n\t\t\tcoroutine operator()(call_environment const &env, int) const\n\t\t\t{\n\t\t\t\treturn coroutine(env.L, env.suspend_requested);\n\t\t\t}\n\t\t};\n\n\t\ttemplate \n\t\tauto call_with_converted_arguments(Function &func, call_environment const &env, ranges::v3::integer_sequence)\n\t\t{\n\t\t\treturn func(argument_converter()(env, 1 + Indices)...);\n\t\t}\n\n\t\ttemplate \n\t\tstruct caller\n\t\t{\n\t\t\ttemplate \n\t\t\tresult_or_yield operator()(call_environment const &env, F const &f, Arguments &&...args) const\n\t\t\t{\n\t\t\t\tassert(!env.suspend_requested || !*env.suspend_requested); \/\/TODO\n\t\t\t\tNonVoid result = f(std::forward(args)...);\n\t\t\t\tpush(env.L, std::move(result));\n\t\t\t\tif (sizeof...(Arguments))\n\t\t\t\t{\n\t\t\t\t\tint const top = lua_gettop(&env.L);\n\t\t\t\t\tlua_replace(&env.L, (top - sizeof...(Arguments)));\n\t\t\t\t\tlua_pop(&env.L, (sizeof...(Arguments) - 1));\n\t\t\t\t}\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t};\n\n\t\ttemplate <>\n\t\tstruct caller\n\t\t{\n\t\t\ttemplate \n\t\t\tresult_or_yield operator()(call_environment const &env, F const &f, Arguments &&...args) const\n\t\t\t{\n\t\t\t\tf(std::forward(args)...);\n\t\t\t\tlua_pop(&env.L, sizeof...(Arguments));\n\t\t\t\tif (env.suspend_requested && *env.suspend_requested)\n\t\t\t\t{\n\t\t\t\t\treturn yield();\n\t\t\t\t}\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t};\n\n\t\ttemplate \n\t\tstack_value register_any_function_helper(stack &s, F func, R (F::*)(Parameters...) const)\n\t\t{\n\t\t\treturn register_closure(s, [func\n#ifndef _MSC_VER\n\t\t\t\t= std::move(func)\n#endif\n\t\t\t](lua_State *L)\n\t\t\t{\n\t\t\t\tbool suspend_requested = false;\n\t\t\t\tcall_environment env{*L, &suspend_requested};\n\t\t\t\treturn caller()(env, [\n#ifdef _MSC_VER\n\t\t\t\t\tfunc, &env\n#else\n\t\t\t\t&\n#endif\n\t\t\t\t]()\n\t\t\t\t{\n\t\t\t\t\treturn call_with_converted_arguments(func, env, typename ranges::v3::make_integer_sequence::type());\n\t\t\t\t});\n\t\t\t});\n\t\t}\n\n\t\ttemplate \n\t\tstack_value register_any_function_helper(stack &s, F func, R (F::*)(Parameters...))\n\t\t{\n\t\t\treturn register_closure(s, [func\n#ifndef _MSC_VER\n\t\t\t\t= std::move(func)\n#endif\n\t\t\t](lua_State *L) mutable\n\t\t\t{\n\t\t\t\tbool suspend_requested = false;\n\t\t\t\tcall_environment env{*L, &suspend_requested};\n\t\t\t\treturn caller()(env, [&]()\n\t\t\t\t{\n\t\t\t\t\treturn call_with_converted_arguments(func, env, typename ranges::v3::make_integer_sequence::type());\n\t\t\t\t});\n\t\t\t});\n\t\t}\n\t}\n\n\ttemplate \n\tstack_value register_any_function(stack &s, Function &&f)\n\t{\n\t\ttypedef typename std::decay::type clean_function;\n\t\tauto call_operator = &clean_function::operator();\n\t\treturn detail::register_any_function_helper(s, std::forward(f), call_operator);\n\t}\n}\n\n#endif\nsilence a warning inside lua_pop#ifndef LUACPP_REGISTER_ANY_FUNCTION_HPP\n#define LUACPP_REGISTER_ANY_FUNCTION_HPP\n\n#include \"luacpp\/stack.hpp\"\n#include \"luacpp\/register_closure.hpp\"\n#include \"luacpp\/from_lua_cast.hpp\"\n#include \"luacpp\/coroutine.hpp\"\n#include \n\nnamespace lua\n{\n\tnamespace detail\n\t{\n\t\tstruct call_environment\n\t\t{\n\t\t\tlua_State &L;\n\t\t\tbool *suspend_requested;\n\t\t};\n\n\t\ttemplate \n\t\tstruct argument_converter\n\t\t{\n\t\t\tT operator()(call_environment const &env, int address) const\n\t\t\t{\n\t\t\t\treturn from_lua_cast(env.L, address);\n\t\t\t}\n\t\t};\n\n\t\ttemplate \n\t\tstruct argument_converter : argument_converter\n\t\t{\n\t\t};\n\n\t\ttemplate <>\n\t\tstruct argument_converter\n\t\t{\n\t\t\tcoroutine operator()(call_environment const &env, int) const\n\t\t\t{\n\t\t\t\treturn coroutine(env.L, env.suspend_requested);\n\t\t\t}\n\t\t};\n\n\t\ttemplate \n\t\tauto call_with_converted_arguments(Function &func, call_environment const &env, ranges::v3::integer_sequence)\n\t\t{\n\t\t\treturn func(argument_converter()(env, 1 + Indices)...);\n\t\t}\n\n\t\ttemplate \n\t\tstruct caller\n\t\t{\n\t\t\ttemplate \n\t\t\tresult_or_yield operator()(call_environment const &env, F const &f, Arguments &&...args) const\n\t\t\t{\n\t\t\t\tassert(!env.suspend_requested || !*env.suspend_requested); \/\/TODO\n\t\t\t\tNonVoid result = f(std::forward(args)...);\n\t\t\t\tpush(env.L, std::move(result));\n\t\t\t\tif (sizeof...(Arguments))\n\t\t\t\t{\n\t\t\t\t\tint const top = lua_gettop(&env.L);\n\t\t\t\t\tlua_replace(&env.L, (top - sizeof...(Arguments)));\n\t\t\t\t\tlua_pop(&env.L, (sizeof...(Arguments) - 1));\n\t\t\t\t}\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t};\n\n\t\ttemplate <>\n\t\tstruct caller\n\t\t{\n\t\t\ttemplate \n\t\t\tresult_or_yield operator()(call_environment const &env, F const &f, Arguments &&...args) const\n\t\t\t{\n\t\t\t\tf(std::forward(args)...);\n\t\t\t\tlua_pop(&env.L, static_cast(sizeof...(Arguments)));\n\t\t\t\tif (env.suspend_requested && *env.suspend_requested)\n\t\t\t\t{\n\t\t\t\t\treturn yield();\n\t\t\t\t}\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t};\n\n\t\ttemplate \n\t\tstack_value register_any_function_helper(stack &s, F func, R (F::*)(Parameters...) const)\n\t\t{\n\t\t\treturn register_closure(s, [func\n#ifndef _MSC_VER\n\t\t\t\t= std::move(func)\n#endif\n\t\t\t](lua_State *L)\n\t\t\t{\n\t\t\t\tbool suspend_requested = false;\n\t\t\t\tcall_environment env{*L, &suspend_requested};\n\t\t\t\treturn caller()(env, [\n#ifdef _MSC_VER\n\t\t\t\t\tfunc, &env\n#else\n\t\t\t\t&\n#endif\n\t\t\t\t]()\n\t\t\t\t{\n\t\t\t\t\treturn call_with_converted_arguments(func, env, typename ranges::v3::make_integer_sequence::type());\n\t\t\t\t});\n\t\t\t});\n\t\t}\n\n\t\ttemplate \n\t\tstack_value register_any_function_helper(stack &s, F func, R (F::*)(Parameters...))\n\t\t{\n\t\t\treturn register_closure(s, [func\n#ifndef _MSC_VER\n\t\t\t\t= std::move(func)\n#endif\n\t\t\t](lua_State *L) mutable\n\t\t\t{\n\t\t\t\tbool suspend_requested = false;\n\t\t\t\tcall_environment env{*L, &suspend_requested};\n\t\t\t\treturn caller()(env, [&]()\n\t\t\t\t{\n\t\t\t\t\treturn call_with_converted_arguments(func, env, typename ranges::v3::make_integer_sequence::type());\n\t\t\t\t});\n\t\t\t});\n\t\t}\n\t}\n\n\ttemplate \n\tstack_value register_any_function(stack &s, Function &&f)\n\t{\n\t\ttypedef typename std::decay::type clean_function;\n\t\tauto call_operator = &clean_function::operator();\n\t\treturn detail::register_any_function_helper(s, std::forward(f), call_operator);\n\t}\n}\n\n#endif\n<|endoftext|>"} {"text":"\/*\n * Copyright 2017 Andrei Pangin\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n#include \n#include \n#include \"vmStructs.h\"\n#include \"vmEntry.h\"\n\n\nNativeCodeCache* VMStructs::_libjvm = NULL;\n\nbool VMStructs::_has_class_names = false;\nbool VMStructs::_has_class_loader_data = false;\nbool VMStructs::_has_thread_bridge = false;\nbool VMStructs::_has_perm_gen = false;\n\nint VMStructs::_klass_name_offset = -1;\nint VMStructs::_symbol_length_offset = -1;\nint VMStructs::_symbol_length_and_refcount_offset = -1;\nint VMStructs::_symbol_body_offset = -1;\nint VMStructs::_class_loader_data_offset = -1;\nint VMStructs::_methods_offset = -1;\nint VMStructs::_thread_osthread_offset = -1;\nint VMStructs::_thread_anchor_offset = -1;\nint VMStructs::_osthread_id_offset = -1;\nint VMStructs::_anchor_sp_offset = -1;\nint VMStructs::_anchor_pc_offset = -1;\nint VMStructs::_frame_size_offset = -1;\n\njfieldID VMStructs::_eetop;\njfieldID VMStructs::_tid;\njfieldID VMStructs::_klass = NULL;\nint VMStructs::_tls_index = -1;\nintptr_t VMStructs::_env_offset;\n\nVMStructs::GetStackTraceFunc VMStructs::_get_stack_trace = NULL;\nVMStructs::UnsafeParkFunc VMStructs::_unsafe_park = NULL;\nVMStructs::FindBlobFunc VMStructs::_find_blob = NULL;\nVMStructs::LockFunc VMStructs::_lock_func;\nVMStructs::LockFunc VMStructs::_unlock_func;\n\n\nuintptr_t VMStructs::readSymbol(const char* symbol_name) {\n const void* symbol = _libjvm->findSymbol(symbol_name);\n if (symbol == NULL) {\n \/\/ Avoid JVM crash in case of missing symbols\n return 0;\n }\n return *(uintptr_t*)symbol;\n}\n\nvoid VMStructs::init(NativeCodeCache* libjvm) {\n _libjvm = libjvm;\n\n initOffsets();\n initJvmFunctions();\n\n JNIEnv* env = VM::jni();\n initThreadBridge(env);\n initLogging(env);\n env->ExceptionClear();\n}\n\nvoid VMStructs::initOffsets() {\n uintptr_t entry = readSymbol(\"gHotSpotVMStructs\");\n uintptr_t stride = readSymbol(\"gHotSpotVMStructEntryArrayStride\");\n uintptr_t type_offset = readSymbol(\"gHotSpotVMStructEntryTypeNameOffset\");\n uintptr_t field_offset = readSymbol(\"gHotSpotVMStructEntryFieldNameOffset\");\n uintptr_t offset_offset = readSymbol(\"gHotSpotVMStructEntryOffsetOffset\");\n uintptr_t address_offset = readSymbol(\"gHotSpotVMStructEntryAddressOffset\");\n\n if (entry == 0 || stride == 0) {\n return;\n }\n\n while (true) {\n const char* type = *(const char**)(entry + type_offset);\n const char* field = *(const char**)(entry + field_offset);\n if (type == NULL || field == NULL) {\n break;\n }\n\n if (strcmp(type, \"Klass\") == 0) {\n if (strcmp(field, \"_name\") == 0) {\n _klass_name_offset = *(int*)(entry + offset_offset);\n }\n } else if (strcmp(type, \"Symbol\") == 0) {\n if (strcmp(field, \"_length\") == 0) {\n _symbol_length_offset = *(int*)(entry + offset_offset);\n } else if (strcmp(field, \"_length_and_refcount\") == 0) {\n _symbol_length_and_refcount_offset = *(int*)(entry + offset_offset);\n } else if (strcmp(field, \"_body\") == 0) {\n _symbol_body_offset = *(int*)(entry + offset_offset);\n }\n } else if (strcmp(type, \"InstanceKlass\") == 0) {\n if (strcmp(field, \"_class_loader_data\") == 0) {\n _class_loader_data_offset = *(int*)(entry + offset_offset);\n } else if (strcmp(field, \"_methods\") == 0) {\n _methods_offset = *(int*)(entry + offset_offset);\n }\n } else if (strcmp(type, \"java_lang_Class\") == 0) {\n if (strcmp(field, \"_klass_offset\") == 0) {\n int klass_offset = **(int**)(entry + address_offset);\n _klass = (jfieldID)(uintptr_t)(klass_offset << 2 | 2);\n }\n } else if (strcmp(type, \"JavaThread\") == 0) {\n if (strcmp(field, \"_osthread\") == 0) {\n _thread_osthread_offset = *(int*)(entry + offset_offset);\n } else if (strcmp(field, \"_anchor\") == 0) {\n _thread_anchor_offset = *(int*)(entry + offset_offset);\n }\n } else if (strcmp(type, \"OSThread\") == 0) {\n if (strcmp(field, \"_thread_id\") == 0) {\n _osthread_id_offset = *(int*)(entry + offset_offset);\n }\n } else if (strcmp(type, \"JavaFrameAnchor\") == 0) {\n if (strcmp(field, \"_last_Java_sp\") == 0) {\n _anchor_sp_offset = *(int*)(entry + offset_offset);\n } else if (strcmp(field, \"_last_Java_pc\") == 0) {\n _anchor_pc_offset = *(int*)(entry + offset_offset);\n }\n } else if (strcmp(type, \"CodeBlob\") == 0) {\n if (strcmp(field, \"_frame_size\") == 0) {\n _frame_size_offset = *(int*)(entry + offset_offset);\n }\n } else if (strcmp(type, \"PermGen\") == 0) {\n _has_perm_gen = true;\n }\n\n entry += stride;\n }\n\n _has_class_names = _klass_name_offset >= 0\n && (_symbol_length_offset >= 0 || _symbol_length_and_refcount_offset >= 0)\n && _symbol_body_offset >= 0\n && _klass != NULL;\n}\n\nvoid VMStructs::initJvmFunctions() {\n _get_stack_trace = (GetStackTraceFunc)_libjvm->findSymbol(\"_ZN8JvmtiEnv13GetStackTraceEP10JavaThreadiiP15_jvmtiFrameInfoPi\");\n if (_get_stack_trace == NULL) {\n _get_stack_trace = (GetStackTraceFunc)_libjvm->findSymbol(\"_ZN8JvmtiEnv13GetStackTraceEP10JavaThreadiiP14jvmtiFrameInfoPi\");\n }\n\n _unsafe_park = (UnsafeParkFunc)_libjvm->findSymbol(\"Unsafe_Park\");\n if (_unsafe_park == NULL) {\n \/\/ In some macOS builds of JDK 11 Unsafe_Park appears to have a C++ decorated name\n _unsafe_park = (UnsafeParkFunc)_libjvm->findSymbol(\"_ZL11Unsafe_ParkP7JNIEnv_P8_jobjecthl\");\n }\n\n if (_frame_size_offset >= 0) {\n _find_blob = (FindBlobFunc)_libjvm->findSymbol(\"_ZN9CodeCache16find_blob_unsafeEPv\");\n if (_find_blob == NULL) {\n _find_blob = (FindBlobFunc)_libjvm->findSymbol(\"_ZN9CodeCache9find_blobEPv\");\n }\n }\n\n if (VM::hotspot_version() == 8 && _class_loader_data_offset >= 0 && _methods_offset >= 0 && _klass != NULL) {\n _lock_func = (LockFunc)_libjvm->findSymbol(\"_ZN7Monitor28lock_without_safepoint_checkEv\");\n _unlock_func = (LockFunc)_libjvm->findSymbol(\"_ZN7Monitor6unlockEv\");\n _has_class_loader_data = _lock_func != NULL && _unlock_func != NULL;\n }\n}\n\nvoid VMStructs::initThreadBridge(JNIEnv* env) {\n \/\/ Get eetop field - a bridge from Java Thread to VMThread\n jthread thread;\n if (VM::jvmti()->GetCurrentThread(&thread) != 0) {\n return;\n }\n\n jclass thread_class = env->GetObjectClass(thread);\n _eetop = env->GetFieldID(thread_class, \"eetop\", \"J\");\n _tid = env->GetFieldID(thread_class, \"tid\", \"J\");\n if (_eetop == NULL || _tid == NULL) {\n return;\n }\n\n VMThread* vm_thread = VMThread::fromJavaThread(env, thread);\n if (vm_thread == NULL) {\n return;\n }\n\n \/\/ Workaround for JDK-8132510: it's not safe to call GetEnv() inside a signal handler\n \/\/ since JDK 9, so we do it only for threads already registered in ThreadLocalStorage\n if (VM::hotspot_version() >= 9) {\n for (int i = 0; i < 1024; i++) {\n if (pthread_getspecific((pthread_key_t)i) == vm_thread) {\n _tls_index = i;\n break;\n }\n }\n }\n\n _env_offset = (intptr_t)env - (intptr_t)vm_thread;\n _has_thread_bridge = true;\n}\n\nvoid VMStructs::initLogging(JNIEnv* env) {\n \/\/ Workaround for JDK-8238460\n if (VM::hotspot_version() >= 15) {\n VMManagement* management = VM::management();\n if (management != NULL) {\n management->ExecuteDiagnosticCommand(env, env->NewStringUTF(\"VM.log what=jni+resolve=error\"));\n }\n }\n}\n\nbool VMStructs::hasJNIEnv() {\n return _tls_index < 0 || pthread_getspecific((pthread_key_t)_tls_index) != NULL;\n}\nFixed possible deadlock on non-HotSpot JVMs\/*\n * Copyright 2017 Andrei Pangin\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n#include \n#include \n#include \"vmStructs.h\"\n#include \"vmEntry.h\"\n\n\nNativeCodeCache* VMStructs::_libjvm = NULL;\n\nbool VMStructs::_has_class_names = false;\nbool VMStructs::_has_class_loader_data = false;\nbool VMStructs::_has_thread_bridge = false;\nbool VMStructs::_has_perm_gen = false;\n\nint VMStructs::_klass_name_offset = -1;\nint VMStructs::_symbol_length_offset = -1;\nint VMStructs::_symbol_length_and_refcount_offset = -1;\nint VMStructs::_symbol_body_offset = -1;\nint VMStructs::_class_loader_data_offset = -1;\nint VMStructs::_methods_offset = -1;\nint VMStructs::_thread_osthread_offset = -1;\nint VMStructs::_thread_anchor_offset = -1;\nint VMStructs::_osthread_id_offset = -1;\nint VMStructs::_anchor_sp_offset = -1;\nint VMStructs::_anchor_pc_offset = -1;\nint VMStructs::_frame_size_offset = -1;\n\njfieldID VMStructs::_eetop;\njfieldID VMStructs::_tid;\njfieldID VMStructs::_klass = NULL;\nint VMStructs::_tls_index = -1;\nintptr_t VMStructs::_env_offset;\n\nVMStructs::GetStackTraceFunc VMStructs::_get_stack_trace = NULL;\nVMStructs::UnsafeParkFunc VMStructs::_unsafe_park = NULL;\nVMStructs::FindBlobFunc VMStructs::_find_blob = NULL;\nVMStructs::LockFunc VMStructs::_lock_func;\nVMStructs::LockFunc VMStructs::_unlock_func;\n\n\nuintptr_t VMStructs::readSymbol(const char* symbol_name) {\n const void* symbol = _libjvm->findSymbol(symbol_name);\n if (symbol == NULL) {\n \/\/ Avoid JVM crash in case of missing symbols\n return 0;\n }\n return *(uintptr_t*)symbol;\n}\n\nvoid VMStructs::init(NativeCodeCache* libjvm) {\n _libjvm = libjvm;\n\n initOffsets();\n initJvmFunctions();\n\n JNIEnv* env = VM::jni();\n initThreadBridge(env);\n initLogging(env);\n env->ExceptionClear();\n}\n\nvoid VMStructs::initOffsets() {\n uintptr_t entry = readSymbol(\"gHotSpotVMStructs\");\n uintptr_t stride = readSymbol(\"gHotSpotVMStructEntryArrayStride\");\n uintptr_t type_offset = readSymbol(\"gHotSpotVMStructEntryTypeNameOffset\");\n uintptr_t field_offset = readSymbol(\"gHotSpotVMStructEntryFieldNameOffset\");\n uintptr_t offset_offset = readSymbol(\"gHotSpotVMStructEntryOffsetOffset\");\n uintptr_t address_offset = readSymbol(\"gHotSpotVMStructEntryAddressOffset\");\n\n if (entry == 0 || stride == 0) {\n return;\n }\n\n while (true) {\n const char* type = *(const char**)(entry + type_offset);\n const char* field = *(const char**)(entry + field_offset);\n if (type == NULL || field == NULL) {\n break;\n }\n\n if (strcmp(type, \"Klass\") == 0) {\n if (strcmp(field, \"_name\") == 0) {\n _klass_name_offset = *(int*)(entry + offset_offset);\n }\n } else if (strcmp(type, \"Symbol\") == 0) {\n if (strcmp(field, \"_length\") == 0) {\n _symbol_length_offset = *(int*)(entry + offset_offset);\n } else if (strcmp(field, \"_length_and_refcount\") == 0) {\n _symbol_length_and_refcount_offset = *(int*)(entry + offset_offset);\n } else if (strcmp(field, \"_body\") == 0) {\n _symbol_body_offset = *(int*)(entry + offset_offset);\n }\n } else if (strcmp(type, \"InstanceKlass\") == 0) {\n if (strcmp(field, \"_class_loader_data\") == 0) {\n _class_loader_data_offset = *(int*)(entry + offset_offset);\n } else if (strcmp(field, \"_methods\") == 0) {\n _methods_offset = *(int*)(entry + offset_offset);\n }\n } else if (strcmp(type, \"java_lang_Class\") == 0) {\n if (strcmp(field, \"_klass_offset\") == 0) {\n int klass_offset = **(int**)(entry + address_offset);\n _klass = (jfieldID)(uintptr_t)(klass_offset << 2 | 2);\n }\n } else if (strcmp(type, \"JavaThread\") == 0) {\n if (strcmp(field, \"_osthread\") == 0) {\n _thread_osthread_offset = *(int*)(entry + offset_offset);\n } else if (strcmp(field, \"_anchor\") == 0) {\n _thread_anchor_offset = *(int*)(entry + offset_offset);\n }\n } else if (strcmp(type, \"OSThread\") == 0) {\n if (strcmp(field, \"_thread_id\") == 0) {\n _osthread_id_offset = *(int*)(entry + offset_offset);\n }\n } else if (strcmp(type, \"JavaFrameAnchor\") == 0) {\n if (strcmp(field, \"_last_Java_sp\") == 0) {\n _anchor_sp_offset = *(int*)(entry + offset_offset);\n } else if (strcmp(field, \"_last_Java_pc\") == 0) {\n _anchor_pc_offset = *(int*)(entry + offset_offset);\n }\n } else if (strcmp(type, \"CodeBlob\") == 0) {\n if (strcmp(field, \"_frame_size\") == 0) {\n _frame_size_offset = *(int*)(entry + offset_offset);\n }\n } else if (strcmp(type, \"PermGen\") == 0) {\n _has_perm_gen = true;\n }\n\n entry += stride;\n }\n\n _has_class_names = _klass_name_offset >= 0\n && (_symbol_length_offset >= 0 || _symbol_length_and_refcount_offset >= 0)\n && _symbol_body_offset >= 0\n && _klass != NULL;\n}\n\nvoid VMStructs::initJvmFunctions() {\n _get_stack_trace = (GetStackTraceFunc)_libjvm->findSymbol(\"_ZN8JvmtiEnv13GetStackTraceEP10JavaThreadiiP15_jvmtiFrameInfoPi\");\n if (_get_stack_trace == NULL) {\n _get_stack_trace = (GetStackTraceFunc)_libjvm->findSymbol(\"_ZN8JvmtiEnv13GetStackTraceEP10JavaThreadiiP14jvmtiFrameInfoPi\");\n }\n\n _unsafe_park = (UnsafeParkFunc)_libjvm->findSymbol(\"Unsafe_Park\");\n if (_unsafe_park == NULL) {\n \/\/ In some macOS builds of JDK 11 Unsafe_Park appears to have a C++ decorated name\n _unsafe_park = (UnsafeParkFunc)_libjvm->findSymbol(\"_ZL11Unsafe_ParkP7JNIEnv_P8_jobjecthl\");\n }\n\n if (_frame_size_offset >= 0) {\n _find_blob = (FindBlobFunc)_libjvm->findSymbol(\"_ZN9CodeCache16find_blob_unsafeEPv\");\n if (_find_blob == NULL) {\n _find_blob = (FindBlobFunc)_libjvm->findSymbol(\"_ZN9CodeCache9find_blobEPv\");\n }\n }\n\n if (VM::hotspot_version() == 8 && _class_loader_data_offset >= 0 && _methods_offset >= 0 && _klass != NULL) {\n _lock_func = (LockFunc)_libjvm->findSymbol(\"_ZN7Monitor28lock_without_safepoint_checkEv\");\n _unlock_func = (LockFunc)_libjvm->findSymbol(\"_ZN7Monitor6unlockEv\");\n _has_class_loader_data = _lock_func != NULL && _unlock_func != NULL;\n }\n}\n\nvoid VMStructs::initThreadBridge(JNIEnv* env) {\n \/\/ Get eetop field - a bridge from Java Thread to VMThread\n jthread thread;\n if (VM::jvmti()->GetCurrentThread(&thread) != 0) {\n return;\n }\n\n jclass thread_class = env->GetObjectClass(thread);\n _eetop = env->GetFieldID(thread_class, \"eetop\", \"J\");\n _tid = env->GetFieldID(thread_class, \"tid\", \"J\");\n if (_eetop == NULL || _tid == NULL) {\n return;\n }\n\n VMThread* vm_thread = VMThread::fromJavaThread(env, thread);\n if (vm_thread == NULL) {\n return;\n }\n\n \/\/ Workaround for JDK-8132510: it's not safe to call GetEnv() inside a signal handler\n \/\/ since JDK 9, so we do it only for threads already registered in ThreadLocalStorage\n if (VM::hotspot_version() >= 9 || VM::hotspot_version() == 0) {\n for (int i = 0; i < 1024; i++) {\n if (pthread_getspecific((pthread_key_t)i) == vm_thread) {\n _tls_index = i;\n break;\n }\n }\n }\n\n _env_offset = (intptr_t)env - (intptr_t)vm_thread;\n _has_thread_bridge = true;\n}\n\nvoid VMStructs::initLogging(JNIEnv* env) {\n \/\/ Workaround for JDK-8238460\n if (VM::hotspot_version() >= 15) {\n VMManagement* management = VM::management();\n if (management != NULL) {\n management->ExecuteDiagnosticCommand(env, env->NewStringUTF(\"VM.log what=jni+resolve=error\"));\n }\n }\n}\n\nbool VMStructs::hasJNIEnv() {\n return _tls_index < 0 || pthread_getspecific((pthread_key_t)_tls_index) != NULL;\n}\n<|endoftext|>"} {"text":"\/*!\n \\copyright (c) RDO-Team, 2011\n \\file rdortp.cpp\n \\authors Барс Александр\n \\authors Урусов Андрей (rdo@rk9.bmstu.ru)\n \\date 11.06.2006\n \\brief Типы ресурсов\n \\indent 4T\n*\/\n\n\/\/ ---------------------------------------------------------------------------- PCH\n#include \"simulator\/compiler\/parser\/pch.h\"\n\/\/ ----------------------------------------------------------------------- INCLUDES\n#include \n\/\/ ----------------------------------------------------------------------- SYNOPSIS\n#include \"simulator\/compiler\/parser\/rdortp.h\"\n#include \"simulator\/compiler\/parser\/rdoparser.h\"\n#include \"simulator\/compiler\/parser\/rdoparser_lexer.h\"\n#include \"simulator\/runtime\/calc\/resource\/calc_resource.h\"\n\/\/ --------------------------------------------------------------------------------\n\nOPEN_RDO_PARSER_NAMESPACE\n\nnamespace\n{\n\nrdo::runtime::LPRDOResource createSimpleResource(\n\tconst rdo::runtime::LPRDORuntime runtime,\n\tconst rdo::runtime::RDOResource::ParamList& params,\n\tconst rdo::runtime::LPIResourceType& type,\n\tstd::size_t resource_id,\n\tstd::size_t type_id,\n\tbool trace,\n\tbool temporary,\n\tbool isNested)\n{\n\treturn rdo::Factory::create(runtime, params, type, resource_id, type_id, trace, temporary, isNested);\n}\n\nrdo::runtime::LPRDOPROCResource createProcessResource(\n\tconst rdo::runtime::LPRDORuntime runtime,\n\tconst rdo::runtime::RDOResource::ParamList& params,\n\tconst rdo::runtime::LPIResourceType& type,\n\tstd::size_t resource_id,\n\tstd::size_t type_id,\n\tbool trace,\n\tbool temporary)\n{\n\treturn rdo::Factory::create(runtime, params, type, resource_id, type_id, trace, temporary);\n}\n\nrdo::runtime::LPRDOPROCTransact createProcessTransact(\n\tconst rdo::runtime::LPRDORuntime runtime,\n\tconst rdo::runtime::RDOResource::ParamList& params,\n\tconst rdo::runtime::LPIResourceType& type,\n\tstd::size_t resource_id,\n\tstd::size_t type_id,\n\tbool trace,\n\tbool temporary)\n{\n\treturn rdo::Factory::create(runtime, params, type, resource_id, type_id, trace, temporary);\n}\n\n}\n\nint rtplex(YYSTYPE* lpval, YYLTYPE* llocp, void* lexer)\n{\n\tLEXER->m_lpval = lpval;\n\tLEXER->m_lploc = llocp;\n\treturn LEXER->yylex();\n}\n\nvoid rtperror(YYLTYPE* \/*llocp*\/, void* \/*lexer*\/, const char* \/*message*\/)\n{}\n\n\/\/ --------------------------------------------------------------------------------\n\/\/ -------------------- RDORTPResType\n\/\/ --------------------------------------------------------------------------------\nRDORTPResType::RDORTPResType(const LPRDOParser& pParser, const RDOParserSrcInfo& src_info, bool permanent)\n\t: RDOParserSrcInfo(src_info)\n\t, RDOResourceTypeList(pParser->getRTP_id(), pParser->runtime())\n\t, m_number(pParser->getRTP_id()) \/\/ TODO кажется ненужным\n\t, m_permanent(permanent)\n{\n\tpParser->insertRTPResType(LPRDORTPResType(this));\n}\n\nRDORTPResType::~RDORTPResType()\n{}\n\nint RDORTPResType::getNumber() const\n{\n\treturn m_number;\n}\n\nbool RDORTPResType::isPermanent() const\n{\n\treturn m_permanent;\n}\n\nbool RDORTPResType::isTemporary() const\n{\n\treturn !m_permanent;\n}\n\nconst RDORTPResType::ParamList& RDORTPResType::getParams() const\n{\n\treturn m_params;\n}\n\nruntime::RDOType::TypeID RDORTPResType::typeID() const\n{\n\treturn runtime::RDOType::t_pointer;\n}\n\nLPRDORSSResource RDORTPResType::createRes(const LPRDOParser& pParser, const RDOParserSrcInfo& src_info)\n{\n\treturn rdo::Factory::create(pParser, src_info, this);\n}\n\nvoid RDORTPResType::addParam(const LPRDORTPParam& param)\n{\n\tif (findRTPParam(param->name()))\n\t{\n\t\tRDOParser::s_parser()->error().error(param->src_info(), rdo::format(\"Параметр уже существует: %s\", param->name().c_str()));\n\t}\n\tm_params.push_back(param);\n}\n\nvoid RDORTPResType::addParam(const std::string& \/*param_name*\/, rdo::runtime::RDOType::TypeID \/*param_typeID*\/)\n{}\n\nLPRDORTPParam RDORTPResType::findRTPParam(const std::string& paramName) const\n{\n\tParamList::const_iterator it = std::find_if(m_params.begin(), m_params.end(), compareName(paramName));\n\treturn it != m_params.end() ? *it : LPRDORTPParam();\n}\n\nstd::size_t RDORTPResType::getRTPParamNumber(const std::string& paramName) const\n{\n\tParamList::const_iterator it = std::find_if(m_params.begin(), m_params.end(), compareName(paramName));\n\treturn it != m_params.end() ? it - m_params.begin() : UNDEFINED_PARAM;\n}\n\nvoid RDORTPResType::writeModelStructure(std::ostream& stream) const\n{\n\tstream << getNumber() << \" \" << name() << \" \" << getParams().size() << std::endl;\n\tfor (std::size_t i = 0; i < getParams().size(); i++)\n\t{\n\t\tstream << \" \" << (i+1) << \" \";\n\t\tgetParams().at(i)->writeModelStructure(stream);\n\t}\n}\n\nstd::string RDORTPResType::name() const\n{\n\tstatic std::string s_name;\n\ts_name = src_text();\n\treturn s_name;\n}\n\nLPIType RDORTPResType::type_cast(const LPIType& pFrom, const RDOParserSrcInfo& from_src_info, const RDOParserSrcInfo& to_src_info, const RDOParserSrcInfo& src_info) const\n{\n\tswitch (pFrom.object_dynamic_cast()->typeID())\n\t{\n\tcase rdo::runtime::RDOType::t_pointer:\n\t\t{\n\t\t\tLPIType pThisRTPType(const_cast(this));\n\n\t\t\t\/\/! Это один и тот же тип\n\t\t\tif (pThisRTPType == pFrom)\n\t\t\t\treturn pThisRTPType;\n\n\t\t\t\/\/! Типы разные, сгенерим ошибку\n\t\t\tparser::g_error().push_only(src_info, \"Несоответствие типов ресурсов\");\n\t\t\tparser::g_error().push_only(to_src_info, to_src_info.src_text());\n\t\t\tparser::g_error().push_done();\n\t\t\tbreak;\n\t\t}\n\tdefault:\n\t\t{\n\t\t\tparser::g_error().push_only(src_info, rdo::format(\"Ожидается тип ресурса, найдено: %s\", from_src_info.src_text().c_str()));\n\t\t\tparser::g_error().push_only(to_src_info, rdo::format(\"См. тип: %s\", to_src_info.src_text().c_str()));\n\t\t\tparser::g_error().push_done();\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn LPIType(NULL);\n}\n\nLPRDOValue RDORTPResType::value_cast(const LPRDOValue& pFrom, const RDOParserSrcInfo& to_src_info, const RDOParserSrcInfo& src_info) const\n{\n\tASSERT(pFrom);\n\n\tLPRDORTPResType pRTPResType = pFrom->typeInfo()->itype().object_dynamic_cast();\n\tif (pRTPResType)\n\t{\n\t\tLPIType pThisType = const_cast(this);\n\n\t\t\/\/! Это один и тот же тип\n\t\tif (pThisType == pRTPResType.object_dynamic_cast())\n\t\t\treturn pFrom;\n\n\t\t\/\/! Типы разные, сгенерим ошибку\n\t\tparser::g_error().push_only(src_info, \"Несоответствие типов ресурсов\");\n\t\tparser::g_error().push_only(to_src_info, rdo::format( \"Ожидается: %s\", to_src_info.src_text().c_str()));\n\t\tparser::g_error().push_only(src_info, rdo::format( \"Пришел: %s\", pFrom->src_text().c_str()));\n\t\tparser::g_error().push_only(to_src_info, to_src_info.src_text());\n\t\tparser::g_error().push_done();\n\t}\n\tparser::g_error().push_only(src_info, rdo::format(\"Ожидается ресурс, найдено: %s\", pFrom->src_text().c_str()));\n\tparser::g_error().push_only(to_src_info, rdo::format(\"См. тип: %s\", to_src_info.src_text().c_str()));\n\tparser::g_error().push_done();\n\n\treturn LPRDOValue(NULL);\n}\n\nrdo::runtime::LPRDOCalc RDORTPResType::calc_cast(const rdo::runtime::LPRDOCalc& pCalc, const LPIType& pType) const\n{\n\treturn pCalc;\n}\n\nrdo::runtime::RDOValue RDORTPResType::get_default() const\n{\n\tNEVER_REACH_HERE;\n\treturn rdo::runtime::RDOValue();\n\t\/\/return rdo::runtime::RDOValue (pResourceType,pResource);\n}\n\nnamespace\n{\n\nLPExpression contextTypeOfResourceType(const LPRDORTPResType& resourceType, const RDOParserSrcInfo& srcInfo)\n{\n\treturn rdo::Factory::create(\n\t\trdo::Factory::create(resourceType, srcInfo),\n\t\trdo::runtime::LPRDOCalc(NULL),\n\t\tsrcInfo\n\t);\n}\n\n}\n\nContext::LPFindResult RDORTPResType::onFindContext(const std::string& method, const Context::Params& params, const RDOParserSrcInfo& srcInfo) const\n{\n\tif (method == Context::METHOD_GET)\n\t{\n\t\tconst std::string paramName = params.identifier();\n\n\t\tconst std::size_t parNumb = getRTPParamNumber(paramName);\n\t\tif (parNumb == RDORTPResType::UNDEFINED_PARAM)\n\t\t{\n\t\t\tRDOParser::s_parser()->error().error(srcInfo, rdo::format(\"Неизвестный параметр ресурса: %s\", paramName.c_str()));\n\t\t}\n\n\t\tContext::Params params_;\n\t\tparams_[RDORSSResource::GET_RESOURCE] = params.get(RDORSSResource::GET_RESOURCE);\n\t\tparams_[RDOParam::CONTEXT_PARAM_PARAM_ID] = parNumb;\n\n\t\tLPContext pParam = findRTPParam(paramName);\n\t\tASSERT(pParam);\n\t\treturn pParam->find(Context::METHOD_GET, params_, srcInfo);\n\t}\n\n\tif (method == Context::METHOD_OPERATOR_DOT)\n\t{\n\t\tconst std::string paramName = params.identifier();\n\n\t\tconst std::size_t parNumb = getRTPParamNumber(paramName);\n\t\tif (parNumb == RDORTPResType::UNDEFINED_PARAM)\n\t\t\treturn rdo::Factory::create();\n\n\t\tLPRDOParam pParam = findRTPParam(paramName);\n\t\tASSERT(pParam);\n\n\t\tContext::Params params_;\n\t\tparams_[RDORSSResource::GET_RESOURCE] = params.get(RDORSSResource::GET_RESOURCE);\n\t\tparams_[RDOParam::CONTEXT_PARAM_PARAM_ID] = parNumb;\n\t\tparams_[Context::Params::IDENTIFIER] = paramName;\n\n\t\tLPRDORTPResType pParamType =\n\t\t\tpParam->getTypeInfo()->itype().object_dynamic_cast();\n\n\t\tif (!pParamType)\n\t\t\treturn rdo::Factory::create(SwitchContext(pParam, params_));\n\n\t\tContext::LPFindResult result = pParam->find(Context::METHOD_GET, params_, srcInfo);\n\t\tLPExpression pNestedResource = result->getCreateExpression()();\n\n\t\tContext::Params params__;\n\t\tparams__[RDORSSResource::GET_RESOURCE] = pNestedResource;\n\n\t\treturn rdo::Factory::create(SwitchContext(pParamType, params__));\n\t}\n\n\n\n\tif (method == Context::METHOD_TYPE_OF)\n\t{\n\t\tLPRDORTPResType pThis(const_cast(this));\n\t\treturn rdo::Factory::create(CreateExpression(boost::bind(&contextTypeOfResourceType, pThis, srcInfo)));\n\t}\n\n\treturn rdo::Factory::create();\n}\n\nvoid RDORTPResType::setSubtype(Subtype type)\n{\n\tASSERT(!m_subtype.is_initialized() || m_subtype.get() == type);\n\tm_subtype = type;\n}\n\nvoid RDORTPResType::setupRuntimeFactory()\n{\n\tSubtype subtype = m_subtype.is_initialized()\n\t\t? m_subtype.get()\n\t\t: RT_SIMPLE;\n\n\truntime::RDOResourceTypeList::Create create;\n\tswitch (subtype)\n\t{\n\tcase RT_SIMPLE:\n\t\tcreate = boost::bind(&createSimpleResource, _1, _2, _3, _4, _5, _6, _7, _8);\n\t\tbreak;\n\tcase RT_PROCESS_RESOURCE:\n\t\tcreate = boost::bind(&createProcessResource, _1, _2, _3, _4, _5, _6, _7);\n\t\tbreak;\n\tcase RT_PROCESS_TRANSACT:\n\t\tcreate = boost::bind(&createProcessTransact, _1, _2, _3, _4, _5, _6, _7);\n\t\tbreak;\n\tdefault:\n\t\tNEVER_REACH_HERE;\n\t}\n\tsetFactoryMethod(create);\n}\n\n\/*\n\/\/ --------------------------------------------------------------------------------\n\/\/ -------------------- RDORTPFuzzyMembershiftFun - ф-ия принадлежности нечеткого терма\n\/\/ --------------------------------------------------------------------------------\nRDORTPFuzzyMembershiftFun::RDORTPFuzzyMembershiftFun(const LPRDOParser& pParser):\n\tRDOParserObject(pParser)\n{\n\tfor (std::size_t i = 0; i < m_points.size(); i++)\n\t{\n\/\/\t\tdouble x = m_points[i]->getX();\n\t}\n\n\tItems::iterator it = m_points.begin();\n\twhile (it != m_points.end())\n\t{\n\t\tdouble x = (*it)->getX();\n\t\tit++;\n\t}\n}\n\/\/ --------------------------------------------------------------------------------\n\/\/ -------------------- RDORTPFuzzyTerm - нечеткий термин\n\/\/ --------------------------------------------------------------------------------\nRDORTPFuzzyTerm::RDORTPFuzzyTerm(const LPRDOParser& pParser, const RDOParserSrcInfo& src_info, RDORTPFuzzyMembershiftFun* pMembersfift_fun):\n\tRDOParserObject(pParser)\n{\n\n}*\/\n\nCLOSE_RDO_PARSER_NAMESPACE\nзаплатка для контекста типа ресурса\/*!\n \\copyright (c) RDO-Team, 2011\n \\file rdortp.cpp\n \\authors Барс Александр\n \\authors Урусов Андрей (rdo@rk9.bmstu.ru)\n \\date 11.06.2006\n \\brief Типы ресурсов\n \\indent 4T\n*\/\n\n\/\/ ---------------------------------------------------------------------------- PCH\n#include \"simulator\/compiler\/parser\/pch.h\"\n\/\/ ----------------------------------------------------------------------- INCLUDES\n#include \n\/\/ ----------------------------------------------------------------------- SYNOPSIS\n#include \"simulator\/compiler\/parser\/rdortp.h\"\n#include \"simulator\/compiler\/parser\/rdoparser.h\"\n#include \"simulator\/compiler\/parser\/rdoparser_lexer.h\"\n#include \"simulator\/runtime\/calc\/resource\/calc_resource.h\"\n\/\/ --------------------------------------------------------------------------------\n\nOPEN_RDO_PARSER_NAMESPACE\n\nnamespace\n{\n\nrdo::runtime::LPRDOResource createSimpleResource(\n\tconst rdo::runtime::LPRDORuntime runtime,\n\tconst rdo::runtime::RDOResource::ParamList& params,\n\tconst rdo::runtime::LPIResourceType& type,\n\tstd::size_t resource_id,\n\tstd::size_t type_id,\n\tbool trace,\n\tbool temporary,\n\tbool isNested)\n{\n\treturn rdo::Factory::create(runtime, params, type, resource_id, type_id, trace, temporary, isNested);\n}\n\nrdo::runtime::LPRDOPROCResource createProcessResource(\n\tconst rdo::runtime::LPRDORuntime runtime,\n\tconst rdo::runtime::RDOResource::ParamList& params,\n\tconst rdo::runtime::LPIResourceType& type,\n\tstd::size_t resource_id,\n\tstd::size_t type_id,\n\tbool trace,\n\tbool temporary)\n{\n\treturn rdo::Factory::create(runtime, params, type, resource_id, type_id, trace, temporary);\n}\n\nrdo::runtime::LPRDOPROCTransact createProcessTransact(\n\tconst rdo::runtime::LPRDORuntime runtime,\n\tconst rdo::runtime::RDOResource::ParamList& params,\n\tconst rdo::runtime::LPIResourceType& type,\n\tstd::size_t resource_id,\n\tstd::size_t type_id,\n\tbool trace,\n\tbool temporary)\n{\n\treturn rdo::Factory::create(runtime, params, type, resource_id, type_id, trace, temporary);\n}\n\n}\n\nint rtplex(YYSTYPE* lpval, YYLTYPE* llocp, void* lexer)\n{\n\tLEXER->m_lpval = lpval;\n\tLEXER->m_lploc = llocp;\n\treturn LEXER->yylex();\n}\n\nvoid rtperror(YYLTYPE* \/*llocp*\/, void* \/*lexer*\/, const char* \/*message*\/)\n{}\n\n\/\/ --------------------------------------------------------------------------------\n\/\/ -------------------- RDORTPResType\n\/\/ --------------------------------------------------------------------------------\nRDORTPResType::RDORTPResType(const LPRDOParser& pParser, const RDOParserSrcInfo& src_info, bool permanent)\n\t: RDOParserSrcInfo(src_info)\n\t, RDOResourceTypeList(pParser->getRTP_id(), pParser->runtime())\n\t, m_number(pParser->getRTP_id()) \/\/ TODO кажется ненужным\n\t, m_permanent(permanent)\n{\n\tpParser->insertRTPResType(LPRDORTPResType(this));\n}\n\nRDORTPResType::~RDORTPResType()\n{}\n\nint RDORTPResType::getNumber() const\n{\n\treturn m_number;\n}\n\nbool RDORTPResType::isPermanent() const\n{\n\treturn m_permanent;\n}\n\nbool RDORTPResType::isTemporary() const\n{\n\treturn !m_permanent;\n}\n\nconst RDORTPResType::ParamList& RDORTPResType::getParams() const\n{\n\treturn m_params;\n}\n\nruntime::RDOType::TypeID RDORTPResType::typeID() const\n{\n\treturn runtime::RDOType::t_pointer;\n}\n\nLPRDORSSResource RDORTPResType::createRes(const LPRDOParser& pParser, const RDOParserSrcInfo& src_info)\n{\n\treturn rdo::Factory::create(pParser, src_info, this);\n}\n\nvoid RDORTPResType::addParam(const LPRDORTPParam& param)\n{\n\tif (findRTPParam(param->name()))\n\t{\n\t\tRDOParser::s_parser()->error().error(param->src_info(), rdo::format(\"Параметр уже существует: %s\", param->name().c_str()));\n\t}\n\tm_params.push_back(param);\n}\n\nvoid RDORTPResType::addParam(const std::string& \/*param_name*\/, rdo::runtime::RDOType::TypeID \/*param_typeID*\/)\n{}\n\nLPRDORTPParam RDORTPResType::findRTPParam(const std::string& paramName) const\n{\n\tParamList::const_iterator it = std::find_if(m_params.begin(), m_params.end(), compareName(paramName));\n\treturn it != m_params.end() ? *it : LPRDORTPParam();\n}\n\nstd::size_t RDORTPResType::getRTPParamNumber(const std::string& paramName) const\n{\n\tParamList::const_iterator it = std::find_if(m_params.begin(), m_params.end(), compareName(paramName));\n\treturn it != m_params.end() ? it - m_params.begin() : UNDEFINED_PARAM;\n}\n\nvoid RDORTPResType::writeModelStructure(std::ostream& stream) const\n{\n\tstream << getNumber() << \" \" << name() << \" \" << getParams().size() << std::endl;\n\tfor (std::size_t i = 0; i < getParams().size(); i++)\n\t{\n\t\tstream << \" \" << (i+1) << \" \";\n\t\tgetParams().at(i)->writeModelStructure(stream);\n\t}\n}\n\nstd::string RDORTPResType::name() const\n{\n\tstatic std::string s_name;\n\ts_name = src_text();\n\treturn s_name;\n}\n\nLPIType RDORTPResType::type_cast(const LPIType& pFrom, const RDOParserSrcInfo& from_src_info, const RDOParserSrcInfo& to_src_info, const RDOParserSrcInfo& src_info) const\n{\n\tswitch (pFrom.object_dynamic_cast()->typeID())\n\t{\n\tcase rdo::runtime::RDOType::t_pointer:\n\t\t{\n\t\t\tLPIType pThisRTPType(const_cast(this));\n\n\t\t\t\/\/! Это один и тот же тип\n\t\t\tif (pThisRTPType == pFrom)\n\t\t\t\treturn pThisRTPType;\n\n\t\t\t\/\/! Типы разные, сгенерим ошибку\n\t\t\tparser::g_error().push_only(src_info, \"Несоответствие типов ресурсов\");\n\t\t\tparser::g_error().push_only(to_src_info, to_src_info.src_text());\n\t\t\tparser::g_error().push_done();\n\t\t\tbreak;\n\t\t}\n\tdefault:\n\t\t{\n\t\t\tparser::g_error().push_only(src_info, rdo::format(\"Ожидается тип ресурса, найдено: %s\", from_src_info.src_text().c_str()));\n\t\t\tparser::g_error().push_only(to_src_info, rdo::format(\"См. тип: %s\", to_src_info.src_text().c_str()));\n\t\t\tparser::g_error().push_done();\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn LPIType(NULL);\n}\n\nLPRDOValue RDORTPResType::value_cast(const LPRDOValue& pFrom, const RDOParserSrcInfo& to_src_info, const RDOParserSrcInfo& src_info) const\n{\n\tASSERT(pFrom);\n\n\tLPRDORTPResType pRTPResType = pFrom->typeInfo()->itype().object_dynamic_cast();\n\tif (pRTPResType)\n\t{\n\t\tLPIType pThisType = const_cast(this);\n\n\t\t\/\/! Это один и тот же тип\n\t\tif (pThisType == pRTPResType.object_dynamic_cast())\n\t\t\treturn pFrom;\n\n\t\t\/\/! Типы разные, сгенерим ошибку\n\t\tparser::g_error().push_only(src_info, \"Несоответствие типов ресурсов\");\n\t\tparser::g_error().push_only(to_src_info, rdo::format( \"Ожидается: %s\", to_src_info.src_text().c_str()));\n\t\tparser::g_error().push_only(src_info, rdo::format( \"Пришел: %s\", pFrom->src_text().c_str()));\n\t\tparser::g_error().push_only(to_src_info, to_src_info.src_text());\n\t\tparser::g_error().push_done();\n\t}\n\tparser::g_error().push_only(src_info, rdo::format(\"Ожидается ресурс, найдено: %s\", pFrom->src_text().c_str()));\n\tparser::g_error().push_only(to_src_info, rdo::format(\"См. тип: %s\", to_src_info.src_text().c_str()));\n\tparser::g_error().push_done();\n\n\treturn LPRDOValue(NULL);\n}\n\nrdo::runtime::LPRDOCalc RDORTPResType::calc_cast(const rdo::runtime::LPRDOCalc& pCalc, const LPIType& pType) const\n{\n\treturn pCalc;\n}\n\nrdo::runtime::RDOValue RDORTPResType::get_default() const\n{\n\tNEVER_REACH_HERE;\n\treturn rdo::runtime::RDOValue();\n\t\/\/return rdo::runtime::RDOValue (pResourceType,pResource);\n}\n\nnamespace\n{\n\nLPExpression contextTypeOfResourceType(const LPRDORTPResType& resourceType, const RDOParserSrcInfo& srcInfo)\n{\n\treturn rdo::Factory::create(\n\t\trdo::Factory::create(resourceType, srcInfo),\n\t\trdo::runtime::LPRDOCalc(NULL),\n\t\tsrcInfo\n\t);\n}\n\n}\n\nContext::LPFindResult RDORTPResType::onFindContext(const std::string& method, const Context::Params& params, const RDOParserSrcInfo& srcInfo) const\n{\n\tif (method == Context::METHOD_GET)\n\t{\n\t\tconst std::string paramName = params.identifier();\n\n\t\tconst std::size_t parNumb = getRTPParamNumber(paramName);\n\t\tif (parNumb == RDORTPResType::UNDEFINED_PARAM)\n\t\t{\n\t\t\tRDOParser::s_parser()->error().error(srcInfo, rdo::format(\"Неизвестный параметр ресурса: %s\", paramName.c_str()));\n\t\t}\n\n\t\tContext::Params params_;\n\t\tparams_[RDORSSResource::GET_RESOURCE] = params.get(RDORSSResource::GET_RESOURCE);\n\t\tparams_[RDOParam::CONTEXT_PARAM_PARAM_ID] = parNumb;\n\n\t\tLPContext pParam = findRTPParam(paramName);\n\t\tASSERT(pParam);\n\t\treturn pParam->find(Context::METHOD_GET, params_, srcInfo);\n\t}\n\n\tif (method == Context::METHOD_OPERATOR_DOT)\n\t{\n\t\tconst std::string paramName = params.identifier();\n\n\t\tconst std::size_t parNumb = getRTPParamNumber(paramName);\n\t\tif (parNumb == RDORTPResType::UNDEFINED_PARAM)\n\t\t\treturn rdo::Factory::create();\n\n\t\tif (!params.exists(RDORSSResource::GET_RESOURCE))\n\t\t\tRDOParser::s_parser()->error().error(srcInfo, rdo::format(\"Недопустимая конструкция\"));\n\n\t\tLPRDOParam pParam = findRTPParam(paramName);\n\t\tASSERT(pParam);\n\n\t\tContext::Params params_;\n\t\tparams_[RDORSSResource::GET_RESOURCE] = params.get(RDORSSResource::GET_RESOURCE);\n\t\tparams_[RDOParam::CONTEXT_PARAM_PARAM_ID] = parNumb;\n\t\tparams_[Context::Params::IDENTIFIER] = paramName;\n\n\t\tLPRDORTPResType pParamType =\n\t\t\tpParam->getTypeInfo()->itype().object_dynamic_cast();\n\n\t\tif (!pParamType)\n\t\t\treturn rdo::Factory::create(SwitchContext(pParam, params_));\n\n\t\tContext::LPFindResult result = pParam->find(Context::METHOD_GET, params_, srcInfo);\n\t\tLPExpression pNestedResource = result->getCreateExpression()();\n\n\t\tContext::Params params__;\n\t\tparams__[RDORSSResource::GET_RESOURCE] = pNestedResource;\n\n\t\treturn rdo::Factory::create(SwitchContext(pParamType, params__));\n\t}\n\n\n\n\tif (method == Context::METHOD_TYPE_OF)\n\t{\n\t\tLPRDORTPResType pThis(const_cast(this));\n\t\treturn rdo::Factory::create(CreateExpression(boost::bind(&contextTypeOfResourceType, pThis, srcInfo)));\n\t}\n\n\treturn rdo::Factory::create();\n}\n\nvoid RDORTPResType::setSubtype(Subtype type)\n{\n\tASSERT(!m_subtype.is_initialized() || m_subtype.get() == type);\n\tm_subtype = type;\n}\n\nvoid RDORTPResType::setupRuntimeFactory()\n{\n\tSubtype subtype = m_subtype.is_initialized()\n\t\t? m_subtype.get()\n\t\t: RT_SIMPLE;\n\n\truntime::RDOResourceTypeList::Create create;\n\tswitch (subtype)\n\t{\n\tcase RT_SIMPLE:\n\t\tcreate = boost::bind(&createSimpleResource, _1, _2, _3, _4, _5, _6, _7, _8);\n\t\tbreak;\n\tcase RT_PROCESS_RESOURCE:\n\t\tcreate = boost::bind(&createProcessResource, _1, _2, _3, _4, _5, _6, _7);\n\t\tbreak;\n\tcase RT_PROCESS_TRANSACT:\n\t\tcreate = boost::bind(&createProcessTransact, _1, _2, _3, _4, _5, _6, _7);\n\t\tbreak;\n\tdefault:\n\t\tNEVER_REACH_HERE;\n\t}\n\tsetFactoryMethod(create);\n}\n\n\/*\n\/\/ --------------------------------------------------------------------------------\n\/\/ -------------------- RDORTPFuzzyMembershiftFun - ф-ия принадлежности нечеткого терма\n\/\/ --------------------------------------------------------------------------------\nRDORTPFuzzyMembershiftFun::RDORTPFuzzyMembershiftFun(const LPRDOParser& pParser):\n\tRDOParserObject(pParser)\n{\n\tfor (std::size_t i = 0; i < m_points.size(); i++)\n\t{\n\/\/\t\tdouble x = m_points[i]->getX();\n\t}\n\n\tItems::iterator it = m_points.begin();\n\twhile (it != m_points.end())\n\t{\n\t\tdouble x = (*it)->getX();\n\t\tit++;\n\t}\n}\n\/\/ --------------------------------------------------------------------------------\n\/\/ -------------------- RDORTPFuzzyTerm - нечеткий термин\n\/\/ --------------------------------------------------------------------------------\nRDORTPFuzzyTerm::RDORTPFuzzyTerm(const LPRDOParser& pParser, const RDOParserSrcInfo& src_info, RDORTPFuzzyMembershiftFun* pMembersfift_fun):\n\tRDOParserObject(pParser)\n{\n\n}*\/\n\nCLOSE_RDO_PARSER_NAMESPACE\n<|endoftext|>"} {"text":"\/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License. *\/\n\n#include \n#include \n\n#include \/\/ NOLINT\n\n#include \"gflags\/gflags.h\"\n#include \"paddle\/fluid\/inference\/api\/api_impl.h\"\n#include \"paddle\/fluid\/inference\/tests\/test_helper.h\"\n\nDEFINE_string(dirname, \"\", \"Directory of the inference model.\");\n\nnamespace paddle {\n\nPaddleTensor LodTensorToPaddleTensor(framework::LoDTensor* t) {\n PaddleTensor pt;\n\n if (t->type() == typeid(int64_t)) {\n pt.data.Reset(t->data(), t->numel() * sizeof(int64_t));\n pt.dtype = PaddleDType::INT64;\n } else if (t->type() == typeid(float)) {\n pt.data.Reset(t->data(), t->numel() * sizeof(float));\n pt.dtype = PaddleDType::FLOAT32;\n } else {\n LOG(FATAL) << \"unsupported type.\";\n }\n pt.shape = framework::vectorize2int(t->dims());\n return pt;\n}\n\nNativeConfig GetConfig() {\n NativeConfig config;\n config.model_dir = FLAGS_dirname + \"\/word2vec.inference.model\";\n LOG(INFO) << \"dirname \" << config.model_dir;\n config.fraction_of_gpu_memory = 0.15;\n#ifdef PADDLE_WITH_CUDA\n config.use_gpu = true;\n#else\n config.use_gpu = false;\n#endif\n config.device = 0;\n return config;\n}\n\nvoid MainWord2Vec(bool use_gpu) {\n NativeConfig config = GetConfig();\n auto predictor = CreatePaddlePredictor(config);\n config.use_gpu = use_gpu;\n\n framework::LoDTensor first_word, second_word, third_word, fourth_word;\n framework::LoD lod{{0, 1}};\n int64_t dict_size = 2073; \/\/ The size of dictionary\n\n SetupLoDTensor(&first_word, lod, static_cast(0), dict_size - 1);\n SetupLoDTensor(&second_word, lod, static_cast(0), dict_size - 1);\n SetupLoDTensor(&third_word, lod, static_cast(0), dict_size - 1);\n SetupLoDTensor(&fourth_word, lod, static_cast(0), dict_size - 1);\n\n std::vector paddle_tensor_feeds;\n paddle_tensor_feeds.push_back(LodTensorToPaddleTensor(&first_word));\n paddle_tensor_feeds.push_back(LodTensorToPaddleTensor(&second_word));\n paddle_tensor_feeds.push_back(LodTensorToPaddleTensor(&third_word));\n paddle_tensor_feeds.push_back(LodTensorToPaddleTensor(&fourth_word));\n\n std::vector outputs;\n ASSERT_TRUE(predictor->Run(paddle_tensor_feeds, &outputs));\n ASSERT_EQ(outputs.size(), 1UL);\n size_t len = outputs[0].data.length();\n float* data = static_cast(outputs[0].data.data());\n for (size_t j = 0; j < len \/ sizeof(float); ++j) {\n ASSERT_LT(data[j], 1.0);\n ASSERT_GT(data[j], -1.0);\n }\n\n std::vector cpu_feeds;\n cpu_feeds.push_back(&first_word);\n cpu_feeds.push_back(&second_word);\n cpu_feeds.push_back(&third_word);\n cpu_feeds.push_back(&fourth_word);\n\n framework::LoDTensor output1;\n std::vector cpu_fetchs1;\n cpu_fetchs1.push_back(&output1);\n\n TestInference(config.model_dir, cpu_feeds, cpu_fetchs1);\n\n float* lod_data = output1.data();\n for (int i = 0; i < output1.numel(); ++i) {\n EXPECT_LT(lod_data[i] - data[i], 1e-3);\n EXPECT_GT(lod_data[i] - data[i], -1e-3);\n }\n}\n\nvoid MainImageClassification(bool use_gpu) {\n int batch_size = 2;\n bool repeat = false;\n NativeConfig config = GetConfig();\n config.use_gpu = use_gpu;\n config.model_dir =\n FLAGS_dirname + \"\/image_classification_resnet.inference.model\";\n\n const bool is_combined = false;\n std::vector> feed_target_shapes =\n GetFeedTargetShapes(config.model_dir, is_combined);\n\n framework::LoDTensor input;\n \/\/ Use normilized image pixels as input data,\n \/\/ which should be in the range [0.0, 1.0].\n feed_target_shapes[0][0] = batch_size;\n framework::DDim input_dims = framework::make_ddim(feed_target_shapes[0]);\n SetupTensor(&input, input_dims, static_cast(0),\n static_cast(1));\n std::vector cpu_feeds;\n cpu_feeds.push_back(&input);\n\n framework::LoDTensor output1;\n std::vector cpu_fetchs1;\n cpu_fetchs1.push_back(&output1);\n\n TestInference(\n config.model_dir, cpu_feeds, cpu_fetchs1, repeat, is_combined);\n\n auto predictor = CreatePaddlePredictor(config);\n std::vector paddle_tensor_feeds;\n paddle_tensor_feeds.push_back(LodTensorToPaddleTensor(&input));\n\n std::vector outputs;\n ASSERT_TRUE(predictor->Run(paddle_tensor_feeds, &outputs));\n ASSERT_EQ(outputs.size(), 1UL);\n size_t len = outputs[0].data.length();\n float* data = static_cast(outputs[0].data.data());\n float* lod_data = output1.data();\n for (size_t j = 0; j < len \/ sizeof(float); ++j) {\n EXPECT_NEAR(lod_data[j], data[j], 1e-3);\n }\n}\n\nvoid MainThreadsWord2Vec(bool use_gpu) {\n NativeConfig config = GetConfig();\n config.use_gpu = use_gpu;\n auto main_predictor = CreatePaddlePredictor(config);\n\n \/\/ prepare inputs data and reference results\n constexpr int num_jobs = 3;\n std::vector> jobs(num_jobs);\n std::vector> paddle_tensor_feeds(num_jobs);\n std::vector refs(num_jobs);\n for (size_t i = 0; i < jobs.size(); ++i) {\n \/\/ each job has 4 words\n jobs[i].resize(4);\n for (size_t j = 0; j < 4; ++j) {\n framework::LoD lod{{0, 1}};\n int64_t dict_size = 2073; \/\/ The size of dictionary\n SetupLoDTensor(&jobs[i][j], lod, static_cast(0), dict_size - 1);\n paddle_tensor_feeds[i].push_back(LodTensorToPaddleTensor(&jobs[i][j]));\n }\n\n \/\/ get reference result of each job\n std::vector ref_feeds;\n std::vector ref_fetches(1, &refs[i]);\n for (auto& word : jobs[i]) {\n ref_feeds.push_back(&word);\n }\n TestInference(config.model_dir, ref_feeds, ref_fetches);\n }\n\n \/\/ create threads and each thread run 1 job\n std::vector threads;\n for (int tid = 0; tid < num_jobs; ++tid) {\n threads.emplace_back([&, tid]() {\n auto predictor = main_predictor->Clone();\n auto& local_inputs = paddle_tensor_feeds[tid];\n std::vector local_outputs;\n ASSERT_TRUE(predictor->Run(local_inputs, &local_outputs));\n\n \/\/ check outputs range\n ASSERT_EQ(local_outputs.size(), 1UL);\n const size_t len = local_outputs[0].data.length();\n float* data = static_cast(local_outputs[0].data.data());\n for (size_t j = 0; j < len \/ sizeof(float); ++j) {\n ASSERT_LT(data[j], 1.0);\n ASSERT_GT(data[j], -1.0);\n }\n\n \/\/ check outputs correctness\n float* ref_data = refs[tid].data();\n EXPECT_EQ(refs[tid].numel(), static_cast(len \/ sizeof(float)));\n for (int i = 0; i < refs[tid].numel(); ++i) {\n EXPECT_NEAR(ref_data[i], data[i], 1e-3);\n }\n });\n }\n for (int i = 0; i < num_jobs; ++i) {\n threads[i].join();\n }\n}\n\nvoid MainThreadsImageClassification(bool use_gpu) {\n constexpr int num_jobs = 4; \/\/ each job run 1 batch\n constexpr int batch_size = 1;\n NativeConfig config = GetConfig();\n config.use_gpu = use_gpu;\n config.model_dir =\n FLAGS_dirname + \"\/image_classification_resnet.inference.model\";\n\n auto main_predictor = CreatePaddlePredictor(config);\n std::vector jobs(num_jobs);\n std::vector> paddle_tensor_feeds(num_jobs);\n std::vector refs(num_jobs);\n for (size_t i = 0; i < jobs.size(); ++i) {\n \/\/ prepare inputs\n std::vector> feed_target_shapes =\n GetFeedTargetShapes(config.model_dir, \/*is_combined*\/ false);\n feed_target_shapes[0][0] = batch_size;\n framework::DDim input_dims = framework::make_ddim(feed_target_shapes[0]);\n SetupTensor(&jobs[i], input_dims, 0.f, 1.f);\n paddle_tensor_feeds[i].push_back(LodTensorToPaddleTensor(&jobs[i]));\n\n \/\/ get reference result of each job\n std::vector ref_feeds(1, &jobs[i]);\n std::vector ref_fetches(1, &refs[i]);\n TestInference(config.model_dir, ref_feeds, ref_fetches);\n }\n\n \/\/ create threads and each thread run 1 job\n std::vector threads;\n for (int tid = 0; tid < num_jobs; ++tid) {\n threads.emplace_back([&, tid]() {\n auto predictor = main_predictor->Clone();\n auto& local_inputs = paddle_tensor_feeds[tid];\n std::vector local_outputs;\n ASSERT_TRUE(predictor->Run(local_inputs, &local_outputs));\n\n \/\/ check outputs correctness\n ASSERT_EQ(local_outputs.size(), 1UL);\n const size_t len = local_outputs[0].data.length();\n float* data = static_cast(local_outputs[0].data.data());\n float* ref_data = refs[tid].data();\n EXPECT_EQ((size_t)refs[tid].numel(), len \/ sizeof(float));\n for (int i = 0; i < refs[tid].numel(); ++i) {\n EXPECT_NEAR(ref_data[i], data[i], 1e-3);\n }\n });\n }\n for (int i = 0; i < num_jobs; ++i) {\n threads[i].join();\n }\n}\n\nTEST(inference_api_native, word2vec_cpu) { MainWord2Vec(false \/*use_gpu*\/); }\nTEST(inference_api_native, word2vec_cpu_threads) {\n MainThreadsWord2Vec(false \/*use_gpu*\/);\n}\nTEST(inference_api_native, image_classification_cpu) {\n MainThreadsImageClassification(false \/*use_gpu*\/);\n}\nTEST(inference_api_native, image_classification_cpu_threads) {\n MainThreadsImageClassification(false \/*use_gpu*\/);\n}\n\n#ifdef PADDLE_WITH_CUDA\nTEST(inference_api_native, word2vec_gpu) { MainWord2Vec(true \/*use_gpu*\/); }\nTEST(inference_api_native, word2vec_gpu_threads) {\n MainThreadsWord2Vec(true \/*use_gpu*\/);\n}\nTEST(inference_api_native, image_classification_gpu) {\n MainThreadsImageClassification(true \/*use_gpu*\/);\n}\nTEST(inference_api_native, image_classification_gpu_threads) {\n MainThreadsImageClassification(true \/*use_gpu*\/);\n}\n\n#endif\n\n} \/\/ namespace paddle\ntest=develop\/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License. *\/\n\n#include \n#include \n\n#include \/\/ NOLINT\n\n#include \"gflags\/gflags.h\"\n#include \"paddle\/fluid\/inference\/api\/api_impl.h\"\n#include \"paddle\/fluid\/inference\/tests\/test_helper.h\"\n\n#ifdef __clang__\n#define ACC_DIFF 4e-3\n#else\n#define ACC_DIFF 1e-3\n#endif\n\nDEFINE_string(dirname, \"\", \"Directory of the inference model.\");\n\nnamespace paddle {\n\nPaddleTensor LodTensorToPaddleTensor(framework::LoDTensor* t) {\n PaddleTensor pt;\n\n if (t->type() == typeid(int64_t)) {\n pt.data.Reset(t->data(), t->numel() * sizeof(int64_t));\n pt.dtype = PaddleDType::INT64;\n } else if (t->type() == typeid(float)) {\n pt.data.Reset(t->data(), t->numel() * sizeof(float));\n pt.dtype = PaddleDType::FLOAT32;\n } else {\n LOG(FATAL) << \"unsupported type.\";\n }\n pt.shape = framework::vectorize2int(t->dims());\n return pt;\n}\n\nNativeConfig GetConfig() {\n NativeConfig config;\n config.model_dir = FLAGS_dirname + \"\/word2vec.inference.model\";\n LOG(INFO) << \"dirname \" << config.model_dir;\n config.fraction_of_gpu_memory = 0.15;\n#ifdef PADDLE_WITH_CUDA\n config.use_gpu = true;\n#else\n config.use_gpu = false;\n#endif\n config.device = 0;\n return config;\n}\n\nvoid MainWord2Vec(bool use_gpu) {\n NativeConfig config = GetConfig();\n auto predictor = CreatePaddlePredictor(config);\n config.use_gpu = use_gpu;\n\n framework::LoDTensor first_word, second_word, third_word, fourth_word;\n framework::LoD lod{{0, 1}};\n int64_t dict_size = 2073; \/\/ The size of dictionary\n\n SetupLoDTensor(&first_word, lod, static_cast(0), dict_size - 1);\n SetupLoDTensor(&second_word, lod, static_cast(0), dict_size - 1);\n SetupLoDTensor(&third_word, lod, static_cast(0), dict_size - 1);\n SetupLoDTensor(&fourth_word, lod, static_cast(0), dict_size - 1);\n\n std::vector paddle_tensor_feeds;\n paddle_tensor_feeds.push_back(LodTensorToPaddleTensor(&first_word));\n paddle_tensor_feeds.push_back(LodTensorToPaddleTensor(&second_word));\n paddle_tensor_feeds.push_back(LodTensorToPaddleTensor(&third_word));\n paddle_tensor_feeds.push_back(LodTensorToPaddleTensor(&fourth_word));\n\n std::vector outputs;\n ASSERT_TRUE(predictor->Run(paddle_tensor_feeds, &outputs));\n ASSERT_EQ(outputs.size(), 1UL);\n size_t len = outputs[0].data.length();\n float* data = static_cast(outputs[0].data.data());\n for (size_t j = 0; j < len \/ sizeof(float); ++j) {\n ASSERT_LT(data[j], 1.0);\n ASSERT_GT(data[j], -1.0);\n }\n\n std::vector cpu_feeds;\n cpu_feeds.push_back(&first_word);\n cpu_feeds.push_back(&second_word);\n cpu_feeds.push_back(&third_word);\n cpu_feeds.push_back(&fourth_word);\n\n framework::LoDTensor output1;\n std::vector cpu_fetchs1;\n cpu_fetchs1.push_back(&output1);\n\n TestInference(config.model_dir, cpu_feeds, cpu_fetchs1);\n\n float* lod_data = output1.data();\n for (int i = 0; i < output1.numel(); ++i) {\n EXPECT_LT(lod_data[i] - data[i], ACC_DIFF);\n EXPECT_GT(lod_data[i] - data[i], -ACC_DIFF);\n }\n}\n\nvoid MainImageClassification(bool use_gpu) {\n int batch_size = 2;\n bool repeat = false;\n NativeConfig config = GetConfig();\n config.use_gpu = use_gpu;\n config.model_dir =\n FLAGS_dirname + \"\/image_classification_resnet.inference.model\";\n\n const bool is_combined = false;\n std::vector> feed_target_shapes =\n GetFeedTargetShapes(config.model_dir, is_combined);\n\n framework::LoDTensor input;\n \/\/ Use normilized image pixels as input data,\n \/\/ which should be in the range [0.0, 1.0].\n feed_target_shapes[0][0] = batch_size;\n framework::DDim input_dims = framework::make_ddim(feed_target_shapes[0]);\n SetupTensor(&input, input_dims, static_cast(0),\n static_cast(1));\n std::vector cpu_feeds;\n cpu_feeds.push_back(&input);\n\n framework::LoDTensor output1;\n std::vector cpu_fetchs1;\n cpu_fetchs1.push_back(&output1);\n\n TestInference(\n config.model_dir, cpu_feeds, cpu_fetchs1, repeat, is_combined);\n\n auto predictor = CreatePaddlePredictor(config);\n std::vector paddle_tensor_feeds;\n paddle_tensor_feeds.push_back(LodTensorToPaddleTensor(&input));\n\n std::vector outputs;\n ASSERT_TRUE(predictor->Run(paddle_tensor_feeds, &outputs));\n ASSERT_EQ(outputs.size(), 1UL);\n size_t len = outputs[0].data.length();\n float* data = static_cast(outputs[0].data.data());\n float* lod_data = output1.data();\n for (size_t j = 0; j < len \/ sizeof(float); ++j) {\n EXPECT_NEAR(lod_data[j], data[j], ACC_DIFF);\n }\n}\n\nvoid MainThreadsWord2Vec(bool use_gpu) {\n NativeConfig config = GetConfig();\n config.use_gpu = use_gpu;\n auto main_predictor = CreatePaddlePredictor(config);\n\n \/\/ prepare inputs data and reference results\n constexpr int num_jobs = 3;\n std::vector> jobs(num_jobs);\n std::vector> paddle_tensor_feeds(num_jobs);\n std::vector refs(num_jobs);\n for (size_t i = 0; i < jobs.size(); ++i) {\n \/\/ each job has 4 words\n jobs[i].resize(4);\n for (size_t j = 0; j < 4; ++j) {\n framework::LoD lod{{0, 1}};\n int64_t dict_size = 2073; \/\/ The size of dictionary\n SetupLoDTensor(&jobs[i][j], lod, static_cast(0), dict_size - 1);\n paddle_tensor_feeds[i].push_back(LodTensorToPaddleTensor(&jobs[i][j]));\n }\n\n \/\/ get reference result of each job\n std::vector ref_feeds;\n std::vector ref_fetches(1, &refs[i]);\n for (auto& word : jobs[i]) {\n ref_feeds.push_back(&word);\n }\n TestInference(config.model_dir, ref_feeds, ref_fetches);\n }\n\n \/\/ create threads and each thread run 1 job\n std::vector threads;\n for (int tid = 0; tid < num_jobs; ++tid) {\n threads.emplace_back([&, tid]() {\n auto predictor = main_predictor->Clone();\n auto& local_inputs = paddle_tensor_feeds[tid];\n std::vector local_outputs;\n ASSERT_TRUE(predictor->Run(local_inputs, &local_outputs));\n\n \/\/ check outputs range\n ASSERT_EQ(local_outputs.size(), 1UL);\n const size_t len = local_outputs[0].data.length();\n float* data = static_cast(local_outputs[0].data.data());\n for (size_t j = 0; j < len \/ sizeof(float); ++j) {\n ASSERT_LT(data[j], 1.0);\n ASSERT_GT(data[j], -1.0);\n }\n\n \/\/ check outputs correctness\n float* ref_data = refs[tid].data();\n EXPECT_EQ(refs[tid].numel(), static_cast(len \/ sizeof(float)));\n for (int i = 0; i < refs[tid].numel(); ++i) {\n EXPECT_NEAR(ref_data[i], data[i], ACC_DIFF);\n }\n });\n }\n for (int i = 0; i < num_jobs; ++i) {\n threads[i].join();\n }\n}\n\nvoid MainThreadsImageClassification(bool use_gpu) {\n constexpr int num_jobs = 4; \/\/ each job run 1 batch\n constexpr int batch_size = 1;\n NativeConfig config = GetConfig();\n config.use_gpu = use_gpu;\n config.model_dir =\n FLAGS_dirname + \"\/image_classification_resnet.inference.model\";\n\n auto main_predictor = CreatePaddlePredictor(config);\n std::vector jobs(num_jobs);\n std::vector> paddle_tensor_feeds(num_jobs);\n std::vector refs(num_jobs);\n for (size_t i = 0; i < jobs.size(); ++i) {\n \/\/ prepare inputs\n std::vector> feed_target_shapes =\n GetFeedTargetShapes(config.model_dir, \/*is_combined*\/ false);\n feed_target_shapes[0][0] = batch_size;\n framework::DDim input_dims = framework::make_ddim(feed_target_shapes[0]);\n SetupTensor(&jobs[i], input_dims, 0.f, 1.f);\n paddle_tensor_feeds[i].push_back(LodTensorToPaddleTensor(&jobs[i]));\n\n \/\/ get reference result of each job\n std::vector ref_feeds(1, &jobs[i]);\n std::vector ref_fetches(1, &refs[i]);\n TestInference(config.model_dir, ref_feeds, ref_fetches);\n }\n\n \/\/ create threads and each thread run 1 job\n std::vector threads;\n for (int tid = 0; tid < num_jobs; ++tid) {\n threads.emplace_back([&, tid]() {\n auto predictor = main_predictor->Clone();\n auto& local_inputs = paddle_tensor_feeds[tid];\n std::vector local_outputs;\n ASSERT_TRUE(predictor->Run(local_inputs, &local_outputs));\n\n \/\/ check outputs correctness\n ASSERT_EQ(local_outputs.size(), 1UL);\n const size_t len = local_outputs[0].data.length();\n float* data = static_cast(local_outputs[0].data.data());\n float* ref_data = refs[tid].data();\n EXPECT_EQ((size_t)refs[tid].numel(), len \/ sizeof(float));\n for (int i = 0; i < refs[tid].numel(); ++i) {\n EXPECT_NEAR(ref_data[i], data[i], ACC_DIFF);\n }\n });\n }\n for (int i = 0; i < num_jobs; ++i) {\n threads[i].join();\n }\n}\n\nTEST(inference_api_native, word2vec_cpu) { MainWord2Vec(false \/*use_gpu*\/); }\nTEST(inference_api_native, word2vec_cpu_threads) {\n MainThreadsWord2Vec(false \/*use_gpu*\/);\n}\nTEST(inference_api_native, image_classification_cpu) {\n MainThreadsImageClassification(false \/*use_gpu*\/);\n}\nTEST(inference_api_native, image_classification_cpu_threads) {\n MainThreadsImageClassification(false \/*use_gpu*\/);\n}\n\n#ifdef PADDLE_WITH_CUDA\nTEST(inference_api_native, word2vec_gpu) { MainWord2Vec(true \/*use_gpu*\/); }\nTEST(inference_api_native, word2vec_gpu_threads) {\n MainThreadsWord2Vec(true \/*use_gpu*\/);\n}\nTEST(inference_api_native, image_classification_gpu) {\n MainThreadsImageClassification(true \/*use_gpu*\/);\n}\nTEST(inference_api_native, image_classification_gpu_threads) {\n MainThreadsImageClassification(true \/*use_gpu*\/);\n}\n\n#endif\n\n} \/\/ namespace paddle\n<|endoftext|>"} {"text":"#include \n\nusing namespace std;\nusing namespace microscopes::common;\n\ntypedef fixed_group_manager fixed_group;\ntypedef group_manager group;\n\nstatic inline bool\nalmost_eq(float a, float b)\n{\n return fabs(a - b) <= 1e-5;\n}\n\ntemplate \nstatic void assert_vectors_equal(const vector &as, const vector &bs)\n{\n MICROSCOPES_CHECK(as.size() == bs.size(), \"size\");\n for (size_t i = 0; i < as.size(); i++)\n MICROSCOPES_CHECK(as[i] == bs[i], \"element\");\n}\n\nstatic void\ntest_fixed_serialization()\n{\n const size_t k = 3;\n fixed_group fg(10, k);\n\n for (size_t i = 0; i < k; i++)\n fg.get_hp_mutator(\"alphas\").set(1.+float(i), i);\n\n const vector assignment_vec({\n -1, 2, 1, 0, 0, 1, 2, -1, -1, 0\n });\n for (size_t i = 0; i < assignment_vec.size(); i++) {\n if (assignment_vec[i] == -1)\n continue;\n fg.add_value(assignment_vec[i], i)++;\n }\n\n const auto serialized = fg.serialize([](size_t i) {\n return to_string(i);\n });\n\n fixed_group fg1(serialized, [](const string &s) {\n return strtoul(s.c_str(), nullptr, 10);\n });\n\n for (size_t i = 0; i < k; i++)\n MICROSCOPES_CHECK(\n almost_eq(\n fg.get_hp_mutator(\"alphas\").accessor().get(i),\n fg1.get_hp_mutator(\"alphas\").accessor().get(i)),\n \"did not save alphas properly\");\n\n assert_vectors_equal(fg.assignments(), fg1.assignments());\n MICROSCOPES_CHECK(fg.ngroups() == fg1.ngroups(), \"ngroups\");\n for (size_t i = 0; i < fg.ngroups(); i++)\n MICROSCOPES_CHECK(fg.group(i) == fg1.group(i), \"group count\/data\");\n}\n\nstatic void\ntest_serialization()\n{\n group g(10);\n\n g.get_hp_mutator(\"alpha\").set(2.0, 0);\n\n const vector assignment_vec({\n -1, 2, 1, 0, 6, 1, 2, -1, -1, 5\n });\n for (size_t i = 0; i < 7; i++)\n g.create_group();\n g.delete_group(3);\n for (size_t i = 0; i < assignment_vec.size(); i++) {\n if (assignment_vec[i] == -1)\n continue;\n g.add_value(assignment_vec[i], i)++;\n }\n\n const auto serialized = g.serialize([](size_t i) {\n return to_string(i);\n });\n\n group g1(serialized, [](const string &s) {\n return strtoul(s.c_str(), nullptr, 10);\n });\n\n MICROSCOPES_CHECK(\n almost_eq(\n g.get_hp_mutator(\"alpha\").accessor().get(0),\n g1.get_hp_mutator(\"alpha\").accessor().get(0)),\n \"did not save alpha properly\");\n\n assert_vectors_equal(g.assignments(), g1.assignments());\n MICROSCOPES_CHECK(g.ngroups() == g1.ngroups(), \"ngroups\");\n for (auto gid : g.groups())\n MICROSCOPES_CHECK(g.group(gid) == g1.group(gid), \"group count\/data\");\n}\n\nint\nmain(void)\n{\n test_fixed_serialization();\n test_serialization();\n return 0;\n}\nRemove fixed references from test_group_manager.cpp#include \n\nusing namespace std;\nusing namespace microscopes::common;\n\ntypedef group_manager group;\n\nstatic inline bool\nalmost_eq(float a, float b)\n{\n return fabs(a - b) <= 1e-5;\n}\n\ntemplate \nstatic void assert_vectors_equal(const vector &as, const vector &bs)\n{\n MICROSCOPES_CHECK(as.size() == bs.size(), \"size\");\n for (size_t i = 0; i < as.size(); i++)\n MICROSCOPES_CHECK(as[i] == bs[i], \"element\");\n}\n\nstatic void\ntest_serialization()\n{\n group g(10);\n\n g.get_hp_mutator(\"alpha\").set(2.0, 0);\n\n const vector assignment_vec({\n -1, 2, 1, 0, 6, 1, 2, -1, -1, 5\n });\n for (size_t i = 0; i < 7; i++)\n g.create_group();\n g.delete_group(3);\n for (size_t i = 0; i < assignment_vec.size(); i++) {\n if (assignment_vec[i] == -1)\n continue;\n g.add_value(assignment_vec[i], i)++;\n }\n\n const auto serialized = g.serialize([](size_t i) {\n return to_string(i);\n });\n\n group g1(serialized, [](const string &s) {\n return strtoul(s.c_str(), nullptr, 10);\n });\n\n MICROSCOPES_CHECK(\n almost_eq(\n g.get_hp_mutator(\"alpha\").accessor().get(0),\n g1.get_hp_mutator(\"alpha\").accessor().get(0)),\n \"did not save alpha properly\");\n\n assert_vectors_equal(g.assignments(), g1.assignments());\n MICROSCOPES_CHECK(g.ngroups() == g1.ngroups(), \"ngroups\");\n for (auto gid : g.groups())\n MICROSCOPES_CHECK(g.group(gid) == g1.group(gid), \"group count\/data\");\n}\n\nint\nmain(void)\n{\n test_serialization();\n return 0;\n}\n<|endoftext|>"} {"text":"#include \"generated_fused_sparse_resnet_block.o.h\"\n\n#include \"Halide.h\"\n#include \n#include \n#include \n#include \n#include \n#include \"configure.h\"\n\/\/ Original version by: Kyle Spafford Adapted for CSR format\nvoid initRandomWeights(float* fin_values, int* filter_idx, int* filter_finptr, const int n, const int KK, const int fin_size, const int fout_size, int seed)\n{\n int nnzAssigned = 0;\n \/\/ Figure out the probability that a nonzero should be assigned to a given\n \/\/ spot in the matrix\n int total_num_entries = KK * KK * fin_size * fout_size;\n double prob = (double)n \/ ((double) total_num_entries);\n\n \/\/ Seed random number generator\n srand(seed);\n\n \/\/ Randomly decide whether entry gets a value, but ensure n values\n \/\/ are assigned\n int fillRemaining = 0;\n\n \/\/ We order the weights in the values array such that we do blocking over FIN\n for (int fout = 0; fout < fout_size; fout++)\n {\n filter_finptr[fout] = nnzAssigned;\n for (int fin_b = 0; fin_b < fin_size\/FIN_BL; fin_b++)\n {\n for (int ky = 0; ky < KK; ky++)\n {\n for (int kx = 0; kx < KK; kx++)\n {\n for (int ffin = 0; ffin duration_vector;\n double start, end;\n\n \/\/ ---------------------------------------------------------------------\n \/\/ ---------------------------------------------------------------------\n \/\/ ---------------------------------------------------------------------\n std::string filename = \"resnet_10.csr\";\n std::string filename2 = \"resnet_10.csr\";\n\n float *filter_values;\n int *filter_idx;\n int *filter_finptr;\n\n int FNNZ;\n int used_FOUT;\n int used_FIN;\n int used_K;\n int n;\n if (IMPORT_CSR_FROM_FILE)\n importCSRFromFile(filename, &filter_values, &filter_finptr, &filter_idx, &used_FOUT, &used_FIN, &used_K, &FNNZ, &n);\n else{\n used_FOUT = FOut;\n used_FIN = FIn;\n used_K = K;\n n = N;\n FNNZ = generateCSRWeights(&filter_values, WEIGHTS_DENSITY, &filter_idx, &filter_finptr, K, FIn, FOut, 2);\n }\n printf(\"Layer 1 Density : %.2f %%. Weights imported from %s\\n\", ((float)FNNZ \/ (FOut * FIn * K * K))*100, filename.c_str());\n\n \/\/ Assertions to ensure that the generated tiramisu code has the right parameters\n \/\/ because we are defining the parameters in the configure.h files to get specialized fast code\n assert((used_FOUT == FOut) && (\"FOut parameter specified in configure.h doesn't match the csr weights file's FOUT parameter.\"));\n assert((used_FIN == FIn) && (\"FIn parameter specified in configure.h doesn't match the csr weights file's FIn parameter\"));\n assert((used_K == K) && (\"K parameter specified in configure.h doesn't match the csr weights file's K parameter\"));\n assert((n == N) && (\"N parameter specified in configure.h doesn't match the csr weights file's N parameter\"));\n\n Halide::Buffer b_SIZES(2);\n b_SIZES(0) = FNNZ;\n Halide::Buffer b_input((N+2) * (N+2) * FIn, BATCH_SIZE);\n\n Halide::Buffer b_filter_values(filter_values, FNNZ);\n Halide::Buffer b_filter_idx(filter_idx, FNNZ);\n Halide::Buffer b_filter_finptr(filter_finptr, FOut + 1);\n\n Halide::Buffer b_bias(FOut);\n Halide::Buffer b_bn_scale(FOut);\n Halide::Buffer b_bn_shift(FOut);\n Halide::Buffer b_bn_mean(FOut);\n Halide::Buffer b_bn_variance(FOut);\n\n Halide::Buffer b_conv1_result(N + 2, N + 2, FOut, BATCH_SIZE);\n\n \/\/ Second convolution\n float *filter_values2;\n int *filter_idx2;\n int *filter_finptr2;\n\n int FNNZ2;\n if (IMPORT_CSR_FROM_FILE)\n importCSRFromFile(filename2, &filter_values2, &filter_finptr2, &filter_idx2, &used_FOUT, &used_FIN, &used_K, &FNNZ2, &n);\n else{\n used_FOUT = FOut;\n used_FIN = FOut;\n used_K = K;\n n = N;\n FNNZ2 = generateCSRWeights(&filter_values2, WEIGHTS_DENSITY, &filter_idx2, &filter_finptr2, K, FOut, FOut, 5);\n }\n printf(\"Layer 2 Density : %.2f %%. Weights imported from %s\\n\", ((float)FNNZ2 \/ (FOut * FOut * K * K))*100, filename2.c_str());\n \/\/ Assertions to ensure that the generated tiramisu code has the right parameters\n \/\/ because we are defining the parameters in the configure.h files to get specialized fast code\n assert((used_FOUT == FOut) && (\"FOut parameter specified in configure.h doesn't match the csr weights file's FOUT parameter.\"));\n assert((used_FIN == FOut) && (\"FOut parameter specified in configure.h doesn't match the csr weights file's FIn parameter\"));\n assert((used_K == K) && (\"K parameter specified in configure.h doesn't match the csr weights file's K parameter\"));\n assert((n == N) && (\"N parameter specified in configure.h doesn't match the csr weights file's N parameter\"));\n\n b_SIZES(1) = FNNZ2;\n Halide::Buffer b_filter_values2(filter_values2, FNNZ2);\n Halide::Buffer b_filter_idx2(filter_idx2, FNNZ2);\n Halide::Buffer b_filter_finptr2(filter_finptr2, FOut + 1);\n\n Halide::Buffer b_bias2(FOut);\n Halide::Buffer b_bn2_scale(FOut);\n Halide::Buffer b_bn2_shift(FOut);\n Halide::Buffer b_bn2_mean(FOut);\n Halide::Buffer b_bn2_variance(FOut);\n\n Halide::Buffer b_result(N, N, FOut, BATCH_SIZE);\n srand(3);\n \/\/ First convolution\n for (int n=0; n < BATCH_SIZE; ++n)\n for (int z=0; z < FIn; ++z)\n for (int y=0; y < N+2; ++y)\n for (int x=0; x < N+2; ++x)\n b_input(x + y * (N + 2) + z* (N + 2) * (N + 2), n) = ((float)(rand()%256 - 128)) \/ 127.f;\n\n for (int q=0; q> tmp;\n if (std::abs(b_result(x, y, fout, b) - tmp) <= 0.002)\n nb_correct++;\n }\n\n std::cout << \"\\n\\t\\tPercentage of correctness \" << 100*(((double)nb_correct)\/(BATCH_SIZE * FOut * N * N)) << \"%\" << std::endl << std::endl;\n }\n\n free(filter_idx);\n free(filter_values);\n free(filter_finptr);\n return 0;\n}\nFix formatting#include \"generated_fused_sparse_resnet_block.o.h\"\n\n#include \"Halide.h\"\n#include \n#include \n#include \n#include \n#include \n#include \"configure.h\"\n\/\/ Original version by: Kyle Spafford Adapted for CSR format\nvoid initRandomWeights(float* fin_values, int* filter_idx, int* filter_finptr, const int n, const int KK, const int fin_size, const int fout_size, int seed)\n{\n int nnzAssigned = 0;\n \/\/ Figure out the probability that a nonzero should be assigned to a given\n \/\/ spot in the matrix\n int total_num_entries = KK * KK * fin_size * fout_size;\n double prob = (double)n \/ ((double) total_num_entries);\n\n \/\/ Seed random number generator\n srand(seed);\n\n \/\/ Randomly decide whether entry gets a value, but ensure n values\n \/\/ are assigned\n int fillRemaining = 0;\n\n \/\/ We order the weights in the values array such that we do blocking over FIN\n for (int fout = 0; fout < fout_size; fout++)\n {\n filter_finptr[fout] = nnzAssigned;\n for (int fin_b = 0; fin_b < fin_size\/FIN_BL; fin_b++)\n {\n for (int ky = 0; ky < KK; ky++)\n {\n for (int kx = 0; kx < KK; kx++)\n {\n for (int ffin = 0; ffin duration_vector;\n double start, end;\n\n \/\/ ---------------------------------------------------------------------\n \/\/ ---------------------------------------------------------------------\n \/\/ ---------------------------------------------------------------------\n std::string filename = \"resnet_10.csr\";\n std::string filename2 = \"resnet_10.csr\";\n\n float *filter_values;\n int *filter_idx;\n int *filter_finptr;\n\n int FNNZ;\n int used_FOUT;\n int used_FIN;\n int used_K;\n int n;\n if (IMPORT_CSR_FROM_FILE)\n importCSRFromFile(filename, &filter_values, &filter_finptr, &filter_idx, &used_FOUT, &used_FIN, &used_K, &FNNZ, &n);\n else{\n used_FOUT = FOut;\n used_FIN = FIn;\n used_K = K;\n n = N;\n FNNZ = generateCSRWeights(&filter_values, WEIGHTS_DENSITY, &filter_idx, &filter_finptr, K, FIn, FOut, 2);\n }\n printf(\"Layer 1 Density : %.2f %%. Weights imported from %s\\n\", ((float)FNNZ \/ (FOut * FIn * K * K))*100, filename.c_str());\n\n \/\/ Assertions to ensure that the generated tiramisu code has the right parameters\n \/\/ because we are defining the parameters in the configure.h files to get specialized fast code\n assert((used_FOUT == FOut) && (\"FOut parameter specified in configure.h doesn't match the csr weights file's FOUT parameter.\"));\n assert((used_FIN == FIn) && (\"FIn parameter specified in configure.h doesn't match the csr weights file's FIn parameter\"));\n assert((used_K == K) && (\"K parameter specified in configure.h doesn't match the csr weights file's K parameter\"));\n assert((n == N) && (\"N parameter specified in configure.h doesn't match the csr weights file's N parameter\"));\n\n Halide::Buffer b_SIZES(2);\n b_SIZES(0) = FNNZ;\n Halide::Buffer b_input((N+2) * (N+2) * FIn, BATCH_SIZE);\n\n Halide::Buffer b_filter_values(filter_values, FNNZ);\n Halide::Buffer b_filter_idx(filter_idx, FNNZ);\n Halide::Buffer b_filter_finptr(filter_finptr, FOut + 1);\n\n Halide::Buffer b_bias(FOut);\n Halide::Buffer b_bn_scale(FOut);\n Halide::Buffer b_bn_shift(FOut);\n Halide::Buffer b_bn_mean(FOut);\n Halide::Buffer b_bn_variance(FOut);\n\n Halide::Buffer b_conv1_result(N + 2, N + 2, FOut, BATCH_SIZE);\n\n \/\/ Second convolution\n float *filter_values2;\n int *filter_idx2;\n int *filter_finptr2;\n\n int FNNZ2;\n if (IMPORT_CSR_FROM_FILE)\n importCSRFromFile(filename2, &filter_values2, &filter_finptr2, &filter_idx2, &used_FOUT, &used_FIN, &used_K, &FNNZ2, &n);\n else{\n used_FOUT = FOut;\n used_FIN = FOut;\n used_K = K;\n n = N;\n FNNZ2 = generateCSRWeights(&filter_values2, WEIGHTS_DENSITY, &filter_idx2, &filter_finptr2, K, FOut, FOut, 5);\n }\n printf(\"Layer 2 Density : %.2f %%. Weights imported from %s\\n\", ((float)FNNZ2 \/ (FOut * FOut * K * K))*100, filename2.c_str());\n \/\/ Assertions to ensure that the generated tiramisu code has the right parameters\n \/\/ because we are defining the parameters in the configure.h files to get specialized fast code\n assert((used_FOUT == FOut) && (\"FOut parameter specified in configure.h doesn't match the csr weights file's FOUT parameter.\"));\n assert((used_FIN == FOut) && (\"FOut parameter specified in configure.h doesn't match the csr weights file's FIn parameter\"));\n assert((used_K == K) && (\"K parameter specified in configure.h doesn't match the csr weights file's K parameter\"));\n assert((n == N) && (\"N parameter specified in configure.h doesn't match the csr weights file's N parameter\"));\n\n b_SIZES(1) = FNNZ2;\n Halide::Buffer b_filter_values2(filter_values2, FNNZ2);\n Halide::Buffer b_filter_idx2(filter_idx2, FNNZ2);\n Halide::Buffer b_filter_finptr2(filter_finptr2, FOut + 1);\n\n Halide::Buffer b_bias2(FOut);\n Halide::Buffer b_bn2_scale(FOut);\n Halide::Buffer b_bn2_shift(FOut);\n Halide::Buffer b_bn2_mean(FOut);\n Halide::Buffer b_bn2_variance(FOut);\n\n Halide::Buffer b_result(N, N, FOut, BATCH_SIZE);\n srand(3);\n \/\/ First convolution\n for (int n=0; n < BATCH_SIZE; ++n)\n for (int z=0; z < FIn; ++z)\n for (int y=0; y < N+2; ++y)\n for (int x=0; x < N+2; ++x)\n b_input(x + y * (N + 2) + z* (N + 2) * (N + 2), n) = ((float)(rand()%256 - 128)) \/ 127.f;\n\n for (int q=0; q> tmp;\n if (std::abs(b_result(x, y, fout, b) - tmp) <= 0.002)\n nb_correct++;\n }\n\n std::cout << \"\\n\\t\\tPercentage of correctness \" << 100*(((double)nb_correct)\/(BATCH_SIZE * FOut * N * N)) << \"%\" << std::endl << std::endl;\n }\n\n free(filter_idx);\n free(filter_values);\n free(filter_finptr);\n return 0;\n}\n<|endoftext|>"} {"text":"#include \"OutputProbes.h\"\n#include \n\nusing namespace ibpm;\n\nnamespace {\n\ndouble tol = 1e-14;\n \nclass OutputProbesTest : public testing::Test {\nprotected:\n OutputProbesTest( ) : \n _nx(8),\n _ny(12),\n _ngrid(3),\n _xLength(2),\n _yLength(_xLength * _ny\/_nx),\n _xOffset(-1),\n _yOffset(-3),\n _dx(_xLength\/_nx),\n _filename(\"testOutputProbes.probe\"), \n _grid(_nx, _ny, _ngrid, _xLength, _xOffset, _yOffset),\n\t\t_flagInitialization(false),\n\t\t_probe(_filename, _grid) {\t\t\t\n\t\t}\n\t\n virtual ~OutputProbesTest() {}\n\n int _nx;\n int _ny;\n int _ngrid;\n double _xLength;\n double _yLength;\n double _xOffset;\n double _yOffset;\n double _dx;\n\tstring _filename;\n\tGrid _grid;\n\tint _lev;\n\tint _numProbes;\n\tint _dimen;\n\tbool _flagInitialization;\n\tArray::Array2 _probePositions;\n\tOutputProbes _probe;\n};\n\nTEST_F(OutputProbesTest, TestgetProbeInfoFunctions){\n\/\/ test getNumProbes, getProbeIndexX, getProbeIndexY, addProbebyIndex, addProbebyPosition\n\tint i = 4; \tint j = 3; \/\/ probe 1\n\tint ii = 6; int jj = 8; \/\/ probe 2\n\tint lev = 0;\n\tOutputProbes probe(_filename, _grid);\n\tEXPECT_DOUBLE_EQ( 0, probe.getNumProbes() );\t\t\n\tprobe.addProbeByIndex( i , j ); \n\tEXPECT_DOUBLE_EQ( 1, probe.getNumProbes() );\n\tprobe.addProbeByIndex( ii, jj ); \n\tEXPECT_DOUBLE_EQ( 2, probe.getNumProbes() );\n\tEXPECT_DOUBLE_EQ( i, probe.getProbeIndexX(1) );\n\tEXPECT_DOUBLE_EQ( j, probe.getProbeIndexY(1) );\n\tEXPECT_DOUBLE_EQ( ii, probe.getProbeIndexX(2) );\n\tEXPECT_DOUBLE_EQ( jj, probe.getProbeIndexY(2) );\n\tEXPECT_DOUBLE_EQ( _grid.getXEdge(lev, ii), probe.getProbeCoordX(2) );\n\tEXPECT_DOUBLE_EQ( _grid.getYEdge(lev, jj), probe.getProbeCoordY(2) );\n\tprobe.addProbeByPosition( _grid.getXEdge(lev, ii), _grid.getYEdge(lev, jj) ); \n\tEXPECT_DOUBLE_EQ( 3, probe.getNumProbes() );\n\tEXPECT_DOUBLE_EQ( ii, probe.getProbeIndexX(3) );\n\tEXPECT_DOUBLE_EQ( jj, probe.getProbeIndexY(3) );\n}\n\n} \/\/ namespace\nDeleted ibSolver branch. Check out an earlier revision to access that data.#include \"OutputProbes.h\"\n#include \n\nusing namespace ibpm;\n\nnamespace {\n\ndouble tol = 1e-14;\n \nclass OutputProbesTest : public testing::Test {\nprotected:\n OutputProbesTest( ) : \n _nx(8),\n _ny(12),\n _ngrid(3),\n _xLength(2),\n _yLength(_xLength * _ny\/_nx),\n _xOffset(-1),\n _yOffset(-3),\n _dx(_xLength\/_nx),\n _filename(\"testOutputProbes.probe\"), \n _grid(_nx, _ny, _ngrid, _xLength, _xOffset, _yOffset),\n\t\t_flagInitialization(false),\n\t\t_probe(_filename, _grid) {\t\t\t\n\t\t}\n\t\n virtual ~OutputProbesTest() { }\n\n int _nx;\n int _ny;\n int _ngrid;\n double _xLength;\n double _yLength;\n double _xOffset;\n double _yOffset;\n double _dx;\n\tstring _filename;\n\tGrid _grid;\n\tint _lev;\n\tint _numProbes;\n\tint _dimen;\n\tbool _flagInitialization;\n\tArray::Array2 _probePositions;\n\tOutputProbes _probe;\n};\n\nTEST_F(OutputProbesTest, TestgetProbeInfoFunctions){\n\/\/ test getNumProbes, getProbeIndexX, getProbeIndexY, addProbebyIndex, addProbebyPosition\n\tint i = 4; \tint j = 3; \/\/ probe 1\n\tint ii = 6; int jj = 8; \/\/ probe 2\n\tint lev = 0;\n\tOutputProbes probe(_filename, _grid);\n\tEXPECT_DOUBLE_EQ( 0, probe.getNumProbes() );\t\t\n\tprobe.addProbeByIndex( i , j ); \n\tEXPECT_DOUBLE_EQ( 1, probe.getNumProbes() );\n\tprobe.addProbeByIndex( ii, jj ); \n\tEXPECT_DOUBLE_EQ( 2, probe.getNumProbes() );\n\tEXPECT_DOUBLE_EQ( i, probe.getProbeIndexX(1) );\n\tEXPECT_DOUBLE_EQ( j, probe.getProbeIndexY(1) );\n\tEXPECT_DOUBLE_EQ( ii, probe.getProbeIndexX(2) );\n\tEXPECT_DOUBLE_EQ( jj, probe.getProbeIndexY(2) );\n\tEXPECT_DOUBLE_EQ( _grid.getXEdge(lev, ii), probe.getProbeCoordX(2) );\n\tEXPECT_DOUBLE_EQ( _grid.getYEdge(lev, jj), probe.getProbeCoordY(2) );\n\tprobe.addProbeByPosition( _grid.getXEdge(lev, ii), _grid.getYEdge(lev, jj) ); \n\tEXPECT_DOUBLE_EQ( 3, probe.getNumProbes() );\n\tEXPECT_DOUBLE_EQ( ii, probe.getProbeIndexX(3) );\n\tEXPECT_DOUBLE_EQ( jj, probe.getProbeIndexY(3) );\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ The Loki Library\n\/\/ Copyright (c) 2006 Peter Kmmel\n\/\/ Permission to use, copy, modify, distribute and sell this software for any \n\/\/ purpose is hereby granted without fee, provided that the above copyright \n\/\/ notice appear in all copies and that both that copyright notice and this \n\/\/ permission notice appear in supporting documentation.\n\/\/ The author makes no representations about the \n\/\/ suitability of this software for any purpose. It is provided \"as is\" \n\/\/ without express or implied warranty.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ $Header:\n\n\n\n#include \n#include \n#include \n#include \n\n\nvoid Decrement(int& x) \n{ \n\t--x; \n}\n\nstruct UserDatabase\n{\n void AddFriend(const std::string&, const std::string&)\n {\n throw 55;\n }\n};\n\nclass User\n{\npublic:\n User(UserDatabase* db) : fCount(0), pDB_(db)\n\t{}\n\n std::string GetName();\n\n void AddFriend(User& newFriend);\n void AddFriendGuarded(User& newFriend);\n\n size_t countFriends();\n \n int fCount;\n\nprivate:\n typedef std::vector UserCont;\n UserCont friends_;\n UserDatabase* pDB_;\n};\n\nstd::string User::GetName()\n{\n return \"A name\";\n}\n\nsize_t User::countFriends()\n{\n return friends_.size();\n}\n\nvoid User::AddFriend(User& newFriend)\n{\n friends_.push_back(&newFriend);\n fCount++;\n pDB_->AddFriend(GetName(), newFriend.GetName());\n}\n\nvoid User::AddFriendGuarded(User& newFriend)\n{\n friends_.push_back(&newFriend);\n Loki::ScopeGuard guard = Loki::MakeObjGuard(friends_, &UserCont::pop_back);\n \n fCount++;\n Loki::ScopeGuard guardRef = Loki::MakeGuard(Decrement, Loki::ByRef(fCount));\n (void) guardRef;\n\n pDB_->AddFriend(GetName(), newFriend.GetName());\n guard.Dismiss();\n}\n\n\nint main()\n{\n UserDatabase db;\n\n User u1(&db);\n User u2(&db);\n\n try{ u1.AddFriend(u2); }\n catch (...){}\n std::cout << \"u1 countFriends: \" << u1.countFriends() << \"\\n\";\n\tstd::cout << \"u1 fCount : \" << u1.fCount << \"\\n\";\n\n try{ u2.AddFriendGuarded(u1); }\n catch (...){}\n std::cout << \"u2 countFriends: \" << u2.countFriends() << \"\\n\";\n\tstd::cout << \"u2 fCount : \" << u2.fCount << \"\\n\";\n\n#if defined(__BORLANDC__) || defined(_MSC_VER)\n system(\"PAUSE\");\n#endif\n\n}\nuse RefToValue.h, add dismiss for the ref guard\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ The Loki Library\n\/\/ Copyright (c) 2006 Peter Kmmel\n\/\/ Permission to use, copy, modify, distribute and sell this software for any \n\/\/ purpose is hereby granted without fee, provided that the above copyright \n\/\/ notice appear in all copies and that both that copyright notice and this \n\/\/ permission notice appear in supporting documentation.\n\/\/ The author makes no representations about the \n\/\/ suitability of this software for any purpose. It is provided \"as is\" \n\/\/ without express or implied warranty.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ $Header:\n\n\n#include \n#include \n\n#include \n#include \n#include \n\n\nvoid Decrement(int& x) \n{ \n --x; \n}\n\nstruct UserDatabase\n{\n void AddFriend(const std::string&, const std::string&)\n {\n throw 55;\n }\n};\n\nclass User\n{\npublic:\n User(UserDatabase* db) : fCount(0), pDB_(db)\n {}\n\n std::string GetName();\n\n void AddFriend(User& newFriend);\n void AddFriendGuarded(User& newFriend);\n\n size_t countFriends();\n \n int fCount;\n\nprivate:\n typedef std::vector UserCont;\n UserCont friends_;\n UserDatabase* pDB_;\n};\n\nstd::string User::GetName()\n{\n return \"A name\";\n}\n\nsize_t User::countFriends()\n{\n return friends_.size();\n}\n\nvoid User::AddFriend(User& newFriend)\n{\n friends_.push_back(&newFriend);\n fCount++;\n pDB_->AddFriend(GetName(), newFriend.GetName());\n}\n\nvoid User::AddFriendGuarded(User& newFriend)\n{\n friends_.push_back(&newFriend);\n Loki::ScopeGuard guard = Loki::MakeObjGuard(friends_, &UserCont::pop_back);\n \n fCount++;\n Loki::ScopeGuard guardRef = Loki::MakeGuard(Decrement, Loki::ByRef(fCount));\n\n pDB_->AddFriend(GetName(), newFriend.GetName());\n guard.Dismiss();\n guardRef.Dismiss();\n}\n\n\nint main()\n{\n UserDatabase db;\n\n User u1(&db);\n User u2(&db);\n\n try{ u1.AddFriend(u2); }\n catch (...){}\n std::cout << \"u1 countFriends: \" << u1.countFriends() << \"\\n\";\n std::cout << \"u1 fCount : \" << u1.fCount << \"\\n\";\n\n try{ u2.AddFriendGuarded(u1); }\n catch (...){}\n std::cout << \"u2 countFriends: \" << u2.countFriends() << \"\\n\";\n std::cout << \"u2 fCount : \" << u2.fCount << \"\\n\";\n\n#if defined(__BORLANDC__) || defined(_MSC_VER)\n system(\"PAUSE\");\n#endif\n\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2010 Gregory Szorc\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#pragma once\n\n#include \n#include \n#include \n\n#include \n#include \n\nusing ::pblog::server::Broker;\nusing ::std::cout;\nusing ::std::endl;\n\nint main(int argc, const char * const argv[])\n{\n if (argc != 2) {\n cout << \"Usage: pblogd \/path\/to\/config\/file.lua\" << endl;\n return 1;\n }\n\n Broker broker = Broker(argv[1]);\n broker.run();\n\n return 0;\n}\nreflect project renaming\/\/ Copyright 2010 Gregory Szorc\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#pragma once\n\n#include \n#include \n#include \n\n#include \n#include \n\nusing ::zippylog::server::Broker;\nusing ::std::cout;\nusing ::std::endl;\n\nint main(int argc, const char * const argv[])\n{\n if (argc != 2) {\n cout << \"Usage: pblogd \/path\/to\/config\/file.lua\" << endl;\n return 1;\n }\n\n Broker broker = Broker(argv[1]);\n broker.run();\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \"imported_search_context.h\"\n#include \"attributeiterators.hpp\"\n#include \"imported_attribute_vector.h\"\n#include \"reference_attribute.h\"\n#include \n#include \n#include \n#include \n#include \"dociditerator.h\"\n\nusing search::datastore::EntryRef;\nusing search::queryeval::EmptySearch;\nusing search::queryeval::SearchIterator;\nusing search::attribute::ReferenceAttribute;\nusing search::AttributeVector;\n\nusing ReverseMappingRefs = ReferenceAttribute::ReverseMappingRefs;\nusing ReverseMapping = ReferenceAttribute::ReverseMapping;\nusing SearchContext = AttributeVector::SearchContext;\n\n\nnamespace search {\nnamespace attribute {\n\nImportedSearchContext::ImportedSearchContext(\n std::unique_ptr term,\n const SearchContextParams& params,\n const ImportedAttributeVector& imported_attribute)\n : _imported_attribute(imported_attribute),\n _reference_attribute(*_imported_attribute.getReferenceAttribute()),\n _target_attribute(*_imported_attribute.getTargetAttribute()),\n _target_search_context(_target_attribute.getSearch(std::move(term), params)),\n _referencedLids(_reference_attribute.getReferencedLids()),\n _merger(_reference_attribute.getCommittedDocIdLimit()),\n _fetchPostingsDone(false)\n{\n}\n\nImportedSearchContext::~ImportedSearchContext() {\n}\n\nunsigned int ImportedSearchContext::approximateHits() const {\n return _reference_attribute.getNumDocs();\n}\n\nstd::unique_ptr\nImportedSearchContext::createIterator(fef::TermFieldMatchData* matchData, bool strict) {\n if (_merger.hasArray()) {\n if (_merger.emptyArray()) {\n return SearchIterator::UP(new EmptySearch());\n } else {\n using Posting = btree::BTreeKeyData;\n using DocIt = DocIdIterator;\n DocIt postings;\n auto array = _merger.getArray();\n postings.set(&array[0], &array[array.size()]);\n return std::make_unique>(true, matchData, postings);\n }\n }\n if (!strict) {\n return std::make_unique>(*this, matchData);\n } else {\n return std::make_unique>(*this, matchData);\n }\n}\n\nnamespace {\n\nstruct WeightedRef {\n EntryRef revMapIdx;\n int32_t weight;\n\n WeightedRef(EntryRef revMapIdx_, int32_t weight_)\n : revMapIdx(revMapIdx_),\n weight(weight_)\n {\n }\n};\n\nstruct TargetResult {\n std::vector weightedRefs;\n size_t sizeSum;\n\n TargetResult()\n : weightedRefs(),\n sizeSum(0)\n {\n }\n};\n\nTargetResult\ngetTargetResult(ReverseMappingRefs reverseMappingRefs,\n const ReverseMapping &reverseMapping,\n SearchContext &target_search_context)\n{\n TargetResult targetResult;\n fef::TermFieldMatchData matchData;\n auto targetItr = target_search_context.createIterator(&matchData, true);\n uint32_t docIdLimit = reverseMappingRefs.size();\n uint32_t lid = 1;\n targetItr->initRange(1, docIdLimit);\n while (lid < docIdLimit) {\n if (targetItr->seek(lid)) {\n EntryRef revMapIdx = reverseMappingRefs[lid];\n if (revMapIdx.valid()) {\n uint32_t size = reverseMapping.frozenSize(revMapIdx);\n targetResult.sizeSum += size;\n targetItr->unpack(lid);\n int32_t weight = matchData.getWeight();\n targetResult.weightedRefs.emplace_back(revMapIdx, weight);\n }\n ++lid;\n } else {\n ++lid;\n uint32_t nextLid = targetItr->getDocId();\n if (nextLid > lid) {\n lid = nextLid;\n }\n }\n }\n return targetResult;\n}\n\nclass ReverseMappingPostingList\n{\n const ReverseMapping &_reverseMapping;\n EntryRef _revMapIdx;\n int32_t _weight;\npublic:\n ReverseMappingPostingList(const ReverseMapping &reverseMapping, EntryRef revMapIdx, int32_t weight)\n : _reverseMapping(reverseMapping),\n _revMapIdx(revMapIdx),\n _weight(weight)\n {\n }\n ~ReverseMappingPostingList() { }\n template \n void foreach(Func func) const {\n int32_t weight = _weight;\n _reverseMapping.foreach_frozen_key(_revMapIdx, [func, weight](uint32_t lid) { func(lid, weight); });\n }\n};\n\n}\n\nvoid ImportedSearchContext::makeMergedPostings()\n{\n TargetResult targetResult(getTargetResult(_reference_attribute.getReverseMappingRefs(),\n _reference_attribute.getReverseMapping(),\n *_target_search_context));\n _merger.reserveArray(targetResult.weightedRefs.size(), targetResult.sizeSum);\n const auto &reverseMapping = _reference_attribute.getReverseMapping();\n for (const auto &weightedRef : targetResult.weightedRefs) {\n _merger.addToArray(ReverseMappingPostingList(reverseMapping, weightedRef.revMapIdx, weightedRef.weight));\n }\n _merger.merge();\n}\n\nvoid ImportedSearchContext::fetchPostings(bool strict) {\n assert(!_fetchPostingsDone);\n _fetchPostingsDone = true;\n _target_search_context->fetchPostings(strict);\n if (strict) {\n makeMergedPostings();\n }\n}\n\nbool ImportedSearchContext::valid() const {\n return _target_search_context->valid();\n}\n\nInt64Range ImportedSearchContext::getAsIntegerTerm() const {\n return _target_search_context->getAsIntegerTerm();\n}\n\nconst QueryTermBase& ImportedSearchContext::queryTerm() const {\n return _target_search_context->queryTerm();\n}\n\nconst vespalib::string& ImportedSearchContext::attributeName() const {\n return _imported_attribute.getName();\n}\n\nbool ImportedSearchContext::cmp(DocId docId, int32_t& weight) const {\n return _target_search_context->cmp(_referencedLids[docId], weight);\n}\n\nbool ImportedSearchContext::cmp(DocId docId) const {\n return _target_search_context->cmp(_referencedLids[docId]);\n}\n\n} \/\/ attribute\n} \/\/ search\nAvoid race between readers and writer that could cause reader to read uninitialized or unmapped data when accessing target attribute.\/\/ Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \"imported_search_context.h\"\n#include \"attributeiterators.hpp\"\n#include \"imported_attribute_vector.h\"\n#include \"reference_attribute.h\"\n#include \n#include \n#include \n#include \n#include \"dociditerator.h\"\n\nusing search::datastore::EntryRef;\nusing search::queryeval::EmptySearch;\nusing search::queryeval::SearchIterator;\nusing search::attribute::ReferenceAttribute;\nusing search::AttributeVector;\n\nusing ReverseMappingRefs = ReferenceAttribute::ReverseMappingRefs;\nusing ReverseMapping = ReferenceAttribute::ReverseMapping;\nusing SearchContext = AttributeVector::SearchContext;\n\n\nnamespace search {\nnamespace attribute {\n\nImportedSearchContext::ImportedSearchContext(\n std::unique_ptr term,\n const SearchContextParams& params,\n const ImportedAttributeVector& imported_attribute)\n : _imported_attribute(imported_attribute),\n _reference_attribute(*_imported_attribute.getReferenceAttribute()),\n _target_attribute(*_imported_attribute.getTargetAttribute()),\n _target_search_context(_target_attribute.getSearch(std::move(term), params)),\n _referencedLids(_reference_attribute.getReferencedLids()),\n _merger(_reference_attribute.getCommittedDocIdLimit()),\n _fetchPostingsDone(false)\n{\n}\n\nImportedSearchContext::~ImportedSearchContext() {\n}\n\nunsigned int ImportedSearchContext::approximateHits() const {\n return _reference_attribute.getNumDocs();\n}\n\nstd::unique_ptr\nImportedSearchContext::createIterator(fef::TermFieldMatchData* matchData, bool strict) {\n if (_merger.hasArray()) {\n if (_merger.emptyArray()) {\n return SearchIterator::UP(new EmptySearch());\n } else {\n using Posting = btree::BTreeKeyData;\n using DocIt = DocIdIterator;\n DocIt postings;\n auto array = _merger.getArray();\n postings.set(&array[0], &array[array.size()]);\n return std::make_unique>(true, matchData, postings);\n }\n }\n if (!strict) {\n return std::make_unique>(*this, matchData);\n } else {\n return std::make_unique>(*this, matchData);\n }\n}\n\nnamespace {\n\nstruct WeightedRef {\n EntryRef revMapIdx;\n int32_t weight;\n\n WeightedRef(EntryRef revMapIdx_, int32_t weight_)\n : revMapIdx(revMapIdx_),\n weight(weight_)\n {\n }\n};\n\nstruct TargetResult {\n std::vector weightedRefs;\n size_t sizeSum;\n\n TargetResult()\n : weightedRefs(),\n sizeSum(0)\n {\n }\n};\n\nTargetResult\ngetTargetResult(ReverseMappingRefs reverseMappingRefs,\n const ReverseMapping &reverseMapping,\n SearchContext &target_search_context,\n uint32_t committedDocIdLimit)\n{\n TargetResult targetResult;\n fef::TermFieldMatchData matchData;\n auto targetItr = target_search_context.createIterator(&matchData, true);\n uint32_t docIdLimit = reverseMappingRefs.size();\n if (docIdLimit > committedDocIdLimit) {\n docIdLimit = committedDocIdLimit;\n }\n uint32_t lid = 1;\n targetItr->initRange(1, docIdLimit);\n while (lid < docIdLimit) {\n if (targetItr->seek(lid)) {\n EntryRef revMapIdx = reverseMappingRefs[lid];\n if (revMapIdx.valid()) {\n uint32_t size = reverseMapping.frozenSize(revMapIdx);\n targetResult.sizeSum += size;\n targetItr->unpack(lid);\n int32_t weight = matchData.getWeight();\n targetResult.weightedRefs.emplace_back(revMapIdx, weight);\n }\n ++lid;\n } else {\n ++lid;\n uint32_t nextLid = targetItr->getDocId();\n if (nextLid > lid) {\n lid = nextLid;\n }\n }\n }\n return targetResult;\n}\n\nclass ReverseMappingPostingList\n{\n const ReverseMapping &_reverseMapping;\n EntryRef _revMapIdx;\n int32_t _weight;\npublic:\n ReverseMappingPostingList(const ReverseMapping &reverseMapping, EntryRef revMapIdx, int32_t weight)\n : _reverseMapping(reverseMapping),\n _revMapIdx(revMapIdx),\n _weight(weight)\n {\n }\n ~ReverseMappingPostingList() { }\n template \n void foreach(Func func) const {\n int32_t weight = _weight;\n _reverseMapping.foreach_frozen_key(_revMapIdx, [func, weight](uint32_t lid) { func(lid, weight); });\n }\n};\n\n}\n\nvoid ImportedSearchContext::makeMergedPostings()\n{\n uint32_t committedTargetDocIdLimit = _target_attribute.getCommittedDocIdLimit();\n std::atomic_thread_fence(std::memory_order_acquire);\n TargetResult targetResult(getTargetResult(_reference_attribute.getReverseMappingRefs(),\n _reference_attribute.getReverseMapping(),\n *_target_search_context,\n committedTargetDocIdLimit));\n _merger.reserveArray(targetResult.weightedRefs.size(), targetResult.sizeSum);\n const auto &reverseMapping = _reference_attribute.getReverseMapping();\n for (const auto &weightedRef : targetResult.weightedRefs) {\n _merger.addToArray(ReverseMappingPostingList(reverseMapping, weightedRef.revMapIdx, weightedRef.weight));\n }\n _merger.merge();\n}\n\nvoid ImportedSearchContext::fetchPostings(bool strict) {\n assert(!_fetchPostingsDone);\n _fetchPostingsDone = true;\n _target_search_context->fetchPostings(strict);\n if (strict) {\n makeMergedPostings();\n }\n}\n\nbool ImportedSearchContext::valid() const {\n return _target_search_context->valid();\n}\n\nInt64Range ImportedSearchContext::getAsIntegerTerm() const {\n return _target_search_context->getAsIntegerTerm();\n}\n\nconst QueryTermBase& ImportedSearchContext::queryTerm() const {\n return _target_search_context->queryTerm();\n}\n\nconst vespalib::string& ImportedSearchContext::attributeName() const {\n return _imported_attribute.getName();\n}\n\nbool ImportedSearchContext::cmp(DocId docId, int32_t& weight) const {\n return _target_search_context->cmp(_referencedLids[docId], weight);\n}\n\nbool ImportedSearchContext::cmp(DocId docId) const {\n return _target_search_context->cmp(_referencedLids[docId]);\n}\n\n} \/\/ attribute\n} \/\/ search\n<|endoftext|>"} {"text":"#ifndef STAN_MATH_MIX_HPP\n#define STAN_MATH_MIX_HPP\n\n#include \n#include \n#include \n\n#ifdef STAN_OPENCL\n#include \n#endif\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n\n#endif\nUpdate mix.hpp#ifndef STAN_MATH_MIX_HPP\n#define STAN_MATH_MIX_HPP\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#ifdef STAN_OPENCL\n#include \n#endif\n\n#include \n#include \n#include \n#include \n\n#include \n\n#endif\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2013 The WebM project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \n#include \"test\/codec_factory.h\"\n#include \"test\/decode_test_driver.h\"\n#include \"test\/encode_test_driver.h\"\n#include \"test\/i420_video_source.h\"\n#include \"test\/ivf_video_source.h\"\n#include \"test\/md5_helper.h\"\n#include \"test\/util.h\"\n#include \"test\/webm_video_source.h\"\n#include \"vpx_ports\/vpx_timer.h\"\n#include \".\/ivfenc.h\"\n#include \".\/vpx_version.h\"\n\nusing std::tr1::make_tuple;\n\nnamespace {\n\n#define VIDEO_NAME 0\n#define THREADS 1\n\nconst int kMaxPsnr = 100;\nconst double kUsecsInSec = 1000000.0;\nstatic const char *kNewEncodeOutputFile = \"new_encode.ivf\";\n\n\/*\n DecodePerfTest takes a tuple of filename + number of threads to decode with\n *\/\ntypedef std::tr1::tuple DecodePerfParam;\n\nconst DecodePerfParam kVP9DecodePerfVectors[] = {\n make_tuple(\"vp90-2-bbb_426x240_tile_1x1_180kbps.webm\", 1),\n make_tuple(\"vp90-2-bbb_640x360_tile_1x2_337kbps.webm\", 2),\n make_tuple(\"vp90-2-bbb_854x480_tile_1x2_651kbps.webm\", 2),\n make_tuple(\"vp90-2-bbb_1280x720_tile_1x4_1310kbps.webm\", 4),\n make_tuple(\"vp90-2-bbb_1920x1080_tile_1x1_2581kbps.webm\", 1),\n make_tuple(\"vp90-2-bbb_1920x1080_tile_1x4_2586kbps.webm\", 4),\n make_tuple(\"vp90-2-bbb_1920x1080_tile_1x4_fpm_2304kbps.webm\", 4),\n make_tuple(\"vp90-2-sintel_426x182_tile_1x1_171kbps.webm\", 1),\n make_tuple(\"vp90-2-sintel_640x272_tile_1x2_318kbps.webm\", 2),\n make_tuple(\"vp90-2-sintel_854x364_tile_1x2_621kbps.webm\", 2),\n make_tuple(\"vp90-2-sintel_1280x546_tile_1x4_1257kbps.webm\", 4),\n make_tuple(\"vp90-2-sintel_1920x818_tile_1x4_fpm_2279kbps.webm\", 4),\n make_tuple(\"vp90-2-tos_426x178_tile_1x1_181kbps.webm\", 1),\n make_tuple(\"vp90-2-tos_640x266_tile_1x2_336kbps.webm\", 2),\n make_tuple(\"vp90-2-tos_854x356_tile_1x2_656kbps.webm\", 2),\n make_tuple(\"vp90-2-tos_854x356_tile_1x2_fpm_546kbps.webm\", 2),\n make_tuple(\"vp90-2-tos_1280x534_tile_1x4_1306kbps.webm\", 4),\n make_tuple(\"vp90-2-tos_1280x534_tile_1x4_fpm_952kbps.webm\", 4),\n make_tuple(\"vp90-2-tos_1920x800_tile_1x4_fpm_2335kbps.webm\", 4),\n};\n\n\/*\n In order to reflect real world performance as much as possible, Perf tests\n *DO NOT* do any correctness checks. Please run them alongside correctness\n tests to ensure proper codec integrity. Furthermore, in this test we\n deliberately limit the amount of system calls we make to avoid OS\n preemption.\n\n TODO(joshualitt) create a more detailed perf measurement test to collect\n power\/temp\/min max frame decode times\/etc\n *\/\n\nclass DecodePerfTest : public ::testing::TestWithParam {\n};\n\nTEST_P(DecodePerfTest, PerfTest) {\n const char *const video_name = GET_PARAM(VIDEO_NAME);\n const unsigned threads = GET_PARAM(THREADS);\n\n libvpx_test::WebMVideoSource video(video_name);\n video.Init();\n\n vpx_codec_dec_cfg_t cfg = vpx_codec_dec_cfg_t();\n cfg.threads = threads;\n libvpx_test::VP9Decoder decoder(cfg, 0);\n\n vpx_usec_timer t;\n vpx_usec_timer_start(&t);\n\n for (video.Begin(); video.cxdata() != NULL; video.Next()) {\n decoder.DecodeFrame(video.cxdata(), video.frame_size());\n }\n\n vpx_usec_timer_mark(&t);\n const double elapsed_secs = double(vpx_usec_timer_elapsed(&t))\n \/ kUsecsInSec;\n const unsigned frames = video.frame_number();\n const double fps = double(frames) \/ elapsed_secs;\n\n printf(\"{\\n\");\n printf(\"\\t\\\"type\\\" : \\\"decode_perf_test\\\",\\n\");\n printf(\"\\t\\\"version\\\" : \\\"%s\\\",\\n\", VERSION_STRING_NOSP);\n printf(\"\\t\\\"videoName\\\" : \\\"%s\\\",\\n\", video_name);\n printf(\"\\t\\\"threadCount\\\" : %u,\\n\", threads);\n printf(\"\\t\\\"decodeTimeSecs\\\" : %f,\\n\", elapsed_secs);\n printf(\"\\t\\\"totalFrames\\\" : %u,\\n\", frames);\n printf(\"\\t\\\"framesPerSecond\\\" : %f\\n\", fps);\n printf(\"}\\n\");\n}\n\nINSTANTIATE_TEST_CASE_P(VP9, DecodePerfTest,\n ::testing::ValuesIn(kVP9DecodePerfVectors));\n\nclass VP9NewEncodeDecodePerfTest : public ::libvpx_test::EncoderTest,\n public ::libvpx_test::CodecTestWithParam {\n protected:\n VP9NewEncodeDecodePerfTest()\n : EncoderTest(GET_PARAM(0)),\n encoding_mode_(GET_PARAM(1)),\n speed_(0),\n outfile_(0),\n out_frames_(0) {\n }\n\n virtual ~VP9NewEncodeDecodePerfTest() {}\n\n virtual void SetUp() {\n InitializeConfig();\n SetMode(encoding_mode_);\n\n cfg_.g_lag_in_frames = 25;\n cfg_.rc_min_quantizer = 2;\n cfg_.rc_max_quantizer = 56;\n cfg_.rc_dropframe_thresh = 0;\n cfg_.rc_undershoot_pct = 50;\n cfg_.rc_overshoot_pct = 50;\n cfg_.rc_buf_sz = 1000;\n cfg_.rc_buf_initial_sz = 500;\n cfg_.rc_buf_optimal_sz = 600;\n cfg_.rc_resize_allowed = 0;\n cfg_.rc_end_usage = VPX_VBR;\n }\n\n virtual void PreEncodeFrameHook(::libvpx_test::VideoSource *video,\n ::libvpx_test::Encoder *encoder) {\n if (video->frame() == 1) {\n encoder->Control(VP8E_SET_CPUUSED, speed_);\n encoder->Control(VP9E_SET_FRAME_PARALLEL_DECODING, 1);\n encoder->Control(VP9E_SET_TILE_COLUMNS, 2);\n }\n }\n\n virtual void BeginPassHook(unsigned int \/*pass*\/) {\n const std::string data_path = getenv(\"LIBVPX_TEST_DATA_PATH\");\n const std::string path_to_source = data_path + \"\/\" + kNewEncodeOutputFile;\n outfile_ = fopen(path_to_source.c_str(), \"wb\");\n }\n\n virtual void EndPassHook() {\n if (outfile_) {\n if (!fseek(outfile_, 0, SEEK_SET))\n ivf_write_file_header(outfile_, &cfg_, VP9_FOURCC, out_frames_);\n fclose(outfile_);\n outfile_ = NULL;\n }\n }\n\n virtual void FramePktHook(const vpx_codec_cx_pkt_t *pkt) {\n ++out_frames_;\n\n \/\/ Write initial file header if first frame.\n if (pkt->data.frame.pts == 0)\n ivf_write_file_header(outfile_, &cfg_, VP9_FOURCC, out_frames_);\n\n \/\/ Write frame header and data.\n ivf_write_frame_header(outfile_, out_frames_, pkt->data.frame.sz);\n (void)fwrite(pkt->data.frame.buf, 1, pkt->data.frame.sz, outfile_);\n }\n\n virtual bool DoDecode() { return 0; }\n\n void set_speed(unsigned int speed) {\n speed_ = speed;\n }\n\n private:\n libvpx_test::TestMode encoding_mode_;\n uint32_t speed_;\n FILE *outfile_;\n uint32_t out_frames_;\n};\n\n\nstruct EncodePerfTestVideo {\n EncodePerfTestVideo(const char *name_, uint32_t width_, uint32_t height_,\n uint32_t bitrate_, int frames_)\n : name(name_),\n width(width_),\n height(height_),\n bitrate(bitrate_),\n frames(frames_) {}\n const char *name;\n uint32_t width;\n uint32_t height;\n uint32_t bitrate;\n int frames;\n};\n\nconst EncodePerfTestVideo kVP9EncodePerfTestVectors[] = {\n EncodePerfTestVideo(\"niklas_1280_720_30.yuv\", 1280, 720, 600, 470),\n};\n\nTEST_P(VP9NewEncodeDecodePerfTest, PerfTest) {\n SetUp();\n\n \/\/ TODO(JBB): Make this work by going through the set of given files.\n const int i = 0;\n const vpx_rational timebase = { 33333333, 1000000000 };\n cfg_.g_timebase = timebase;\n cfg_.rc_target_bitrate = kVP9EncodePerfTestVectors[i].bitrate;\n\n init_flags_ = VPX_CODEC_USE_PSNR;\n\n const char *video_name = kVP9EncodePerfTestVectors[i].name;\n libvpx_test::I420VideoSource video(\n video_name,\n kVP9EncodePerfTestVectors[i].width,\n kVP9EncodePerfTestVectors[i].height,\n timebase.den, timebase.num, 0,\n kVP9EncodePerfTestVectors[i].frames);\n set_speed(2);\n\n ASSERT_NO_FATAL_FAILURE(RunLoop(&video));\n\n const uint32_t threads = 4;\n\n libvpx_test::IVFVideoSource decode_video(kNewEncodeOutputFile);\n decode_video.Init();\n\n vpx_codec_dec_cfg_t cfg = vpx_codec_dec_cfg_t();\n cfg.threads = threads;\n libvpx_test::VP9Decoder decoder(cfg, 0);\n\n vpx_usec_timer t;\n vpx_usec_timer_start(&t);\n\n for (decode_video.Begin(); decode_video.cxdata() != NULL;\n decode_video.Next()) {\n decoder.DecodeFrame(decode_video.cxdata(), decode_video.frame_size());\n }\n\n vpx_usec_timer_mark(&t);\n const double elapsed_secs =\n double(vpx_usec_timer_elapsed(&t)) \/ kUsecsInSec;\n const unsigned decode_frames = decode_video.frame_number();\n const double fps = double(decode_frames) \/ elapsed_secs;\n\n printf(\"{\\n\");\n printf(\"\\t\\\"type\\\" : \\\"decode_perf_test\\\",\\n\");\n printf(\"\\t\\\"version\\\" : \\\"%s\\\",\\n\", VERSION_STRING_NOSP);\n printf(\"\\t\\\"videoName\\\" : \\\"%s\\\",\\n\", kNewEncodeOutputFile);\n printf(\"\\t\\\"threadCount\\\" : %u,\\n\", threads);\n printf(\"\\t\\\"decodeTimeSecs\\\" : %f,\\n\", elapsed_secs);\n printf(\"\\t\\\"totalFrames\\\" : %u,\\n\", decode_frames);\n printf(\"\\t\\\"framesPerSecond\\\" : %f\\n\", fps);\n printf(\"}\\n\");\n}\n\nVP9_INSTANTIATE_TEST_CASE(\n VP9NewEncodeDecodePerfTest, ::testing::Values(::libvpx_test::kTwoPassGood));\n} \/\/ namespace\nResolve several style issues in decode_perf_test\/*\n * Copyright (c) 2013 The WebM project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \n#include \"test\/codec_factory.h\"\n#include \"test\/decode_test_driver.h\"\n#include \"test\/encode_test_driver.h\"\n#include \"test\/i420_video_source.h\"\n#include \"test\/ivf_video_source.h\"\n#include \"test\/md5_helper.h\"\n#include \"test\/util.h\"\n#include \"test\/webm_video_source.h\"\n#include \"vpx_ports\/vpx_timer.h\"\n#include \".\/ivfenc.h\"\n#include \".\/vpx_version.h\"\n\nusing std::tr1::make_tuple;\n\nnamespace {\n\n#define VIDEO_NAME 0\n#define THREADS 1\n\nconst int kMaxPsnr = 100;\nconst double kUsecsInSec = 1000000.0;\nconst char kNewEncodeOutputFile[] = \"new_encode.ivf\";\n\n\/*\n DecodePerfTest takes a tuple of filename + number of threads to decode with\n *\/\ntypedef std::tr1::tuple DecodePerfParam;\n\nconst DecodePerfParam kVP9DecodePerfVectors[] = {\n make_tuple(\"vp90-2-bbb_426x240_tile_1x1_180kbps.webm\", 1),\n make_tuple(\"vp90-2-bbb_640x360_tile_1x2_337kbps.webm\", 2),\n make_tuple(\"vp90-2-bbb_854x480_tile_1x2_651kbps.webm\", 2),\n make_tuple(\"vp90-2-bbb_1280x720_tile_1x4_1310kbps.webm\", 4),\n make_tuple(\"vp90-2-bbb_1920x1080_tile_1x1_2581kbps.webm\", 1),\n make_tuple(\"vp90-2-bbb_1920x1080_tile_1x4_2586kbps.webm\", 4),\n make_tuple(\"vp90-2-bbb_1920x1080_tile_1x4_fpm_2304kbps.webm\", 4),\n make_tuple(\"vp90-2-sintel_426x182_tile_1x1_171kbps.webm\", 1),\n make_tuple(\"vp90-2-sintel_640x272_tile_1x2_318kbps.webm\", 2),\n make_tuple(\"vp90-2-sintel_854x364_tile_1x2_621kbps.webm\", 2),\n make_tuple(\"vp90-2-sintel_1280x546_tile_1x4_1257kbps.webm\", 4),\n make_tuple(\"vp90-2-sintel_1920x818_tile_1x4_fpm_2279kbps.webm\", 4),\n make_tuple(\"vp90-2-tos_426x178_tile_1x1_181kbps.webm\", 1),\n make_tuple(\"vp90-2-tos_640x266_tile_1x2_336kbps.webm\", 2),\n make_tuple(\"vp90-2-tos_854x356_tile_1x2_656kbps.webm\", 2),\n make_tuple(\"vp90-2-tos_854x356_tile_1x2_fpm_546kbps.webm\", 2),\n make_tuple(\"vp90-2-tos_1280x534_tile_1x4_1306kbps.webm\", 4),\n make_tuple(\"vp90-2-tos_1280x534_tile_1x4_fpm_952kbps.webm\", 4),\n make_tuple(\"vp90-2-tos_1920x800_tile_1x4_fpm_2335kbps.webm\", 4),\n};\n\n\/*\n In order to reflect real world performance as much as possible, Perf tests\n *DO NOT* do any correctness checks. Please run them alongside correctness\n tests to ensure proper codec integrity. Furthermore, in this test we\n deliberately limit the amount of system calls we make to avoid OS\n preemption.\n\n TODO(joshualitt) create a more detailed perf measurement test to collect\n power\/temp\/min max frame decode times\/etc\n *\/\n\nclass DecodePerfTest : public ::testing::TestWithParam {\n};\n\nTEST_P(DecodePerfTest, PerfTest) {\n const char *const video_name = GET_PARAM(VIDEO_NAME);\n const unsigned threads = GET_PARAM(THREADS);\n\n libvpx_test::WebMVideoSource video(video_name);\n video.Init();\n\n vpx_codec_dec_cfg_t cfg = vpx_codec_dec_cfg_t();\n cfg.threads = threads;\n libvpx_test::VP9Decoder decoder(cfg, 0);\n\n vpx_usec_timer t;\n vpx_usec_timer_start(&t);\n\n for (video.Begin(); video.cxdata() != NULL; video.Next()) {\n decoder.DecodeFrame(video.cxdata(), video.frame_size());\n }\n\n vpx_usec_timer_mark(&t);\n const double elapsed_secs = double(vpx_usec_timer_elapsed(&t))\n \/ kUsecsInSec;\n const unsigned frames = video.frame_number();\n const double fps = double(frames) \/ elapsed_secs;\n\n printf(\"{\\n\");\n printf(\"\\t\\\"type\\\" : \\\"decode_perf_test\\\",\\n\");\n printf(\"\\t\\\"version\\\" : \\\"%s\\\",\\n\", VERSION_STRING_NOSP);\n printf(\"\\t\\\"videoName\\\" : \\\"%s\\\",\\n\", video_name);\n printf(\"\\t\\\"threadCount\\\" : %u,\\n\", threads);\n printf(\"\\t\\\"decodeTimeSecs\\\" : %f,\\n\", elapsed_secs);\n printf(\"\\t\\\"totalFrames\\\" : %u,\\n\", frames);\n printf(\"\\t\\\"framesPerSecond\\\" : %f\\n\", fps);\n printf(\"}\\n\");\n}\n\nINSTANTIATE_TEST_CASE_P(VP9, DecodePerfTest,\n ::testing::ValuesIn(kVP9DecodePerfVectors));\n\nclass VP9NewEncodeDecodePerfTest :\n public ::libvpx_test::EncoderTest,\n public ::libvpx_test::CodecTestWithParam {\n protected:\n VP9NewEncodeDecodePerfTest()\n : EncoderTest(GET_PARAM(0)),\n encoding_mode_(GET_PARAM(1)),\n speed_(0),\n outfile_(0),\n out_frames_(0) {\n }\n\n virtual ~VP9NewEncodeDecodePerfTest() {}\n\n virtual void SetUp() {\n InitializeConfig();\n SetMode(encoding_mode_);\n\n cfg_.g_lag_in_frames = 25;\n cfg_.rc_min_quantizer = 2;\n cfg_.rc_max_quantizer = 56;\n cfg_.rc_dropframe_thresh = 0;\n cfg_.rc_undershoot_pct = 50;\n cfg_.rc_overshoot_pct = 50;\n cfg_.rc_buf_sz = 1000;\n cfg_.rc_buf_initial_sz = 500;\n cfg_.rc_buf_optimal_sz = 600;\n cfg_.rc_resize_allowed = 0;\n cfg_.rc_end_usage = VPX_VBR;\n }\n\n virtual void PreEncodeFrameHook(::libvpx_test::VideoSource *video,\n ::libvpx_test::Encoder *encoder) {\n if (video->frame() == 1) {\n encoder->Control(VP8E_SET_CPUUSED, speed_);\n encoder->Control(VP9E_SET_FRAME_PARALLEL_DECODING, 1);\n encoder->Control(VP9E_SET_TILE_COLUMNS, 2);\n }\n }\n\n virtual void BeginPassHook(unsigned int \/*pass*\/) {\n const std::string data_path = getenv(\"LIBVPX_TEST_DATA_PATH\");\n const std::string path_to_source = data_path + \"\/\" + kNewEncodeOutputFile;\n outfile_ = fopen(path_to_source.c_str(), \"wb\");\n ASSERT_TRUE(outfile_ != NULL);\n }\n\n virtual void EndPassHook() {\n if (outfile_ != NULL) {\n if (!fseek(outfile_, 0, SEEK_SET))\n ivf_write_file_header(outfile_, &cfg_, VP9_FOURCC, out_frames_);\n fclose(outfile_);\n outfile_ = NULL;\n }\n }\n\n virtual void FramePktHook(const vpx_codec_cx_pkt_t *pkt) {\n ++out_frames_;\n\n \/\/ Write initial file header if first frame.\n if (pkt->data.frame.pts == 0)\n ivf_write_file_header(outfile_, &cfg_, VP9_FOURCC, out_frames_);\n\n \/\/ Write frame header and data.\n ivf_write_frame_header(outfile_, out_frames_, pkt->data.frame.sz);\n ASSERT_GT(fwrite(pkt->data.frame.buf, 1, pkt->data.frame.sz, outfile_), 0);\n }\n\n virtual bool DoDecode() { return false; }\n\n void set_speed(unsigned int speed) {\n speed_ = speed;\n }\n\n private:\n libvpx_test::TestMode encoding_mode_;\n uint32_t speed_;\n FILE *outfile_;\n uint32_t out_frames_;\n};\n\nstruct EncodePerfTestVideo {\n EncodePerfTestVideo(const char *name_, uint32_t width_, uint32_t height_,\n uint32_t bitrate_, int frames_)\n : name(name_),\n width(width_),\n height(height_),\n bitrate(bitrate_),\n frames(frames_) {}\n const char *name;\n uint32_t width;\n uint32_t height;\n uint32_t bitrate;\n int frames;\n};\n\nconst EncodePerfTestVideo kVP9EncodePerfTestVectors[] = {\n EncodePerfTestVideo(\"niklas_1280_720_30.yuv\", 1280, 720, 600, 470),\n};\n\nTEST_P(VP9NewEncodeDecodePerfTest, PerfTest) {\n SetUp();\n\n \/\/ TODO(JBB): Make this work by going through the set of given files.\n const int i = 0;\n const vpx_rational timebase = { 33333333, 1000000000 };\n cfg_.g_timebase = timebase;\n cfg_.rc_target_bitrate = kVP9EncodePerfTestVectors[i].bitrate;\n\n init_flags_ = VPX_CODEC_USE_PSNR;\n\n const char *video_name = kVP9EncodePerfTestVectors[i].name;\n libvpx_test::I420VideoSource video(\n video_name,\n kVP9EncodePerfTestVectors[i].width,\n kVP9EncodePerfTestVectors[i].height,\n timebase.den, timebase.num, 0,\n kVP9EncodePerfTestVectors[i].frames);\n set_speed(2);\n\n ASSERT_NO_FATAL_FAILURE(RunLoop(&video));\n\n const uint32_t threads = 4;\n\n libvpx_test::IVFVideoSource decode_video(kNewEncodeOutputFile);\n decode_video.Init();\n\n vpx_codec_dec_cfg_t cfg = vpx_codec_dec_cfg_t();\n cfg.threads = threads;\n libvpx_test::VP9Decoder decoder(cfg, 0);\n\n vpx_usec_timer t;\n vpx_usec_timer_start(&t);\n\n for (decode_video.Begin(); decode_video.cxdata() != NULL;\n decode_video.Next()) {\n decoder.DecodeFrame(decode_video.cxdata(), decode_video.frame_size());\n }\n\n vpx_usec_timer_mark(&t);\n const double elapsed_secs =\n static_cast(vpx_usec_timer_elapsed(&t)) \/ kUsecsInSec;\n const unsigned decode_frames = decode_video.frame_number();\n const double fps = static_cast(decode_frames) \/ elapsed_secs;\n\n printf(\"{\\n\");\n printf(\"\\t\\\"type\\\" : \\\"decode_perf_test\\\",\\n\");\n printf(\"\\t\\\"version\\\" : \\\"%s\\\",\\n\", VERSION_STRING_NOSP);\n printf(\"\\t\\\"videoName\\\" : \\\"%s\\\",\\n\", kNewEncodeOutputFile);\n printf(\"\\t\\\"threadCount\\\" : %u,\\n\", threads);\n printf(\"\\t\\\"decodeTimeSecs\\\" : %f,\\n\", elapsed_secs);\n printf(\"\\t\\\"totalFrames\\\" : %u,\\n\", decode_frames);\n printf(\"\\t\\\"framesPerSecond\\\" : %f\\n\", fps);\n printf(\"}\\n\");\n}\n\nVP9_INSTANTIATE_TEST_CASE(\n VP9NewEncodeDecodePerfTest, ::testing::Values(::libvpx_test::kTwoPassGood));\n} \/\/ namespace\n<|endoftext|>"} {"text":"#include \nusing namespace mettle;\n\n#include \n#include \n#include \n\n#include \nusing namespace mettle::posix;\n\nsuite test_scoped_pipe(\"scoped_pipe\", [](auto &_) {\n _.setup([](scoped_pipe &pipe) {\n expect(\"open pipe\", pipe.open(), equal_to(0));\n });\n\n _.test(\"open()\", [](scoped_pipe &pipe) {\n expect(\"read fd\", pipe.read_fd, greater_equal(0));\n expect(\"write fd\", pipe.write_fd, greater_equal(0));\n });\n\n _.test(\"close()\", [](scoped_pipe &pipe) {\n int read_fd, write_fd;\n read_fd = pipe.read_fd;\n write_fd = pipe.write_fd;\n\n expect(\"close read fd\", pipe.close_read(), equal_to(0));\n expect(\"read fd\", pipe.read_fd, equal_to(-1));\n expect(\"close read fd again\", pipe.close_read(), equal_to(-1));\n\n expect(\"get read fd flags\", fcntl(read_fd, F_GETFD), equal_to(-1));\n expect(errno, equal_to(EBADF));\n\n expect(\"close write fd\", pipe.close_write(), equal_to(0));\n expect(\"write fd\", pipe.write_fd, equal_to(-1));\n expect(\"close write fd again\", pipe.close_write(), equal_to(-1));\n\n expect(\"get write fd flags\", fcntl(write_fd, F_GETFD), equal_to(-1));\n expect(errno, equal_to(EBADF));\n });\n\n _.test(\"~scoped_pipe()\", [](scoped_pipe &) {\n int read_fd, write_fd;\n {\n scoped_pipe pipe;\n expect(\"open pipe\", pipe.open(), equal_to(0));\n read_fd = pipe.read_fd;\n write_fd = pipe.write_fd;\n }\n\n expect(\"get read fd flags\", fcntl(read_fd, F_GETFD), equal_to(-1));\n expect(errno, equal_to(EBADF));\n\n expect(\"get write fd flags\", fcntl(write_fd, F_GETFD), equal_to(-1));\n expect(errno, equal_to(EBADF));\n });\n\n _.test(\"read()\/write()\", [](scoped_pipe &pipe) {\n char in_data[] = \"hello\";\n expect(write(pipe.write_fd, in_data, sizeof(in_data)),\n equal_to(sizeof(in_data)));\n\n char out_data[sizeof(in_data)];\n expect(read(pipe.read_fd, out_data, sizeof(out_data)),\n equal_to(sizeof(in_data)));\n\n expect(std::string(out_data), equal_to(in_data));\n });\n\n \/\/ These might be a bit dangerous, since we're clobbering stdin\/stdout...\n\n _.test(\"move_read()\", [](scoped_pipe &pipe) {\n pipe.move_read(STDIN_FILENO);\n char in_data[] = \"hello\";\n expect(write(pipe.write_fd, in_data, sizeof(in_data) - 1),\n equal_to(sizeof(in_data) - 1));\n pipe.close_write();\n\n std::string out_data;\n std::cin >> out_data;\n expect(std::string(out_data), equal_to(in_data));\n });\n\n _.test(\"move_write()\", [](scoped_pipe &pipe) {\n pipe.move_write(STDOUT_FILENO);\n char in_data[] = \"hello\";\n std::cout << in_data << std::flush;\n close(STDOUT_FILENO);\n\n char out_data[sizeof(in_data)];\n expect(read(pipe.read_fd, out_data, sizeof(out_data)),\n equal_to(sizeof(in_data) - 1));\n expect(std::string(out_data), equal_to(in_data));\n });\n});\nImprove scoped_pipe tests#include \nusing namespace mettle;\n\n#include \n#include \n#include \n#include \n\n#include \nusing namespace mettle::posix;\n\nsuite>\ntest_scoped_pipe(\"scoped_pipe\", [](auto &_) {\n _.setup([](auto &pipe) {\n pipe = std::make_unique();\n expect(\"open pipe\", pipe->open(), equal_to(0));\n });\n\n _.test(\"open()\", [](auto &pipe) {\n expect(\"read fd\", pipe->read_fd, greater_equal(0));\n expect(\"write fd\", pipe->write_fd, greater_equal(0));\n\n expect(\"reopen pipe\", [&pipe]() { pipe->open(); }, killed(SIGABRT));\n });\n\n _.test(\"close()\", [](auto &pipe) {\n int read_fd, write_fd;\n read_fd = pipe->read_fd;\n write_fd = pipe->write_fd;\n\n expect(\"close read fd\", pipe->close_read(), equal_to(0));\n expect(\"read fd\", pipe->read_fd, equal_to(-1));\n expect(\"close read fd again\", pipe->close_read(), equal_to(-1));\n\n expect(\"get read fd flags\", fcntl(read_fd, F_GETFD), equal_to(-1));\n expect(errno, equal_to(EBADF));\n\n expect(\"close write fd\", pipe->close_write(), equal_to(0));\n expect(\"write fd\", pipe->write_fd, equal_to(-1));\n expect(\"close write fd again\", pipe->close_write(), equal_to(-1));\n\n expect(\"get write fd flags\", fcntl(write_fd, F_GETFD), equal_to(-1));\n expect(errno, equal_to(EBADF));\n });\n\n _.test(\"~scoped_pipe()\", [](auto &pipe) {\n int read_fd = pipe->read_fd;\n int write_fd = pipe->write_fd;\n pipe.reset();\n\n expect(\"get read fd flags\", fcntl(read_fd, F_GETFD), equal_to(-1));\n expect(errno, equal_to(EBADF));\n\n expect(\"get write fd flags\", fcntl(write_fd, F_GETFD), equal_to(-1));\n expect(errno, equal_to(EBADF));\n });\n\n _.test(\"read()\/write()\", [](auto &pipe) {\n char in_data[] = \"hello\";\n expect(\"write data\", write(pipe->write_fd, in_data, sizeof(in_data)),\n equal_to(sizeof(in_data)));\n\n char out_data[sizeof(in_data)];\n expect(\"read data\", read(pipe->read_fd, out_data, sizeof(out_data)),\n equal_to(sizeof(in_data)));\n\n expect(std::string(out_data), equal_to(in_data));\n });\n\n \/\/ These might be a bit dangerous, since we're clobbering stdin\/stdout...\n\n _.test(\"move_read()\", [](auto &pipe) {\n pipe->move_read(STDIN_FILENO);\n char in_data[] = \"hello\";\n expect(\"write data\", write(pipe->write_fd, in_data, sizeof(in_data) - 1),\n equal_to(sizeof(in_data) - 1));\n pipe->close_write();\n\n std::string out_data;\n std::cin >> out_data;\n expect(std::string(out_data), equal_to(in_data));\n });\n\n _.test(\"move_write()\", [](auto &pipe) {\n pipe->move_write(STDOUT_FILENO);\n char in_data[] = \"hello\";\n std::cout << in_data << std::flush;\n close(STDOUT_FILENO);\n\n char out_data[sizeof(in_data)];\n expect(\"read data\", read(pipe->read_fd, out_data, sizeof(out_data)),\n equal_to(sizeof(in_data) - 1));\n expect(std::string(out_data), equal_to(in_data));\n });\n});\n<|endoftext|>"} {"text":"\/\/ Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima).\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/**\n * @file PubSubWriter.hpp\n *\n *\/\n\n#ifndef _TEST_PROFILING_PUBSUBWRITER_HPP_\n#define _TEST_PROFILING_PUBSUBWRITER_HPP_\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\ntemplate\nclass PubSubWriter \n{\n class Listener : public eprosima::fastrtps::PublisherListener\n {\n public:\n\n Listener(PubSubWriter &writer) : writer_(writer){};\n\n ~Listener(){};\n\n void onPublicationMatched(eprosima::fastrtps::Publisher* \/*pub*\/, MatchingInfo &info)\n {\n if (info.status == MATCHED_MATCHING)\n writer_.matched();\n else\n writer_.unmatched();\n }\n\n private:\n\n Listener& operator=(const Listener&) NON_COPYABLE_CXX11;\n\n PubSubWriter &writer_;\n\n } listener_;\n\n public:\n\n typedef TypeSupport type_support;\n typedef typename type_support::type type;\n\n PubSubWriter(const std::string &topic_name) : listener_(*this), participant_(nullptr),\n publisher_(nullptr), topic_name_(topic_name), initialized_(false), matched_(0)\n {\n publisher_attr_.topic.topicDataType = type_.getName();\n \/\/ Generate topic name\n std::ostringstream t;\n t << topic_name_ << \"_\" << boost::asio::ip::host_name() << \"_\" << boost::interprocess::ipcdetail::get_current_process_id();\n publisher_attr_.topic.topicName = t.str();\n }\n \n ~PubSubWriter()\n {\n if(participant_ != nullptr)\n eprosima::fastrtps::Domain::removeParticipant(participant_);\n }\n\n void init()\n {\n \/\/Create participant\n eprosima::fastrtps::ParticipantAttributes pattr;\n pattr.rtps.builtin.domainId = (uint32_t)boost::interprocess::ipcdetail::get_current_process_id() % 230;\n participant_ = eprosima::fastrtps::Domain::createParticipant(pattr);\n\n if(participant_ != nullptr)\n {\n \/\/ Register type\n eprosima::fastrtps::Domain::registerType(participant_, &type_);\n\n \/\/Create publisher\n publisher_ = eprosima::fastrtps::Domain::createPublisher(participant_, publisher_attr_, &listener_);\n\n if(publisher_ != nullptr)\n {\n initialized_ = true;\n return;\n }\n\n eprosima::fastrtps::Domain::removeParticipant(participant_);\n }\n }\n\n bool isInitialized() const { return initialized_; }\n\n void destroy()\n {\n if(participant_ != nullptr)\n {\n eprosima::fastrtps::Domain::removeParticipant(participant_);\n participant_ = nullptr;\n }\n }\n\n void send(std::list& msgs)\n {\n auto it = msgs.begin();\n \n while(it != msgs.end())\n {\n if(publisher_->write((void*)&(*it)))\n {\n it = msgs.erase(it);\n }\n else\n break;\n }\n }\n\n void waitDiscovery()\n {\n std::cout << \"Writer waiting for discovery...\" << std::endl;\n std::unique_lock lock(mutex_);\n\n if(matched_ == 0)\n cv_.wait_for(lock, std::chrono::seconds(10));\n\n std::cout << \"Writer discovery phase finished\" << std::endl;\n }\n\n void waitRemoval()\n {\n std::unique_lock lock(mutex_);\n\n if(matched_ != 0)\n cv_.wait_for(lock, std::chrono::seconds(10));\n }\n\n bool waitForAllAcked(const std::chrono::seconds& max_wait)\n {\n return publisher_->wait_for_all_acked(Time_t((int32_t)max_wait.count(), 0));\n }\n\n \/*** Function to change QoS ***\/\n PubSubWriter& reliability(const eprosima::fastrtps::ReliabilityQosPolicyKind kind)\n {\n publisher_attr_.qos.m_reliability.kind = kind;\n return *this;\n }\n\n PubSubWriter& asynchronously(const eprosima::fastrtps::PublishModeQosPolicyKind kind)\n {\n publisher_attr_.qos.m_publishMode.kind = kind;\n return *this;\n }\n\n PubSubWriter& history_kind(const eprosima::fastrtps::HistoryQosPolicyKind kind)\n {\n publisher_attr_.topic.historyQos.kind = kind;\n return *this;\n }\n\n PubSubWriter& history_depth(const int32_t depth)\n {\n publisher_attr_.topic.historyQos.depth = depth;\n return *this;\n }\n\n PubSubWriter& durability_kind(const eprosima::fastrtps::DurabilityQosPolicyKind kind)\n {\n publisher_attr_.qos.m_durability.kind = kind;\n return *this;\n }\n\n PubSubWriter& resource_limits_max_samples(const int32_t max)\n {\n publisher_attr_.topic.resourceLimitsQos.max_samples = max;\n return *this;\n }\n\n PubSubWriter& heartbeat_period_seconds(int32_t sec)\n {\n publisher_attr_.times.heartbeatPeriod.seconds = sec;\n return *this;\n }\n\n PubSubWriter& heartbeat_period_fraction(uint32_t frac)\n {\n publisher_attr_.times.heartbeatPeriod.fraction = frac;\n return *this;\n }\n\n private:\n\n void matched()\n {\n std::unique_lock lock(mutex_);\n ++matched_;\n cv_.notify_one();\n }\n\n void unmatched()\n {\n std::unique_lock lock(mutex_);\n --matched_;\n cv_.notify_one();\n }\n\n PubSubWriter& operator=(const PubSubWriter&)NON_COPYABLE_CXX11;\n\n eprosima::fastrtps::Participant *participant_;\n eprosima::fastrtps::PublisherAttributes publisher_attr_;\n eprosima::fastrtps::Publisher *publisher_;\n std::string topic_name_;\n bool initialized_;\n std::mutex mutex_;\n std::condition_variable cv_;\n unsigned int matched_;\n type_support type_;\n};\n\n#endif \/\/ _TEST_PROFILING_PUBSUBWRITER_HPP_\nRefs #1706. Remove reference to gtest\/\/ Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima).\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/**\n * @file PubSubWriter.hpp\n *\n *\/\n\n#ifndef _TEST_PROFILING_PUBSUBWRITER_HPP_\n#define _TEST_PROFILING_PUBSUBWRITER_HPP_\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\ntemplate\nclass PubSubWriter \n{\n class Listener : public eprosima::fastrtps::PublisherListener\n {\n public:\n\n Listener(PubSubWriter &writer) : writer_(writer){};\n\n ~Listener(){};\n\n void onPublicationMatched(eprosima::fastrtps::Publisher* \/*pub*\/, MatchingInfo &info)\n {\n if (info.status == MATCHED_MATCHING)\n writer_.matched();\n else\n writer_.unmatched();\n }\n\n private:\n\n Listener& operator=(const Listener&) NON_COPYABLE_CXX11;\n\n PubSubWriter &writer_;\n\n } listener_;\n\n public:\n\n typedef TypeSupport type_support;\n typedef typename type_support::type type;\n\n PubSubWriter(const std::string &topic_name) : listener_(*this), participant_(nullptr),\n publisher_(nullptr), topic_name_(topic_name), initialized_(false), matched_(0)\n {\n publisher_attr_.topic.topicDataType = type_.getName();\n \/\/ Generate topic name\n std::ostringstream t;\n t << topic_name_ << \"_\" << boost::asio::ip::host_name() << \"_\" << boost::interprocess::ipcdetail::get_current_process_id();\n publisher_attr_.topic.topicName = t.str();\n }\n \n ~PubSubWriter()\n {\n if(participant_ != nullptr)\n eprosima::fastrtps::Domain::removeParticipant(participant_);\n }\n\n void init()\n {\n \/\/Create participant\n eprosima::fastrtps::ParticipantAttributes pattr;\n pattr.rtps.builtin.domainId = (uint32_t)boost::interprocess::ipcdetail::get_current_process_id() % 230;\n participant_ = eprosima::fastrtps::Domain::createParticipant(pattr);\n\n if(participant_ != nullptr)\n {\n \/\/ Register type\n eprosima::fastrtps::Domain::registerType(participant_, &type_);\n\n \/\/Create publisher\n publisher_ = eprosima::fastrtps::Domain::createPublisher(participant_, publisher_attr_, &listener_);\n\n if(publisher_ != nullptr)\n {\n initialized_ = true;\n return;\n }\n\n eprosima::fastrtps::Domain::removeParticipant(participant_);\n }\n }\n\n bool isInitialized() const { return initialized_; }\n\n void destroy()\n {\n if(participant_ != nullptr)\n {\n eprosima::fastrtps::Domain::removeParticipant(participant_);\n participant_ = nullptr;\n }\n }\n\n void send(std::list& msgs)\n {\n auto it = msgs.begin();\n \n while(it != msgs.end())\n {\n if(publisher_->write((void*)&(*it)))\n {\n it = msgs.erase(it);\n }\n else\n break;\n }\n }\n\n void waitDiscovery()\n {\n std::cout << \"Writer waiting for discovery...\" << std::endl;\n std::unique_lock lock(mutex_);\n\n if(matched_ == 0)\n cv_.wait_for(lock, std::chrono::seconds(10));\n\n std::cout << \"Writer discovery phase finished\" << std::endl;\n }\n\n void waitRemoval()\n {\n std::unique_lock lock(mutex_);\n\n if(matched_ != 0)\n cv_.wait_for(lock, std::chrono::seconds(10));\n }\n\n bool waitForAllAcked(const std::chrono::seconds& max_wait)\n {\n return publisher_->wait_for_all_acked(Time_t((int32_t)max_wait.count(), 0));\n }\n\n \/*** Function to change QoS ***\/\n PubSubWriter& reliability(const eprosima::fastrtps::ReliabilityQosPolicyKind kind)\n {\n publisher_attr_.qos.m_reliability.kind = kind;\n return *this;\n }\n\n PubSubWriter& asynchronously(const eprosima::fastrtps::PublishModeQosPolicyKind kind)\n {\n publisher_attr_.qos.m_publishMode.kind = kind;\n return *this;\n }\n\n PubSubWriter& history_kind(const eprosima::fastrtps::HistoryQosPolicyKind kind)\n {\n publisher_attr_.topic.historyQos.kind = kind;\n return *this;\n }\n\n PubSubWriter& history_depth(const int32_t depth)\n {\n publisher_attr_.topic.historyQos.depth = depth;\n return *this;\n }\n\n PubSubWriter& durability_kind(const eprosima::fastrtps::DurabilityQosPolicyKind kind)\n {\n publisher_attr_.qos.m_durability.kind = kind;\n return *this;\n }\n\n PubSubWriter& resource_limits_max_samples(const int32_t max)\n {\n publisher_attr_.topic.resourceLimitsQos.max_samples = max;\n return *this;\n }\n\n PubSubWriter& heartbeat_period_seconds(int32_t sec)\n {\n publisher_attr_.times.heartbeatPeriod.seconds = sec;\n return *this;\n }\n\n PubSubWriter& heartbeat_period_fraction(uint32_t frac)\n {\n publisher_attr_.times.heartbeatPeriod.fraction = frac;\n return *this;\n }\n\n private:\n\n void matched()\n {\n std::unique_lock lock(mutex_);\n ++matched_;\n cv_.notify_one();\n }\n\n void unmatched()\n {\n std::unique_lock lock(mutex_);\n --matched_;\n cv_.notify_one();\n }\n\n PubSubWriter& operator=(const PubSubWriter&)NON_COPYABLE_CXX11;\n\n eprosima::fastrtps::Participant *participant_;\n eprosima::fastrtps::PublisherAttributes publisher_attr_;\n eprosima::fastrtps::Publisher *publisher_;\n std::string topic_name_;\n bool initialized_;\n std::mutex mutex_;\n std::condition_variable cv_;\n unsigned int matched_;\n type_support type_;\n};\n\n#endif \/\/ _TEST_PROFILING_PUBSUBWRITER_HPP_\n<|endoftext|>"} {"text":"\/\/ Copyright 2004-present Facebook. All Rights Reserved.\n\n#include \n#include \n#include \n#include \"src\/FrameTransport.h\"\n#include \"src\/NullRequestHandler.h\"\n#include \"src\/SmartPointers.h\"\n#include \"src\/StandardReactiveSocket.h\"\n#include \"src\/SubscriptionBase.h\"\n#include \"src\/framed\/FramedDuplexConnection.h\"\n#include \"src\/tcp\/TcpDuplexConnection.h\"\n#include \"test\/simple\/PrintSubscriber.h\"\n#include \"test\/simple\/StatsPrinter.h\"\n\nusing namespace ::testing;\nusing namespace ::reactivesocket;\nusing namespace ::folly;\n\nDEFINE_string(address, \"9898\", \"host:port to listen to\");\n\nnamespace {\n\nstd::vector,\n ResumeIdentificationToken>>\n g_reactiveSockets;\n\nclass ServerSubscription : public SubscriptionBase {\n public:\n explicit ServerSubscription(std::shared_ptr> response)\n : ExecutorBase(defaultExecutor()), response_(std::move(response)) {}\n\n ~ServerSubscription() {\n LOG(INFO) << \"~ServerSubscription \" << this;\n }\n\n \/\/ Subscription methods\n void requestImpl(size_t n) override {\n LOG(INFO) << \"request \" << this;\n response_.onNext(Payload(\"from server\"));\n response_.onNext(Payload(\"from server2\"));\n LOG(INFO) << \"calling onComplete\";\n response_.onComplete();\n \/\/ response_.onError(std::runtime_error(\"XXX\"));\n }\n\n void cancelImpl() override {\n LOG(INFO) << \"cancel \" << this;\n }\n\n private:\n SubscriberPtr> response_;\n};\n\nclass ServerRequestHandler : public DefaultRequestHandler {\n public:\n explicit ServerRequestHandler(std::shared_ptr streamState)\n : streamState_(streamState) {}\n\n \/\/\/ Handles a new inbound Subscription requested by the other end.\n void handleRequestSubscription(\n Payload request,\n StreamId streamId,\n const std::shared_ptr>& response) override {\n LOG(INFO) << \"ServerRequestHandler.handleRequestSubscription \" << request;\n response->onSubscribe(std::make_shared(response));\n }\n\n \/\/\/ Handles a new inbound Stream requested by the other end.\n void handleRequestStream(\n Payload request,\n StreamId streamId,\n const std::shared_ptr>& response) override {\n LOG(INFO) << \"ServerRequestHandler.handleRequestStream \" << request;\n\n response->onSubscribe(std::make_shared(response));\n }\n\n void handleFireAndForgetRequest(Payload request, StreamId streamId) override {\n LOG(INFO) << \"ServerRequestHandler.handleFireAndForgetRequest \" << request\n << \"\\n\";\n }\n\n void handleMetadataPush(std::unique_ptr request) override {\n LOG(INFO) << \"ServerRequestHandler.handleMetadataPush \"\n << request->moveToFbString() << \"\\n\";\n }\n\n std::shared_ptr handleSetupPayload(\n ReactiveSocket& socket,\n ConnectionSetupPayload request) override {\n std::stringstream str;\n\n str << \"ServerRequestHandler.handleSetupPayload \" << request\n << \" setup token <\";\n for (uint8_t byte : request.token.data()) {\n str << (int)byte;\n }\n str << \"> \" << streamState_.get() << \" \" << streamState_->streams_.size()\n << \"\\n\";\n LOG(INFO) << str.str();\n \/\/ TODO: we need to get ReactiveSocket pointer somehow\n g_reactiveSockets[0].second = request.token;\n \/\/ TODO: the return value is not used now\n return streamState_;\n }\n\n bool handleResume(\n ReactiveSocket& socket,\n const ResumeIdentificationToken& token,\n ResumePosition position) override {\n std::stringstream str;\n\n str << \"ServerRequestHandler.handleResume resume token <\";\n for (uint8_t byte : token.data()) {\n str << (int)byte;\n }\n str << \"> \" << streamState_.get() << \" \" << streamState_->streams_.size()\n << \"\\n\";\n\n LOG(INFO) << str.str();\n\n CHECK(g_reactiveSockets.size() == 2);\n CHECK(g_reactiveSockets[0].second == token);\n\n LOG(INFO) << \"detaching frame transport\";\n auto frameTransport = g_reactiveSockets[1].first->detachFrameTransport();\n LOG(INFO) << \"tryResumeServer...\";\n auto result =\n g_reactiveSockets[0].first->tryResumeServer(frameTransport, position);\n LOG(INFO) << \"resume \" << (result ? \"SUCCEEDED\" : \"FAILED\");\n\n \/\/ TODO(lehecka): unused, make it used again\n \/\/ return streamState_;\n return false;\n }\n\n void handleCleanResume(std::shared_ptr response) override {\n LOG(INFO) << \"clean resume stream\"\n << \"\\n\";\n }\n\n void handleDirtyResume(std::shared_ptr response) override {\n LOG(INFO) << \"dirty resume stream\"\n << \"\\n\";\n }\n\n private:\n \/\/ only keeping one\n std::shared_ptr streamState_;\n};\n\nclass Callback : public AsyncServerSocket::AcceptCallback {\n public:\n Callback(EventBase& eventBase, Stats& stats)\n : streamState_(std::make_shared(Stats::noop())),\n eventBase_(eventBase),\n stats_(stats){};\n\n virtual ~Callback() = default;\n\n virtual void connectionAccepted(\n int fd,\n const SocketAddress& clientAddr) noexcept override {\n LOG(INFO) << \"connectionAccepted\" << clientAddr.describe();\n\n auto socket =\n folly::AsyncSocket::UniquePtr(new AsyncSocket(&eventBase_, fd));\n\n std::unique_ptr connection =\n folly::make_unique(std::move(socket), stats_);\n std::unique_ptr framedConnection =\n folly::make_unique(\n std::move(connection), inlineExecutor());\n std::unique_ptr requestHandler =\n folly::make_unique(streamState_);\n\n std::unique_ptr rs =\n StandardReactiveSocket::disconnectedServer(\n eventBase_, std::move(requestHandler), stats_);\n\n rs->onConnected([](ReactiveSocket& socket) {\n LOG(INFO) << \"socket connected \" << &socket;\n });\n rs->onDisconnected([](ReactiveSocket& socket) {\n LOG(INFO) << \"socket disconnect \" << &socket;\n \/\/ to verify these frames will be queued up\n socket.requestStream(\n Payload(\"from server resume\"), std::make_shared());\n });\n rs->onClosed([](ReactiveSocket& socket) {\n LOG(INFO) << \"socket closed \" << &socket;\n });\n\n if (g_reactiveSockets.empty()) {\n LOG(INFO) << \"requestStream\";\n rs->requestStream(\n Payload(\"from server\"), std::make_shared());\n }\n\n LOG(INFO) << \"serverConnecting ...\";\n rs->serverConnect(\n std::make_shared(std::move(framedConnection)), true);\n\n LOG(INFO) << \"RS \" << rs.get();\n\n g_reactiveSockets.emplace_back(\n std::move(rs), ResumeIdentificationToken::generateNew());\n }\n\n void removeSocket(ReactiveSocket& socket) {\n if (!shuttingDown) {\n g_reactiveSockets.erase(std::remove_if(\n g_reactiveSockets.begin(),\n g_reactiveSockets.end(),\n [&socket](const std::pair<\n std::unique_ptr,\n ResumeIdentificationToken>& kv) {\n return kv.first.get() == &socket;\n }));\n }\n }\n\n virtual void acceptError(const std::exception& ex) noexcept override {\n LOG(INFO) << \"acceptError\" << ex.what();\n }\n\n void shutdown() {\n shuttingDown = true;\n g_reactiveSockets.clear();\n }\n\n private:\n \/\/ only one for demo purposes. Should be token dependent.\n std::shared_ptr streamState_;\n EventBase& eventBase_;\n Stats& stats_;\n bool shuttingDown{false};\n};\n}\n\nint main(int argc, char* argv[]) {\n FLAGS_logtostderr = true;\n FLAGS_minloglevel = 0;\n\n google::ParseCommandLineFlags(&argc, &argv, true);\n google::InitGoogleLogging(argv[0]);\n google::InstallFailureSignalHandler();\n\n reactivesocket::StatsPrinter statsPrinter;\n\n EventBase eventBase;\n auto thread = std::thread([&eventBase]() { eventBase.loopForever(); });\n\n Callback callback(eventBase, statsPrinter);\n\n auto serverSocket = AsyncServerSocket::newSocket(&eventBase);\n\n eventBase.runInEventBaseThreadAndWait(\n [&callback, &eventBase, &serverSocket]() {\n folly::SocketAddress addr;\n addr.setFromLocalIpPort(FLAGS_address);\n\n serverSocket->setReusePortEnabled(true);\n serverSocket->bind(addr);\n serverSocket->addAcceptCallback(&callback, &eventBase);\n serverSocket->listen(10);\n serverSocket->startAccepting();\n\n LOG(INFO) << \"server listening on \";\n for (auto i : serverSocket->getAddresses())\n LOG(INFO) << i.describe() << ' ';\n });\n\n std::string name;\n std::getline(std::cin, name);\n\n eventBase.runInEventBaseThreadAndWait([&callback]() { callback.shutdown(); });\n eventBase.terminateLoopSoon();\n\n thread.join();\n}\nfixing travis\/\/ Copyright 2004-present Facebook. All Rights Reserved.\n\n#include \n#include \n#include \n#include \"src\/FrameTransport.h\"\n#include \"src\/NullRequestHandler.h\"\n#include \"src\/SmartPointers.h\"\n#include \"src\/StandardReactiveSocket.h\"\n#include \"src\/SubscriptionBase.h\"\n#include \"src\/framed\/FramedDuplexConnection.h\"\n#include \"src\/tcp\/TcpDuplexConnection.h\"\n#include \"test\/simple\/PrintSubscriber.h\"\n#include \"test\/simple\/StatsPrinter.h\"\n\nusing namespace ::testing;\nusing namespace ::reactivesocket;\nusing namespace ::folly;\n\nDEFINE_string(address, \"9898\", \"host:port to listen to\");\n\nnamespace {\n\nstd::vector,\n ResumeIdentificationToken>>\n g_reactiveSockets;\n\nclass ServerSubscription : public SubscriptionBase {\n public:\n explicit ServerSubscription(std::shared_ptr> response)\n : ExecutorBase(defaultExecutor()), response_(std::move(response)) {}\n\n ~ServerSubscription() {\n LOG(INFO) << \"~ServerSubscription \" << this;\n }\n\n \/\/ Subscription methods\n void requestImpl(size_t n) override {\n LOG(INFO) << \"request \" << this;\n response_.onNext(Payload(\"from server\"));\n response_.onNext(Payload(\"from server2\"));\n LOG(INFO) << \"calling onComplete\";\n response_.onComplete();\n \/\/ response_.onError(std::runtime_error(\"XXX\"));\n }\n\n void cancelImpl() override {\n LOG(INFO) << \"cancel \" << this;\n }\n\n private:\n SubscriberPtr> response_;\n};\n\nclass ServerRequestHandler : public DefaultRequestHandler {\n public:\n explicit ServerRequestHandler(std::shared_ptr streamState)\n : streamState_(streamState) {}\n\n \/\/\/ Handles a new inbound Subscription requested by the other end.\n void handleRequestSubscription(\n Payload request,\n StreamId streamId,\n const std::shared_ptr>& response) override {\n LOG(INFO) << \"ServerRequestHandler.handleRequestSubscription \" << request;\n response->onSubscribe(std::make_shared(response));\n }\n\n \/\/\/ Handles a new inbound Stream requested by the other end.\n void handleRequestStream(\n Payload request,\n StreamId streamId,\n const std::shared_ptr>& response) override {\n LOG(INFO) << \"ServerRequestHandler.handleRequestStream \" << request;\n\n response->onSubscribe(std::make_shared(response));\n }\n\n void handleFireAndForgetRequest(Payload request, StreamId streamId) override {\n LOG(INFO) << \"ServerRequestHandler.handleFireAndForgetRequest \" << request\n << \"\\n\";\n }\n\n void handleMetadataPush(std::unique_ptr request) override {\n LOG(INFO) << \"ServerRequestHandler.handleMetadataPush \"\n << request->moveToFbString() << \"\\n\";\n }\n\n std::shared_ptr handleSetupPayload(\n ReactiveSocket& socket,\n ConnectionSetupPayload request) override {\n std::stringstream str;\n\n str << \"ServerRequestHandler.handleSetupPayload \" << request\n << \" setup token <\";\n for (uint8_t byte : request.token.data()) {\n str << (int)byte;\n }\n str << \"> \" << streamState_.get() << \" \" << streamState_->streams_.size()\n << \"\\n\";\n LOG(INFO) << str.str();\n \/\/ TODO: we need to get ReactiveSocket pointer somehow\n g_reactiveSockets[0].second = request.token;\n \/\/ TODO: the return value is not used now\n return streamState_;\n }\n\n bool handleResume(\n ReactiveSocket& socket,\n const ResumeIdentificationToken& token,\n ResumePosition position) override {\n std::stringstream str;\n\n str << \"ServerRequestHandler.handleResume resume token <\";\n for (uint8_t byte : token.data()) {\n str << (int)byte;\n }\n str << \"> \" << streamState_.get() << \" \" << streamState_->streams_.size()\n << \"\\n\";\n\n LOG(INFO) << str.str();\n\n CHECK(g_reactiveSockets.size() == 2);\n CHECK(g_reactiveSockets[0].second == token);\n\n LOG(INFO) << \"detaching frame transport\";\n auto frameTransport = g_reactiveSockets[1].first->detachFrameTransport();\n LOG(INFO) << \"tryResumeServer...\";\n auto result =\n g_reactiveSockets[0].first->tryResumeServer(frameTransport, position);\n LOG(INFO) << \"resume \" << (result ? \"SUCCEEDED\" : \"FAILED\");\n\n \/\/ TODO(lehecka): unused, make it used again\n \/\/ return streamState_;\n return false;\n }\n\n void handleCleanResume(std::shared_ptr response) override {\n LOG(INFO) << \"clean resume stream\"\n << \"\\n\";\n }\n\n void handleDirtyResume(std::shared_ptr response) override {\n LOG(INFO) << \"dirty resume stream\"\n << \"\\n\";\n }\n\n private:\n \/\/ only keeping one\n std::shared_ptr streamState_;\n};\n\nclass Callback : public AsyncServerSocket::AcceptCallback {\n public:\n Callback(EventBase& eventBase, Stats& stats)\n : streamState_(std::make_shared(Stats::noop())),\n eventBase_(eventBase),\n stats_(stats){};\n\n virtual ~Callback() = default;\n\n virtual void connectionAccepted(\n int fd,\n const SocketAddress& clientAddr) noexcept override {\n LOG(INFO) << \"connectionAccepted\" << clientAddr.describe();\n\n auto socket =\n folly::AsyncSocket::UniquePtr(new AsyncSocket(&eventBase_, fd));\n\n std::unique_ptr connection =\n folly::make_unique(std::move(socket), stats_);\n std::unique_ptr framedConnection =\n folly::make_unique(\n std::move(connection), inlineExecutor());\n std::unique_ptr requestHandler =\n folly::make_unique(streamState_);\n\n std::unique_ptr rs =\n StandardReactiveSocket::disconnectedServer(\n eventBase_, std::move(requestHandler), stats_);\n\n rs->onConnected([](ReactiveSocket& socket) {\n LOG(INFO) << \"socket connected \" << &socket;\n });\n rs->onDisconnected([](ReactiveSocket& socket) {\n LOG(INFO) << \"socket disconnect \" << &socket;\n \/\/ to verify these frames will be queued up\n socket.requestStream(\n Payload(\"from server resume\"), std::make_shared());\n });\n rs->onClosed([](ReactiveSocket& socket) {\n LOG(INFO) << \"socket closed \" << &socket;\n });\n\n if (g_reactiveSockets.empty()) {\n LOG(INFO) << \"requestStream\";\n rs->requestStream(\n Payload(\"from server\"), std::make_shared());\n }\n\n LOG(INFO) << \"serverConnecting ...\";\n rs->serverConnect(\n std::make_shared(std::move(framedConnection)), true);\n\n LOG(INFO) << \"RS \" << rs.get();\n\n g_reactiveSockets.emplace_back(\n std::move(rs), ResumeIdentificationToken::generateNew());\n }\n\n void removeSocket(ReactiveSocket& socket) {\n if (!shuttingDown) {\n g_reactiveSockets.erase(std::remove_if(\n g_reactiveSockets.begin(),\n g_reactiveSockets.end(),\n [&socket](const std::pair<\n std::unique_ptr,\n ResumeIdentificationToken>& kv) {\n return kv.first.get() == &socket;\n }));\n }\n }\n\n virtual void acceptError(const std::exception& ex) noexcept override {\n LOG(INFO) << \"acceptError\" << ex.what();\n }\n\n void shutdown() {\n shuttingDown = true;\n g_reactiveSockets.clear();\n }\n\n private:\n \/\/ only one for demo purposes. Should be token dependent.\n std::shared_ptr streamState_;\n EventBase& eventBase_;\n Stats& stats_;\n bool shuttingDown{false};\n};\n}\n\nint main(int argc, char* argv[]) {\n FLAGS_logtostderr = true;\n FLAGS_minloglevel = 0;\n\n google::ParseCommandLineFlags(&argc, &argv, true);\n google::InitGoogleLogging(argv[0]);\n google::InstallFailureSignalHandler();\n\n reactivesocket::StatsPrinter statsPrinter;\n\n EventBase eventBase;\n auto thread = std::thread([&eventBase]() { eventBase.loopForever(); });\n\n Callback callback(eventBase, statsPrinter);\n\n auto serverSocket = AsyncServerSocket::newSocket(&eventBase);\n\n eventBase.runInEventBaseThreadAndWait(\n [&callback, &eventBase, &serverSocket]() {\n folly::SocketAddress addr;\n addr.setFromLocalIpPort(FLAGS_address);\n\n serverSocket->setReusePortEnabled(true);\n serverSocket->bind(addr);\n serverSocket->addAcceptCallback(&callback, &eventBase);\n serverSocket->listen(10);\n serverSocket->startAccepting();\n\n LOG(INFO) << \"server listening on \";\n for (auto i : serverSocket->getAddresses())\n LOG(INFO) << i.describe() << ' ';\n });\n\n std::string name;\n std::getline(std::cin, name);\n\n eventBase.runInEventBaseThreadAndWait([&callback]() { callback.shutdown(); });\n eventBase.terminateLoopSoon();\n\n thread.join();\n}\n<|endoftext|>"} {"text":"Update: system_io prototype<|endoftext|>"} {"text":"\/**\n * @file nearest_neighbor_rules_impl.hpp\n * @author Ryan Curtin\n *\n * Implementation of NearestNeighborRules.\n *\/\n#ifndef __MLPACK_METHODS_NEIGHBOR_SEARCH_NEAREST_NEIGHBOR_RULES_IMPL_HPP\n#define __MLPACK_METHODS_NEIGHBOR_SEARCH_NEAREST_NEIGHBOR_RULES_IMPL_HPP\n\n\/\/ In case it hasn't been included yet.\n#include \"neighbor_search_rules.hpp\"\n\nnamespace mlpack {\nnamespace neighbor {\n\ntemplate\nNeighborSearchRules::NeighborSearchRules(\n const arma::mat& referenceSet,\n const arma::mat& querySet,\n arma::Mat& neighbors,\n arma::mat& distances,\n MetricType& metric) :\n referenceSet(referenceSet),\n querySet(querySet),\n neighbors(neighbors),\n distances(distances),\n metric(metric)\n{ \/* Nothing left to do. *\/ }\n\ntemplate\ninline force_inline \/\/ Absolutely MUST be inline so optimizations can happen.\ndouble NeighborSearchRules::\nBaseCase(const size_t queryIndex, const size_t referenceIndex)\n{\n \/\/ If the datasets are the same, then this search is only using one dataset\n \/\/ and we should not return identical points.\n if ((&querySet == &referenceSet) && (queryIndex == referenceIndex))\n return 0.0;\n\n double distance = metric.Evaluate(querySet.unsafe_col(queryIndex),\n referenceSet.unsafe_col(referenceIndex));\n\n \/\/ If this distance is better than any of the current candidates, the\n \/\/ SortDistance() function will give us the position to insert it into.\n arma::vec queryDist = distances.unsafe_col(queryIndex);\n size_t insertPosition = SortPolicy::SortDistance(queryDist, distance);\n\n \/\/ SortDistance() returns (size_t() - 1) if we shouldn't add it.\n if (insertPosition != (size_t() - 1))\n InsertNeighbor(queryIndex, insertPosition, referenceIndex, distance);\n\n return distance;\n}\n\ntemplate\ninline double NeighborSearchRules::Prescore(\n TreeType& queryNode,\n TreeType& referenceNode,\n TreeType& referenceChildNode,\n const double baseCaseResult) const\n{\n const double distance = SortPolicy::BestNodeToNodeDistance(&queryNode,\n &referenceNode, &referenceChildNode, baseCaseResult);\n\n \/\/ Update our bound.\n queryNode.Stat().Bound() = CalculateBound(queryNode);\n const double bestDistance = queryNode.Stat().Bound();\n\n return (SortPolicy::IsBetter(distance, bestDistance)) ? distance : DBL_MAX;\n}\n\ntemplate\ninline double NeighborSearchRules::PrescoreQ(\n TreeType& queryNode,\n TreeType& queryChildNode,\n TreeType& referenceNode,\n const double baseCaseResult) const\n{\n const double distance = SortPolicy::BestNodeToNodeDistance(&referenceNode,\n &queryNode, &queryChildNode, baseCaseResult);\n\n \/\/ Update our bound.\n queryNode.Stat().Bound() = CalculateBound(queryNode);\n const double bestDistance = queryNode.Stat().Bound();\n\n return (SortPolicy::IsBetter(distance, bestDistance)) ? distance : DBL_MAX;\n}\n\ntemplate\ninline double NeighborSearchRules::Score(\n const size_t queryIndex,\n TreeType& referenceNode) const\n{\n const arma::vec queryPoint = querySet.unsafe_col(queryIndex);\n const double distance = SortPolicy::BestPointToNodeDistance(queryPoint,\n &referenceNode);\n const double bestDistance = distances(distances.n_rows - 1, queryIndex);\n\n return (SortPolicy::IsBetter(distance, bestDistance)) ? distance : DBL_MAX;\n}\n\ntemplate\ninline double NeighborSearchRules::Score(\n const size_t queryIndex,\n TreeType& referenceNode,\n const double baseCaseResult) const\n{\n const arma::vec queryPoint = querySet.unsafe_col(queryIndex);\n const double distance = SortPolicy::BestPointToNodeDistance(queryPoint,\n &referenceNode, baseCaseResult);\n const double bestDistance = distances(distances.n_rows - 1, queryIndex);\n\n return (SortPolicy::IsBetter(distance, bestDistance)) ? distance : DBL_MAX;\n}\n\ntemplate\ninline double NeighborSearchRules::Rescore(\n const size_t queryIndex,\n TreeType& \/* referenceNode *\/,\n const double oldScore) const\n{\n \/\/ If we are already pruning, still prune.\n if (oldScore == DBL_MAX)\n return oldScore;\n\n \/\/ Just check the score again against the distances.\n const double bestDistance = distances(distances.n_rows - 1, queryIndex);\n\n return (SortPolicy::IsBetter(oldScore, bestDistance)) ? oldScore : DBL_MAX;\n}\n\ntemplate\ninline double NeighborSearchRules::Score(\n TreeType& queryNode,\n TreeType& referenceNode) const\n{\n const double distance = SortPolicy::BestNodeToNodeDistance(&queryNode,\n &referenceNode);\n\n \/\/ Update our bound.\n queryNode.Stat().Bound() = CalculateBound(queryNode);\n const double bestDistance = queryNode.Stat().Bound();\n\n return (SortPolicy::IsBetter(distance, bestDistance)) ? distance : DBL_MAX;\n}\n\ntemplate\ninline double NeighborSearchRules::Score(\n TreeType& queryNode,\n TreeType& referenceNode,\n const double baseCaseResult) const\n{\n const double distance = SortPolicy::BestNodeToNodeDistance(&queryNode,\n &referenceNode, baseCaseResult);\n\n \/\/ Update our bound.\n queryNode.Stat().Bound() = CalculateBound(queryNode);\n const double bestDistance = queryNode.Stat().Bound();\n\n return (SortPolicy::IsBetter(distance, bestDistance)) ? distance : DBL_MAX;\n}\n\ntemplate\ninline double NeighborSearchRules::Rescore(\n TreeType& queryNode,\n TreeType& \/* referenceNode *\/,\n const double oldScore) const\n{\n if (oldScore == DBL_MAX)\n return oldScore;\n\n \/\/ Update our bound.\n queryNode.Stat().Bound() = CalculateBound(queryNode);\n const double bestDistance = queryNode.Stat().Bound();\n\n return (SortPolicy::IsBetter(oldScore, bestDistance)) ? oldScore : DBL_MAX;\n}\n\/*\ntemplate\ninline double NeighborSearchRules::FinishNode(\n TreeType& queryNode) const\n{\n \/\/ Find the bound of points contained in this node.\n double pointBound = SortPolicy::BestDistance();\n const double maxDescendantDistance = queryNode.FurthestDescendantDistance();\n\n for (size_t i = 0; i < queryNode.NumPoints(); ++i)\n {\n \/\/ The bound for this point is the k-th best distance plus the maximum\n \/\/ distance to a child of this node.\n const double bound = distances(distances.n_rows - 1, queryNode.Point(i)) +\n maxDescendantDistance;\n if (SortPolicy::IsBetter(pointBound, bound))\n pointBound = bound;\n }\n\n \/\/ Push bound to parent.\n}\n*\/\n\n\/\/ Calculate the bound for a given query node in its current state.\ntemplate\ninline double NeighborSearchRules::\n CalculateBound(TreeType& queryNode) const\n{\n double pointBound = SortPolicy::BestDistance();\n double childBound = SortPolicy::BestDistance();\n const double maxDescendantDistance = queryNode.FurthestDescendantDistance();\n\n \/\/ Find the bound of the points contained in this node.\n for (size_t i = 0; i < queryNode.NumPoints(); ++i)\n {\n \/\/ The bound for this point is the k-th best distance plus the maximum\n \/\/ distance to a child of this node.\n const double bound = distances(distances.n_rows - 1, queryNode.Point(i)) +\n maxDescendantDistance;\n if (SortPolicy::IsBetter(pointBound, bound))\n pointBound = bound;\n }\n\n \/\/ Find the bound of the children.\n for (size_t i = 0; i < queryNode.NumChildren(); ++i)\n {\n const double bound = queryNode.Child(i).Stat().Bound();\n if (SortPolicy::IsBetter(childBound, bound))\n childBound = bound;\n }\n\n \/\/ If the bound of the children is uninitialized\n \/\/ (SortPolicy::WorstDistance()), then maybe we can create a bound for the\n \/\/ children. But this requires a point bound to exist.\n if (childBound == SortPolicy::WorstDistance() &&\n pointBound != SortPolicy::BestDistance()) \/\/ This could fail!\n \/\/ SortPolicy::BestDistance() could be a valid bound!\n {\n \/\/ Should we be considering queryNode.Stat().Bound() too?\n childBound = pointBound + maxDescendantDistance;\n Log::Debug << \"Child bound is \" << childBound << std::endl;\n }\n\n \/\/ Return the worse of the two bounds.\n if (SortPolicy::IsBetter(childBound, pointBound))\n return pointBound;\n else\n return childBound;\n}\n\n\/**\n * Helper function to insert a point into the neighbors and distances matrices.\n *\n * @param queryIndex Index of point whose neighbors we are inserting into.\n * @param pos Position in list to insert into.\n * @param neighbor Index of reference point which is being inserted.\n * @param distance Distance from query point to reference point.\n *\/\ntemplate\nvoid NeighborSearchRules::InsertNeighbor(\n const size_t queryIndex,\n const size_t pos,\n const size_t neighbor,\n const double distance)\n{\n \/\/ We only memmove() if there is actually a need to shift something.\n if (pos < (distances.n_rows - 1))\n {\n int len = (distances.n_rows - 1) - pos;\n memmove(distances.colptr(queryIndex) + (pos + 1),\n distances.colptr(queryIndex) + pos,\n sizeof(double) * len);\n memmove(neighbors.colptr(queryIndex) + (pos + 1),\n neighbors.colptr(queryIndex) + pos,\n sizeof(size_t) * len);\n }\n\n \/\/ Now put the new information in the right index.\n distances(pos, queryIndex) = distance;\n neighbors(pos, queryIndex) = neighbor;\n}\n\n}; \/\/ namespace neighbor\n}; \/\/ namespace mlpack\n\n#endif \/\/ __MLPACK_METHODS_NEIGHBOR_SEARCH_NEAREST_NEIGHBOR_RULES_IMPL_HPP\nBetter calculation of bound. We could still optimize a little bit. Debug output is for #243; this solves #264.\/**\n * @file nearest_neighbor_rules_impl.hpp\n * @author Ryan Curtin\n *\n * Implementation of NearestNeighborRules.\n *\/\n#ifndef __MLPACK_METHODS_NEIGHBOR_SEARCH_NEAREST_NEIGHBOR_RULES_IMPL_HPP\n#define __MLPACK_METHODS_NEIGHBOR_SEARCH_NEAREST_NEIGHBOR_RULES_IMPL_HPP\n\n\/\/ In case it hasn't been included yet.\n#include \"neighbor_search_rules.hpp\"\n\nnamespace mlpack {\nnamespace neighbor {\n\ntemplate\nNeighborSearchRules::NeighborSearchRules(\n const arma::mat& referenceSet,\n const arma::mat& querySet,\n arma::Mat& neighbors,\n arma::mat& distances,\n MetricType& metric) :\n referenceSet(referenceSet),\n querySet(querySet),\n neighbors(neighbors),\n distances(distances),\n metric(metric)\n{ \/* Nothing left to do. *\/ }\n\ntemplate\ninline force_inline \/\/ Absolutely MUST be inline so optimizations can happen.\ndouble NeighborSearchRules::\nBaseCase(const size_t queryIndex, const size_t referenceIndex)\n{\n \/\/ If the datasets are the same, then this search is only using one dataset\n \/\/ and we should not return identical points.\n if ((&querySet == &referenceSet) && (queryIndex == referenceIndex))\n return 0.0;\n\n double distance = metric.Evaluate(querySet.unsafe_col(queryIndex),\n referenceSet.unsafe_col(referenceIndex));\n\n \/\/ If this distance is better than any of the current candidates, the\n \/\/ SortDistance() function will give us the position to insert it into.\n arma::vec queryDist = distances.unsafe_col(queryIndex);\n size_t insertPosition = SortPolicy::SortDistance(queryDist, distance);\n\n \/\/ SortDistance() returns (size_t() - 1) if we shouldn't add it.\n if (insertPosition != (size_t() - 1))\n InsertNeighbor(queryIndex, insertPosition, referenceIndex, distance);\n\n return distance;\n}\n\ntemplate\ninline double NeighborSearchRules::Prescore(\n TreeType& queryNode,\n TreeType& referenceNode,\n TreeType& referenceChildNode,\n const double baseCaseResult) const\n{\n const double distance = SortPolicy::BestNodeToNodeDistance(&queryNode,\n &referenceNode, &referenceChildNode, baseCaseResult);\n\n \/\/ Update our bound.\n queryNode.Stat().Bound() = CalculateBound(queryNode);\n const double bestDistance = queryNode.Stat().Bound();\n\n return (SortPolicy::IsBetter(distance, bestDistance)) ? distance : DBL_MAX;\n}\n\ntemplate\ninline double NeighborSearchRules::PrescoreQ(\n TreeType& queryNode,\n TreeType& queryChildNode,\n TreeType& referenceNode,\n const double baseCaseResult) const\n{\n const double distance = SortPolicy::BestNodeToNodeDistance(&referenceNode,\n &queryNode, &queryChildNode, baseCaseResult);\n\n \/\/ Update our bound.\n queryNode.Stat().Bound() = CalculateBound(queryNode);\n const double bestDistance = queryNode.Stat().Bound();\n\n return (SortPolicy::IsBetter(distance, bestDistance)) ? distance : DBL_MAX;\n}\n\ntemplate\ninline double NeighborSearchRules::Score(\n const size_t queryIndex,\n TreeType& referenceNode) const\n{\n const arma::vec queryPoint = querySet.unsafe_col(queryIndex);\n const double distance = SortPolicy::BestPointToNodeDistance(queryPoint,\n &referenceNode);\n const double bestDistance = distances(distances.n_rows - 1, queryIndex);\n\n return (SortPolicy::IsBetter(distance, bestDistance)) ? distance : DBL_MAX;\n}\n\ntemplate\ninline double NeighborSearchRules::Score(\n const size_t queryIndex,\n TreeType& referenceNode,\n const double baseCaseResult) const\n{\n const arma::vec queryPoint = querySet.unsafe_col(queryIndex);\n const double distance = SortPolicy::BestPointToNodeDistance(queryPoint,\n &referenceNode, baseCaseResult);\n const double bestDistance = distances(distances.n_rows - 1, queryIndex);\n\n return (SortPolicy::IsBetter(distance, bestDistance)) ? distance : DBL_MAX;\n}\n\ntemplate\ninline double NeighborSearchRules::Rescore(\n const size_t queryIndex,\n TreeType& \/* referenceNode *\/,\n const double oldScore) const\n{\n \/\/ If we are already pruning, still prune.\n if (oldScore == DBL_MAX)\n return oldScore;\n\n \/\/ Just check the score again against the distances.\n const double bestDistance = distances(distances.n_rows - 1, queryIndex);\n\n return (SortPolicy::IsBetter(oldScore, bestDistance)) ? oldScore : DBL_MAX;\n}\n\ntemplate\ninline double NeighborSearchRules::Score(\n TreeType& queryNode,\n TreeType& referenceNode) const\n{\n const double distance = SortPolicy::BestNodeToNodeDistance(&queryNode,\n &referenceNode);\n\n \/\/ Update our bound.\n queryNode.Stat().Bound() = CalculateBound(queryNode);\n const double bestDistance = queryNode.Stat().Bound();\n\n return (SortPolicy::IsBetter(distance, bestDistance)) ? distance : DBL_MAX;\n}\n\ntemplate\ninline double NeighborSearchRules::Score(\n TreeType& queryNode,\n TreeType& referenceNode,\n const double baseCaseResult) const\n{\n const double distance = SortPolicy::BestNodeToNodeDistance(&queryNode,\n &referenceNode, baseCaseResult);\n\n \/\/ Update our bound.\n queryNode.Stat().Bound() = CalculateBound(queryNode);\n const double bestDistance = queryNode.Stat().Bound();\n\n return (SortPolicy::IsBetter(distance, bestDistance)) ? distance : DBL_MAX;\n}\n\ntemplate\ninline double NeighborSearchRules::Rescore(\n TreeType& queryNode,\n TreeType& \/* referenceNode *\/,\n const double oldScore) const\n{\n if (oldScore == DBL_MAX)\n return oldScore;\n\n \/\/ Update our bound.\n queryNode.Stat().Bound() = CalculateBound(queryNode);\n const double bestDistance = queryNode.Stat().Bound();\n\n return (SortPolicy::IsBetter(oldScore, bestDistance)) ? oldScore : DBL_MAX;\n}\n\/*\ntemplate\ninline double NeighborSearchRules::FinishNode(\n TreeType& queryNode) const\n{\n \/\/ Find the bound of points contained in this node.\n double pointBound = SortPolicy::BestDistance();\n const double maxDescendantDistance = queryNode.FurthestDescendantDistance();\n\n for (size_t i = 0; i < queryNode.NumPoints(); ++i)\n {\n \/\/ The bound for this point is the k-th best distance plus the maximum\n \/\/ distance to a child of this node.\n const double bound = distances(distances.n_rows - 1, queryNode.Point(i)) +\n maxDescendantDistance;\n if (SortPolicy::IsBetter(pointBound, bound))\n pointBound = bound;\n }\n\n \/\/ Push bound to parent.\n}\n*\/\n\n\/\/ Calculate the bound for a given query node in its current state.\ntemplate\ninline double NeighborSearchRules::\n CalculateBound(TreeType& queryNode) const\n{\n double pointBound = SortPolicy::BestDistance();\n double childBound = SortPolicy::BestDistance();\n const double maxDescendantDistance = queryNode.FurthestDescendantDistance();\n\n \/\/ Find the bound of the points contained in this node.\n for (size_t i = 0; i < queryNode.NumPoints(); ++i)\n {\n \/\/ The bound for this point is the k-th best distance plus the maximum\n \/\/ distance to a child of this node.\n const double bound = distances(distances.n_rows - 1, queryNode.Point(i)) +\n maxDescendantDistance;\n if (SortPolicy::IsBetter(pointBound, bound))\n pointBound = bound;\n }\n\n \/\/ Find the bound of the children.\n for (size_t i = 0; i < queryNode.NumChildren(); ++i)\n {\n const double bound = queryNode.Child(i).Stat().Bound();\n if (SortPolicy::IsBetter(childBound, bound))\n childBound = bound;\n }\n\n \/\/ If there are no points, then break; the bound must be the child bound.\n if (queryNode.NumPoints() == 0)\n return childBound;\n\n \/\/ If there are no children, then break; the bound must be the point bound.\n if (queryNode.NumChildren() == 0)\n return pointBound;\n\n\/\/ Log::Debug << \"Point bound \" << pointBound << std::endl;\n\/\/ Log::Debug << \"Child bound \" << childBound << std::endl;\n\/\/ Log::Debug << \"Furthest descendant distance \" << maxDescendantDistance <<\n\/\/ std::endl;\n\n \/\/ If the bound of the children is uninitialized\n \/\/ (SortPolicy::WorstDistance()), then maybe we can create a bound for the\n \/\/ children. But this requires a point bound to exist.\n\n \/\/ It is possible that we could calculate a better bound for the children.\n if (pointBound != SortPolicy::WorstDistance())\n {\n const double pointChildBound = pointBound + maxDescendantDistance;\n\/\/ Log::Debug << \"Point-child bound is \" << pointChildBound << std::endl;\n\n if (SortPolicy::IsBetter(pointChildBound, childBound))\n {\n \/\/ The calculated bound is a tighter bound than the existing child bounds.\n \/\/ Update all of the child bounds to this new, tighter bound.\n for (size_t i = 0; i < queryNode.NumChildren(); ++i)\n {\n\/\/ Log::Debug << \"Update child \" << i << \" bound from \" <<\n\/\/ queryNode.Child(i).Stat().Bound() << \" to \" << pointChildBound <<\n\/\/ std::endl;\n if (SortPolicy::IsBetter(pointChildBound,\n queryNode.Child(i).Stat().Bound()))\n queryNode.Child(i).Stat().Bound() = pointChildBound;\n\/\/ else\n\/\/ Log::Debug << \"Did not update child!\\n\";\n }\n\n childBound = pointChildBound;\n }\n }\n\n \/\/ Return the worse of the two bounds.\n if (SortPolicy::IsBetter(childBound, pointBound))\n return pointBound;\n else\n return childBound;\n}\n\n\/**\n * Helper function to insert a point into the neighbors and distances matrices.\n *\n * @param queryIndex Index of point whose neighbors we are inserting into.\n * @param pos Position in list to insert into.\n * @param neighbor Index of reference point which is being inserted.\n * @param distance Distance from query point to reference point.\n *\/\ntemplate\nvoid NeighborSearchRules::InsertNeighbor(\n const size_t queryIndex,\n const size_t pos,\n const size_t neighbor,\n const double distance)\n{\n \/\/ We only memmove() if there is actually a need to shift something.\n if (pos < (distances.n_rows - 1))\n {\n int len = (distances.n_rows - 1) - pos;\n memmove(distances.colptr(queryIndex) + (pos + 1),\n distances.colptr(queryIndex) + pos,\n sizeof(double) * len);\n memmove(neighbors.colptr(queryIndex) + (pos + 1),\n neighbors.colptr(queryIndex) + pos,\n sizeof(size_t) * len);\n }\n\n \/\/ Now put the new information in the right index.\n distances(pos, queryIndex) = distance;\n neighbors(pos, queryIndex) = neighbor;\n}\n\n}; \/\/ namespace neighbor\n}; \/\/ namespace mlpack\n\n#endif \/\/ __MLPACK_METHODS_NEIGHBOR_SEARCH_NEAREST_NEIGHBOR_RULES_IMPL_HPP\n<|endoftext|>"} {"text":"#ifndef itkGMMKCPointSetToPointSetMetric_hxx\n#define itkGMMKCPointSetToPointSetMetric_hxx\n\n#include \"itkGMMKCPointSetToPointSetMetric.h\"\n\nnamespace itk\n{\n\/**\n * Constructor\n *\/\ntemplate \nGMMKCPointSetToPointSetMetric::GMMKCPointSetToPointSetMetric()\n{\n}\n\n\/** Initialize the metric *\/\ntemplate< typename TFixedPointSet, typename TMovingPointSet >\nvoid\nGMMKCPointSetToPointSetMetric< TFixedPointSet, TMovingPointSet >\n::Initialize(void)\nthrow (ExceptionObject)\n{\n Superclass::Initialize();\n\n m_Gradient1.set_size(m_MovingPointSet->GetNumberOfPoints(), MovingPointSetDimension);\n m_Gradient2.set_size(m_MovingPointSet->GetNumberOfPoints(), MovingPointSetDimension);\n}\n\n\/**\n * Get the match Measure\n *\/\ntemplate \ntypename GMMKCPointSetToPointSetMetric::MeasureType\nGMMKCPointSetToPointSetMetric::GetValue(const TransformParametersType & parameters) const\n{\n itkExceptionMacro(<< \"not implemented\");\n}\n\/**\n * Get the Derivative Measure\n *\/\ntemplate \nvoid GMMKCPointSetToPointSetMetric::GetDerivative(const TransformParametersType & parameters, DerivativeType & derivative) const\n{\n itkExceptionMacro(<< \"not implemented\");\n}\n\n\/*\n * Get both the match Measure and theDerivative Measure\n *\/\ntemplate \nvoid GMMKCPointSetToPointSetMetric::GetValueAndDerivative(const TransformParametersType & parameters, MeasureType & value, DerivativeType & derivative) const\n{\n m_Transform->SetParameters(parameters);\n\n if (derivative.size() != m_NumberOfParameters) {\n derivative.set_size(m_NumberOfParameters);\n }\n\n m_TransformedPointSet = MovingPointSetType::New();\n for (MovingPointIterator iter = m_MovingPointSet->GetPoints()->Begin(); iter != m_MovingPointSet->GetPoints()->End(); ++iter) {\n m_TransformedPointSet->SetPoint(iter.Index(), m_Transform->TransformPoint(iter.Value()));\n }\n\n double value1 = 0;\n double value2 = 0;\n\n GradientType gradient1;\n GradientType gradient2;\n\n LocalDerivativeType derivative1(m_NumberOfParameters);\n derivative1.Fill(NumericTraits::ZeroValue());\n\n LocalDerivativeType derivative2(m_NumberOfParameters);\n derivative2.Fill(NumericTraits::ZeroValue());\n\n for (MovingPointIterator movingIter1 = m_TransformedPointSet->GetPoints()->Begin(); movingIter1 != m_TransformedPointSet->GetPoints()->End(); ++movingIter1) {\n const typename MovingPointSetType::PointType transformedPoint1 = movingIter1.Value();\n\n \/\/------------------------------------\n \/\/ compute gradient for the first part\n gradient1.Fill(0);\n\n for (FixedPointIterator fixedIter = m_FixedPointSet->GetPoints()->Begin(); fixedIter != m_FixedPointSet->GetPoints()->End(); ++fixedIter) {\n const typename FixedPointSetType::PointType fixedPoint = fixedIter.Value();\n\n double distance = 0;\n for (size_t dim = 0; dim < PointDimension; ++dim) {\n distance += pow(transformedPoint1[dim] \/ m_MovingPointSetScale - fixedPoint[dim] \/ m_FixedPointSetScale, 2);\n }\n \n value1 += exp(-distance);\n\n for (size_t dim = 0; dim < PointDimension; ++dim) {\n gradient1[dim] += (-2.0) * exp(-distance) * (transformedPoint1[dim] \/ m_MovingPointSetScale - fixedPoint[dim] \/ m_FixedPointSetScale) \/ m_MovingPointSetScale;\n }\n }\n\n \/\/-------------------------------------\n \/\/ compute gradient for the second part\n gradient2.Fill(0);\n\n for (MovingPointIterator movingIter2 = m_TransformedPointSet->GetPoints()->Begin(); movingIter2 != m_TransformedPointSet->GetPoints()->End(); ++movingIter2) {\n const typename MovingPointSetType::PointType transformedPoint2 = movingIter2.Value();\n\n double distance = 0;\n for (size_t dim = 0; dim < PointDimension; ++dim) {\n distance += pow(transformedPoint1[dim] \/ m_MovingPointSetScale - transformedPoint2[dim] \/ m_MovingPointSetScale, 2);\n }\n\n value2 += exp(-distance);\n\n for (size_t dim = 0; dim < PointDimension; ++dim) {\n gradient2[dim] += (-2.0) * exp(-distance) * (transformedPoint1[dim] \/ m_MovingPointSetScale - transformedPoint2[dim] \/ m_MovingPointSetScale) \/ m_MovingPointSetScale;\n }\n }\n\n \/\/-------------------------------------\n \/\/ compute derivatives\n m_Transform->ComputeJacobianWithRespectToParametersCachedTemporaries(m_MovingPointSet->GetPoint(movingIter1.Index()), m_Jacobian, m_JacobianCache);\n\n for (size_t par = 0; par < m_NumberOfParameters; par++) {\n for (size_t dim = 0; dim < PointDimension; dim++) {\n derivative1[par] += m_Jacobian(dim, par) * gradient1[dim];\n derivative2[par] += m_Jacobian(dim, par) * gradient2[dim];\n }\n }\n }\n\n const double factor = m_MovingPointSet->GetNumberOfPoints() * m_FixedPointSet->GetNumberOfPoints();\n const double ratio = value1 \/ value2;\n \n value = -value1 * ratio \/ factor;\n\n for (size_t par = 0; par < m_NumberOfParameters; par++) {\n derivative[par] = 2.0 * ratio * (derivative2[par] * ratio - derivative1[par]) \/ factor;\n }\n}\n}\n\n#endif\nrefactoring#ifndef itkGMMKCPointSetToPointSetMetric_hxx\n#define itkGMMKCPointSetToPointSetMetric_hxx\n\n#include \"itkGMMKCPointSetToPointSetMetric.h\"\n\nnamespace itk\n{\n\/**\n * Constructor\n *\/\ntemplate \nGMMKCPointSetToPointSetMetric::GMMKCPointSetToPointSetMetric()\n{\n}\n\n\/** Initialize the metric *\/\ntemplate< typename TFixedPointSet, typename TMovingPointSet >\nvoid\nGMMKCPointSetToPointSetMetric< TFixedPointSet, TMovingPointSet >\n::Initialize(void)\nthrow (ExceptionObject)\n{\n Superclass::Initialize();\n\n m_Gradient1.set_size(m_MovingPointSet->GetNumberOfPoints(), MovingPointSetDimension);\n m_Gradient2.set_size(m_MovingPointSet->GetNumberOfPoints(), MovingPointSetDimension);\n}\n\n\/**\n * Get the match Measure\n *\/\ntemplate \ntypename GMMKCPointSetToPointSetMetric::MeasureType\nGMMKCPointSetToPointSetMetric::GetValue(const TransformParametersType & parameters) const\n{\n itkExceptionMacro(<< \"not implemented\");\n}\n\/**\n * Get the Derivative Measure\n *\/\ntemplate \nvoid GMMKCPointSetToPointSetMetric::GetDerivative(const TransformParametersType & parameters, DerivativeType & derivative) const\n{\n itkExceptionMacro(<< \"not implemented\");\n}\n\n\/*\n * Get both the match Measure and theDerivative Measure\n *\/\ntemplate \nvoid GMMKCPointSetToPointSetMetric::GetValueAndDerivative(const TransformParametersType & parameters, MeasureType & value, DerivativeType & derivative) const\n{\n m_Transform->SetParameters(parameters);\n\n if (derivative.size() != m_NumberOfParameters) {\n derivative.set_size(m_NumberOfParameters);\n }\n\n m_TransformedPointSet = MovingPointSetType::New();\n for (MovingPointIterator iter = m_MovingPointSet->GetPoints()->Begin(); iter != m_MovingPointSet->GetPoints()->End(); ++iter) {\n m_TransformedPointSet->SetPoint(iter.Index(), m_Transform->TransformPoint(iter.Value()));\n }\n\n double value1 = 0;\n double value2 = 0;\n\n GradientType gradient1;\n GradientType gradient2;\n\n LocalDerivativeType derivative1(m_NumberOfParameters);\n derivative1.Fill(NumericTraits::ZeroValue());\n\n LocalDerivativeType derivative2(m_NumberOfParameters);\n derivative2.Fill(NumericTraits::ZeroValue());\n\n for (MovingPointIterator movingIter1 = m_TransformedPointSet->GetPoints()->Begin(); movingIter1 != m_TransformedPointSet->GetPoints()->End(); ++movingIter1) {\n const typename MovingPointSetType::PointType transformedPoint1 = movingIter1.Value();\n\n \/\/------------------------------------\n \/\/ compute gradient for the first part\n gradient1.Fill(0);\n\n for (FixedPointIterator fixedIter = m_FixedPointSet->GetPoints()->Begin(); fixedIter != m_FixedPointSet->GetPoints()->End(); ++fixedIter) {\n const typename FixedPointSetType::PointType fixedPoint = fixedIter.Value();\n\n double distance = 0;\n for (size_t dim = 0; dim < PointDimension; ++dim) {\n distance += pow(transformedPoint1[dim] \/ m_MovingPointSetScale - fixedPoint[dim] \/ m_FixedPointSetScale, 2);\n }\n \n value1 += exp(-distance);\n\n for (size_t dim = 0; dim < PointDimension; ++dim) {\n gradient1[dim] += (-2.0) * exp(-distance) * (transformedPoint1[dim] \/ m_MovingPointSetScale - fixedPoint[dim] \/ m_FixedPointSetScale) \/ m_MovingPointSetScale;\n }\n }\n\n \/\/-------------------------------------\n \/\/ compute gradient for the second part\n gradient2.Fill(0);\n\n for (MovingPointIterator movingIter2 = m_TransformedPointSet->GetPoints()->Begin(); movingIter2 != m_TransformedPointSet->GetPoints()->End(); ++movingIter2) {\n const typename MovingPointSetType::PointType transformedPoint2 = movingIter2.Value();\n\n double distance = 0;\n for (size_t dim = 0; dim < PointDimension; ++dim) {\n distance += pow(transformedPoint1[dim] \/ m_MovingPointSetScale - transformedPoint2[dim] \/ m_MovingPointSetScale, 2);\n }\n\n value2 += exp(-distance);\n\n for (size_t dim = 0; dim < PointDimension; ++dim) {\n gradient2[dim] += (-2.0) * exp(-distance) * (transformedPoint1[dim] \/ m_MovingPointSetScale - transformedPoint2[dim] \/ m_MovingPointSetScale) \/ m_MovingPointSetScale;\n }\n }\n\n \/\/-------------------------------------\n \/\/ compute derivatives\n m_Transform->ComputeJacobianWithRespectToParametersCachedTemporaries(m_MovingPointSet->GetPoint(movingIter1.Index()), m_Jacobian, m_JacobianCache);\n\n for (size_t par = 0; par < m_NumberOfParameters; par++) {\n for (size_t dim = 0; dim < PointDimension; dim++) {\n derivative1[par] += m_Jacobian(dim, par) * gradient1[dim];\n derivative2[par] += m_Jacobian(dim, par) * gradient2[dim];\n }\n }\n }\n\n const double factor = m_MovingPointSet->GetNumberOfPoints() * m_FixedPointSet->GetNumberOfPoints();\n const double ratio = value1 \/ value2;\n \n value = -value1 * ratio \/ factor;\n\n for (size_t par = 0; par < m_NumberOfParameters; par++) {\n derivative[par] = (-2.0) * (derivative1[par] - derivative2[par] * ratio) * ratio \/ factor;\n }\n}\n}\n\n#endif\n<|endoftext|>"} {"text":"\/*******************************************************************************\n\nLicensed to the OpenCOR team under one or more contributor license agreements.\nSee the NOTICE.txt file distributed with this work for additional information\nregarding copyright ownership. The OpenCOR team licenses this file to you under\nthe Apache License, Version 2.0 (the \"License\"); you may not use this file\nexcept in compliance with the License. You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed\nunder the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\nCONDITIONS OF ANY KIND, either express or implied. See the License for the\nspecific language governing permissions and limitations under the License.\n\n*******************************************************************************\/\n\n\/\/==============================================================================\n\/\/ BioSignalML data store exporter class\n\/\/==============================================================================\n\n#include \"bsmldatastoreexporter.h\"\n#include \"biosignalml\/biosignalml.h\"\n#include \"biosignalml\/data\/hdf5.h\"\n\n\/\/==============================================================================\n\n#include \"corecliutils.h\"\n\n\/\/==============================================================================\n\n#include \n#include \n#include \n#include \n#include \n\n\/\/==============================================================================\n\nnamespace OpenCOR {\nnamespace BSMLDataStore {\n\n\/\/==============================================================================\n\nBioSignalMLExporter::BioSignalMLExporter(QMainWindow *pMainWindow, const QString &pId) :\n DataStore::DataStoreExporter(pId),\n mSaveDialog(new BioSignalMLSaveDialog(pMainWindow))\n{\n}\n\n\/\/==============================================================================\n\nvoid BioSignalMLExporter::execute(DataStore::DataStore *pDataStore) const\n{\n \/\/ Export the given data store to a BioSignalML file\n\n QString comment = \"Generated by \" + Core::version(qApp)\n + \" at \" + QDateTime::currentDateTimeUtc().toString(Qt::ISODate)\n + \" from \" + pDataStore->uri();\n\n mSaveDialog->setComment(comment);\n if (mSaveDialog->run()) {\n\n QString fileName = mSaveDialog->fileName();\n std::string rec_uri = QUrl::fromLocalFile(fileName).toString().toStdString();\n std::string base_units = pDataStore->uri().toStdString() + \"\/units#\";\n\n bsml::HDF5::Recording *recording = nullptr;\n try {\n recording = new bsml::HDF5::Recording(rec_uri, fileName.toStdString(), true);\n recording->set_comment(comment.toStdString());\n recording->set_label(mSaveDialog->shortName().toStdString()) ;\n recording->set_description(mSaveDialog->description().toStdString()) ;\n recording->set_investigator(rdf::Literal(mSaveDialog->author().toStdString())) ;\n\n recording->add_prefix(rdf::Namespace(\"units\", base_units)) ;\n\n DataStore::DataStoreVariable *voi = pDataStore->voi();\n auto clock = recording->new_clock(voi->uri().toStdString(),\n rdf::URI(base_units + voi->unit().toStdString()),\n voi->values(), voi->size());\n clock->set_label(voi->label().toStdString()) ;\n\n DataStore::DataStoreVariables variables = pDataStore->variables();\n auto variableBegin = variables.constBegin();\n auto variableEnd = variables.constEnd();\n\n std::vector uris;\n std::vector units;\n for (auto variable = variableBegin; variable != variableEnd; ++variable) {\n uris.push_back((*variable)->uri().toStdString());\n units.push_back(rdf::URI(base_units + (*variable)->unit().toStdString()));\n }\n\n auto sigs = recording->new_signalarray(uris, units, clock) ;\n size_t nvars = variables.size();\n for (size_t i = 0 ; i < nvars ; ++i) {\n (*sigs)[i]->set_label(variables[i]->label().toStdString()) ;\n }\n\n#define BUFFER_ROWS 50000\n double *data = new double[BUFFER_ROWS*nvars];\n double *dp = data;\n int rowcount = 0;\n\n for (qulonglong i = 0; i < pDataStore->size(); ++i) {\n for (auto variable = variableBegin; variable != variableEnd; ++variable)\n *dp++ = (*variable)->value(i);\n ++rowcount;\n if (rowcount >= BUFFER_ROWS) {\n sigs->extend(data, BUFFER_ROWS*nvars);\n dp = data;\n rowcount = 0;\n }\n\n qApp->processEvents();\n\/\/---GRY--- THE CALL TO qApp->processEvents() SHOULD BE REMOVED AND THE EXPORTER\n\/\/ BE SUCH THAT IT DOESN'T BLOCK THE MAIN THREAD (E.G. WHEN EXPORTING\n\/\/ LONG SIMULATIONS). MAYBE THIS COULD BE DONE BY MAKING THE EXPORTER\n\/\/ WORK IN ITS OWN THREAD?...\n }\n\n sigs->extend(data, rowcount*nvars);\n\n delete[] data;\n }\n\n catch (bsml::data::Exception e) {\n std::cerr << \"EXCEPTION: \" << e.what() << std::endl;\n \/\/ **** Need to bring up alert....\n }\n\n if (recording != nullptr) {\n recording->close();\n delete recording;\n }\n\n }\n\n}\n\n\/\/==============================================================================\n\n} \/\/ namespace BSMLDataStore\n} \/\/ namespace OpenCOR\n\n\/\/==============================================================================\n\/\/ End of file\n\/\/==============================================================================\nUse full URIs for signals.\/*******************************************************************************\n\nLicensed to the OpenCOR team under one or more contributor license agreements.\nSee the NOTICE.txt file distributed with this work for additional information\nregarding copyright ownership. The OpenCOR team licenses this file to you under\nthe Apache License, Version 2.0 (the \"License\"); you may not use this file\nexcept in compliance with the License. You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed\nunder the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\nCONDITIONS OF ANY KIND, either express or implied. See the License for the\nspecific language governing permissions and limitations under the License.\n\n*******************************************************************************\/\n\n\/\/==============================================================================\n\/\/ BioSignalML data store exporter class\n\/\/==============================================================================\n\n#include \"bsmldatastoreexporter.h\"\n#include \"biosignalml\/biosignalml.h\"\n#include \"biosignalml\/data\/hdf5.h\"\n\n\/\/==============================================================================\n\n#include \"corecliutils.h\"\n\n\/\/==============================================================================\n\n#include \n#include \n#include \n#include \n#include \n\n\/\/==============================================================================\n\nnamespace OpenCOR {\nnamespace BSMLDataStore {\n\n\/\/==============================================================================\n\nBioSignalMLExporter::BioSignalMLExporter(QMainWindow *pMainWindow, const QString &pId) :\n DataStore::DataStoreExporter(pId),\n mSaveDialog(new BioSignalMLSaveDialog(pMainWindow))\n{\n}\n\n\/\/==============================================================================\n\nvoid BioSignalMLExporter::execute(DataStore::DataStore *pDataStore) const\n{\n \/\/ Export the given data store to a BioSignalML file\n\n QString comment = \"Generated by \" + Core::version(qApp)\n + \" at \" + QDateTime::currentDateTimeUtc().toString(Qt::ISODate)\n + \" from \" + pDataStore->uri();\n\n mSaveDialog->setComment(comment);\n if (mSaveDialog->run()) {\n\n QString fileName = mSaveDialog->fileName();\n std::string rec_uri = QUrl::fromLocalFile(fileName).toString().toStdString();\n std::string base_units = pDataStore->uri().toStdString() + \"\/units#\";\n\n bsml::HDF5::Recording *recording = nullptr;\n try {\n recording = new bsml::HDF5::Recording(rec_uri, fileName.toStdString(), true);\n recording->set_comment(comment.toStdString());\n recording->set_label(mSaveDialog->shortName().toStdString()) ;\n recording->set_description(mSaveDialog->description().toStdString()) ;\n recording->set_investigator(rdf::Literal(mSaveDialog->author().toStdString())) ;\n\n recording->add_prefix(rdf::Namespace(\"units\", base_units)) ;\n\n DataStore::DataStoreVariable *voi = pDataStore->voi();\n auto clock = recording->new_clock(voi->uri().toStdString(),\n rdf::URI(base_units + voi->unit().toStdString()),\n voi->values(), voi->size());\n clock->set_label(voi->label().toStdString()) ;\n\n DataStore::DataStoreVariables variables = pDataStore->variables();\n auto variableBegin = variables.constBegin();\n auto variableEnd = variables.constEnd();\n\n std::vector uris;\n std::vector units;\n for (auto variable = variableBegin; variable != variableEnd; ++variable) {\n uris.push_back(rec_uri + \"\/signal\/\" + (*variable)->uri().toStdString());\n units.push_back(rdf::URI(base_units + (*variable)->unit().toStdString()));\n }\n\n auto sigs = recording->new_signalarray(uris, units, clock) ;\n size_t nvars = variables.size();\n for (size_t i = 0 ; i < nvars ; ++i) {\n (*sigs)[i]->set_label(variables[i]->label().toStdString()) ;\n }\n\n#define BUFFER_ROWS 50000\n double *data = new double[BUFFER_ROWS*nvars];\n double *dp = data;\n int rowcount = 0;\n\n for (qulonglong i = 0; i < pDataStore->size(); ++i) {\n for (auto variable = variableBegin; variable != variableEnd; ++variable)\n *dp++ = (*variable)->value(i);\n ++rowcount;\n if (rowcount >= BUFFER_ROWS) {\n sigs->extend(data, BUFFER_ROWS*nvars);\n dp = data;\n rowcount = 0;\n }\n\n qApp->processEvents();\n\/\/---GRY--- THE CALL TO qApp->processEvents() SHOULD BE REMOVED AND THE EXPORTER\n\/\/ BE SUCH THAT IT DOESN'T BLOCK THE MAIN THREAD (E.G. WHEN EXPORTING\n\/\/ LONG SIMULATIONS). MAYBE THIS COULD BE DONE BY MAKING THE EXPORTER\n\/\/ WORK IN ITS OWN THREAD?...\n }\n\n sigs->extend(data, rowcount*nvars);\n\n delete[] data;\n }\n\n catch (bsml::data::Exception e) {\n std::cerr << \"EXCEPTION: \" << e.what() << std::endl;\n \/\/ **** Need to bring up alert....\n }\n\n if (recording != nullptr) {\n recording->close();\n delete recording;\n }\n\n }\n\n}\n\n\/\/==============================================================================\n\n} \/\/ namespace BSMLDataStore\n} \/\/ namespace OpenCOR\n\n\/\/==============================================================================\n\/\/ End of file\n\/\/==============================================================================\n<|endoftext|>"} {"text":"\/\/ ======================================================================== \/\/\n\/\/ Copyright 2015-2019 Ingo Wald \/\/\n\/\/ \/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); \/\/\n\/\/ you may not use this file except in compliance with the License. \/\/\n\/\/ You may obtain a copy of the License at \/\/\n\/\/ \/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0 \/\/\n\/\/ \/\/\n\/\/ Unless required by applicable law or agreed to in writing, software \/\/\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS, \/\/\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \/\/\n\/\/ See the License for the specific language governing permissions and \/\/\n\/\/ limitations under the License. \/\/\n\/\/ ======================================================================== \/\/\n\n\/\/ ospcommon, which we use for a vector class\n#include \"pbrtParser\/Scene.h\"\n\/\/ stl\n#include \n#include \n#include \n#include \n\nnamespace pbrt {\n namespace semantic {\n \n using std::cout;\n using std::endl;\n\n bool endsWith(const std::string &s, const std::string &suffix)\n {\n return s.substr(s.size()-suffix.size(),suffix.size()) == suffix;\n }\n\n struct PBRTInfo {\n PBRTInfo(Scene::SP scene)\n {\n traverse(scene->world);\n numObjects.print(\"objects\");\n numAreaLights.print(\"areaLights\");\n numShapes.print(\"shapes\");\n numTriangles.print(\"triangles\");\n numQuads.print(\"quads\");\n numDisks.print(\"disks\");\n numSpheres.print(\"spheres\");\n numCurves.print(\"curves\");\n numCurveSegments.print(\"curve segments\");\n numLights.print(\"lights\");\n std::cout << \"total num materials \" << usedMaterials.size() << std::endl;\n for (auto mat : usedMaterials)\n std::cout << \" - \" << (mat ? mat->name : \"\") << std::endl;\n std::cout << \"scene bounds \" << scene->getBounds() << std::endl;\n }\n\n void traverse(Object::SP object)\n {\n const bool firstTime = (alreadyTraversed.find(object) == alreadyTraversed.end());\n alreadyTraversed.insert(object);\n\n numObjects.add(firstTime,1);\n \/\/ numLights.add(firstTime,object->lightSources.size());\n \/\/ numVolumes.add(firstTime,object->volumes.size());\n numShapes.add(firstTime,object->shapes.size());\n \n for (auto shape : object->shapes) {\n usedMaterials.insert(shape->material);\n if (shape->areaLight)\n numAreaLights.add(firstTime,1);\n if (TriangleMesh::SP mesh=std::dynamic_pointer_cast(shape)){\n numTriangles.add(firstTime,mesh->index.size());\n } else if (QuadMesh::SP mesh=std::dynamic_pointer_cast(shape)){\n numQuads.add(firstTime,mesh->index.size());\n } else if (Sphere::SP sphere=std::dynamic_pointer_cast(shape)){\n numSpheres.add(firstTime,1);\n } else if (Disk::SP disk=std::dynamic_pointer_cast(shape)){\n numDisks.add(firstTime,1);\n } else if (Curve::SP curves=std::dynamic_pointer_cast(shape)){\n numCurves.add(firstTime,1);\n } else\n std::cout << \"un-handled geometry type : \" << shape->toString() << std::endl;\n }\n\n numInstances.add(firstTime,object->instances.size());\n for (auto inst : object->instances) {\n traverse(inst->object);\n }\n }\n\n struct Counter\n {\n void print(const std::string &name)\n {\n std::cout << \"number of \" << name << std::endl;\n std::cout << \" - unique : \" << math::prettyNumber(unique) << std::endl;\n std::cout << \" - instanced : \" << math::prettyNumber(instanced) << std::endl;\n }\n void add(bool firstTime, size_t N) { instanced += N; if (firstTime) unique += N; }\n \n size_t unique = 0;\n size_t instanced = 0;\n };\n \n Counter numInstances;\n Counter numTriangles;\n Counter numQuads;\n Counter numSpheres;\n Counter numDisks;\n Counter numObjects;\n Counter numAreaLights;\n Counter numVertices;\n Counter numCurves;\n Counter numCurveSegments;\n Counter numShapes;\n Counter numLights;\n Counter numVolumes;\n \n std::set alreadyTraversed;\n std::set usedMaterials;\n };\n \n void pbrtInfo(int ac, char **av)\n {\n std::string fileName;\n bool parseOnly = false;\n for (int i=1;i scene;\n try {\n if (endsWith(fileName,\".pbrt\"))\n scene = importPBRT(fileName);\n else if (endsWith(fileName,\".pbf\"))\n scene = Scene::loadFrom(fileName);\n else\n throw std::runtime_error(\"un-recognized input file extension\");\n \n std::cout << \" => yay! parsing successful...\" << std::endl;\n if (parseOnly) exit(0);\n PBRTInfo info(scene);\n } catch (std::runtime_error e) {\n std::cerr << \"**** ERROR IN PARSING ****\" << std::endl << e.what() << std::endl;\n std::cerr << \"(this means that either there's something wrong with that PBRT file, or that the parser can't handle it)\" << std::endl;\n exit(1);\n }\n }\n \n extern \"C\" int main(int ac, char **av)\n {\n pbrtInfo(ac,av);\n return 0;\n }\n \n } \/\/ ::pbrt::semantic\n} \/\/ ::pbrt\nfixed null material outputs in pbrtInfo\/\/ ======================================================================== \/\/\n\/\/ Copyright 2015-2019 Ingo Wald \/\/\n\/\/ \/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); \/\/\n\/\/ you may not use this file except in compliance with the License. \/\/\n\/\/ You may obtain a copy of the License at \/\/\n\/\/ \/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0 \/\/\n\/\/ \/\/\n\/\/ Unless required by applicable law or agreed to in writing, software \/\/\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS, \/\/\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \/\/\n\/\/ See the License for the specific language governing permissions and \/\/\n\/\/ limitations under the License. \/\/\n\/\/ ======================================================================== \/\/\n\n\/\/ ospcommon, which we use for a vector class\n#include \"pbrtParser\/Scene.h\"\n\/\/ stl\n#include \n#include \n#include \n#include \n\nnamespace pbrt {\n namespace semantic {\n \n using std::cout;\n using std::endl;\n\n bool endsWith(const std::string &s, const std::string &suffix)\n {\n return s.substr(s.size()-suffix.size(),suffix.size()) == suffix;\n }\n\n struct PBRTInfo {\n PBRTInfo(Scene::SP scene)\n {\n traverse(scene->world);\n numObjects.print(\"objects\");\n numAreaLights.print(\"areaLights\");\n numShapes.print(\"shapes\");\n numTriangles.print(\"triangles\");\n numQuads.print(\"quads\");\n numDisks.print(\"disks\");\n numSpheres.print(\"spheres\");\n numCurves.print(\"curves\");\n numCurveSegments.print(\"curve segments\");\n numLights.print(\"lights\");\n std::cout << \"total num materials \" << usedMaterials.size() << std::endl;\n for (auto mat : usedMaterials)\n std::cout << \" - \" << (mat ? mat->name : \" (ie, shape w\/o material - possibly light source)\") << std::endl;\n std::cout << \"scene bounds \" << scene->getBounds() << std::endl;\n }\n\n void traverse(Object::SP object)\n {\n const bool firstTime = (alreadyTraversed.find(object) == alreadyTraversed.end());\n alreadyTraversed.insert(object);\n\n numObjects.add(firstTime,1);\n \/\/ numLights.add(firstTime,object->lightSources.size());\n \/\/ numVolumes.add(firstTime,object->volumes.size());\n numShapes.add(firstTime,object->shapes.size());\n \n for (auto shape : object->shapes) {\n usedMaterials.insert(shape->material);\n if (shape->areaLight)\n numAreaLights.add(firstTime,1);\n if (TriangleMesh::SP mesh=std::dynamic_pointer_cast(shape)){\n numTriangles.add(firstTime,mesh->index.size());\n } else if (QuadMesh::SP mesh=std::dynamic_pointer_cast(shape)){\n numQuads.add(firstTime,mesh->index.size());\n } else if (Sphere::SP sphere=std::dynamic_pointer_cast(shape)){\n numSpheres.add(firstTime,1);\n } else if (Disk::SP disk=std::dynamic_pointer_cast(shape)){\n numDisks.add(firstTime,1);\n } else if (Curve::SP curves=std::dynamic_pointer_cast(shape)){\n numCurves.add(firstTime,1);\n } else\n std::cout << \"un-handled geometry type : \" << shape->toString() << std::endl;\n }\n\n numInstances.add(firstTime,object->instances.size());\n for (auto inst : object->instances) {\n traverse(inst->object);\n }\n }\n\n struct Counter\n {\n void print(const std::string &name)\n {\n std::cout << \"number of \" << name << std::endl;\n std::cout << \" - unique : \" << math::prettyNumber(unique) << std::endl;\n std::cout << \" - instanced : \" << math::prettyNumber(instanced) << std::endl;\n }\n void add(bool firstTime, size_t N) { instanced += N; if (firstTime) unique += N; }\n \n size_t unique = 0;\n size_t instanced = 0;\n };\n \n Counter numInstances;\n Counter numTriangles;\n Counter numQuads;\n Counter numSpheres;\n Counter numDisks;\n Counter numObjects;\n Counter numAreaLights;\n Counter numVertices;\n Counter numCurves;\n Counter numCurveSegments;\n Counter numShapes;\n Counter numLights;\n Counter numVolumes;\n \n std::set alreadyTraversed;\n std::set usedMaterials;\n };\n \n void pbrtInfo(int ac, char **av)\n {\n std::string fileName;\n bool parseOnly = false;\n for (int i=1;i scene;\n try {\n if (endsWith(fileName,\".pbrt\"))\n scene = importPBRT(fileName);\n else if (endsWith(fileName,\".pbf\"))\n scene = Scene::loadFrom(fileName);\n else\n throw std::runtime_error(\"un-recognized input file extension\");\n \n std::cout << \" => yay! parsing successful...\" << std::endl;\n if (parseOnly) exit(0);\n PBRTInfo info(scene);\n } catch (std::runtime_error e) {\n std::cerr << \"**** ERROR IN PARSING ****\" << std::endl << e.what() << std::endl;\n std::cerr << \"(this means that either there's something wrong with that PBRT file, or that the parser can't handle it)\" << std::endl;\n exit(1);\n }\n }\n \n extern \"C\" int main(int ac, char **av)\n {\n pbrtInfo(ac,av);\n return 0;\n }\n \n } \/\/ ::pbrt::semantic\n} \/\/ ::pbrt\n<|endoftext|>"} {"text":"\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Peloton\n\/\/\n\/\/ optimizer_sql_test.cpp\n\/\/\n\/\/ Identification: test\/sql\/optimizer_sql_test.cpp\n\/\/\n\/\/ Copyright (c) 2015-16, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \n\n#include \"sql\/testing_sql_util.h\"\n#include \"catalog\/catalog.h\"\n#include \"common\/harness.h\"\n#include \"executor\/create_executor.h\"\n#include \"optimizer\/optimizer.h\"\n#include \"optimizer\/simple_optimizer.h\"\n#include \"planner\/create_plan.h\"\n#include \"planner\/order_by_plan.h\"\n\nusing std::vector;\nusing std::unordered_set;\nusing std::string;\nusing std::unique_ptr;\nusing std::shared_ptr;\n\nnamespace peloton {\nnamespace test {\n\nclass OptimizerSQLTests : public PelotonTest {\n protected:\n virtual void SetUp() override {\n \/\/ Call parent virtual function first\n PelotonTest::SetUp();\n\n \/\/ Create test database\n CreateAndLoadTable();\n optimizer.reset(new optimizer::Optimizer());\n }\n\n virtual void TearDown() override {\n \/\/ Destroy test database\n auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();\n auto txn = txn_manager.BeginTransaction();\n catalog::Catalog::GetInstance()->DropDatabaseWithName(DEFAULT_DB_NAME, txn);\n txn_manager.CommitTransaction(txn);\n\n \/\/ Call parent virtual function\n PelotonTest::TearDown();\n }\n\n \/*** Helper functions **\/\n void CreateAndLoadTable() {\n \/\/ Create database\n catalog::Catalog::GetInstance()->CreateDatabase(DEFAULT_DB_NAME, nullptr);\n\n \/\/ Create a table first\n TestingSQLUtil::ExecuteSQLQuery(\n \"CREATE TABLE test(a INT PRIMARY KEY, b INT, c INT);\");\n\n \/\/ Insert tuples into table\n TestingSQLUtil::ExecuteSQLQuery(\"INSERT INTO test VALUES (1, 22, 333);\");\n TestingSQLUtil::ExecuteSQLQuery(\"INSERT INTO test VALUES (2, 11, 000);\");\n TestingSQLUtil::ExecuteSQLQuery(\"INSERT INTO test VALUES (3, 33, 444);\");\n TestingSQLUtil::ExecuteSQLQuery(\"INSERT INTO test VALUES (4, 00, 555);\");\n }\n\n void TestUtil(string query, vector ref_result, bool ordered,\n vector expected_plans={}) {\n LOG_DEBUG(\"Running Query \\\"%s\\\"\", query.c_str());\n \n \/\/ Check Plan Nodes are correct if provided\n if (expected_plans.size() > 0) {\n auto plan = TestingSQLUtil::GeneratePlanWithOptimizer(optimizer, query);\n auto plan_ptr = plan.get();\n vector actual_plans;\n while (true) {\n actual_plans.push_back(plan_ptr->GetPlanNodeType());\n if (plan_ptr->GetChildren().size() == 0)\n break;\n plan_ptr = plan_ptr->GetChildren()[0].get();\n }\n EXPECT_EQ(actual_plans, expected_plans);\n }\n \n \/\/ Check plan execution results are correct\n TestingSQLUtil::ExecuteSQLQueryWithOptimizer(optimizer, query, result,\n tuple_descriptor, rows_changed,\n error_message);\n EXPECT_EQ(ref_result.size(), result.size());\n if (ordered) {\n \/\/ If deterministic, do comparision with expected result in order\n for (unsigned i = 0; i < ref_result.size(); i++) {\n EXPECT_EQ(ref_result[i],\n TestingSQLUtil::GetResultValueAsString(result, i));\n }\n } else {\n \/\/ If non-deterministic, make sure they have the same set of value\n unordered_set ref_set(ref_result.begin(), ref_result.end());\n for (unsigned i = 0; i < result.size(); i++) {\n string result_str = TestingSQLUtil::GetResultValueAsString(result, i);\n EXPECT_TRUE(ref_set.find(result_str) != ref_set.end());\n }\n }\n }\n\n protected:\n unique_ptr optimizer;\n vector result;\n vector tuple_descriptor;\n string error_message;\n int rows_changed;\n};\n\nTEST_F(OptimizerSQLTests, SimpleSelectTest) {\n \/\/ Testing select star expression\n TestUtil(\"SELECT * from test\", {\"333\", \"22\", \"1\", \"2\", \"11\", \"0\", \"3\", \"33\",\n \"444\", \"4\", \"0\", \"555\"}, false);\n\n \/\/ Testing predicate\n TestUtil(\"SELECT c, b from test where a=1\", {\"333\", \"22\"}, false);\n}\n\nTEST_F(OptimizerSQLTests, SelectOrderByTest) {\n \/\/ Testing order by columns different from select columns\n TestUtil(\"SELECT b from test order by c\", {\"11\", \"22\", \"33\", \"0\"}, true);\n\n \/\/ Testing order by desc\n TestUtil(\"SELECT a from test order by c desc\", {\"4\", \"3\", \"1\", \"2\"}, true);\n\n \/\/ Testing order by complex expression\n TestUtil(\"SELECT * from test order by a + c\", {\"2\", \"11\", \"0\", \"1\", \"22\",\n \"333\", \"3\", \"33\", \"444\", \"4\", \"0\", \"555\"}, true);\n}\n\nTEST_F(OptimizerSQLTests, SelectLimitTest) {\n \/\/ Test limit with default offset\n TestUtil(\"SELECT b FROM test ORDER BY b LIMIT 3\", {\"0\", \"11\", \"22\"}, true);\n\n \/\/ Test limit with offset\n TestUtil(\"SELECT b FROM test ORDER BY b LIMIT 2 OFFSET 2\", {\"22\", \"33\"}, true);\n}\n\nTEST_F(OptimizerSQLTests, SelectProjectionTest) {\n \/\/ Test complex expression projection\n TestUtil(\"SELECT a * 5 + b, -1 + c from test\", {\"27\", \"332\", \"48\", \"443\",\n \"21\", \"-1\", \"20\", \"554\"}, false);\n\n \/\/ Test complex expression in select and order by\n TestUtil(\"SELECT a * 5 + b - c FROM test ORDER BY a * 10 + b\", {\"21\", \"-306\",\n \"-535\", \"-396\"}, true);\n\n \/\/ Test mixing up select simple columns with complex expression\n TestUtil(\"SELECT a, a + c FROM test ORDER BY a * 3 * b DESC, b + c \/ 5 ASC\",\n {\"3\", \"447\", \"2\", \"2\", \"1\", \"334\", \"4\", \"559\"}, true);\n}\n\nTEST_F(OptimizerSQLTests, DeleteSqlTest) {\n \/\/ TODO: Test for index scan\n\n \/\/ Delete with predicates\n string query = \"DELETE FROM test WHERE a = 1 and c = 333\";\n TestingSQLUtil::ExecuteSQLQueryWithOptimizer(\n optimizer, query, result, tuple_descriptor, rows_changed, error_message);\n EXPECT_EQ(1, rows_changed);\n TestingSQLUtil::ExecuteSQLQueryWithOptimizer(optimizer, \"SELECT * FROM test\",\n result, tuple_descriptor,\n rows_changed, error_message);\n EXPECT_EQ(9, result.size());\n\n \/\/ Delete with predicates\n query = \"DELETE FROM test WHERE b = 33\";\n TestingSQLUtil::ExecuteSQLQueryWithOptimizer(\n optimizer, query, result, tuple_descriptor, rows_changed, error_message);\n EXPECT_EQ(1, rows_changed);\n TestingSQLUtil::ExecuteSQLQueryWithOptimizer(optimizer, \"SELECT * FROM test\",\n result, tuple_descriptor,\n rows_changed, error_message);\n EXPECT_EQ(6, result.size());\n\n \/\/ Delete with false predicates\n query = \"DELETE FROM test WHERE b = 123\";\n TestingSQLUtil::ExecuteSQLQueryWithOptimizer(\n optimizer, query, result, tuple_descriptor, rows_changed, error_message);\n EXPECT_EQ(0, rows_changed);\n TestingSQLUtil::ExecuteSQLQueryWithOptimizer(optimizer, \"SELECT * FROM test\",\n result, tuple_descriptor,\n rows_changed, error_message);\n EXPECT_EQ(6, result.size());\n\n \/\/ Full deletion\n query = \"DELETE FROM test\";\n TestingSQLUtil::ExecuteSQLQueryWithOptimizer(\n optimizer, query, result, tuple_descriptor, rows_changed, error_message);\n EXPECT_EQ(2, rows_changed);\n TestingSQLUtil::ExecuteSQLQueryWithOptimizer(optimizer, \"SELECT * FROM test\",\n result, tuple_descriptor,\n rows_changed, error_message);\n EXPECT_EQ(0, result.size());\n}\n\nTEST_F(OptimizerSQLTests, UpdateSqlTest) {\n \/\/ Test Update with complex expression and predicate\n string query = \"UPDATE test SET c = b + 1 WHERE a = 1\";\n TestingSQLUtil::ExecuteSQLQueryWithOptimizer(\n optimizer, query, result, tuple_descriptor, rows_changed, error_message);\n EXPECT_EQ(1, rows_changed);\n TestUtil(\"SELECT c FROM test WHERE a=1\", {\"23\"}, false);\n}\n\nTEST_F(OptimizerSQLTests, InsertSqlTest) {\n string query = \"INSERT INTO test VALUES (5, 55, 555);\";\n TestingSQLUtil::ExecuteSQLQueryWithOptimizer(\n optimizer, query, result, tuple_descriptor, rows_changed, error_message);\n EXPECT_EQ(1, rows_changed);\n\n \/\/ Test the tuple is succesfully inserted\n TestUtil(\"SELECT * FROM test WHERE a=5\", {\"5\", \"55\", \"555\"}, false);\n}\n\nTEST_F(OptimizerSQLTests, DDLSqlTest) {\n \/\/ Test creating new table\n string query = \"CREATE TABLE test2(a INT PRIMARY KEY, b INT, c INT);\";\n TestingSQLUtil::ExecuteSQLQueryWithOptimizer(\n optimizer, query, result, tuple_descriptor, rows_changed, error_message);\n\n auto table = catalog::Catalog::GetInstance()->GetTableWithName(\n DEFAULT_DB_NAME, \"test2\");\n EXPECT_NE(nullptr, table);\n auto cols = table->GetSchema()->GetColumns();\n EXPECT_EQ(3, cols.size());\n EXPECT_EQ(\"a\", cols[0].column_name);\n EXPECT_EQ(true, cols[0].is_primary_);\n EXPECT_EQ(type::Type::INTEGER, cols[0].GetType());\n EXPECT_EQ(\"b\", cols[1].column_name);\n EXPECT_EQ(type::Type::INTEGER, cols[1].GetType());\n EXPECT_EQ(\"c\", cols[2].column_name);\n EXPECT_EQ(type::Type::INTEGER, cols[2].GetType());\n\n \/\/ Test dropping existing table\n query = \"DROP TABLE test2\";\n TestingSQLUtil::ExecuteSQLQueryWithOptimizer(\n optimizer, query, result, tuple_descriptor, rows_changed, error_message);\n try {\n catalog::Catalog::GetInstance()->GetTableWithName(DEFAULT_DB_NAME, \"test2\");\n EXPECT_TRUE(false);\n } catch (Exception &e) {\n LOG_INFO(\"Correct! Exception(%s) catched\", e.what());\n }\n}\n\nTEST_F(OptimizerSQLTests, GroupByTest) {\n \/\/ Insert additional tuples to test group by\n TestingSQLUtil::ExecuteSQLQuery(\"INSERT INTO test VALUES (5, 11, 000);\");\n TestingSQLUtil::ExecuteSQLQuery(\"INSERT INTO test VALUES (6, 22, 333);\");\n\n \/\/ Test basic case\n TestUtil(\"SELECT b FROM test GROUP BY b having b=11 or b=22\", {\"22\", \"11\"},\n false);\n\n \/\/ Test Aggregate function: COUNT(*)\n TestUtil(\"SELECT COUNT(*) FROM test GROUP BY b\", {\"1\", \"1\", \"2\", \"2\"}, false);\n\n \/\/ Test Aggregate function: COUNT(a)\n TestUtil(\"SELECT COUNT(a) FROM test GROUP BY b\", {\"1\", \"1\", \"2\", \"2\"}, false);\n\n \/\/ Test basic case\n TestUtil(\"SELECT b FROM test GROUP BY b having b=11 or b=22\", {\"22\", \"11\"},\n false);\n\n \/\/ Test Aggregate function: COUNT(*)\n TestUtil(\"SELECT COUNT(*) FROM test GROUP BY b\", {\"1\", \"1\", \"2\", \"2\"}, false);\n\n \/\/ Test Aggregate function: COUNT(a)\n TestUtil(\"SELECT COUNT(a) FROM test GROUP BY b\", {\"1\", \"1\", \"2\", \"2\"}, false);\n\n \/\/ Test group by with having\n TestUtil(\"SELECT AVG(a), b FROM test GROUP BY b having b=22\", {\"3.5\", \"22\"},\n false);\n\n \/\/ Test Aggregate function: MIN(b)\n TestUtil(\"SELECT MIN(a), b FROM test GROUP BY b having b=22\", {\"1\", \"22\"},\n false);\n\n \/\/ Test Aggregate function: MAX(b)\n TestUtil(\"SELECT MAX(a), b FROM test GROUP BY b having b=22\", {\"6\", \"22\"},\n false);\n\n \/\/ Test group by combined with ORDER BY\n TestUtil(\"SELECT b FROM test GROUP BY b ORDER BY b\", {\"0\", \"11\", \"22\", \"33\"},\n true);\n\n \/\/ Test complex expression in aggregation\n TestUtil(\"SELECT b, MAX(a + c) FROM test GROUP BY b ORDER BY b\",\n {\"0\", \"559\", \"11\", \"5\", \"22\", \"339\", \"33\", \"447\"}, true);\n\n \/\/ Test complex expression in select list and order by complex expr\n TestUtil(\"SELECT b + c, SUM(c * a) FROM test GROUP BY b,c ORDER BY b + c\",\n {\"11\", \"0\", \"355\", \"2331\", \"477\", \"1332\", \"555\", \"2220\"}, true);\n\n \/\/ Test Plain aggregation without group by\n TestUtil(\"SELECT SUM(c * a) FROM test\", {\"5883\"}, false);\n}\n\nTEST_F(OptimizerSQLTests, SelectDistinctTest) {\n\/\/ TestingSQLUtil::ExecuteSQLQuery(\"INSERT INTO test VALUES (1, 22, 333);\");\n\/\/ TestingSQLUtil::ExecuteSQLQuery(\"INSERT INTO test VALUES (2, 11, 000);\");\n\/\/ TestingSQLUtil::ExecuteSQLQuery(\"INSERT INTO test VALUES (3, 33, 444);\");\n\/\/ TestingSQLUtil::ExecuteSQLQuery(\"INSERT INTO test VALUES (4, 00, 555);\");\n TestingSQLUtil::ExecuteSQLQuery(\"INSERT INTO test VALUES (5, 00, 555);\");\n TestingSQLUtil::ExecuteSQLQuery(\"INSERT INTO test VALUES (6, 22, 333);\");\n \n \/\/ Test DISTINCT and GROUP BY have the same columns. Avoid additional HashPlan\n TestUtil(\"SELECT DISTINCT b,c FROM test GROUP BY b,c\",\n {\"0\", \"555\", \"33\", \"444\", \"11\", \"0\", \"22\", \"333\"}, false,\n {PlanNodeType::AGGREGATE_V2, PlanNodeType::SEQSCAN});\n \n \/\/ Test GROUP BY cannot satisfied DISTINCT\n TestUtil(\"SELECT DISTINCT b FROM test GROUP BY b,c\",\n {\"22\", \"11\", \"0\", \"33\"}, false, {PlanNodeType::HASH,\n PlanNodeType::AGGREGATE_V2, PlanNodeType::SEQSCAN});\n \n TestingSQLUtil::ExecuteSQLQuery(\"INSERT INTO test VALUES (7, 00, 444);\");\n\n \/\/ Test distinct with order by\n TestUtil(\"SELECT DISTINCT b FROM test ORDER BY b\", {\"0\", \"11\", \"22\", \"33\"},\n true);\n\n \/\/ Test distinct with complex order by\n TestUtil(\"SELECT DISTINCT b, c FROM test ORDER BY 10 * b + c\", {\"11\", \"0\",\n \"0\", \"444\", \"22\", \"333\", \"0\", \"555\", \"33\", \"444\"}, true);\n\n \/\/ Test distinct with limit and star expression\n TestUtil(\"SELECT DISTINCT * FROM test ORDER BY a + 10 * b + c LIMIT 3\",\n {\"2\", \"11\", \"0\", \"7\", \"0\", \"444\", \"1\", \"22\", \"333\"}, true);\n \n \n\n \/\/ Insert additional tuples to test distinct with group by\n TestingSQLUtil::ExecuteSQLQuery(\"INSERT INTO test VALUES (5, 11, 000);\");\n TestingSQLUtil::ExecuteSQLQuery(\"INSERT INTO test VALUES (6, 22, 333);\");\n\n \/\/ Test distinct and group by complex expression\n TestUtil(\"SELECT DISTINCT b + c FROM test GROUP BY b + c ORDER BY b + c\",\n {\"11\", \"355\", \"444\", \"477\", \"555\"}, true);\n}\n} \/\/ namespace test\n} \/\/ namespace peloton\nChange TestUtil to output more information\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Peloton\n\/\/\n\/\/ optimizer_sql_test.cpp\n\/\/\n\/\/ Identification: test\/sql\/optimizer_sql_test.cpp\n\/\/\n\/\/ Copyright (c) 2015-16, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \n\n#include \"sql\/testing_sql_util.h\"\n#include \"catalog\/catalog.h\"\n#include \"common\/harness.h\"\n#include \"executor\/create_executor.h\"\n#include \"optimizer\/optimizer.h\"\n#include \"optimizer\/simple_optimizer.h\"\n#include \"planner\/create_plan.h\"\n#include \"planner\/order_by_plan.h\"\n\nusing std::vector;\nusing std::unordered_set;\nusing std::string;\nusing std::unique_ptr;\nusing std::shared_ptr;\n\nnamespace peloton {\nnamespace test {\n\nclass OptimizerSQLTests : public PelotonTest {\n protected:\n virtual void SetUp() override {\n \/\/ Call parent virtual function first\n PelotonTest::SetUp();\n\n \/\/ Create test database\n CreateAndLoadTable();\n optimizer.reset(new optimizer::Optimizer());\n }\n\n virtual void TearDown() override {\n \/\/ Destroy test database\n auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();\n auto txn = txn_manager.BeginTransaction();\n catalog::Catalog::GetInstance()->DropDatabaseWithName(DEFAULT_DB_NAME, txn);\n txn_manager.CommitTransaction(txn);\n\n \/\/ Call parent virtual function\n PelotonTest::TearDown();\n }\n\n \/*** Helper functions **\/\n void CreateAndLoadTable() {\n \/\/ Create database\n catalog::Catalog::GetInstance()->CreateDatabase(DEFAULT_DB_NAME, nullptr);\n\n \/\/ Create a table first\n TestingSQLUtil::ExecuteSQLQuery(\n \"CREATE TABLE test(a INT PRIMARY KEY, b INT, c INT);\");\n\n \/\/ Insert tuples into table\n TestingSQLUtil::ExecuteSQLQuery(\"INSERT INTO test VALUES (1, 22, 333);\");\n TestingSQLUtil::ExecuteSQLQuery(\"INSERT INTO test VALUES (2, 11, 000);\");\n TestingSQLUtil::ExecuteSQLQuery(\"INSERT INTO test VALUES (3, 33, 444);\");\n TestingSQLUtil::ExecuteSQLQuery(\"INSERT INTO test VALUES (4, 00, 555);\");\n }\n\n void TestUtil(string query, vector ref_result, bool ordered,\n vector expected_plans={}) {\n LOG_DEBUG(\"Running Query \\\"%s\\\"\", query.c_str());\n \n \/\/ Check Plan Nodes are correct if provided\n if (expected_plans.size() > 0) {\n auto plan = TestingSQLUtil::GeneratePlanWithOptimizer(optimizer, query);\n auto plan_ptr = plan.get();\n vector actual_plans;\n while (true) {\n actual_plans.push_back(plan_ptr->GetPlanNodeType());\n if (plan_ptr->GetChildren().size() == 0)\n break;\n plan_ptr = plan_ptr->GetChildren()[0].get();\n }\n EXPECT_EQ(actual_plans, expected_plans);\n }\n \n \/\/ Check plan execution results are correct\n TestingSQLUtil::ExecuteSQLQueryWithOptimizer(optimizer, query, result,\n tuple_descriptor, rows_changed,\n error_message);\n EXPECT_EQ(ref_result.size(), result.size());\n vector actual_result;\n if (ordered) {\n \/\/ If deterministic, do comparision with expected result in order\n for (unsigned i = 0; i < result.size(); i++)\n actual_result.push_back(TestingSQLUtil::GetResultValueAsString(result, i));\n EXPECT_EQ(actual_result, ref_result);\n } else {\n \/\/ If non-deterministic, make sure they have the same set of value\n unordered_set ref_set(ref_result.begin(), ref_result.end());\n for (unsigned i = 0; i < result.size(); i++) {\n string result_str = TestingSQLUtil::GetResultValueAsString(result, i);\n EXPECT_TRUE(ref_set.find(result_str) != ref_set.end());\n }\n }\n }\n\n protected:\n unique_ptr optimizer;\n vector result;\n vector tuple_descriptor;\n string error_message;\n int rows_changed;\n};\n\nTEST_F(OptimizerSQLTests, SimpleSelectTest) {\n \/\/ Testing select star expression\n TestUtil(\"SELECT * from test\", {\"333\", \"22\", \"1\", \"2\", \"11\", \"0\", \"3\", \"33\",\n \"444\", \"4\", \"0\", \"555\"}, false);\n\n \/\/ Testing predicate\n TestUtil(\"SELECT c, b from test where a=1\", {\"333\", \"22\"}, false);\n}\n\nTEST_F(OptimizerSQLTests, SelectOrderByTest) {\n \/\/ Testing order by columns different from select columns\n TestUtil(\"SELECT b from test order by c\", {\"11\", \"22\", \"33\", \"0\"}, true);\n\n \/\/ Testing order by desc\n TestUtil(\"SELECT a from test order by c desc\", {\"4\", \"3\", \"1\", \"2\"}, true);\n\n \/\/ Testing order by complex expression\n TestUtil(\"SELECT * from test order by a + c\", {\"2\", \"11\", \"0\", \"1\", \"22\",\n \"333\", \"3\", \"33\", \"444\", \"4\", \"0\", \"555\"}, true);\n}\n\nTEST_F(OptimizerSQLTests, SelectLimitTest) {\n \/\/ Test limit with default offset\n TestUtil(\"SELECT b FROM test ORDER BY b LIMIT 3\", {\"0\", \"11\", \"22\"}, true);\n\n \/\/ Test limit with offset\n TestUtil(\"SELECT b FROM test ORDER BY b LIMIT 2 OFFSET 2\", {\"22\", \"33\"}, true);\n}\n\nTEST_F(OptimizerSQLTests, SelectProjectionTest) {\n \/\/ Test complex expression projection\n TestUtil(\"SELECT a * 5 + b, -1 + c from test\", {\"27\", \"332\", \"48\", \"443\",\n \"21\", \"-1\", \"20\", \"554\"}, false);\n\n \/\/ Test complex expression in select and order by\n TestUtil(\"SELECT a * 5 + b - c FROM test ORDER BY a * 10 + b\", {\"21\", \"-306\",\n \"-535\", \"-396\"}, true);\n\n \/\/ Test mixing up select simple columns with complex expression\n TestUtil(\"SELECT a, a + c FROM test ORDER BY a * 3 * b DESC, b + c \/ 5 ASC\",\n {\"3\", \"447\", \"2\", \"2\", \"1\", \"334\", \"4\", \"559\"}, true);\n}\n\nTEST_F(OptimizerSQLTests, DeleteSqlTest) {\n \/\/ TODO: Test for index scan\n\n \/\/ Delete with predicates\n string query = \"DELETE FROM test WHERE a = 1 and c = 333\";\n TestingSQLUtil::ExecuteSQLQueryWithOptimizer(\n optimizer, query, result, tuple_descriptor, rows_changed, error_message);\n EXPECT_EQ(1, rows_changed);\n TestingSQLUtil::ExecuteSQLQueryWithOptimizer(optimizer, \"SELECT * FROM test\",\n result, tuple_descriptor,\n rows_changed, error_message);\n EXPECT_EQ(9, result.size());\n\n \/\/ Delete with predicates\n query = \"DELETE FROM test WHERE b = 33\";\n TestingSQLUtil::ExecuteSQLQueryWithOptimizer(\n optimizer, query, result, tuple_descriptor, rows_changed, error_message);\n EXPECT_EQ(1, rows_changed);\n TestingSQLUtil::ExecuteSQLQueryWithOptimizer(optimizer, \"SELECT * FROM test\",\n result, tuple_descriptor,\n rows_changed, error_message);\n EXPECT_EQ(6, result.size());\n\n \/\/ Delete with false predicates\n query = \"DELETE FROM test WHERE b = 123\";\n TestingSQLUtil::ExecuteSQLQueryWithOptimizer(\n optimizer, query, result, tuple_descriptor, rows_changed, error_message);\n EXPECT_EQ(0, rows_changed);\n TestingSQLUtil::ExecuteSQLQueryWithOptimizer(optimizer, \"SELECT * FROM test\",\n result, tuple_descriptor,\n rows_changed, error_message);\n EXPECT_EQ(6, result.size());\n\n \/\/ Full deletion\n query = \"DELETE FROM test\";\n TestingSQLUtil::ExecuteSQLQueryWithOptimizer(\n optimizer, query, result, tuple_descriptor, rows_changed, error_message);\n EXPECT_EQ(2, rows_changed);\n TestingSQLUtil::ExecuteSQLQueryWithOptimizer(optimizer, \"SELECT * FROM test\",\n result, tuple_descriptor,\n rows_changed, error_message);\n EXPECT_EQ(0, result.size());\n}\n\nTEST_F(OptimizerSQLTests, UpdateSqlTest) {\n \/\/ Test Update with complex expression and predicate\n string query = \"UPDATE test SET c = b + 1 WHERE a = 1\";\n TestingSQLUtil::ExecuteSQLQueryWithOptimizer(\n optimizer, query, result, tuple_descriptor, rows_changed, error_message);\n EXPECT_EQ(1, rows_changed);\n TestUtil(\"SELECT c FROM test WHERE a=1\", {\"23\"}, false);\n}\n\nTEST_F(OptimizerSQLTests, InsertSqlTest) {\n string query = \"INSERT INTO test VALUES (5, 55, 555);\";\n TestingSQLUtil::ExecuteSQLQueryWithOptimizer(\n optimizer, query, result, tuple_descriptor, rows_changed, error_message);\n EXPECT_EQ(1, rows_changed);\n\n \/\/ Test the tuple is succesfully inserted\n TestUtil(\"SELECT * FROM test WHERE a=5\", {\"5\", \"55\", \"555\"}, false);\n}\n\nTEST_F(OptimizerSQLTests, DDLSqlTest) {\n \/\/ Test creating new table\n string query = \"CREATE TABLE test2(a INT PRIMARY KEY, b INT, c INT);\";\n TestingSQLUtil::ExecuteSQLQueryWithOptimizer(\n optimizer, query, result, tuple_descriptor, rows_changed, error_message);\n\n auto table = catalog::Catalog::GetInstance()->GetTableWithName(\n DEFAULT_DB_NAME, \"test2\");\n EXPECT_NE(nullptr, table);\n auto cols = table->GetSchema()->GetColumns();\n EXPECT_EQ(3, cols.size());\n EXPECT_EQ(\"a\", cols[0].column_name);\n EXPECT_EQ(true, cols[0].is_primary_);\n EXPECT_EQ(type::Type::INTEGER, cols[0].GetType());\n EXPECT_EQ(\"b\", cols[1].column_name);\n EXPECT_EQ(type::Type::INTEGER, cols[1].GetType());\n EXPECT_EQ(\"c\", cols[2].column_name);\n EXPECT_EQ(type::Type::INTEGER, cols[2].GetType());\n\n \/\/ Test dropping existing table\n query = \"DROP TABLE test2\";\n TestingSQLUtil::ExecuteSQLQueryWithOptimizer(\n optimizer, query, result, tuple_descriptor, rows_changed, error_message);\n try {\n catalog::Catalog::GetInstance()->GetTableWithName(DEFAULT_DB_NAME, \"test2\");\n EXPECT_TRUE(false);\n } catch (Exception &e) {\n LOG_INFO(\"Correct! Exception(%s) catched\", e.what());\n }\n}\n\nTEST_F(OptimizerSQLTests, GroupByTest) {\n \/\/ Insert additional tuples to test group by\n TestingSQLUtil::ExecuteSQLQuery(\"INSERT INTO test VALUES (5, 11, 000);\");\n TestingSQLUtil::ExecuteSQLQuery(\"INSERT INTO test VALUES (6, 22, 333);\");\n\n \/\/ Test basic case\n TestUtil(\"SELECT b FROM test GROUP BY b having b=11 or b=22\", {\"22\", \"11\"},\n false);\n\n \/\/ Test Aggregate function: COUNT(*)\n TestUtil(\"SELECT COUNT(*) FROM test GROUP BY b\", {\"1\", \"1\", \"2\", \"2\"}, false);\n\n \/\/ Test Aggregate function: COUNT(a)\n TestUtil(\"SELECT COUNT(a) FROM test GROUP BY b\", {\"1\", \"1\", \"2\", \"2\"}, false);\n\n \/\/ Test basic case\n TestUtil(\"SELECT b FROM test GROUP BY b having b=11 or b=22\", {\"22\", \"11\"},\n false);\n\n \/\/ Test Aggregate function: COUNT(*)\n TestUtil(\"SELECT COUNT(*) FROM test GROUP BY b\", {\"1\", \"1\", \"2\", \"2\"}, false);\n\n \/\/ Test Aggregate function: COUNT(a)\n TestUtil(\"SELECT COUNT(a) FROM test GROUP BY b\", {\"1\", \"1\", \"2\", \"2\"}, false);\n\n \/\/ Test group by with having\n TestUtil(\"SELECT AVG(a), b FROM test GROUP BY b having b=22\", {\"3.5\", \"22\"},\n false);\n\n \/\/ Test Aggregate function: MIN(b)\n TestUtil(\"SELECT MIN(a), b FROM test GROUP BY b having b=22\", {\"1\", \"22\"},\n false);\n\n \/\/ Test Aggregate function: MAX(b)\n TestUtil(\"SELECT MAX(a), b FROM test GROUP BY b having b=22\", {\"6\", \"22\"},\n false);\n\n \/\/ Test group by combined with ORDER BY\n TestUtil(\"SELECT b FROM test GROUP BY b ORDER BY b\", {\"0\", \"11\", \"22\", \"33\"},\n true);\n\n \/\/ Test complex expression in aggregation\n TestUtil(\"SELECT b, MAX(a + c) FROM test GROUP BY b ORDER BY b\",\n {\"0\", \"559\", \"11\", \"5\", \"22\", \"339\", \"33\", \"447\"}, true);\n\n \/\/ Test complex expression in select list and order by complex expr\n TestUtil(\"SELECT b + c, SUM(c * a) FROM test GROUP BY b,c ORDER BY b + c\",\n {\"11\", \"0\", \"355\", \"2331\", \"477\", \"1332\", \"555\", \"2220\"}, true);\n\n \/\/ Test Plain aggregation without group by\n TestUtil(\"SELECT SUM(c * a) FROM test\", {\"5883\"}, false);\n \n \/\/ Test ORDER BY columns not shown in select list\n TestUtil(\"SELECT a FROM test GROUP BY a,b ORDER BY a + b\",\n {\"4\", \"2\", \"5\", \"1\", \"6\", \"3\"}, true, {PlanNodeType::ORDERBY,\n PlanNodeType::AGGREGATE_V2, PlanNodeType::SEQSCAN});\n}\n\nTEST_F(OptimizerSQLTests, SelectDistinctTest) {\n\/\/ TestingSQLUtil::ExecuteSQLQuery(\"INSERT INTO test VALUES (1, 22, 333);\");\n\/\/ TestingSQLUtil::ExecuteSQLQuery(\"INSERT INTO test VALUES (2, 11, 000);\");\n\/\/ TestingSQLUtil::ExecuteSQLQuery(\"INSERT INTO test VALUES (3, 33, 444);\");\n\/\/ TestingSQLUtil::ExecuteSQLQuery(\"INSERT INTO test VALUES (4, 00, 555);\");\n TestingSQLUtil::ExecuteSQLQuery(\"INSERT INTO test VALUES (5, 00, 555);\");\n TestingSQLUtil::ExecuteSQLQuery(\"INSERT INTO test VALUES (6, 22, 333);\");\n \n \/\/ Test DISTINCT and GROUP BY have the same columns. Avoid additional HashPlan\n TestUtil(\"SELECT DISTINCT b,c FROM test GROUP BY b,c\",\n {\"0\", \"555\", \"33\", \"444\", \"11\", \"0\", \"22\", \"333\"}, false,\n {PlanNodeType::AGGREGATE_V2, PlanNodeType::SEQSCAN});\n \n \/\/ Test GROUP BY cannot satisfied DISTINCT\n TestUtil(\"SELECT DISTINCT b FROM test GROUP BY b,c\",\n {\"22\", \"11\", \"0\", \"33\"}, false, {PlanNodeType::HASH,\n PlanNodeType::AGGREGATE_V2, PlanNodeType::SEQSCAN});\n \n TestingSQLUtil::ExecuteSQLQuery(\"INSERT INTO test VALUES (7, 00, 444);\");\n\n \/\/ Test distinct with order by\n TestUtil(\"SELECT DISTINCT b FROM test ORDER BY b\", {\"0\", \"11\", \"22\", \"33\"},\n true);\n\n \/\/ Test distinct with complex order by\n TestUtil(\"SELECT DISTINCT b, c FROM test ORDER BY 10 * b + c\", {\"11\", \"0\",\n \"0\", \"444\", \"22\", \"333\", \"0\", \"555\", \"33\", \"444\"}, true);\n\n \/\/ Test distinct with limit and star expression\n TestUtil(\"SELECT DISTINCT * FROM test ORDER BY a + 10 * b + c LIMIT 3\",\n {\"2\", \"11\", \"0\", \"7\", \"0\", \"444\", \"1\", \"22\", \"333\"}, true);\n \n \n\n \/\/ Insert additional tuples to test distinct with group by\n TestingSQLUtil::ExecuteSQLQuery(\"INSERT INTO test VALUES (5, 11, 000);\");\n TestingSQLUtil::ExecuteSQLQuery(\"INSERT INTO test VALUES (6, 22, 333);\");\n\n \/\/ Test distinct and group by complex expression\n TestUtil(\"SELECT DISTINCT b + c FROM test GROUP BY b + c ORDER BY b + c\",\n {\"11\", \"355\", \"444\", \"477\", \"555\"}, true);\n}\n} \/\/ namespace test\n} \/\/ namespace peloton\n<|endoftext|>"} {"text":"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nsigned main() {\n\treturn 0;\n}\ntest\/general\/headers: updated.\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nsigned main() {\n\treturn 0;\n}\n<|endoftext|>"} {"text":"\/**********************************************************************\n * $Id$\n *\n * GEOS - Geometry Engine Open Source\n * http:\/\/geos.refractions.net\n *\n * Copyright (C) 2001-2002 Vivid Solutions Inc.\n *\n * This is free software; you can redistribute and\/or modify it under\n * the terms of the GNU Lesser General Public Licence as published\n * by the Free Software Foundation. \n * See the COPYING file for more information.\n *\n **********************************************************************\n * $Log$\n * Revision 1.27 2004\/05\/03 17:15:38 strk\n * leaks on exception fixed.\n *\n * Revision 1.26 2004\/04\/23 00:02:18 strk\n * const-correctness changes\n *\n * Revision 1.25 2004\/04\/20 13:24:15 strk\n * More leaks removed.\n *\n * Revision 1.24 2004\/04\/20 10:14:20 strk\n * Memory leaks removed.\n *\n * Revision 1.23 2004\/04\/19 15:14:46 strk\n * Added missing virtual destructor in SpatialIndex class.\n * Memory leaks fixes. Const and throw specifications added.\n *\n * Revision 1.22 2004\/04\/19 12:51:01 strk\n * Memory leaks fixes. Throw specifications added.\n *\n * Revision 1.21 2004\/04\/16 14:09:17 strk\n * Leaks fixes\n *\n * Revision 1.20 2004\/04\/16 11:04:24 strk\n * Memory leaks plugged on exception thrown\n *\n * Revision 1.19 2004\/04\/16 10:00:08 strk\n * Memory leak fixed.\n *\n * Revision 1.18 2004\/04\/14 09:11:57 strk\n * endCapStyle was never set in BufferOp contructor\n *\n * Revision 1.17 2004\/04\/14 08:38:31 strk\n * BufferOp constructor missed to set argGeom\n *\n * Revision 1.16 2004\/04\/10 22:41:25 ybychkov\n * \"precision\" upgraded to JTS 1.4\n *\n * Revision 1.15 2004\/04\/10 08:40:01 ybychkov\n * \"operation\/buffer\" upgraded to JTS 1.4\n *\n *\n **********************************************************************\/\n\n\n#include \"..\/..\/headers\/opBuffer.h\"\n#include \"..\/..\/headers\/precision.h\"\n\nnamespace geos {\n\n\/**\n* Compute a reasonable scale factor to limit the precision of\n* a given combination of Geometry and buffer distance->\n* The scale factor is based on a heuristic->\n*\n* @param g the Geometry being buffered\n* @param distance the buffer distance\n* @param maxPrecisionDigits the mzx # of digits that should be allowed by\n* the precision determined by the computed scale factor\n*\n* @return a scale factor that allows a reasonable amount of precision for the buffer computation\n*\/\ndouble BufferOp::precisionScaleFactor(Geometry *g,double distance,int maxPrecisionDigits){\n\tEnvelope *env=g->getEnvelopeInternal();\n\tdouble envSize=max(env->getHeight(), env->getWidth());\n\tdelete env;\n\tdouble expandByDistance=distance > 0.0 ? distance : 0.0;\n\tdouble bufEnvSize=envSize + 2 * expandByDistance;\n\t\/\/ the smallest power of 10 greater than the buffer envelope\n\tint bufEnvLog10=(int) (log(bufEnvSize) \/ log(10.0) + 1.0);\n\tint minUnitLog10=bufEnvLog10 - maxPrecisionDigits;\n\t\/\/ scale factor is inverse of min Unit size, so flip sign of exponent\n\tdouble scaleFactor=pow(10.0,-minUnitLog10);\n\treturn scaleFactor;\n}\n\n\/**\n* Computes the buffer of a geometry for a given buffer distance->\n*\n* @param g the geometry to buffer\n* @param distance the buffer distance\n* @return the buffer of the input geometry\n*\/\nGeometry* BufferOp::bufferOp(Geometry *g, double distance){\n\tBufferOp *gBuf=new BufferOp(g);\n\tGeometry* geomBuf;\n\ttry {\n\t\tgeomBuf=gBuf->getResultGeometry(distance);\n\t} catch (...) {\n\t\tdelete gBuf;\n\t\tthrow;\n\t}\n\tdelete gBuf;\n\treturn geomBuf;\n}\n\n\/**\n* Comutes the buffer for a geometry for a given buffer distance\n* and accuracy of approximation->\n*\n* @param g the geometry to buffer\n* @param distance the buffer distance\n* @param quadrantSegments the number of segments used to approximate a quarter circle\n* @return the buffer of the input geometry\n*\n*\/\nGeometry*\nBufferOp::bufferOp(Geometry *g, double distance, int quadrantSegments)\n{\n\tBufferOp *bufOp=new BufferOp(g);\n\tGeometry *geomBuf;\n\tbufOp->setQuadrantSegments(quadrantSegments);\n\ttry {\n\t\tgeomBuf=bufOp->getResultGeometry(distance);\n\t} catch (...) {\n\t\tdelete bufOp;\n\t\tthrow;\n\t}\n\tdelete bufOp;\n\treturn geomBuf;\n}\n\nint BufferOp::MAX_PRECISION_DIGITS=12;\n\/**\n* Initializes a buffer computation for the given geometry\n*\n* @param g the geometry to buffer\n*\/\nBufferOp::BufferOp(Geometry *g) {\n\tquadrantSegments=OffsetCurveBuilder::DEFAULT_QUADRANT_SEGMENTS;\n\tendCapStyle=BufferOp::CAP_ROUND;\n\targGeom = g;\n\tresultGeometry=NULL;\n\tsaveException=NULL;\n}\n\n\/**\n* Specifies the end cap style of the generated buffer->\n* The styles supported are {@link CAP_ROUND}, {@link CAP_BUTT}, and {@link CAP_SQUARE}->\n* The default is CAP_ROUND->\n*\n* @param endCapStyle the end cap style to specify\n*\/\nvoid BufferOp::setEndCapStyle(int nEndCapStyle){\n\tendCapStyle=nEndCapStyle;\n}\n\n\/**\n* Specifies the end cap style of the generated buffer->\n* The styles supported are {@link CAP_ROUND}, {@link CAP_BUTT}, and {@link CAP_SQUARE}->\n* The default is CAP_ROUND->\n*\n* @param endCapStyle the end cap style to specify\n*\/\nvoid BufferOp::setQuadrantSegments(int nQuadrantSegments){\n\tquadrantSegments=nQuadrantSegments;\n}\n\n\/**\n* Returns the buffer computed for a geometry for a given buffer distance->\n*\n* @param g the geometry to buffer\n* @param distance the buffer distance\n* @return the buffer of the input geometry\n*\/\nGeometry* BufferOp::getResultGeometry(double nDistance){\n\tdistance=nDistance;\n\tcomputeGeometry();\n\treturn resultGeometry;\n}\n\n\/**\n* Comutes the buffer for a geometry for a given buffer distance\n* and accuracy of approximation->\n*\n* @param g the geometry to buffer\n* @param distance the buffer distance\n* @param quadrantSegments the number of segments used to approximate a quarter circle\n* @return the buffer of the input geometry\n*\n* @deprecated use setQuadrantSegments instead\n*\/\nGeometry* BufferOp::getResultGeometry(double nDistance, int nQuadrantSegments){\n\tdistance=nDistance;\n\tsetQuadrantSegments(nQuadrantSegments);\n\tcomputeGeometry();\n\treturn resultGeometry;\n}\n\nvoid\nBufferOp::computeGeometry()\n{\n\tbufferOriginalPrecision();\n\tif (resultGeometry!=NULL) return;\n\t\/\/ try and compute with decreasing precision\n\tfor (int precDigits=MAX_PRECISION_DIGITS; precDigits >= 0; precDigits--) \t{\n\t\ttry {\n\t\t\tbufferFixedPrecision(precDigits);\n\t\t} catch (TopologyException *ex) {\n\t\t\tdelete saveException;\n\t\t\tsaveException=ex;\n\t\t\t\/\/ don't propagate the exception - it will be detected by fact that resultGeometry is null\n\t\t} catch (...) {\n\t\t\tthrow;\n\t\t}\n\n\n\t\tif (resultGeometry!=NULL)\n\t\t{\n\t\t\t\/\/ debug\n\t\t\t\/\/if ( saveException ) cerr<toString()<setQuadrantSegments(quadrantSegments);\n\t\tbufBuilder->setEndCapStyle(endCapStyle);\n\t\tresultGeometry=bufBuilder->buffer(argGeom, distance);\n\t} catch (TopologyException *ex) {\n\t\t\/\/ bufBuilder will be deleted below\n\t\tdelete saveException;\n\t\tsaveException=ex;\n\t} catch (...) {\n\t\t\/\/ Unexpected!\n\t\tdelete bufBuilder;\n\t\tthrow;\n\t}\n\tdelete bufBuilder;\n}\n\nvoid\nBufferOp::bufferFixedPrecision(int precisionDigits)\n{\n\tdouble sizeBasedScaleFactor=precisionScaleFactor(argGeom, distance, precisionDigits);\n\tPrecisionModel *fixedPM=new PrecisionModel(sizeBasedScaleFactor);\n\t\/\/ don't change the precision model of the Geometry, just reduce the precision\n\tSimpleGeometryPrecisionReducer *reducer=new SimpleGeometryPrecisionReducer(fixedPM);\n\tGeometry* reducedGeom=reducer->reduce(argGeom);\n\t\/\/cerr<<\"recomputing with precision scale factor=\"<setWorkingPrecisionModel(fixedPM);\n\tbufBuilder->setQuadrantSegments(quadrantSegments);\n\n\t\/\/ this may throw an exception, if robustness errors are encountered\n\ttry {\n\t\tresultGeometry=bufBuilder->buffer(reducedGeom, distance);\n\t} catch (...) {\n\t\tdelete bufBuilder;\n\t\tdelete reducer;\n\t\tdelete fixedPM;\n\t\tdelete reducedGeom;\n\t\tthrow;\n\t}\n\tdelete bufBuilder;\n\tdelete reducer;\n\tdelete fixedPM;\n\tdelete reducedGeom;\n}\n\n}\nReduced dynamic allocations in bufferOriginalPrecision and bufferFixedPrecision.\/**********************************************************************\n * $Id$\n *\n * GEOS - Geometry Engine Open Source\n * http:\/\/geos.refractions.net\n *\n * Copyright (C) 2001-2002 Vivid Solutions Inc.\n *\n * This is free software; you can redistribute and\/or modify it under\n * the terms of the GNU Lesser General Public Licence as published\n * by the Free Software Foundation. \n * See the COPYING file for more information.\n *\n **********************************************************************\n * $Log$\n * Revision 1.28 2004\/05\/05 10:03:49 strk\n * Reduced dynamic allocations in bufferOriginalPrecision and bufferFixedPrecision.\n *\n * Revision 1.27 2004\/05\/03 17:15:38 strk\n * leaks on exception fixed.\n *\n * Revision 1.26 2004\/04\/23 00:02:18 strk\n * const-correctness changes\n *\n * Revision 1.25 2004\/04\/20 13:24:15 strk\n * More leaks removed.\n *\n * Revision 1.24 2004\/04\/20 10:14:20 strk\n * Memory leaks removed.\n *\n * Revision 1.23 2004\/04\/19 15:14:46 strk\n * Added missing virtual destructor in SpatialIndex class.\n * Memory leaks fixes. Const and throw specifications added.\n *\n * Revision 1.22 2004\/04\/19 12:51:01 strk\n * Memory leaks fixes. Throw specifications added.\n *\n * Revision 1.21 2004\/04\/16 14:09:17 strk\n * Leaks fixes\n *\n * Revision 1.20 2004\/04\/16 11:04:24 strk\n * Memory leaks plugged on exception thrown\n *\n * Revision 1.19 2004\/04\/16 10:00:08 strk\n * Memory leak fixed.\n *\n * Revision 1.18 2004\/04\/14 09:11:57 strk\n * endCapStyle was never set in BufferOp contructor\n *\n * Revision 1.17 2004\/04\/14 08:38:31 strk\n * BufferOp constructor missed to set argGeom\n *\n * Revision 1.16 2004\/04\/10 22:41:25 ybychkov\n * \"precision\" upgraded to JTS 1.4\n *\n * Revision 1.15 2004\/04\/10 08:40:01 ybychkov\n * \"operation\/buffer\" upgraded to JTS 1.4\n *\n *\n **********************************************************************\/\n\n\n#include \"..\/..\/headers\/opBuffer.h\"\n#include \"..\/..\/headers\/precision.h\"\n\nnamespace geos {\n\n\/**\n* Compute a reasonable scale factor to limit the precision of\n* a given combination of Geometry and buffer distance->\n* The scale factor is based on a heuristic->\n*\n* @param g the Geometry being buffered\n* @param distance the buffer distance\n* @param maxPrecisionDigits the mzx # of digits that should be allowed by\n* the precision determined by the computed scale factor\n*\n* @return a scale factor that allows a reasonable amount of precision for the buffer computation\n*\/\ndouble BufferOp::precisionScaleFactor(Geometry *g,double distance,int maxPrecisionDigits){\n\tEnvelope *env=g->getEnvelopeInternal();\n\tdouble envSize=max(env->getHeight(), env->getWidth());\n\tdelete env;\n\tdouble expandByDistance=distance > 0.0 ? distance : 0.0;\n\tdouble bufEnvSize=envSize + 2 * expandByDistance;\n\t\/\/ the smallest power of 10 greater than the buffer envelope\n\tint bufEnvLog10=(int) (log(bufEnvSize) \/ log(10.0) + 1.0);\n\tint minUnitLog10=bufEnvLog10 - maxPrecisionDigits;\n\t\/\/ scale factor is inverse of min Unit size, so flip sign of exponent\n\tdouble scaleFactor=pow(10.0,-minUnitLog10);\n\treturn scaleFactor;\n}\n\n\/**\n* Computes the buffer of a geometry for a given buffer distance->\n*\n* @param g the geometry to buffer\n* @param distance the buffer distance\n* @return the buffer of the input geometry\n*\/\nGeometry* BufferOp::bufferOp(Geometry *g, double distance){\n\tBufferOp *gBuf=new BufferOp(g);\n\tGeometry* geomBuf;\n\ttry {\n\t\tgeomBuf=gBuf->getResultGeometry(distance);\n\t} catch (...) {\n\t\tdelete gBuf;\n\t\tthrow;\n\t}\n\tdelete gBuf;\n\treturn geomBuf;\n}\n\n\/**\n* Comutes the buffer for a geometry for a given buffer distance\n* and accuracy of approximation->\n*\n* @param g the geometry to buffer\n* @param distance the buffer distance\n* @param quadrantSegments the number of segments used to approximate a quarter circle\n* @return the buffer of the input geometry\n*\n*\/\nGeometry*\nBufferOp::bufferOp(Geometry *g, double distance, int quadrantSegments)\n{\n\tBufferOp *bufOp=new BufferOp(g);\n\tGeometry *geomBuf;\n\tbufOp->setQuadrantSegments(quadrantSegments);\n\ttry {\n\t\tgeomBuf=bufOp->getResultGeometry(distance);\n\t} catch (...) {\n\t\tdelete bufOp;\n\t\tthrow;\n\t}\n\tdelete bufOp;\n\treturn geomBuf;\n}\n\nint BufferOp::MAX_PRECISION_DIGITS=12;\n\/**\n* Initializes a buffer computation for the given geometry\n*\n* @param g the geometry to buffer\n*\/\nBufferOp::BufferOp(Geometry *g) {\n\tquadrantSegments=OffsetCurveBuilder::DEFAULT_QUADRANT_SEGMENTS;\n\tendCapStyle=BufferOp::CAP_ROUND;\n\targGeom = g;\n\tresultGeometry=NULL;\n\tsaveException=NULL;\n}\n\n\/**\n* Specifies the end cap style of the generated buffer->\n* The styles supported are {@link CAP_ROUND}, {@link CAP_BUTT}, and {@link CAP_SQUARE}->\n* The default is CAP_ROUND->\n*\n* @param endCapStyle the end cap style to specify\n*\/\nvoid BufferOp::setEndCapStyle(int nEndCapStyle){\n\tendCapStyle=nEndCapStyle;\n}\n\n\/**\n* Specifies the end cap style of the generated buffer->\n* The styles supported are {@link CAP_ROUND}, {@link CAP_BUTT}, and {@link CAP_SQUARE}->\n* The default is CAP_ROUND->\n*\n* @param endCapStyle the end cap style to specify\n*\/\nvoid BufferOp::setQuadrantSegments(int nQuadrantSegments){\n\tquadrantSegments=nQuadrantSegments;\n}\n\n\/**\n* Returns the buffer computed for a geometry for a given buffer distance->\n*\n* @param g the geometry to buffer\n* @param distance the buffer distance\n* @return the buffer of the input geometry\n*\/\nGeometry* BufferOp::getResultGeometry(double nDistance){\n\tdistance=nDistance;\n\tcomputeGeometry();\n\treturn resultGeometry;\n}\n\n\/**\n* Comutes the buffer for a geometry for a given buffer distance\n* and accuracy of approximation->\n*\n* @param g the geometry to buffer\n* @param distance the buffer distance\n* @param quadrantSegments the number of segments used to approximate a quarter circle\n* @return the buffer of the input geometry\n*\n* @deprecated use setQuadrantSegments instead\n*\/\nGeometry* BufferOp::getResultGeometry(double nDistance, int nQuadrantSegments){\n\tdistance=nDistance;\n\tsetQuadrantSegments(nQuadrantSegments);\n\tcomputeGeometry();\n\treturn resultGeometry;\n}\n\nvoid\nBufferOp::computeGeometry()\n{\n\tbufferOriginalPrecision();\n\tif (resultGeometry!=NULL) return;\n\t\/\/ try and compute with decreasing precision\n\tfor (int precDigits=MAX_PRECISION_DIGITS; precDigits >= 0; precDigits--) \t{\n\t\ttry {\n\t\t\tbufferFixedPrecision(precDigits);\n\t\t} catch (TopologyException *ex) {\n\t\t\tdelete saveException;\n\t\t\tsaveException=ex;\n\t\t\t\/\/ don't propagate the exception - it will be detected by fact that resultGeometry is null\n\t\t} catch (...) {\n\t\t\tthrow;\n\t\t}\n\n\n\t\tif (resultGeometry!=NULL)\n\t\t{\n\t\t\t\/\/ debug\n\t\t\t\/\/if ( saveException ) cerr<toString()<toString()<"} {"text":"\/\/ Copyright (C) 2012 Rhys Ulerich\n\/\/\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with this program. If not, see .\n\n#include \"ar.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n\/** @file\n * A GNU Octave wrapper estimating the best AR(p) model given signal input.\n * Compare \\ref arsel.cpp.\n *\/\n\n\/\/ Compile-time defaults in the code also appearing in the help message\n#define DEFAULT_SUBMEAN true\n#define DEFAULT_ABSRHO true\n#define DEFAULT_MAXORDER 512\n#define STRINGIFY(x) STRINGIFY_HELPER(x)\n#define STRINGIFY_HELPER(x) #x\n\nDEFUN_DLD(\n arsel, args, nargout,\n \"\\t[A, mu, sigma2eps, eff_var, eff_N, T0] = arsel (d, submean, absrho, maxorder)\\n\"\n \"\\tAutomatically fit an autoregressive model to an input signal.\\n\"\n \"\\t\\n\"\n \"\\tUse ar::burg_method and ar::best_model > to\\n\"\n \"\\tobtain the most likely autoregressive process for input signal d.\\n\"\n \"\\tThe sample mean of d will be subtracted whenever submean is true.\\n\"\n \"\\tThe absolute value of the autocorrelation function will be used\\n\"\n \"\\tin computing the decorrelation time T0 whenever absrho is true.\\n\"\n \"\\tModel orders zero through min(columns(d), maxorder) will be considered.\\n\"\n \"\\t\\n\"\n \"\\tThe filter()-ready process parameters are returned in A, the sample mean\\n\"\n \"\\tin mu, and the innovation variance \\\\sigma^2_\\\\epsilon in sigma2eps.\\n\"\n \"\\tGiven the observed autocorrelation structure, a decorrelation time T0 is\\n\"\n \"\\tcomputed and used to estimate the effective signal variance eff_var.\\n\"\n \"\\tThe number of effectively independent samples is returned in eff_N.\\n\"\n \"\\t\\n\"\n \"\\tOne may simulate N samples from the fitted process by calling:\\n\"\n \"\\t\\n\"\n \"\\t\\tx = mu + filter([1], A, sqrt(sigma2eps)*randn(N,1));\\n\"\n \"\\t\\n\"\n \"\\tWhen not supplied, submean defaults to \" STRINGIFY(DEFAULT_SUBMEAN) \".\\n\"\n \"\\tWhen not supplied, absrho defaults to \" STRINGIFY(DEFAULT_ABSRHO) \".\\n\"\n \"\\tWhen not supplied, maxorder defaults to \" STRINGIFY(DEFAULT_MAXORDER) \".\\n\"\n \"\\tWhen no outputs are requested, a struct with all outputs is returned.\\n\"\n)\n{\n std::size_t maxorder = DEFAULT_MAXORDER;\n bool absrho = DEFAULT_ABSRHO;\n bool submean = DEFAULT_SUBMEAN;\n RowVector data;\n switch (args.length())\n {\n case 4:\n maxorder = args(3).ulong_value();\n case 3:\n absrho = args(2).bool_value();\n case 2:\n submean = args(1).bool_value();\n case 1:\n data = args(0).row_vector_value();\n break;\n default:\n error(\"Invalid call to arsel. Correct usage is: \");\n case 0:\n print_usage();\n return octave_value();\n }\n\n \/\/ How much data will we be processing?\n const size_t N = data.dims().numel();\n if (!N)\n {\n error(\"arsel: input signal d must have nonzero length\");\n return octave_value();\n }\n\n \/\/ Use burg_method to estimate a hierarchy of AR models from input data\n double mu;\n std::vector params, sigma2e, gain, autocor;\n params .reserve(maxorder*(maxorder + 1)\/2);\n sigma2e.reserve(maxorder + 1);\n gain .reserve(maxorder + 1);\n autocor.reserve(maxorder + 1);\n ar::burg_method(data.fortran_vec(), data.fortran_vec() + N,\n mu, maxorder,\n std::back_inserter(params),\n std::back_inserter(sigma2e),\n std::back_inserter(gain),\n std::back_inserter(autocor),\n submean, \/* output hierarchy? *\/ true);\n\n \/\/ Keep only best model according to CIC accounting for subtract_mean.\n if (submean)\n {\n ar::best_model > >(\n N, params, sigma2e, gain, autocor);\n }\n else\n {\n ar::best_model > >(\n N, params, sigma2e, gain, autocor);\n }\n\n \/\/ Compute decorrelation time from the estimated autocorrelation model\n double T0 = std::numeric_limits::quiet_NaN();\n if (nargout == 0 || nargout > 2)\n {\n ar::predictor p = ar::autocorrelation(\n params.begin(), params.end(), gain[0], autocor.begin());\n T0 = ar::decorrelation_time(N, p, absrho);\n }\n\n \/\/ Prepare autoregressive process parameters for Octave's filter function\n RowVector A(params.size() + 1, \/* leading one *\/ 1);\n std::copy(params.begin(), params.end(), A.fortran_vec() + 1);\n\n \/\/ Prepare output: [A, mu, sigma2eps, eff_var, eff_N, T0]\n \/\/ Unbiased effective variance expression from [Trenberth1984]\n octave_value_list result;\n std::list names;\n switch (nargout == 0 ? std::numeric_limits::max() : nargout)\n {\n default:\n if (nargout) warning(\"arsel: too many output values requested\");\n case 6:\n names.push_front(\"T0\");\n result.prepend(T0);\n case 5:\n names.push_front(\"eff_N\");\n result.prepend(N \/ T0);\n case 4:\n names.push_front(\"eff_var\");\n result.prepend((N*gain[0]*sigma2e[0]) \/ (N - T0));\n case 3:\n names.push_front(\"sigma2eps\");\n result.prepend(sigma2e[0]);\n case 2:\n names.push_front(\"mu\");\n result.prepend(mu);\n case 1:\n names.push_front(\"A\");\n result.prepend(A);\n break;\n case 0:\n panic_impossible();\n }\n\n \/\/ Either return requested results in assignment-friendly fashion\n \/\/ or, when nothing was requested, return a struct to likely display.\n if (nargout)\n {\n result.stash_name_tags(names);\n }\n else \/\/ nargout == 0\n {\n Octave_map m;\n int i = 0;\n while (names.size()) {\n m.assign(names.front(), result(i++));\n names.pop_front();\n }\n result.resize(1);\n result(0) = m;\n }\n\n \/\/ Provide no results whenever an error was detected\n if (error_state)\n {\n warning(\"arsel: error detected; no results returned\");\n result.resize(0);\n }\n\n return result;\n}\nProgress on batching within arsel\/\/ Copyright (C) 2012 Rhys Ulerich\n\/\/\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with this program. If not, see .\n\n#include \"ar.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n\/** @file\n * A GNU Octave wrapper estimating the best AR(p) model given signal input.\n * Compare \\ref arsel.cpp.\n *\/\n\n\/\/ Compile-time defaults in the code also appearing in the help message\n#define DEFAULT_SUBMEAN true\n#define DEFAULT_ABSRHO true\n#define DEFAULT_MAXORDER 512\n#define STRINGIFY(x) STRINGIFY_HELPER(x)\n#define STRINGIFY_HELPER(x) #x\n\nDEFUN_DLD(\n arsel, args, nargout,\n \"\\tM = arsel (d, submean, absrho, maxorder)\\n\"\n \"\\tAutomatically fit autoregressive models to input signals.\\n\"\n \"\\t\\n\"\n \"\\tUse ar::burg_method and ar::best_model > to\\n\"\n \"\\tfit an autoregressive process for signals contained in the rows of d.\\n\"\n \"\\tSample means will be subtracted whenever submean is true. Model\\n\"\n \"\\torders zero through min(columns(d), maxorder) will be considered.\\n\"\n \"\\tA structure is returned where each field either contains a result\\n\"\n \"\\tindexable by the signal number (i.e. the row indices of input matrix\\n\"\n \"\\td) or it contains a single scalar applicable to all signals.\\n\"\n \"\\t\\n\"\n \"\\tThe number of samples in d (i.e. the number of rows) is returned\\n\"\n \"\\tin field 'N'. The filter()-ready process parameters are returned\\n\"\n \"\\tin field 'A', the sample mean in 'mu', and the innovation variance\\n\"\n \"\\t\\\\sigma^2_\\\\epsilon in 'sigma2eps'. The process gains are returned\\n\"\n \"\\tin 'gain' and the autocorrelation boundary conditions in 'autocor'\\n\"\n \"\\tfor lags zero through the model order, inclusive.\\n\"\n \"\\t\\n\"\n \"\\tGiven the observed autocorrelation structure, a decorrelation time\\n\"\n \"\\t'T0' is computed and used to estimate the effective signal variance\\n\"\n \"\\t'eff_var'. The number of effectively independent samples is returned\\n\"\n \"\\tin 'eff_N'. These effective values are combined to estimate the\\n\"\n \"\\tsampling error (i.e. the standard deviation of the sample mean)\\n\"\n \"\\tas field 'mu_sigma'. The absolute value of the autocorrelation\\n\"\n \"\\tfunction will be used in computing the decorrelation times whenever\\n\"\n \"\\tabsrho is true.\\n\"\n \"\\t\\n\"\n \"\\tOne may simulate N samples from a fitted process analogously to\\n\"\n \"\\t\\n\"\n \"\\t\\tx = mu + filter([1], A, sqrt(sigma2eps)*randn(N,1));\\n\"\n \"\\t\\n\"\n \"\\tWhen omitted, submean defaults to \" STRINGIFY(DEFAULT_SUBMEAN) \".\\n\"\n \"\\tWhen omitted, absrho defaults to \" STRINGIFY(DEFAULT_ABSRHO) \".\\n\"\n \"\\tWhen omitted, maxorder defaults to \" STRINGIFY(DEFAULT_MAXORDER) \".\\n\"\n)\n{\n std::size_t maxorder = DEFAULT_MAXORDER;\n bool absrho = DEFAULT_ABSRHO;\n bool submean = DEFAULT_SUBMEAN;\n Matrix data;\n switch (args.length())\n {\n case 4: maxorder = args(3).ulong_value();\n case 3: absrho = args(2).bool_value();\n case 2: submean = args(1).bool_value();\n case 1: data = args(0).matrix_value();\n if (!error_state) break;\n default:\n error(\"Invalid call to arsel. Correct usage is: \");\n case 0:\n print_usage();\n return octave_value();\n }\n\n const octave_idx_type M = data.rows(); \/\/ Number of signals\n const octave_idx_type N = data.cols(); \/\/ Samples per signal\n\n \/\/ Prepare per-signal storage locations to return to caller\n Cell _A (dim_vector(M,1));\n Cell _autocor (dim_vector(M,1));\n ColumnVector _eff_N (M);\n ColumnVector _eff_var (M);\n ColumnVector _gain (M);\n ColumnVector _mu (M);\n ColumnVector _mu_sigma (M);\n ColumnVector _sigma2eps(M);\n ColumnVector _T0 (M);\n\n \/\/ Prepare vectors to capture burg_method() output\n std::vector params, sigma2e, gain, autocor;\n params .reserve(maxorder*(maxorder + 1)\/2);\n sigma2e.reserve(maxorder + 1);\n gain .reserve(maxorder + 1);\n autocor.reserve(maxorder + 1);\n\n \/\/ Prepare repeatedly-used working storage for burg_method()\n std::vector f, b, Ak, ac;\n\n \/\/ Process each signal in turn...\n for (octave_idx_type i = 0; i < M; ++i)\n {\n \/\/ Use burg_method to estimate a hierarchy of AR models from input data\n params .clear();\n sigma2e.clear();\n gain .clear();\n autocor.clear();\n ar::strided_adaptor signal_begin(&data(i,0), N);\n ar::strided_adaptor signal_end (&data(i,N), N);\n ar::burg_method(signal_begin, signal_end, _mu(i), maxorder,\n std::back_inserter(params),\n std::back_inserter(sigma2e),\n std::back_inserter(gain),\n std::back_inserter(autocor),\n submean, \/* output hierarchy? *\/ true, f, b, Ak, ac);\n\n \/\/ Keep only best model according to CIC accounting for subtract_mean.\n \/\/ TODO Permit specifying the criterion as a function argument.\n if (submean)\n {\n ar::best_model > >(\n N, params, sigma2e, gain, autocor);\n }\n else\n {\n ar::best_model > >(\n N, params, sigma2e, gain, autocor);\n }\n\n \/\/ Compute decorrelation time from the estimated autocorrelation model\n ar::predictor p = ar::autocorrelation(\n params.begin(), params.end(), gain[0], autocor.begin());\n _T0(i) = ar::decorrelation_time(N, p, absrho);\n\n \/\/ Filter()-ready process parameters in field 'A' with leading one\n {\n RowVector t(params.size() + 1);\n t(0) = 1;\n std::copy(params.begin(), params.end(), t.fortran_vec() + 1);\n _A(i) = t;\n }\n\n \/\/ Field 'sigma2eps'\n _sigma2eps(i) = sigma2e[0];\n\n \/\/ Field 'gain'\n _gain(i) = gain[0];\n\n \/\/ Field 'autocor'\n {\n RowVector t(autocor.size());\n std::copy(autocor.begin(), autocor.end(), t.fortran_vec());\n _autocor.assign(i, t);\n }\n\n \/\/ Field 'eff_var'\n \/\/ Unbiased effective variance expression from [Trenberth1984]\n _eff_var(i) = (N*gain[0]*sigma2e[0]) \/ (N - _T0(i));\n\n \/\/ Field 'eff_N'\n _eff_N(i) = N \/ _T0(i);\n\n \/\/ Field 'mu_sigma'\n \/\/ Variance of the sample mean using effective quantities\n _mu_sigma(i) = std::sqrt(_eff_var(i) \/ _eff_N(i));\n\n \/\/ Permit user to interrupt the computations at this time\n OCTAVE_QUIT;\n }\n\n \/\/ Provide no results whenever an error was detected\n if (error_state)\n {\n warning(\"arsel: error detected; no results returned\");\n return octave_value_list();\n }\n\n \/\/ Build map containing return fields\n Octave_map retval;\n retval.assign(\"A\", octave_value(_A));\n retval.assign(\"absrho\", octave_value(absrho));\n retval.assign(\"autocor\", octave_value(_autocor));\n retval.assign(\"eff_N\", _eff_N);\n retval.assign(\"eff_var\", _eff_var);\n retval.assign(\"gain\", _gain);\n retval.assign(\"maxorder\", octave_value(maxorder));\n retval.assign(\"mu\", _mu);\n retval.assign(\"mu_sigma\", _mu_sigma);\n retval.assign(\"N\", octave_value(N));\n retval.assign(\"sigma2eps\", _sigma2eps);\n retval.assign(\"submean\", octave_value(submean));\n retval.assign(\"T0\", _T0);\n\n return octave_value_list(retval);\n}\n<|endoftext|>"} {"text":"\n#include \n\n#include \"flame\/base.h\"\n#include \"pyflame.h\"\n\n\n#define TRY PyMachine *machine = reinterpret_cast(raw); try\n\nnamespace {\n\nstruct PyMachine {\n PyObject_HEAD\n\n PyObject *weak;\n Machine *machine;\n};\n\nstatic\nint PyMachine_init(PyObject *raw, PyObject *args, PyObject *kws)\n{\n TRY {\n assert(!machine->weak);\n\n std::auto_ptr C(PyGLPSParse2Config(raw, args, kws));\n\n machine->machine = new Machine(*C);\n\n return 0;\n } CATCH3(key_error, KeyError, -1)\n CATCH3(std::invalid_argument, ValueError, -1)\n CATCH3(std::exception, RuntimeError, -1)\n}\n\nstatic\nvoid PyMachine_free(PyObject *raw)\n{\n TRY {\n std::auto_ptr S(machine->machine);\n machine->machine = NULL;\n\n if(machine->weak)\n PyObject_ClearWeakRefs(raw);\n\n Py_TYPE(raw)->tp_free(raw);\n } CATCH2V(std::exception, RuntimeError)\n}\n\nstatic\nPyObject *PyMachine_str(PyObject *raw)\n{\n TRY {\n std::ostringstream strm;\n strm << *(machine->machine);\n return PyString_FromString(strm.str().c_str());\n } CATCH()\n}\n\nstatic\nPyObject *PyMachine_conf(PyObject *raw, PyObject *args, PyObject *kws)\n{\n TRY {\n PyObject *pyindex = Py_None;\n const char *pnames[] = {\"index\", NULL};\n if(!PyArg_ParseTupleAndKeywords(args, kws, \"|O\", (char**)pnames, &pyindex))\n return NULL;\n\n Config C;\n if(pyindex==Py_None) {\n C = machine->machine->conf();\n } else if(PyNumber_Check(pyindex)) {\n PyRef<> pylong(PyNumber_Long(pyindex));\n long index = PyLong_AsLong(pylong.py());\n if(index<0 || (unsigned long)index>=machine->machine->size())\n return PyErr_Format(PyExc_IndexError, \"Element index out of range\");\n C = (*machine->machine)[index]->conf();\n } else {\n return PyErr_Format(PyExc_ValueError, \"'index' must be an integer or None\");\n }\n C.flatten();\n\n return conf2dict(&C);\n } CATCH()\n}\n\nstatic\nPyObject *PyMachine_allocState(PyObject *raw, PyObject *args, PyObject *kws)\n{\n TRY {\n PyObject *d = Py_None, *W = Py_False;\n const char *pnames[] = {\"config\", \"inherit\", NULL};\n if(!PyArg_ParseTupleAndKeywords(args, kws, \"|OO\", (char**)pnames, &d, &W))\n return NULL;\n\n Config C;\n if(d==Py_None) {\n C = machine->machine->conf();\n } else if(PyDict_Check(d)) {\n if(PyObject_IsTrue(W)) {\n C = machine->machine->conf();\n C.push_scope();\n }\n PyRef<> list(PyMapping_Items(d));\n List2Config(C, list.py());\n } else {\n return PyErr_Format(PyExc_ValueError, \"allocState() needs config=None or {}\");\n }\n std::auto_ptr state(machine->machine->allocState(C));\n PyObject *ret = wrapstate(state.get());\n state.release();\n return ret;\n } CATCH()\n}\n\nstruct PyStoreObserver : public Observer\n{\n PyRef<> list;\n PyStoreObserver()\n :list(PyList_New(0))\n {}\n virtual ~PyStoreObserver() {}\n virtual void view(const ElementVoid* elem, const StateBase* state)\n {\n PyRef<> tuple(PyTuple_New(2));\n std::auto_ptr tmpstate(state->clone());\n PyRef<> statecopy(wrapstate(tmpstate.get()));\n tmpstate.release();\n\n PyTuple_SET_ITEM(tuple.py(), 0, PyInt_FromSize_t(elem->index));\n PyTuple_SET_ITEM(tuple.py(), 1, statecopy.release());\n if(PyList_Append(list.py(), tuple.py()))\n throw std::runtime_error(\"\"); \/\/ a py exception is active\n }\n};\n\nstruct PyScopedObserver\n{\n Machine *machine;\n std::vector observed;\n PyScopedObserver(Machine *m) : machine(m) {}\n ~PyScopedObserver() {\n for(size_t i=0; isize(); i++) {\n (*machine)[i]->set_observer(NULL);\n }\n }\n void observe(size_t i, Observer *o)\n {\n if(i>=machine->size())\n throw std::runtime_error(\"element index out of range\");\n observed.push_back(i);\n (*machine)[i]->set_observer(o);\n }\n};\n\nstatic\nPyObject *PyMachine_propagate(PyObject *raw, PyObject *args, PyObject *kws)\n{\n\n TRY {\n PyObject *state, *toobserv = Py_None;\n unsigned long start = 0, max = (unsigned long)-1;\n const char *pnames[] = {\"state\", \"start\", \"max\", \"observe\", NULL};\n if(!PyArg_ParseTupleAndKeywords(args, kws, \"O|kkO\", (char**)pnames, &state, &start, &max, &toobserv))\n return NULL;\n\n PyStoreObserver observer;\n PyScopedObserver observing(machine->machine);\n\n if(toobserv!=Py_None) {\n PyRef<> iter(PyObject_GetIter(toobserv)), item;\n\n while(item.reset(PyIter_Next(iter.py()), PyRef<>::allow_null())) {\n Py_ssize_t num = PyNumber_AsSsize_t(item.py(), PyExc_ValueError);\n if(PyErr_Occurred())\n throw std::runtime_error(\"\"); \/\/ caller will get active python exception\n\n observing.observe(num, &observer);\n\n }\n }\n\n machine->machine->propagate(unwrapstate(state), start, max);\n if(toobserv) {\n return observer.list.release();\n } else {\n Py_RETURN_NONE;\n }\n } CATCH2(std::invalid_argument, ValueError)\n CATCH()\n}\n\nstatic\nPyObject *PyMachine_reconfigure(PyObject *raw, PyObject *args, PyObject *kws)\n{\n TRY{\n unsigned long idx;\n PyObject *conf, *replace = Py_False;\n const char *pnames[] = {\"index\", \"config\", \"replace\", NULL};\n if(!PyArg_ParseTupleAndKeywords(args, kws, \"kO!|O\", (char**)pnames, &idx, &PyDict_Type, &conf, &replace))\n return NULL;\n\n if(idx>=machine->machine->size())\n return PyErr_Format(PyExc_ValueError, \"invalid element index %lu\", idx);\n\n Config newconf;\n if(!PyObject_IsTrue(replace))\n newconf = (*machine->machine)[idx]->conf();\n\n PyRef<> list(PyMapping_Items(conf));\n List2Config(newconf, list.py(), 3); \/\/ set depth=3 to prevent recursion\n\n machine->machine->reconfigure(idx, newconf);\n\n Py_RETURN_NONE;\n } CATCH2(std::invalid_argument, ValueError)\n CATCH()\n}\n\nstatic\nPyObject *PyMachine_find(PyObject *raw, PyObject *args, PyObject *kws)\n{\n TRY{\n const char *ename = NULL, *etype = NULL;\n const char *pnames[] = {\"name\", \"type\", NULL};\n if(!PyArg_ParseTupleAndKeywords(args, kws, \"|zz\", (char**)pnames, &ename, &etype))\n return NULL;\n\n PyRef<> ret(PyList_New(0));\n\n std::pair range;\n\n if(ename && etype) {\n return PyErr_Format(PyExc_ValueError, \"only one of 'ename' or 'etype' may be given\");\n } else if(ename) {\n range = machine->machine->equal_range(ename);\n } else if(etype) {\n range = machine->machine->equal_range_type(etype);\n } else {\n range = machine->machine->all_range();\n }\n\n for(; range.first!=range.second; ++range.first) {\n ElementVoid *elem = *range.first;\n\n PyRef<> pyidx(PyInt_FromLong(elem->index));\n\n if(PyList_Append(ret.py(), pyidx.py()))\n return NULL;\n }\n\n return ret.release();\n }CATCH()\n}\n\nstatic\nPy_ssize_t PyMachine_len(PyObject *raw)\n{\n TRY{\n return machine->machine->size();\n }CATCH1(-1)\n}\n\nstatic PyMethodDef PyMachine_methods[] = {\n {\"conf\", (PyCFunction)&PyMachine_conf, METH_VARARGS|METH_KEYWORDS,\n \"conf() -> {} Machine config\\n\"\n \"conf(index) -> {} Element config\"},\n {\"allocState\", (PyCFunction)&PyMachine_allocState, METH_VARARGS|METH_KEYWORDS,\n \"allocState() -> State\\n\"\n \"allocState({'variable':int|str}) -> State\\n\"\n \"Allocate a new State based on this Machine's configuration.\"\n \" Optionally provide additional configuration\"},\n {\"propagate\", (PyCFunction)&PyMachine_propagate, METH_VARARGS|METH_KEYWORDS,\n \"propagate(State, start=0, max=-1, observe=None)\\n\"\n \"propagate(State, start=0, max=-1, observe=[1,4,...]) -> [(index,State), ...]\\n\"\n \"Propagate the provided State through the simulation.\\n\"\n \"\\n\"\n \"start and max selects through which element the State will be passed.\\n\"\n \"\\n\"\n \"observe may be None or an iterable yielding element indicies.\\n\"\n \"In the second form propagate() returns a list of tuples with the output State of the selected elements.\"\n },\n {\"reconfigure\", (PyCFunction)&PyMachine_reconfigure, METH_VARARGS|METH_KEYWORDS,\n \"reconfigure(index, {'variable':int|str})\\n\"\n \"Change the configuration of an element.\"},\n {\"find\", (PyCFunction)&PyMachine_find, METH_VARARGS|METH_KEYWORDS,\n \"find(ename=None, etype=None) -> [int]\\n\"\n \"Return a list of element indices for element name or type matching the given string.\"},\n {NULL, NULL, 0, NULL}\n};\n\nstatic PySequenceMethods PyMachine_seq = {\n &PyMachine_len\n};\n\nstatic PyTypeObject PyMachineType = {\n#if PY_MAJOR_VERSION >= 3\n PyVarObject_HEAD_INIT(NULL, 0)\n#else\n PyObject_HEAD_INIT(NULL)\n 0,\n#endif\n \"flame._internal.Machine\",\n sizeof(PyMachine),\n};\n\n} \/\/ namespace\n\nstatic const char pymdoc[] =\n \"Machine(config, path=None, extra=None)\\n\"\n \"Machine(config, path='\/directry\/', extra={'variable':float|str}})\\n\"\n \"\\n\"\n \"A Machine() the primary interface to the FLAME simulation engine.\\n\"\n \"\\n\"\n \"The 'config' argument may be a file-like object (with read())\"\n \" or a buffer which will be parsed with the GLPS parser (see GLPSParser::parse).\\n\"\n \" Or it may be a dictionary.\\n\"\n \"\\n\"\n \">>> with open('some.lat', 'rb') as F:\\n\"\n \" M = Machine(F)\\n\"\n \">>>\\n\"\n ;\n\nint registerModMachine(PyObject *mod)\n{\n PyMachineType.tp_doc = pymdoc;\n PyMachineType.tp_str = &PyMachine_str;\n\n PyMachineType.tp_new = &PyType_GenericNew;\n PyMachineType.tp_init = &PyMachine_init;\n PyMachineType.tp_dealloc = &PyMachine_free;\n\n PyMachineType.tp_weaklistoffset = offsetof(PyMachine, weak);\n\n PyMachineType.tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE;\n PyMachineType.tp_methods = PyMachine_methods;\n PyMachineType.tp_as_sequence = &PyMachine_seq;\n\n if(PyType_Ready(&PyMachineType))\n return -1;\n\n Py_INCREF((PyObject*)&PyMachineType);\n if(PyModule_AddObject(mod, \"Machine\", (PyObject*)&PyMachineType)) {\n Py_DECREF((PyObject*)&PyMachineType);\n return -1;\n }\n\n return 0;\n}\nhelp message correction about machine.find() command\n#include \n\n#include \"flame\/base.h\"\n#include \"pyflame.h\"\n\n\n#define TRY PyMachine *machine = reinterpret_cast(raw); try\n\nnamespace {\n\nstruct PyMachine {\n PyObject_HEAD\n\n PyObject *weak;\n Machine *machine;\n};\n\nstatic\nint PyMachine_init(PyObject *raw, PyObject *args, PyObject *kws)\n{\n TRY {\n assert(!machine->weak);\n\n std::auto_ptr C(PyGLPSParse2Config(raw, args, kws));\n\n machine->machine = new Machine(*C);\n\n return 0;\n } CATCH3(key_error, KeyError, -1)\n CATCH3(std::invalid_argument, ValueError, -1)\n CATCH3(std::exception, RuntimeError, -1)\n}\n\nstatic\nvoid PyMachine_free(PyObject *raw)\n{\n TRY {\n std::auto_ptr S(machine->machine);\n machine->machine = NULL;\n\n if(machine->weak)\n PyObject_ClearWeakRefs(raw);\n\n Py_TYPE(raw)->tp_free(raw);\n } CATCH2V(std::exception, RuntimeError)\n}\n\nstatic\nPyObject *PyMachine_str(PyObject *raw)\n{\n TRY {\n std::ostringstream strm;\n strm << *(machine->machine);\n return PyString_FromString(strm.str().c_str());\n } CATCH()\n}\n\nstatic\nPyObject *PyMachine_conf(PyObject *raw, PyObject *args, PyObject *kws)\n{\n TRY {\n PyObject *pyindex = Py_None;\n const char *pnames[] = {\"index\", NULL};\n if(!PyArg_ParseTupleAndKeywords(args, kws, \"|O\", (char**)pnames, &pyindex))\n return NULL;\n\n Config C;\n if(pyindex==Py_None) {\n C = machine->machine->conf();\n } else if(PyNumber_Check(pyindex)) {\n PyRef<> pylong(PyNumber_Long(pyindex));\n long index = PyLong_AsLong(pylong.py());\n if(index<0 || (unsigned long)index>=machine->machine->size())\n return PyErr_Format(PyExc_IndexError, \"Element index out of range\");\n C = (*machine->machine)[index]->conf();\n } else {\n return PyErr_Format(PyExc_ValueError, \"'index' must be an integer or None\");\n }\n C.flatten();\n\n return conf2dict(&C);\n } CATCH()\n}\n\nstatic\nPyObject *PyMachine_allocState(PyObject *raw, PyObject *args, PyObject *kws)\n{\n TRY {\n PyObject *d = Py_None, *W = Py_False;\n const char *pnames[] = {\"config\", \"inherit\", NULL};\n if(!PyArg_ParseTupleAndKeywords(args, kws, \"|OO\", (char**)pnames, &d, &W))\n return NULL;\n\n Config C;\n if(d==Py_None) {\n C = machine->machine->conf();\n } else if(PyDict_Check(d)) {\n if(PyObject_IsTrue(W)) {\n C = machine->machine->conf();\n C.push_scope();\n }\n PyRef<> list(PyMapping_Items(d));\n List2Config(C, list.py());\n } else {\n return PyErr_Format(PyExc_ValueError, \"allocState() needs config=None or {}\");\n }\n std::auto_ptr state(machine->machine->allocState(C));\n PyObject *ret = wrapstate(state.get());\n state.release();\n return ret;\n } CATCH()\n}\n\nstruct PyStoreObserver : public Observer\n{\n PyRef<> list;\n PyStoreObserver()\n :list(PyList_New(0))\n {}\n virtual ~PyStoreObserver() {}\n virtual void view(const ElementVoid* elem, const StateBase* state)\n {\n PyRef<> tuple(PyTuple_New(2));\n std::auto_ptr tmpstate(state->clone());\n PyRef<> statecopy(wrapstate(tmpstate.get()));\n tmpstate.release();\n\n PyTuple_SET_ITEM(tuple.py(), 0, PyInt_FromSize_t(elem->index));\n PyTuple_SET_ITEM(tuple.py(), 1, statecopy.release());\n if(PyList_Append(list.py(), tuple.py()))\n throw std::runtime_error(\"\"); \/\/ a py exception is active\n }\n};\n\nstruct PyScopedObserver\n{\n Machine *machine;\n std::vector observed;\n PyScopedObserver(Machine *m) : machine(m) {}\n ~PyScopedObserver() {\n for(size_t i=0; isize(); i++) {\n (*machine)[i]->set_observer(NULL);\n }\n }\n void observe(size_t i, Observer *o)\n {\n if(i>=machine->size())\n throw std::runtime_error(\"element index out of range\");\n observed.push_back(i);\n (*machine)[i]->set_observer(o);\n }\n};\n\nstatic\nPyObject *PyMachine_propagate(PyObject *raw, PyObject *args, PyObject *kws)\n{\n\n TRY {\n PyObject *state, *toobserv = Py_None;\n unsigned long start = 0, max = (unsigned long)-1;\n const char *pnames[] = {\"state\", \"start\", \"max\", \"observe\", NULL};\n if(!PyArg_ParseTupleAndKeywords(args, kws, \"O|kkO\", (char**)pnames, &state, &start, &max, &toobserv))\n return NULL;\n\n PyStoreObserver observer;\n PyScopedObserver observing(machine->machine);\n\n if(toobserv!=Py_None) {\n PyRef<> iter(PyObject_GetIter(toobserv)), item;\n\n while(item.reset(PyIter_Next(iter.py()), PyRef<>::allow_null())) {\n Py_ssize_t num = PyNumber_AsSsize_t(item.py(), PyExc_ValueError);\n if(PyErr_Occurred())\n throw std::runtime_error(\"\"); \/\/ caller will get active python exception\n\n observing.observe(num, &observer);\n\n }\n }\n\n machine->machine->propagate(unwrapstate(state), start, max);\n if(toobserv) {\n return observer.list.release();\n } else {\n Py_RETURN_NONE;\n }\n } CATCH2(std::invalid_argument, ValueError)\n CATCH()\n}\n\nstatic\nPyObject *PyMachine_reconfigure(PyObject *raw, PyObject *args, PyObject *kws)\n{\n TRY{\n unsigned long idx;\n PyObject *conf, *replace = Py_False;\n const char *pnames[] = {\"index\", \"config\", \"replace\", NULL};\n if(!PyArg_ParseTupleAndKeywords(args, kws, \"kO!|O\", (char**)pnames, &idx, &PyDict_Type, &conf, &replace))\n return NULL;\n\n if(idx>=machine->machine->size())\n return PyErr_Format(PyExc_ValueError, \"invalid element index %lu\", idx);\n\n Config newconf;\n if(!PyObject_IsTrue(replace))\n newconf = (*machine->machine)[idx]->conf();\n\n PyRef<> list(PyMapping_Items(conf));\n List2Config(newconf, list.py(), 3); \/\/ set depth=3 to prevent recursion\n\n machine->machine->reconfigure(idx, newconf);\n\n Py_RETURN_NONE;\n } CATCH2(std::invalid_argument, ValueError)\n CATCH()\n}\n\nstatic\nPyObject *PyMachine_find(PyObject *raw, PyObject *args, PyObject *kws)\n{\n TRY{\n const char *ename = NULL, *etype = NULL;\n const char *pnames[] = {\"name\", \"type\", NULL};\n if(!PyArg_ParseTupleAndKeywords(args, kws, \"|zz\", (char**)pnames, &ename, &etype))\n return NULL;\n\n PyRef<> ret(PyList_New(0));\n\n std::pair range;\n\n if(ename && etype) {\n return PyErr_Format(PyExc_ValueError, \"only one of 'name' or 'type' may be given\");\n } else if(ename) {\n range = machine->machine->equal_range(ename);\n } else if(etype) {\n range = machine->machine->equal_range_type(etype);\n } else {\n range = machine->machine->all_range();\n }\n\n for(; range.first!=range.second; ++range.first) {\n ElementVoid *elem = *range.first;\n\n PyRef<> pyidx(PyInt_FromLong(elem->index));\n\n if(PyList_Append(ret.py(), pyidx.py()))\n return NULL;\n }\n\n return ret.release();\n }CATCH()\n}\n\nstatic\nPy_ssize_t PyMachine_len(PyObject *raw)\n{\n TRY{\n return machine->machine->size();\n }CATCH1(-1)\n}\n\nstatic PyMethodDef PyMachine_methods[] = {\n {\"conf\", (PyCFunction)&PyMachine_conf, METH_VARARGS|METH_KEYWORDS,\n \"conf() -> {} Machine config\\n\"\n \"conf(index) -> {} Element config\"},\n {\"allocState\", (PyCFunction)&PyMachine_allocState, METH_VARARGS|METH_KEYWORDS,\n \"allocState() -> State\\n\"\n \"allocState({'variable':int|str}) -> State\\n\"\n \"Allocate a new State based on this Machine's configuration.\"\n \" Optionally provide additional configuration\"},\n {\"propagate\", (PyCFunction)&PyMachine_propagate, METH_VARARGS|METH_KEYWORDS,\n \"propagate(State, start=0, max=-1, observe=None)\\n\"\n \"propagate(State, start=0, max=-1, observe=[1,4,...]) -> [(index,State), ...]\\n\"\n \"Propagate the provided State through the simulation.\\n\"\n \"\\n\"\n \"start and max selects through which element the State will be passed.\\n\"\n \"\\n\"\n \"observe may be None or an iterable yielding element indicies.\\n\"\n \"In the second form propagate() returns a list of tuples with the output State of the selected elements.\"\n },\n {\"reconfigure\", (PyCFunction)&PyMachine_reconfigure, METH_VARARGS|METH_KEYWORDS,\n \"reconfigure(index, {'variable':int|str})\\n\"\n \"Change the configuration of an element.\"},\n {\"find\", (PyCFunction)&PyMachine_find, METH_VARARGS|METH_KEYWORDS,\n \"find(name=None, type=None) -> [int]\\n\"\n \"Return a list of element indices for element name or type matching the given string.\"},\n {NULL, NULL, 0, NULL}\n};\n\nstatic PySequenceMethods PyMachine_seq = {\n &PyMachine_len\n};\n\nstatic PyTypeObject PyMachineType = {\n#if PY_MAJOR_VERSION >= 3\n PyVarObject_HEAD_INIT(NULL, 0)\n#else\n PyObject_HEAD_INIT(NULL)\n 0,\n#endif\n \"flame._internal.Machine\",\n sizeof(PyMachine),\n};\n\n} \/\/ namespace\n\nstatic const char pymdoc[] =\n \"Machine(config, path=None, extra=None)\\n\"\n \"Machine(config, path='\/directry\/', extra={'variable':float|str}})\\n\"\n \"\\n\"\n \"A Machine() the primary interface to the FLAME simulation engine.\\n\"\n \"\\n\"\n \"The 'config' argument may be a file-like object (with read())\"\n \" or a buffer which will be parsed with the GLPS parser (see GLPSParser::parse).\\n\"\n \" Or it may be a dictionary.\\n\"\n \"\\n\"\n \">>> with open('some.lat', 'rb') as F:\\n\"\n \" M = Machine(F)\\n\"\n \">>>\\n\"\n ;\n\nint registerModMachine(PyObject *mod)\n{\n PyMachineType.tp_doc = pymdoc;\n PyMachineType.tp_str = &PyMachine_str;\n\n PyMachineType.tp_new = &PyType_GenericNew;\n PyMachineType.tp_init = &PyMachine_init;\n PyMachineType.tp_dealloc = &PyMachine_free;\n\n PyMachineType.tp_weaklistoffset = offsetof(PyMachine, weak);\n\n PyMachineType.tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE;\n PyMachineType.tp_methods = PyMachine_methods;\n PyMachineType.tp_as_sequence = &PyMachine_seq;\n\n if(PyType_Ready(&PyMachineType))\n return -1;\n\n Py_INCREF((PyObject*)&PyMachineType);\n if(PyModule_AddObject(mod, \"Machine\", (PyObject*)&PyMachineType)) {\n Py_DECREF((PyObject*)&PyMachineType);\n return -1;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012, Steinwurf ApS\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ * Neither the name of Steinwurf ApS nor the\n\/\/ names of its contributors may be used to endorse or promote products\n\/\/ derived from this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n\/\/ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n\/\/ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\/\/ DISCLAIMED. IN NO EVENT SHALL Steinwurf ApS BE LIABLE FOR ANY\n\/\/ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n\/\/ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n\/\/ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \n\n#include \n\nTEST(TestBuffer, construct)\n{\n sak::buffer b;\n EXPECT_EQ(0U, b.size());\n}\n\nTEST(TestBuffer, resize)\n{\n sak::buffer b;\n b.resize(100);\n EXPECT_EQ(100U, b.size());\n}\n\nTEST(TestBuffer, resize_and_copy)\n{\n sak::buffer b1;\n b1.resize(100);\n EXPECT_EQ(100U, b1.size());\n\n sak::buffer b2 = b1;\n EXPECT_EQ(100U, b2.size());\n}\n\nTEST(TestBuffer, append_to_empty_with_size)\n{\n std::vector data(32);\n EXPECT_EQ(32U, data.size());\n\n sak::buffer b;\n EXPECT_EQ(0U, b.size());\n\n b.append(&data[0], static_cast(data.size()));\n EXPECT_EQ(data.size(), b.size());\n}\n\nTEST(TestBuffer, append_to_empty_with_pointers)\n{\n std::vector data(32);\n EXPECT_EQ(32U, data.size());\n\n sak::buffer b;\n EXPECT_EQ(b.size(), 0U);\n\n b.append(&data[0], &data[0] + data.size());\n EXPECT_EQ(b.size(), data.size());\n}\n\nTEST(TestBuffer, append_to_empty_with_storage)\n{\n std::vector data(32);\n EXPECT_EQ(32U, data.size());\n\n sak::buffer b;\n EXPECT_EQ(b.size(), 0U);\n\n b.append(sak::storage(data));\n EXPECT_EQ(b.size(), data.size());\n}\n\n\n\/\/ TEST(TestBuffer, append_to_initialized)\n\/\/ {\n\/\/ {\n\/\/ sak::buffer b(10);\n\/\/ EXPECT_EQ(b.size(), 0U);\n\/\/\n\/\/ std::vector data(32, 'x');\n\/\/ b.append(&data[0], static_cast(data.size()));\n\/\/ EXPECT_EQ(b.size(), data.size());\n\/\/ }\n\/\/\n\/\/ {\n\/\/ sak::buffer b(10);\n\/\/ EXPECT_EQ(b.size(), 0U);\n\/\/\n\/\/ std::vector data(32, 'x');\n\/\/ b.append(&data[0], &data[0] + data.size());\n\/\/ EXPECT_EQ(b.size(), data.size());\n\/\/ }\n\/\/\n\/\/ {\n\/\/ sak::buffer b(10);\n\/\/ EXPECT_EQ(b.size(), 0U);\n\/\/\n\/\/ std::vector data(32, 'x');\n\/\/ b.append(sak::storage(data));\n\/\/ EXPECT_EQ(b.size(), data.size());\n\/\/ }\n\/\/\n\/\/ }\n\nTEST(TestBuffer, resize_and_clear)\n{\n sak::buffer b(100);\n EXPECT_EQ(0U, b.size());\n std::fill_n(b.data(), b.size(), 'x');\n\n b.resize(10);\n EXPECT_EQ(10U, b.size());\n std::fill_n(b.data(), b.size(), 'x');\n\n b.resize(101);\n EXPECT_EQ(101U, b.size());\n std::fill_n(b.data(), b.size(), 'x');\n\n b.clear();\n EXPECT_EQ(0U, b.size());\n\n b.resize(0);\n EXPECT_EQ(0U, b.size());\n\n b.resize(102);\n EXPECT_EQ(102U, b.size());\n std::fill_n(b.data(), b.size(), 'x');\n\n b.resize(0);\n EXPECT_EQ(0U, b.size());\n\n b.clear();\n EXPECT_EQ(0U, b.size());\n}\nAll tests on in test_buffer.cpp\/\/ Copyright (c) 2012, Steinwurf ApS\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ * Neither the name of Steinwurf ApS nor the\n\/\/ names of its contributors may be used to endorse or promote products\n\/\/ derived from this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n\/\/ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n\/\/ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\/\/ DISCLAIMED. IN NO EVENT SHALL Steinwurf ApS BE LIABLE FOR ANY\n\/\/ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n\/\/ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n\/\/ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \n\n#include \n\nTEST(TestBuffer, construct)\n{\n sak::buffer b;\n EXPECT_EQ(0U, b.size());\n}\n\nTEST(TestBuffer, resize)\n{\n sak::buffer b;\n b.resize(100);\n EXPECT_EQ(100U, b.size());\n}\n\nTEST(TestBuffer, resize_and_copy)\n{\n sak::buffer b1;\n b1.resize(100);\n EXPECT_EQ(100U, b1.size());\n\n sak::buffer b2 = b1;\n EXPECT_EQ(100U, b2.size());\n}\n\nTEST(TestBuffer, append_to_empty_with_size)\n{\n std::vector data(32);\n EXPECT_EQ(32U, data.size());\n\n sak::buffer b;\n EXPECT_EQ(0U, b.size());\n\n b.append(&data[0], static_cast(data.size()));\n EXPECT_EQ(data.size(), b.size());\n}\n\nTEST(TestBuffer, append_to_empty_with_pointers)\n{\n std::vector data(32);\n EXPECT_EQ(32U, data.size());\n\n sak::buffer b;\n EXPECT_EQ(b.size(), 0U);\n\n b.append(&data[0], &data[0] + data.size());\n EXPECT_EQ(b.size(), data.size());\n}\n\nTEST(TestBuffer, append_to_empty_with_storage)\n{\n std::vector data(32);\n EXPECT_EQ(32U, data.size());\n\n sak::buffer b;\n EXPECT_EQ(b.size(), 0U);\n\n b.append(sak::storage(data));\n EXPECT_EQ(b.size(), data.size());\n}\n\n\nTEST(TestBuffer, append_to_initialized)\n{\n {\n sak::buffer b(10);\n EXPECT_EQ(b.size(), 0U);\n\n std::vector data(32, 'x');\n EXPECT_EQ(32U, data.size());\n b.append(&data[0], static_cast(data.size()));\n EXPECT_EQ(b.size(), data.size());\n }\n\n {\n sak::buffer b(10);\n EXPECT_EQ(b.size(), 0U);\n\n std::vector data(32, 'x');\n EXPECT_EQ(32U, data.size());\n b.append(&data[0], &data[0] + data.size());\n EXPECT_EQ(b.size(), data.size());\n }\n\n {\n sak::buffer b(10);\n EXPECT_EQ(b.size(), 0U);\n\n std::vector data(32, 'x');\n EXPECT_EQ(32U, data.size());\n b.append(sak::storage(data));\n EXPECT_EQ(b.size(), data.size());\n }\n}\n\nTEST(TestBuffer, resize_and_clear)\n{\n sak::buffer b(100);\n EXPECT_EQ(0U, b.size());\n std::fill_n(b.data(), b.size(), 'x');\n\n b.resize(10);\n EXPECT_EQ(10U, b.size());\n std::fill_n(b.data(), b.size(), 'x');\n\n b.resize(101);\n EXPECT_EQ(101U, b.size());\n std::fill_n(b.data(), b.size(), 'x');\n\n b.clear();\n EXPECT_EQ(0U, b.size());\n\n b.resize(0);\n EXPECT_EQ(0U, b.size());\n\n b.resize(102);\n EXPECT_EQ(102U, b.size());\n std::fill_n(b.data(), b.size(), 'x');\n\n b.resize(0);\n EXPECT_EQ(0U, b.size());\n\n b.clear();\n EXPECT_EQ(0U, b.size());\n}\n<|endoftext|>"} {"text":"#include \n#include \"helpers.hpp\"\n\n#include \n#include \n#include \n\n#include \"catch.hpp\"\n\nusing iter::accumulate;\nusing itertest::BasicIterable;\n\nusing Vec = const std::vector;\nTEST_CASE(\"Simple sum\", \"[accumulate]\") {\n Vec ns{1, 2, 3, 4, 5};\n\n std::vector v;\n SECTION(\"Normal call\") {\n auto a = accumulate(ns);\n v.assign(std::begin(a), std::end(a));\n }\n SECTION(\"Pipe\") {\n auto a = ns | accumulate;\n v.assign(std::begin(a), std::end(a));\n }\n\n Vec vc{1, 3, 6, 10, 15};\n REQUIRE(v == vc);\n}\n\nTEST_CASE(\"accumulate: With subtraction lambda\", \"[accumulate]\") {\n Vec ns{5, 4, 3, 2, 1};\n std::vector v;\n\n SECTION(\"Normal call\") {\n auto a = accumulate(ns, [](int a, int b) { return a - b; });\n v.assign(std::begin(a), std::end(a));\n }\n SECTION(\"Pipe\") {\n auto a = ns | accumulate([](int a, int b) { return a - b; });\n v.assign(std::begin(a), std::end(a));\n }\n\n Vec vc{5, 1, -2, -4, -5};\n REQUIRE(v == vc);\n}\n\nstruct Integer {\n const int value;\n constexpr Integer(int i) : value{i} {}\n constexpr Integer operator+(Integer other) const noexcept {\n return {this->value + other.value};\n }\n};\n\nTEST_CASE(\"accumulate: intermidate type need not be default constructible\",\n \"[accumulate]\") {\n std::vector v = {{2}, {3}, {10}};\n auto a = accumulate(v, std::plus{});\n auto it = std::begin(a);\n}\n\nTEST_CASE(\"accumulate: binds reference when it should\", \"[accumulate]\") {\n BasicIterable bi{1, 2};\n accumulate(bi);\n REQUIRE_FALSE(bi.was_moved_from());\n}\n\nTEST_CASE(\"accumulate: moves rvalues when it should\", \"[accumulate]\") {\n BasicIterable bi{1, 2};\n accumulate(std::move(bi));\n REQUIRE(bi.was_moved_from());\n}\n\nTEST_CASE(\"accumulate: operator==\", \"[accumulate]\") {\n Vec v;\n auto a = accumulate(v);\n REQUIRE(std::begin(a) == std::end(a));\n}\n\nTEST_CASE(\"accumulate: postfix ++\", \"[accumulate]\") {\n Vec ns{2, 3};\n auto a = accumulate(ns);\n auto it = std::begin(a);\n it++;\n REQUIRE(*it == 5);\n}\n\nTEST_CASE(\"accumulate: operator->\", \"[accumulate]\") {\n Vec ns{7, 3};\n auto a = accumulate(ns);\n auto it = std::begin(a);\n const int* p = it.operator->();\n REQUIRE(*p == 7);\n}\n\nTEST_CASE(\"accumulate: iterator meets requirements\", \"[accumulate]\") {\n Vec ns{};\n auto a = accumulate(ns, [](int a, int b) { return a + b; });\n auto it = std::begin(a);\n it = std::begin(a);\n REQUIRE(itertest::IsIterator::value);\n}\n\ntemplate \nusing ImpT = decltype(accumulate(std::declval()));\nTEST_CASE(\"accumulate: has correct ctor and assign ops\", \"[accumulate]\") {\n REQUIRE(itertest::IsMoveConstructibleOnly>::value);\n REQUIRE(itertest::IsMoveConstructibleOnly>::value);\n}\ntests accumulate with different begin and end#include \n#include \"helpers.hpp\"\n\n#include \n#include \n#include \n\n#include \"catch.hpp\"\n\nusing iter::accumulate;\nusing itertest::BasicIterable;\n\nusing Vec = const std::vector;\nTEST_CASE(\"Simple sum\", \"[accumulate]\") {\n Vec ns{1, 2, 3, 4, 5};\n\n std::vector v;\n SECTION(\"Normal call\") {\n auto a = accumulate(ns);\n v.assign(std::begin(a), std::end(a));\n }\n SECTION(\"Pipe\") {\n auto a = ns | accumulate;\n v.assign(std::begin(a), std::end(a));\n }\n\n Vec vc{1, 3, 6, 10, 15};\n REQUIRE(v == vc);\n}\n\nTEST_CASE(\"accumulate: With subtraction lambda\", \"[accumulate]\") {\n Vec ns{5, 4, 3, 2, 1};\n std::vector v;\n\n SECTION(\"Normal call\") {\n auto a = accumulate(ns, [](int a, int b) { return a - b; });\n v.assign(std::begin(a), std::end(a));\n }\n SECTION(\"Pipe\") {\n auto a = ns | accumulate([](int a, int b) { return a - b; });\n v.assign(std::begin(a), std::end(a));\n }\n\n Vec vc{5, 1, -2, -4, -5};\n REQUIRE(v == vc);\n}\n\nstruct Integer {\n const int value;\n constexpr Integer(int i) : value{i} {}\n constexpr Integer operator+(Integer other) const noexcept {\n return {this->value + other.value};\n }\n};\n\nTEST_CASE(\"accumulate: intermidate type need not be default constructible\",\n \"[accumulate]\") {\n std::vector v = {{2}, {3}, {10}};\n auto a = accumulate(v, std::plus{});\n auto it = std::begin(a);\n}\n\nTEST_CASE(\"accumulate: binds reference when it should\", \"[accumulate]\") {\n BasicIterable bi{1, 2};\n accumulate(bi);\n REQUIRE_FALSE(bi.was_moved_from());\n}\n\nTEST_CASE(\"accumulate: moves rvalues when it should\", \"[accumulate]\") {\n BasicIterable bi{1, 2};\n accumulate(std::move(bi));\n REQUIRE(bi.was_moved_from());\n}\n\nTEST_CASE(\"accumulate: operator==\", \"[accumulate]\") {\n Vec v;\n auto a = accumulate(v);\n REQUIRE(std::begin(a) == std::end(a));\n}\n\nTEST_CASE(\"accumulate: postfix ++\", \"[accumulate]\") {\n Vec ns{2, 3};\n auto a = accumulate(ns);\n auto it = std::begin(a);\n it++;\n REQUIRE(*it == 5);\n}\n\nTEST_CASE(\"accumulate: operator->\", \"[accumulate]\") {\n Vec ns{7, 3};\n auto a = accumulate(ns);\n auto it = std::begin(a);\n const int* p = it.operator->();\n REQUIRE(*p == 7);\n}\n\nTEST_CASE(\"accumulate: iterator meets requirements\", \"[accumulate]\") {\n Vec ns{};\n auto a = accumulate(ns, [](int a, int b) { return a + b; });\n auto it = std::begin(a);\n it = std::begin(a);\n REQUIRE(itertest::IsIterator::value);\n}\n\nTEST_CASE(\"accumulate: Works with different begin and end types\",\n \"[accumulate]\") {\n CharRange cr{'d'};\n auto a = accumulate(cr);\n Vec v(a.begin(), a.end());\n Vec vc{'a', 'a' + 'b', 'a' + 'b' + 'c'};\n REQUIRE(v == vc);\n}\n\n\ntemplate \nusing ImpT = decltype(accumulate(std::declval()));\nTEST_CASE(\"accumulate: has correct ctor and assign ops\", \"[accumulate]\") {\n REQUIRE(itertest::IsMoveConstructibleOnly>::value);\n REQUIRE(itertest::IsMoveConstructibleOnly>::value);\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2021 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"google\/cloud\/pubsub\/internal\/defaults.h\"\n#include \"google\/cloud\/pubsub\/options.h\"\n#include \"google\/cloud\/common_options.h\"\n#include \"google\/cloud\/connection_options.h\"\n#include \"google\/cloud\/grpc_options.h\"\n#include \"google\/cloud\/internal\/getenv.h\"\n#include \"google\/cloud\/internal\/user_agent_prefix.h\"\n#include \"google\/cloud\/options.h\"\n#include \n#include \n#include \n\nnamespace google {\nnamespace cloud {\nnamespace pubsub_internal {\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\nusing std::chrono::seconds;\nusing ms = std::chrono::milliseconds;\n\nstd::size_t DefaultThreadCount() {\n auto constexpr kDefaultThreadCount = 4;\n auto const n = std::thread::hardware_concurrency();\n return n == 0 ? kDefaultThreadCount : n;\n}\n\nOptions DefaultCommonOptions(Options opts) {\n auto emulator = internal::GetEnv(\"PUBSUB_EMULATOR_HOST\");\n if (emulator.has_value()) {\n opts.set(*emulator).set(\n grpc::InsecureChannelCredentials());\n }\n if (!opts.has()) {\n opts.set(\"pubsub.googleapis.com\");\n }\n if (!opts.has()) {\n opts.set(grpc::GoogleDefaultCredentials());\n }\n if (!opts.has()) {\n opts.set(static_cast(DefaultThreadCount()));\n }\n if (!opts.has()) {\n opts.set(internal::DefaultTracingComponents());\n }\n if (!opts.has()) {\n opts.set(internal::DefaultTracingOptions());\n }\n if (!opts.has()) {\n opts.set(\n pubsub::LimitedTimeRetryPolicy(std::chrono::seconds(60)).clone());\n }\n if (!opts.has()) {\n opts.set(\n pubsub::ExponentialBackoffPolicy(std::chrono::milliseconds(100),\n std::chrono::seconds(60), 1.3)\n .clone());\n }\n if (opts.get() == 0) {\n opts.set(DefaultThreadCount());\n }\n\n \/\/ Enforce Constraints\n auto& num_channels = opts.lookup();\n num_channels = (std::max)(num_channels, 1);\n\n \/\/ Inserts our user-agent string at the front.\n auto& products = opts.lookup();\n products.insert(products.begin(), internal::UserAgentPrefix());\n\n return opts;\n}\n\nOptions DefaultPublisherOptions(Options opts) {\n return DefaultCommonOptions(DefaultPublisherOptionsOnly(std::move(opts)));\n}\n\nOptions DefaultPublisherOptionsOnly(Options opts) {\n if (!opts.has()) {\n opts.set(ms(10));\n }\n if (!opts.has()) {\n opts.set(100);\n }\n if (!opts.has()) {\n opts.set(1024 * 1024L);\n }\n if (!opts.has()) {\n opts.set(\n (std::numeric_limits::max)());\n }\n if (!opts.has()) {\n opts.set(\n (std::numeric_limits::max)());\n }\n if (!opts.has()) {\n opts.set(false);\n }\n if (!opts.has()) {\n opts.set(\n pubsub::FullPublisherAction::kBlocks);\n }\n\n return opts;\n}\n\nOptions DefaultSubscriberOptions(Options opts) {\n return DefaultCommonOptions(DefaultSubscriberOptionsOnly(std::move(opts)));\n}\n\nOptions DefaultSubscriberOptionsOnly(Options opts) {\n if (!opts.has()) {\n opts.set(seconds(0));\n }\n if (!opts.has()) {\n opts.set(seconds(600));\n }\n if (!opts.has()) {\n opts.set(1000);\n }\n if (!opts.has()) {\n opts.set(100 * 1024 * 1024L);\n }\n if (opts.get() == 0) {\n opts.set(DefaultThreadCount());\n }\n if (!opts.has()) {\n opts.set(seconds(5));\n }\n \/\/ Subscribers are special: by default we want to retry essentially forever\n \/\/ because (a) the service will disconnect the streaming pull from time to\n \/\/ time, but that is not a \"failure\", (b) applications can change this\n \/\/ behavior if they need, and this is easier than some hard-coded \"treat these\n \/\/ disconnects as non-failures\" code.\n if (!opts.has()) {\n opts.set(\n pubsub::LimitedErrorCountRetryPolicy((std::numeric_limits::max)())\n .clone());\n }\n\n \/\/ Enforce constraints\n auto& extension = opts.lookup();\n extension = (std::max)((std::min)(extension, seconds(600)), seconds(10));\n\n auto& messages = opts.lookup();\n messages = std::max(0, messages);\n\n auto& bytes = opts.lookup();\n bytes = std::max(0, bytes);\n\n return opts;\n}\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END\n} \/\/ namespace pubsub_internal\n} \/\/ namespace cloud\n} \/\/ namespace google\nrefactor(pubsub): use common option initializers (#8454)\/\/ Copyright 2021 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"google\/cloud\/pubsub\/internal\/defaults.h\"\n#include \"google\/cloud\/pubsub\/options.h\"\n#include \"google\/cloud\/common_options.h\"\n#include \"google\/cloud\/connection_options.h\"\n#include \"google\/cloud\/grpc_options.h\"\n#include \"google\/cloud\/internal\/getenv.h\"\n#include \"google\/cloud\/internal\/populate_common_options.h\"\n#include \"google\/cloud\/internal\/populate_grpc_options.h\"\n#include \"google\/cloud\/internal\/user_agent_prefix.h\"\n#include \"google\/cloud\/options.h\"\n#include \n#include \n#include \n\nnamespace google {\nnamespace cloud {\nnamespace pubsub_internal {\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\nusing std::chrono::seconds;\nusing ms = std::chrono::milliseconds;\n\nstd::size_t DefaultThreadCount() {\n auto constexpr kDefaultThreadCount = 4;\n auto const n = std::thread::hardware_concurrency();\n return n == 0 ? kDefaultThreadCount : n;\n}\n\nOptions DefaultCommonOptions(Options opts) {\n opts = internal::PopulateCommonOptions(\n std::move(opts), \"\", \"PUBSUB_EMULATOR_HOST\", \"pubsub.googleapis.com\");\n opts = internal::PopulateGrpcOptions(std::move(opts), \"PUBSUB_EMULATOR_HOST\");\n\n if (!opts.has()) {\n opts.set(static_cast(DefaultThreadCount()));\n }\n if (!opts.has()) {\n opts.set(\n pubsub::LimitedTimeRetryPolicy(std::chrono::seconds(60)).clone());\n }\n if (!opts.has()) {\n opts.set(\n pubsub::ExponentialBackoffPolicy(std::chrono::milliseconds(100),\n std::chrono::seconds(60), 1.3)\n .clone());\n }\n if (opts.get() == 0) {\n opts.set(DefaultThreadCount());\n }\n\n \/\/ Enforce Constraints\n auto& num_channels = opts.lookup();\n num_channels = (std::max)(num_channels, 1);\n\n return opts;\n}\n\nOptions DefaultPublisherOptions(Options opts) {\n return DefaultCommonOptions(DefaultPublisherOptionsOnly(std::move(opts)));\n}\n\nOptions DefaultPublisherOptionsOnly(Options opts) {\n if (!opts.has()) {\n opts.set(ms(10));\n }\n if (!opts.has()) {\n opts.set(100);\n }\n if (!opts.has()) {\n opts.set(1024 * 1024L);\n }\n if (!opts.has()) {\n opts.set(\n (std::numeric_limits::max)());\n }\n if (!opts.has()) {\n opts.set(\n (std::numeric_limits::max)());\n }\n if (!opts.has()) {\n opts.set(false);\n }\n if (!opts.has()) {\n opts.set(\n pubsub::FullPublisherAction::kBlocks);\n }\n\n return opts;\n}\n\nOptions DefaultSubscriberOptions(Options opts) {\n return DefaultCommonOptions(DefaultSubscriberOptionsOnly(std::move(opts)));\n}\n\nOptions DefaultSubscriberOptionsOnly(Options opts) {\n if (!opts.has()) {\n opts.set(seconds(0));\n }\n if (!opts.has()) {\n opts.set(seconds(600));\n }\n if (!opts.has()) {\n opts.set(1000);\n }\n if (!opts.has()) {\n opts.set(100 * 1024 * 1024L);\n }\n if (opts.get() == 0) {\n opts.set(DefaultThreadCount());\n }\n if (!opts.has()) {\n opts.set(seconds(5));\n }\n \/\/ Subscribers are special: by default we want to retry essentially forever\n \/\/ because (a) the service will disconnect the streaming pull from time to\n \/\/ time, but that is not a \"failure\", (b) applications can change this\n \/\/ behavior if they need, and this is easier than some hard-coded \"treat these\n \/\/ disconnects as non-failures\" code.\n if (!opts.has()) {\n opts.set(\n pubsub::LimitedErrorCountRetryPolicy((std::numeric_limits::max)())\n .clone());\n }\n\n \/\/ Enforce constraints\n auto& extension = opts.lookup();\n extension = (std::max)((std::min)(extension, seconds(600)), seconds(10));\n\n auto& messages = opts.lookup();\n messages = std::max(0, messages);\n\n auto& bytes = opts.lookup();\n bytes = std::max(0, bytes);\n\n return opts;\n}\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END\n} \/\/ namespace pubsub_internal\n} \/\/ namespace cloud\n} \/\/ namespace google\n<|endoftext|>"} {"text":"#include \"UI_Image.h\"\n#include \"j1App.h\"\n#include \"j1Render.h\"\n\nvoid Image::BlitElement()\n{\n\tSDL_SetTextureAlphaMod(texture, App->gui->alpha_value);\n\tiPoint globalPos = calculateAbsolutePosition();\n\tApp->render->Blit(texture, globalPos.x, globalPos.y, §ion, false, App->gui->UI_scale);\n}\nsolved a bug with UI_images blit#include \"UI_Image.h\"\n#include \"j1App.h\"\n#include \"j1Render.h\"\n\nvoid Image::BlitElement()\n{\n\tif (texture != App->gui->GetAtlas())\n\t\tSDL_SetTextureAlphaMod(texture, App->gui->alpha_value);\n\tiPoint globalPos = calculateAbsolutePosition();\n\tApp->render->Blit(texture, globalPos.x, globalPos.y, §ion, false, App->gui->UI_scale);\n}\n<|endoftext|>"} {"text":"\/*\n * yosys -- Yosys Open SYnthesis Suite\n *\n * Copyright (C) 2012 Clifford Wolf \n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \"kernel\/yosys.h\"\n#include \"kernel\/sigtools.h\"\n\nUSING_YOSYS_NAMESPACE\nPRIVATE_NAMESPACE_BEGIN\n\ntemplate bool includes(const T &lhs, const T &rhs) {\n\treturn std::includes(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());\n}\n#include \"passes\/pmgen\/ice40_dsp_pm.h\"\n\nvoid create_ice40_dsp(ice40_dsp_pm &pm)\n{\n\tauto &st = pm.st_ice40_dsp;\n\n#if 0\n\tlog(\"\\n\");\n\tlog(\"ffA: %s\\n\", log_id(st.ffA, \"--\"));\n\tlog(\"ffB: %s\\n\", log_id(st.ffB, \"--\"));\n\tlog(\"mul: %s\\n\", log_id(st.mul, \"--\"));\n\tlog(\"ffH: %s\\n\", log_id(st.ffH, \"--\"));\n\tlog(\"addAB: %s\\n\", log_id(st.addAB, \"--\"));\n\tlog(\"muxAB: %s\\n\", log_id(st.muxAB, \"--\"));\n\tlog(\"ffO_lo: %s\\n\", log_id(st.ffO_lo, \"--\"));\n\tlog(\"ffO_hi: %s\\n\", log_id(st.ffO_hi, \"--\"));\n#endif\n\n\tlog(\"Checking %s.%s for iCE40 DSP inference.\\n\", log_id(pm.module), log_id(st.mul));\n\n\tif (GetSize(st.sigA) > 16) {\n\t\tlog(\" input A (%s) is too large (%d > 16).\\n\", log_signal(st.sigA), GetSize(st.sigA));\n\t\treturn;\n\t}\n\n\tif (GetSize(st.sigB) > 16) {\n\t\tlog(\" input B (%s) is too large (%d > 16).\\n\", log_signal(st.sigB), GetSize(st.sigB));\n\t\treturn;\n\t}\n\n\tif (GetSize(st.sigO) > 32) {\n\t\tlog(\" accumulator (%s) is too large (%d > 32).\\n\", log_signal(st.sigO), GetSize(st.sigO));\n\t\treturn;\n\t}\n\n\tif (GetSize(st.sigH) > 32) {\n\t\tlog(\" output (%s) is too large (%d > 32).\\n\", log_signal(st.sigH), GetSize(st.sigH));\n\t\treturn;\n\t}\n\n\tlog(\" replacing %s with SB_MAC16 cell.\\n\", log_id(st.mul->type));\n\n\tCell *cell = pm.module->addCell(NEW_ID, \"\\\\SB_MAC16\");\n\tpm.module->swap_names(cell, st.mul);\n\n\t\/\/ SB_MAC16 Input Interface\n\tbool a_signed = st.mul->getParam(\"\\\\A_SIGNED\").as_bool();\n\tbool b_signed = st.mul->getParam(\"\\\\B_SIGNED\").as_bool();\n\n\tSigSpec A = st.sigA;\n\tA.extend_u0(16, a_signed);\n\n\tSigSpec B = st.sigB;\n\tB.extend_u0(16, b_signed);\n\n\tSigSpec CD = st.sigCD;\n\tCD.extend_u0(32, st.sigCD_signed);\n\n\tcell->setPort(\"\\\\A\", A);\n\tcell->setPort(\"\\\\B\", B);\n\tcell->setPort(\"\\\\C\", CD.extract(16, 16));\n\tcell->setPort(\"\\\\D\", CD.extract(0, 16));\n\n\tcell->setParam(\"\\\\A_REG\", st.ffA ? State::S1 : State::S0);\n\tcell->setParam(\"\\\\B_REG\", st.ffB ? State::S1 : State::S0);\n\n\tcell->setPort(\"\\\\AHOLD\", State::S0);\n\tcell->setPort(\"\\\\BHOLD\", State::S0);\n\tcell->setPort(\"\\\\CHOLD\", State::S0);\n\tcell->setPort(\"\\\\DHOLD\", State::S0);\n\n\tcell->setPort(\"\\\\IRSTTOP\", State::S0);\n\tcell->setPort(\"\\\\IRSTBOT\", State::S0);\n\n\tif (st.clock != SigBit())\n\t{\n\t\tcell->setPort(\"\\\\CLK\", st.clock);\n\t\tcell->setPort(\"\\\\CE\", State::S1);\n\t\tcell->setParam(\"\\\\NEG_TRIGGER\", st.clock_pol ? State::S0 : State::S1);\n\n\t\tlog(\" clock: %s (%s)\", log_signal(st.clock), st.clock_pol ? \"posedge\" : \"negedge\");\n\n\t\tif (st.ffA)\n\t\t\tlog(\" ffA:%s\", log_id(st.ffA));\n\n\t\tif (st.ffB)\n\t\t\tlog(\" ffB:%s\", log_id(st.ffB));\n\n\t\tif (st.ffH)\n\t\t\tlog(\" ffH:%s\", log_id(st.ffH));\n\n\t\tif (st.ffO_lo)\n\t\t\tlog(\" ffO_lo:%s\", log_id(st.ffO_lo));\n\t\tif (st.ffO_hi)\n\t\t\tlog(\" ffO_hi:%s\", log_id(st.ffO_hi));\n\n\t\tlog(\"\\n\");\n\t}\n\telse\n\t{\n\t\tcell->setPort(\"\\\\CLK\", State::S0);\n\t\tcell->setPort(\"\\\\CE\", State::S0);\n\t\tcell->setParam(\"\\\\NEG_TRIGGER\", State::S0);\n\t}\n\n\t\/\/ SB_MAC16 Cascade Interface\n\n\tcell->setPort(\"\\\\SIGNEXTIN\", State::Sx);\n\tcell->setPort(\"\\\\SIGNEXTOUT\", pm.module->addWire(NEW_ID));\n\n\tcell->setPort(\"\\\\CI\", State::Sx);\n\tcell->setPort(\"\\\\CO\", pm.module->addWire(NEW_ID));\n\n\tcell->setPort(\"\\\\ACCUMCI\", State::Sx);\n\tcell->setPort(\"\\\\ACCUMCO\", pm.module->addWire(NEW_ID));\n\n\t\/\/ SB_MAC16 Output Interface\n\n\tSigSpec O = st.sigO;\n\tif (GetSize(O) < 32)\n\t\tO.append(pm.module->addWire(NEW_ID, 32-GetSize(O)));\n\n\tcell->setPort(\"\\\\O\", O);\n\n\tbool accum = false;\n\tif (st.addAB) {\n\t\tif (st.addA)\n\t\t\taccum = (st.ffO_lo && st.ffO_hi && st.addAB->getPort(\"\\\\B\") == st.sigO);\n\t\telse if (st.addB)\n\t\t\taccum = (st.ffO_lo && st.ffO_hi && st.addAB->getPort(\"\\\\A\") == st.sigO);\n\t\telse log_abort();\n\t\tif (accum)\n\t\t\tlog(\" accumulator %s (%s)\\n\", log_id(st.addAB), log_id(st.addAB->type));\n\t\telse\n\t\t\tlog(\" adder %s (%s)\\n\", log_id(st.addAB), log_id(st.addAB->type));\n\t\tcell->setPort(\"\\\\ADDSUBTOP\", st.addAB->type == \"$add\" ? State::S0 : State::S1);\n\t\tcell->setPort(\"\\\\ADDSUBBOT\", st.addAB->type == \"$add\" ? State::S0 : State::S1);\n\t} else {\n\t\tcell->setPort(\"\\\\ADDSUBTOP\", State::S0);\n\t\tcell->setPort(\"\\\\ADDSUBBOT\", State::S0);\n\t}\n\n\tcell->setPort(\"\\\\ORSTTOP\", State::S0);\n\tcell->setPort(\"\\\\ORSTBOT\", State::S0);\n\n\tcell->setPort(\"\\\\OHOLDTOP\", State::S0);\n\tcell->setPort(\"\\\\OHOLDBOT\", State::S0);\n\n\tSigSpec acc_reset = State::S0;\n\tif (st.muxA)\n\t\tacc_reset = st.muxA->getPort(\"\\\\S\");\n\tif (st.muxB)\n\t\tacc_reset = pm.module->Not(NEW_ID, st.muxB->getPort(\"\\\\S\"));\n\n\tcell->setPort(\"\\\\OLOADTOP\", acc_reset);\n\tcell->setPort(\"\\\\OLOADBOT\", acc_reset);\n\n\t\/\/ SB_MAC16 Remaining Parameters\n\n\tcell->setParam(\"\\\\C_REG\", State::S0);\n\tcell->setParam(\"\\\\D_REG\", State::S0);\n\n\tcell->setParam(\"\\\\TOP_8x8_MULT_REG\", st.ffH ? State::S1 : State::S0);\n\tcell->setParam(\"\\\\BOT_8x8_MULT_REG\", st.ffH ? State::S1 : State::S0);\n\tcell->setParam(\"\\\\PIPELINE_16x16_MULT_REG1\", st.ffH ? State::S1 : State::S0);\n\tcell->setParam(\"\\\\PIPELINE_16x16_MULT_REG2\", State::S0);\n\n\tcell->setParam(\"\\\\TOPOUTPUT_SELECT\", Const(st.ffO_hi ? 1 : (st.addAB ? 0 : 3), 2));\n\tcell->setParam(\"\\\\TOPADDSUB_LOWERINPUT\", Const(2, 2));\n\tcell->setParam(\"\\\\TOPADDSUB_UPPERINPUT\", accum ? State::S0 : State::S1);\n\tcell->setParam(\"\\\\TOPADDSUB_CARRYSELECT\", Const(3, 2));\n\n\tcell->setParam(\"\\\\BOTOUTPUT_SELECT\", Const(st.ffO_lo ? 1 : (st.addAB ? 0 : 3), 2));\n\tcell->setParam(\"\\\\BOTADDSUB_LOWERINPUT\", Const(2, 2));\n\tcell->setParam(\"\\\\BOTADDSUB_UPPERINPUT\", accum ? State::S0 : State::S1);\n\tcell->setParam(\"\\\\BOTADDSUB_CARRYSELECT\", Const(0, 2));\n\n\tcell->setParam(\"\\\\MODE_8x8\", State::S0);\n\tcell->setParam(\"\\\\A_SIGNED\", a_signed);\n\tcell->setParam(\"\\\\B_SIGNED\", b_signed);\n\n\tpm.autoremove(st.mul);\n\tpm.autoremove(st.ffH);\n\tpm.autoremove(st.addAB);\n\tif (st.ffO_lo) {\n\t\t\tSigSpec O = st.sigO.extract(0,16);\n\t\t\tst.ffO_lo->connections_.at(\"\\\\Q\").replace(O, pm.module->addWire(NEW_ID, GetSize(O)));\n\t}\n\tif (st.ffO_hi) {\n\t\t\tSigSpec O = st.sigO.extract(16,16);\n\t\t\tst.ffO_hi->connections_.at(\"\\\\Q\").replace(O, pm.module->addWire(NEW_ID, GetSize(O)));\n\t}\n}\n\nstruct Ice40DspPass : public Pass {\n\tIce40DspPass() : Pass(\"ice40_dsp\", \"iCE40: map multipliers\") { }\n\tvoid help() YS_OVERRIDE\n\t{\n\t\t\/\/ |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n\t\tlog(\"\\n\");\n\t\tlog(\" ice40_dsp [options] [selection]\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"Map multipliers and multiply-accumulate blocks to iCE40 DSP resources.\\n\");\n\t\tlog(\"\\n\");\n\t}\n\tvoid execute(std::vector args, RTLIL::Design *design) YS_OVERRIDE\n\t{\n\t\tlog_header(design, \"Executing ICE40_DSP pass (map multipliers).\\n\");\n\n\t\tsize_t argidx;\n\t\tfor (argidx = 1; argidx < args.size(); argidx++)\n\t\t{\n\t\t\t\/\/ if (args[argidx] == \"-singleton\") {\n\t\t\t\/\/ \tsingleton_mode = true;\n\t\t\t\/\/ \tcontinue;\n\t\t\t\/\/ }\n\t\t\tbreak;\n\t\t}\n\t\textra_args(args, argidx, design);\n\n\t\tfor (auto module : design->selected_modules())\n\t\t\tice40_dsp_pm(module, module->selected_cells()).run_ice40_dsp(create_ice40_dsp);\n\t}\n} Ice40DspPass;\n\nPRIVATE_NAMESPACE_END\nAllow adders\/accumulators with 33 bits using CO output\/*\n * yosys -- Yosys Open SYnthesis Suite\n *\n * Copyright (C) 2012 Clifford Wolf \n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \"kernel\/yosys.h\"\n#include \"kernel\/sigtools.h\"\n\nUSING_YOSYS_NAMESPACE\nPRIVATE_NAMESPACE_BEGIN\n\ntemplate bool includes(const T &lhs, const T &rhs) {\n\treturn std::includes(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());\n}\n#include \"passes\/pmgen\/ice40_dsp_pm.h\"\n\nvoid create_ice40_dsp(ice40_dsp_pm &pm)\n{\n\tauto &st = pm.st_ice40_dsp;\n\n#if 0\n\tlog(\"\\n\");\n\tlog(\"ffA: %s\\n\", log_id(st.ffA, \"--\"));\n\tlog(\"ffB: %s\\n\", log_id(st.ffB, \"--\"));\n\tlog(\"mul: %s\\n\", log_id(st.mul, \"--\"));\n\tlog(\"ffH: %s\\n\", log_id(st.ffH, \"--\"));\n\tlog(\"addAB: %s\\n\", log_id(st.addAB, \"--\"));\n\tlog(\"muxAB: %s\\n\", log_id(st.muxAB, \"--\"));\n\tlog(\"ffO_lo: %s\\n\", log_id(st.ffO_lo, \"--\"));\n\tlog(\"ffO_hi: %s\\n\", log_id(st.ffO_hi, \"--\"));\n#endif\n\n\tlog(\"Checking %s.%s for iCE40 DSP inference.\\n\", log_id(pm.module), log_id(st.mul));\n\n\tif (GetSize(st.sigA) > 16) {\n\t\tlog(\" input A (%s) is too large (%d > 16).\\n\", log_signal(st.sigA), GetSize(st.sigA));\n\t\treturn;\n\t}\n\n\tif (GetSize(st.sigB) > 16) {\n\t\tlog(\" input B (%s) is too large (%d > 16).\\n\", log_signal(st.sigB), GetSize(st.sigB));\n\t\treturn;\n\t}\n\n\tif (GetSize(st.sigO) > 33) {\n\t\tlog(\" adder\/accumulator (%s) is too large (%d > 33).\\n\", log_signal(st.sigO), GetSize(st.sigO));\n\t\treturn;\n\t}\n\n\tif (GetSize(st.sigH) > 32) {\n\t\tlog(\" output (%s) is too large (%d > 32).\\n\", log_signal(st.sigH), GetSize(st.sigH));\n\t\treturn;\n\t}\n\n\tlog(\" replacing %s with SB_MAC16 cell.\\n\", log_id(st.mul->type));\n\n\tCell *cell = pm.module->addCell(NEW_ID, \"\\\\SB_MAC16\");\n\tpm.module->swap_names(cell, st.mul);\n\n\t\/\/ SB_MAC16 Input Interface\n\tbool a_signed = st.mul->getParam(\"\\\\A_SIGNED\").as_bool();\n\tbool b_signed = st.mul->getParam(\"\\\\B_SIGNED\").as_bool();\n\n\tSigSpec A = st.sigA;\n\tA.extend_u0(16, a_signed);\n\n\tSigSpec B = st.sigB;\n\tB.extend_u0(16, b_signed);\n\n\tSigSpec CD = st.sigCD;\n\tCD.extend_u0(32, st.sigCD_signed);\n\n\tcell->setPort(\"\\\\A\", A);\n\tcell->setPort(\"\\\\B\", B);\n\tcell->setPort(\"\\\\C\", CD.extract(16, 16));\n\tcell->setPort(\"\\\\D\", CD.extract(0, 16));\n\n\tcell->setParam(\"\\\\A_REG\", st.ffA ? State::S1 : State::S0);\n\tcell->setParam(\"\\\\B_REG\", st.ffB ? State::S1 : State::S0);\n\n\tcell->setPort(\"\\\\AHOLD\", State::S0);\n\tcell->setPort(\"\\\\BHOLD\", State::S0);\n\tcell->setPort(\"\\\\CHOLD\", State::S0);\n\tcell->setPort(\"\\\\DHOLD\", State::S0);\n\n\tcell->setPort(\"\\\\IRSTTOP\", State::S0);\n\tcell->setPort(\"\\\\IRSTBOT\", State::S0);\n\n\tif (st.clock != SigBit())\n\t{\n\t\tcell->setPort(\"\\\\CLK\", st.clock);\n\t\tcell->setPort(\"\\\\CE\", State::S1);\n\t\tcell->setParam(\"\\\\NEG_TRIGGER\", st.clock_pol ? State::S0 : State::S1);\n\n\t\tlog(\" clock: %s (%s)\", log_signal(st.clock), st.clock_pol ? \"posedge\" : \"negedge\");\n\n\t\tif (st.ffA)\n\t\t\tlog(\" ffA:%s\", log_id(st.ffA));\n\n\t\tif (st.ffB)\n\t\t\tlog(\" ffB:%s\", log_id(st.ffB));\n\n\t\tif (st.ffH)\n\t\t\tlog(\" ffH:%s\", log_id(st.ffH));\n\n\t\tif (st.ffO_lo)\n\t\t\tlog(\" ffO_lo:%s\", log_id(st.ffO_lo));\n\t\tif (st.ffO_hi)\n\t\t\tlog(\" ffO_hi:%s\", log_id(st.ffO_hi));\n\n\t\tlog(\"\\n\");\n\t}\n\telse\n\t{\n\t\tcell->setPort(\"\\\\CLK\", State::S0);\n\t\tcell->setPort(\"\\\\CE\", State::S0);\n\t\tcell->setParam(\"\\\\NEG_TRIGGER\", State::S0);\n\t}\n\n\t\/\/ SB_MAC16 Cascade Interface\n\n\tcell->setPort(\"\\\\SIGNEXTIN\", State::Sx);\n\tcell->setPort(\"\\\\SIGNEXTOUT\", pm.module->addWire(NEW_ID));\n\n\tcell->setPort(\"\\\\CI\", State::Sx);\n\n\tcell->setPort(\"\\\\ACCUMCI\", State::Sx);\n\tcell->setPort(\"\\\\ACCUMCO\", pm.module->addWire(NEW_ID));\n\n\t\/\/ SB_MAC16 Output Interface\n\n\tSigSpec O = st.sigO;\n\tif (GetSize(O) == 33)\n\t\tcell->setPort(\"\\\\CO\", st.sigO[32]);\n\telse {\n\t\tlog_assert(GetSize(O) <= 32);\n\t\tcell->setPort(\"\\\\CO\", pm.module->addWire(NEW_ID));\n\t}\n\tif (GetSize(O) < 32)\n\t\tO.append(pm.module->addWire(NEW_ID, 32-GetSize(O)));\n\n\tcell->setPort(\"\\\\O\", O);\n\n\tbool accum = false;\n\tif (st.addAB) {\n\t\tif (st.addA)\n\t\t\taccum = (st.ffO_lo && st.ffO_hi && st.addAB->getPort(\"\\\\B\") == st.sigO);\n\t\telse if (st.addB)\n\t\t\taccum = (st.ffO_lo && st.ffO_hi && st.addAB->getPort(\"\\\\A\") == st.sigO);\n\t\telse log_abort();\n\t\tif (accum)\n\t\t\tlog(\" accumulator %s (%s)\\n\", log_id(st.addAB), log_id(st.addAB->type));\n\t\telse\n\t\t\tlog(\" adder %s (%s)\\n\", log_id(st.addAB), log_id(st.addAB->type));\n\t\tcell->setPort(\"\\\\ADDSUBTOP\", st.addAB->type == \"$add\" ? State::S0 : State::S1);\n\t\tcell->setPort(\"\\\\ADDSUBBOT\", st.addAB->type == \"$add\" ? State::S0 : State::S1);\n\t} else {\n\t\tcell->setPort(\"\\\\ADDSUBTOP\", State::S0);\n\t\tcell->setPort(\"\\\\ADDSUBBOT\", State::S0);\n\t}\n\n\tcell->setPort(\"\\\\ORSTTOP\", State::S0);\n\tcell->setPort(\"\\\\ORSTBOT\", State::S0);\n\n\tcell->setPort(\"\\\\OHOLDTOP\", State::S0);\n\tcell->setPort(\"\\\\OHOLDBOT\", State::S0);\n\n\tSigSpec acc_reset = State::S0;\n\tif (st.muxA)\n\t\tacc_reset = st.muxA->getPort(\"\\\\S\");\n\tif (st.muxB)\n\t\tacc_reset = pm.module->Not(NEW_ID, st.muxB->getPort(\"\\\\S\"));\n\n\tcell->setPort(\"\\\\OLOADTOP\", acc_reset);\n\tcell->setPort(\"\\\\OLOADBOT\", acc_reset);\n\n\t\/\/ SB_MAC16 Remaining Parameters\n\n\tcell->setParam(\"\\\\C_REG\", State::S0);\n\tcell->setParam(\"\\\\D_REG\", State::S0);\n\n\tcell->setParam(\"\\\\TOP_8x8_MULT_REG\", st.ffH ? State::S1 : State::S0);\n\tcell->setParam(\"\\\\BOT_8x8_MULT_REG\", st.ffH ? State::S1 : State::S0);\n\tcell->setParam(\"\\\\PIPELINE_16x16_MULT_REG1\", st.ffH ? State::S1 : State::S0);\n\tcell->setParam(\"\\\\PIPELINE_16x16_MULT_REG2\", State::S0);\n\n\tcell->setParam(\"\\\\TOPOUTPUT_SELECT\", Const(st.ffO_hi ? 1 : (st.addAB ? 0 : 3), 2));\n\tcell->setParam(\"\\\\TOPADDSUB_LOWERINPUT\", Const(2, 2));\n\tcell->setParam(\"\\\\TOPADDSUB_UPPERINPUT\", accum ? State::S0 : State::S1);\n\tcell->setParam(\"\\\\TOPADDSUB_CARRYSELECT\", Const(3, 2));\n\n\tcell->setParam(\"\\\\BOTOUTPUT_SELECT\", Const(st.ffO_lo ? 1 : (st.addAB ? 0 : 3), 2));\n\tcell->setParam(\"\\\\BOTADDSUB_LOWERINPUT\", Const(2, 2));\n\tcell->setParam(\"\\\\BOTADDSUB_UPPERINPUT\", accum ? State::S0 : State::S1);\n\tcell->setParam(\"\\\\BOTADDSUB_CARRYSELECT\", Const(0, 2));\n\n\tcell->setParam(\"\\\\MODE_8x8\", State::S0);\n\tcell->setParam(\"\\\\A_SIGNED\", a_signed);\n\tcell->setParam(\"\\\\B_SIGNED\", b_signed);\n\n\tpm.autoremove(st.mul);\n\tpm.autoremove(st.ffH);\n\tpm.autoremove(st.addAB);\n\tif (st.ffO_lo) {\n\t\t\tSigSpec O = st.sigO.extract(0,16);\n\t\t\tst.ffO_lo->connections_.at(\"\\\\Q\").replace(O, pm.module->addWire(NEW_ID, GetSize(O)));\n\t}\n\tif (st.ffO_hi) {\n\t\t\tSigSpec O = st.sigO.extract(16,16);\n\t\t\tst.ffO_hi->connections_.at(\"\\\\Q\").replace(O, pm.module->addWire(NEW_ID, GetSize(O)));\n\t}\n}\n\nstruct Ice40DspPass : public Pass {\n\tIce40DspPass() : Pass(\"ice40_dsp\", \"iCE40: map multipliers\") { }\n\tvoid help() YS_OVERRIDE\n\t{\n\t\t\/\/ |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n\t\tlog(\"\\n\");\n\t\tlog(\" ice40_dsp [options] [selection]\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"Map multipliers and multiply-accumulate blocks to iCE40 DSP resources.\\n\");\n\t\tlog(\"\\n\");\n\t}\n\tvoid execute(std::vector args, RTLIL::Design *design) YS_OVERRIDE\n\t{\n\t\tlog_header(design, \"Executing ICE40_DSP pass (map multipliers).\\n\");\n\n\t\tsize_t argidx;\n\t\tfor (argidx = 1; argidx < args.size(); argidx++)\n\t\t{\n\t\t\t\/\/ if (args[argidx] == \"-singleton\") {\n\t\t\t\/\/ \tsingleton_mode = true;\n\t\t\t\/\/ \tcontinue;\n\t\t\t\/\/ }\n\t\t\tbreak;\n\t\t}\n\t\textra_args(args, argidx, design);\n\n\t\tfor (auto module : design->selected_modules())\n\t\t\tice40_dsp_pm(module, module->selected_cells()).run_ice40_dsp(create_ice40_dsp);\n\t}\n} Ice40DspPass;\n\nPRIVATE_NAMESPACE_END\n<|endoftext|>"} {"text":"#include \n#ifdef PROFILER\n#include \n#endif\n#include \"matrix_config.h\"\n#include \"io_interface.h\"\n#include \"safs_file.h\"\n#include \"sparse_matrix.h\"\n#include \"NUMA_dense_matrix.h\"\n#include \"matrix\/FG_sparse_matrix.h\"\n\nusing namespace fm;\n\nvoid int_handler(int sig_num)\n{\n#ifdef PROFILER\n\tprintf(\"stop profiling\\n\");\n\tif (!matrix_conf.get_prof_file().empty())\n\t\tProfilerStop();\n#endif\n\texit(0);\n}\n\nvoid test_SpMV(sparse_matrix::ptr mat)\n{\n\tprintf(\"test sparse matrix vector multiplication\\n\");\n\tstruct timeval start, end;\n\tdetail::NUMA_vec_store::ptr in_vec = detail::NUMA_vec_store::create(\n\t\t\tmat->get_num_cols(), matrix_conf.get_num_nodes(),\n\t\t\tget_scalar_type());\n#pragma omp parallel for\n\tfor (size_t i = 0; i < mat->get_num_cols(); i++)\n\t\tin_vec->set(i, i);\n\tprintf(\"initialize the input vector\\n\");\n\n\t\/\/ Initialize the output vector and allocate pages for it.\n\tgettimeofday(&start, NULL);\n\tdetail::NUMA_vec_store::ptr out = detail::NUMA_vec_store::create(\n\t\t\tmat->get_num_rows(), matrix_conf.get_num_nodes(),\n\t\t\tget_scalar_type());\n\tout->reset_data();\n\tgettimeofday(&end, NULL);\n\tprintf(\"initialize a vector of %ld entries takes %.3f seconds\\n\",\n\t\t\tout->get_length(), time_diff(start, end));\n\n#ifdef PROFILER\n\tif (!matrix_conf.get_prof_file().empty())\n\t\tProfilerStart(matrix_conf.get_prof_file().c_str());\n#endif\n\tprintf(\"start SpMV\\n\");\n\tgettimeofday(&start, NULL);\n\tmat->multiply(*in_vec, *out);\n\tgettimeofday(&end, NULL);\n\tprintf(\"SpMV completes\\n\");\n#ifdef PROFILER\n\tif (!matrix_conf.get_prof_file().empty())\n\t\tProfilerStop();\n#endif\n\n\tdouble in_sum = 0;\n\tfor (size_t i = 0; i < mat->get_num_cols(); i++)\n\t\tin_sum += in_vec->get(i);\n\tdouble out_sum = 0;\n\tfor (size_t i = 0; i < mat->get_num_cols(); i++)\n\t\tout_sum += out->get(i);\n\tprintf(\"sum of input: %lf, sum of product: %lf, it takes %.3f seconds\\n\",\n\t\t\tin_sum, out_sum, time_diff(start, end));\n}\n\nclass mat_init_operate: public type_set_operate\n{\npublic:\n\tmat_init_operate(size_t num_rows, size_t num_cols) {\n\t}\n\n\tvirtual void set(double *arr, size_t num_eles, off_t row_idx,\n\t\t\t off_t col_idx) const {\n\t\tfor (size_t i = 0; i < num_eles; i++)\n\t\t\tarr[i] = row_idx * (i + col_idx + 1);\n\t}\n};\n\nvoid test_SpMM(sparse_matrix::ptr mat, size_t mat_width)\n{\n\tprintf(\"test sparse matrix dense matrix multiplication\\n\");\n\tstruct timeval start, end;\n\tdetail::NUMA_row_tall_matrix_store::ptr in\n\t\t= detail::NUMA_row_tall_matrix_store::create(mat->get_num_cols(),\n\t\t\t\tmat_width, matrix_conf.get_num_nodes(),\n\t\t\t\tget_scalar_type());\n\tin->set_data(mat_init_operate(in->get_num_rows(), in->get_num_cols()));\n\tprintf(\"set input data\\n\");\n\n\t\/\/ Initialize the output matrix and allocate pages for it.\n\tdetail::NUMA_row_tall_matrix_store::ptr out\n\t\t= detail::NUMA_row_tall_matrix_store::create(mat->get_num_rows(),\n\t\t\t\tmat_width, matrix_conf.get_num_nodes(),\n\t\t\t\tget_scalar_type());\n\tout->reset_data();\n\tprintf(\"reset output data\\n\");\n\n#ifdef PROFILER\n\tif (!matrix_conf.get_prof_file().empty())\n\t\tProfilerStart(matrix_conf.get_prof_file().c_str());\n#endif\n\tprintf(\"Start SpMM\\n\");\n\tgettimeofday(&start, NULL);\n\tmat->multiply(*in, *out);\n\tgettimeofday(&end, NULL);\n\tprintf(\"SpMM completes\\n\");\n#ifdef PROFILER\n\tif (!matrix_conf.get_prof_file().empty())\n\t\tProfilerStop();\n#endif\n\tprintf(\"it takes %.3f seconds\\n\", time_diff(start, end));\n\n\tfor (size_t k = 0; k < in->get_num_cols(); k++) {\n\t\tdouble in_sum = 0;\n\t\tfor (size_t i = 0; i < in->get_num_rows(); i++)\n\t\t\tin_sum += *(double *) in->get(i, k);\n\t\tdouble out_sum = 0;\n\t\tfor (size_t i = 0; i < mat->get_num_cols(); i++)\n\t\t\tout_sum += *(double *) out->get(i, k);\n\t\tprintf(\"%ld: sum of input: %lf, sum of product: %lf\\n\",\n\t\t\t\tk, in_sum, out_sum);\n\t}\n}\n\nvoid print_usage()\n{\n\tfprintf(stderr, \"test conf_file matrix_file index_file [options]\\n\");\n\tfprintf(stderr,\n\t\t\t\"-w matrix_width: the number of columns of the dense matrix\\n\");\n\tfprintf(stderr, \"-o exec_order: hilbert or seq\\n\");\n\tfprintf(stderr, \"-c cache_size: cpu cache size\\n\");\n\tfprintf(stderr, \"-m: force to run in memory\\n\");\n\tfprintf(stderr, \"-r number: the number of repeats\\n\");\n}\n\nint main(int argc, char *argv[])\n{\n\tif (argc < 4) {\n\t\tprint_usage();\n\t\texit(1);\n\t}\n\n\tsize_t mat_width = 0;\n\tstd::string exec_order = \"hilbert\";\n\tsize_t cpu_cache_size = 1024 * 1024;\n\tint opt;\n\tbool in_mem = false;\n\tsize_t repeats = 1;\n\twhile ((opt = getopt(argc, argv, \"w:o:c:mr:\")) != -1) {\n\t\tswitch (opt) {\n\t\t\tcase 'w':\n\t\t\t\tmat_width = atoi(optarg);\n\t\t\t\tbreak;\n\t\t\tcase 'o':\n\t\t\t\texec_order = optarg;\n\t\t\t\tbreak;\n\t\t\tcase 'c':\n\t\t\t\tcpu_cache_size = atoi(optarg);\n\t\t\t\tbreak;\n\t\t\tcase 'm':\n\t\t\t\tin_mem = true;\n\t\t\t\tbreak;\n\t\t\tcase 'r':\n\t\t\t\trepeats = atoi(optarg);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tprint_usage();\n\t\t\t\tabort();\n\t\t}\n\t}\n\n\tstd::string conf_file = argv[argc - 3];\n\tstd::string matrix_file = argv[argc - 2];\n\tstd::string index_file = argv[argc - 1];\n\tsignal(SIGINT, int_handler);\n\n\tif (exec_order == \"seq\")\n\t\tmatrix_conf.set_hilbert_order(false);\n\tmatrix_conf.set_cpu_cache_size(cpu_cache_size);\n\n\tconfig_map::ptr configs = config_map::create(conf_file);\n\tinit_flash_matrix(configs);\n\n\tSpM_2d_index::ptr index;\n\tsafs::safs_file idx_f(safs::get_sys_RAID_conf(), index_file);\n\tif (idx_f.exist())\n\t\tindex = SpM_2d_index::safs_load(index_file);\n\telse\n\t\tindex = SpM_2d_index::load(index_file);\n\tprintf(\"load the matrix index\\n\");\n\n\tsparse_matrix::ptr mat;\n\tsafs::safs_file mat_f(safs::get_sys_RAID_conf(), matrix_file);\n\tif (mat_f.exist() && in_mem)\n\t\tmat = sparse_matrix::create(index,\n\t\t\t\tSpM_2d_storage::safs_load(matrix_file, index));\n\telse if (mat_f.exist())\n\t\tmat = sparse_matrix::create(index, safs::create_io_factory(\n\t\t\t\t\tmatrix_file, safs::REMOTE_ACCESS));\n\telse\n\t\tmat = sparse_matrix::create(index,\n\t\t\t\tSpM_2d_storage::load(matrix_file, index));\n\tprintf(\"load the matrix image\\n\");\n\n\tif (mat_width == 0) {\n\t\tfor (size_t k = 0; k < repeats; k++)\n\t\t\ttest_SpMV(mat);\n\t\tfor (size_t i = 1; i <= 16; i *= 2)\n\t\t\tfor (size_t k = 0; k < repeats; k++)\n\t\t\t\ttest_SpMM(mat, i);\n\t}\n\telse {\n\t\tfor (size_t k = 0; k < repeats; k++)\n\t\t\ttest_SpMM(mat, mat_width);\n\t}\n\n\tdestroy_flash_matrix();\n}\n[Matrix]: disable testing results of SpMM.#include \n#ifdef PROFILER\n#include \n#endif\n#include \"matrix_config.h\"\n#include \"io_interface.h\"\n#include \"safs_file.h\"\n#include \"sparse_matrix.h\"\n#include \"NUMA_dense_matrix.h\"\n#include \"matrix\/FG_sparse_matrix.h\"\n\nusing namespace fm;\n\nvoid int_handler(int sig_num)\n{\n#ifdef PROFILER\n\tprintf(\"stop profiling\\n\");\n\tif (!matrix_conf.get_prof_file().empty())\n\t\tProfilerStop();\n#endif\n\texit(0);\n}\n\nvoid test_SpMV(sparse_matrix::ptr mat)\n{\n\tprintf(\"test sparse matrix vector multiplication\\n\");\n\tstruct timeval start, end;\n\tdetail::NUMA_vec_store::ptr in_vec = detail::NUMA_vec_store::create(\n\t\t\tmat->get_num_cols(), matrix_conf.get_num_nodes(),\n\t\t\tget_scalar_type());\n#pragma omp parallel for\n\tfor (size_t i = 0; i < mat->get_num_cols(); i++)\n\t\tin_vec->set(i, i);\n\tprintf(\"initialize the input vector\\n\");\n\n\t\/\/ Initialize the output vector and allocate pages for it.\n\tgettimeofday(&start, NULL);\n\tdetail::NUMA_vec_store::ptr out = detail::NUMA_vec_store::create(\n\t\t\tmat->get_num_rows(), matrix_conf.get_num_nodes(),\n\t\t\tget_scalar_type());\n\tout->reset_data();\n\tgettimeofday(&end, NULL);\n\tprintf(\"initialize a vector of %ld entries takes %.3f seconds\\n\",\n\t\t\tout->get_length(), time_diff(start, end));\n\n#ifdef PROFILER\n\tif (!matrix_conf.get_prof_file().empty())\n\t\tProfilerStart(matrix_conf.get_prof_file().c_str());\n#endif\n\tprintf(\"start SpMV\\n\");\n\tgettimeofday(&start, NULL);\n\tmat->multiply(*in_vec, *out);\n\tgettimeofday(&end, NULL);\n\tprintf(\"SpMV completes\\n\");\n#ifdef PROFILER\n\tif (!matrix_conf.get_prof_file().empty())\n\t\tProfilerStop();\n#endif\n\n\tdouble in_sum = 0;\n\tfor (size_t i = 0; i < mat->get_num_cols(); i++)\n\t\tin_sum += in_vec->get(i);\n\tdouble out_sum = 0;\n\tfor (size_t i = 0; i < mat->get_num_cols(); i++)\n\t\tout_sum += out->get(i);\n\tprintf(\"sum of input: %lf, sum of product: %lf, it takes %.3f seconds\\n\",\n\t\t\tin_sum, out_sum, time_diff(start, end));\n}\n\nclass mat_init_operate: public type_set_operate\n{\npublic:\n\tmat_init_operate(size_t num_rows, size_t num_cols) {\n\t}\n\n\tvirtual void set(double *arr, size_t num_eles, off_t row_idx,\n\t\t\t off_t col_idx) const {\n\t\tfor (size_t i = 0; i < num_eles; i++)\n\t\t\tarr[i] = row_idx * (i + col_idx + 1);\n\t}\n};\n\nvoid test_SpMM(sparse_matrix::ptr mat, size_t mat_width)\n{\n\tprintf(\"test sparse matrix dense matrix multiplication\\n\");\n\tstruct timeval start, end;\n\tdetail::NUMA_row_tall_matrix_store::ptr in\n\t\t= detail::NUMA_row_tall_matrix_store::create(mat->get_num_cols(),\n\t\t\t\tmat_width, matrix_conf.get_num_nodes(),\n\t\t\t\tget_scalar_type());\n\tin->set_data(mat_init_operate(in->get_num_rows(), in->get_num_cols()));\n\tprintf(\"set input data\\n\");\n\n\t\/\/ Initialize the output matrix and allocate pages for it.\n\tdetail::NUMA_row_tall_matrix_store::ptr out\n\t\t= detail::NUMA_row_tall_matrix_store::create(mat->get_num_rows(),\n\t\t\t\tmat_width, matrix_conf.get_num_nodes(),\n\t\t\t\tget_scalar_type());\n\tout->reset_data();\n\tprintf(\"reset output data\\n\");\n\n#ifdef PROFILER\n\tif (!matrix_conf.get_prof_file().empty())\n\t\tProfilerStart(matrix_conf.get_prof_file().c_str());\n#endif\n\tprintf(\"Start SpMM\\n\");\n\tgettimeofday(&start, NULL);\n\tmat->multiply(*in, *out);\n\tgettimeofday(&end, NULL);\n\tprintf(\"SpMM completes\\n\");\n#ifdef PROFILER\n\tif (!matrix_conf.get_prof_file().empty())\n\t\tProfilerStop();\n#endif\n\tprintf(\"it takes %.3f seconds\\n\", time_diff(start, end));\n\n#ifdef VERIFY_RESULT\n\tfor (size_t k = 0; k < in->get_num_cols(); k++) {\n\t\tdouble in_sum = 0;\n\t\tfor (size_t i = 0; i < in->get_num_rows(); i++)\n\t\t\tin_sum += *(double *) in->get(i, k);\n\t\tdouble out_sum = 0;\n\t\tfor (size_t i = 0; i < mat->get_num_cols(); i++)\n\t\t\tout_sum += *(double *) out->get(i, k);\n\t\tprintf(\"%ld: sum of input: %lf, sum of product: %lf\\n\",\n\t\t\t\tk, in_sum, out_sum);\n\t}\n#endif\n}\n\nvoid print_usage()\n{\n\tfprintf(stderr, \"test conf_file matrix_file index_file [options]\\n\");\n\tfprintf(stderr,\n\t\t\t\"-w matrix_width: the number of columns of the dense matrix\\n\");\n\tfprintf(stderr, \"-o exec_order: hilbert or seq\\n\");\n\tfprintf(stderr, \"-c cache_size: cpu cache size\\n\");\n\tfprintf(stderr, \"-m: force to run in memory\\n\");\n\tfprintf(stderr, \"-r number: the number of repeats\\n\");\n}\n\nint main(int argc, char *argv[])\n{\n\tif (argc < 4) {\n\t\tprint_usage();\n\t\texit(1);\n\t}\n\n\tsize_t mat_width = 0;\n\tstd::string exec_order = \"hilbert\";\n\tsize_t cpu_cache_size = 1024 * 1024;\n\tint opt;\n\tbool in_mem = false;\n\tsize_t repeats = 1;\n\twhile ((opt = getopt(argc, argv, \"w:o:c:mr:\")) != -1) {\n\t\tswitch (opt) {\n\t\t\tcase 'w':\n\t\t\t\tmat_width = atoi(optarg);\n\t\t\t\tbreak;\n\t\t\tcase 'o':\n\t\t\t\texec_order = optarg;\n\t\t\t\tbreak;\n\t\t\tcase 'c':\n\t\t\t\tcpu_cache_size = atoi(optarg);\n\t\t\t\tbreak;\n\t\t\tcase 'm':\n\t\t\t\tin_mem = true;\n\t\t\t\tbreak;\n\t\t\tcase 'r':\n\t\t\t\trepeats = atoi(optarg);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tprint_usage();\n\t\t\t\tabort();\n\t\t}\n\t}\n\n\tstd::string conf_file = argv[argc - 3];\n\tstd::string matrix_file = argv[argc - 2];\n\tstd::string index_file = argv[argc - 1];\n\tsignal(SIGINT, int_handler);\n\n\tif (exec_order == \"seq\")\n\t\tmatrix_conf.set_hilbert_order(false);\n\tmatrix_conf.set_cpu_cache_size(cpu_cache_size);\n\n\tconfig_map::ptr configs = config_map::create(conf_file);\n\tinit_flash_matrix(configs);\n\n\tSpM_2d_index::ptr index;\n\tsafs::safs_file idx_f(safs::get_sys_RAID_conf(), index_file);\n\tif (idx_f.exist())\n\t\tindex = SpM_2d_index::safs_load(index_file);\n\telse\n\t\tindex = SpM_2d_index::load(index_file);\n\tprintf(\"load the matrix index\\n\");\n\n\tsparse_matrix::ptr mat;\n\tsafs::safs_file mat_f(safs::get_sys_RAID_conf(), matrix_file);\n\tif (mat_f.exist() && in_mem)\n\t\tmat = sparse_matrix::create(index,\n\t\t\t\tSpM_2d_storage::safs_load(matrix_file, index));\n\telse if (mat_f.exist())\n\t\tmat = sparse_matrix::create(index, safs::create_io_factory(\n\t\t\t\t\tmatrix_file, safs::REMOTE_ACCESS));\n\telse\n\t\tmat = sparse_matrix::create(index,\n\t\t\t\tSpM_2d_storage::load(matrix_file, index));\n\tprintf(\"load the matrix image\\n\");\n\n\tif (mat_width == 0) {\n\t\tfor (size_t k = 0; k < repeats; k++)\n\t\t\ttest_SpMV(mat);\n\t\tfor (size_t i = 1; i <= 16; i *= 2)\n\t\t\tfor (size_t k = 0; k < repeats; k++)\n\t\t\t\ttest_SpMM(mat, i);\n\t}\n\telse {\n\t\tfor (size_t k = 0; k < repeats; k++)\n\t\t\ttest_SpMM(mat, mat_width);\n\t}\n\n\tdestroy_flash_matrix();\n}\n<|endoftext|>"} {"text":"#ifndef PROFILER_HH_INCLUDED\r\n#define PROFILER_HH_INCLUDED\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \"misc.hh\"\r\n\r\n\/\/! wraps name, start- and end time for one timing section\r\nstruct TimingData\r\n{\r\n\tclock_t start;\r\n\tclock_t end;\r\n\tstd::string name;\r\n\tTimingData( const std::string _name, const clock_t _start ):start( _start ),end( (clock_t)0.0 ),name( _name ) {};\r\n\tTimingData():start( (clock_t)0.0 ),end( (clock_t)0.0 ),name( \"blank\" ) {};\r\n\r\n};\r\n\r\ntypedef std::map DataMap;\r\ntypedef std::vector MapVector;\r\n\r\n\/** \\brief simple inline profiling class\r\n *\r\n * - User can set as many (even nested) named sections whose total clock time will be computed across all program instances.\\n\r\n * - Provides csv-conform output of process-averaged runtimes.\r\n **\/\r\nclass Profiler\r\n{\r\n friend Profiler& profiler();\r\n\r\n protected:\r\n\t\tProfiler() { Reset(1); }\r\n\t\t~Profiler() {}\r\n\r\n\tpublic:\r\n\t\t\/\/! set this to begin a named section\r\n\t\tvoid StartTiming( const std::string section_name ) {\r\n\t\t\tTimingData td( section_name,clock() );\r\n\t\t\tif ( m_cur_run_num >= m_timings.size() ) {\r\n\t\t\t\tm_timings.push_back( DataMap() );\r\n\t\t\t\tm_total_runs++;\r\n\t\t\t}\r\n\t\t\t(m_timings[m_cur_run_num])[section_name] = td;\r\n\t\t}\r\n\r\n \/\/! stop named section's counter\r\n\t\tvoid StopTiming( const std::string section_name ) {\r\n\t\t\tassert( m_cur_run_num < m_timings.size() );\r\n\t\t\t(m_timings[m_cur_run_num])[section_name].end = clock();\r\n\t\t}\r\n\r\n\t\t\/\/! get runtime of section in seconds\r\n\t\tlong GetTiming( const std::string section_name ) {\r\n\t\t\tassert( m_cur_run_num < m_timings.size() );\r\n clock_t diff = (m_timings[m_cur_run_num])[section_name].end -\r\n (m_timings[m_cur_run_num])[section_name].start;\r\n return long(diff \/ double( CLOCKS_PER_SEC ));\r\n\t\t}\r\n\r\n\t\t\/** output to currently pre-defined (csv) file, does not output individual run results, but average over all recorded results\r\n * \\param comm used to gather and average the runtime data over all processes\r\n * \\tparam CollectiveCommunication should be Dune::CollectiveCommunication< MPI_Comm \/ double >\r\n **\/\r\n template < class CollectiveCommunication >\r\n\t\tlong OutputAveraged( CollectiveCommunication& comm, const int refineLevel, const long numDofs );\r\n\r\n \/** output to \\param filename\r\n * \\param comm used to gather and average the runtime data over all processes\r\n * \\tparam CollectiveCommunication should be Dune::CollectiveCommunication< MPI_Comm \/ double >\r\n **\/\r\n\t\ttemplate < class CollectiveCommunication, class InfoContainer >\r\n\t\tlong OutputCommon( CollectiveCommunication& comm, InfoContainer& run_infos, std::string filename );\r\n\r\n\t\t\/\/! default proxy for output\r\n template < class CollectiveCommunication, class InfoContainer >\r\n\t\tlong Output( CollectiveCommunication& comm, InfoContainer& run_infos );\r\n\r\n\t\t\/\/! proxy for output of a map of runinfos\r\n template < class CollectiveCommunication, class InfoContainerMap >\r\n\t\tvoid OutputMap( CollectiveCommunication& comm, InfoContainerMap& run_infos_map );\r\n\r\n \/** call this with correct numRuns before <\/b> starting any profiling\r\n * if you're planning on doing more than one iteration of your code\r\n * called once fromm ctor with numRuns=1\r\n **\/\r\n\t\tvoid Reset( const int numRuns ) {\r\n\t\t Logger().Dbg() << \"preparing profiler for \" << numRuns << \" runs\" << std::endl;\r\n\t\t\tm_timings.clear();\r\n\t\t\tm_timings = MapVector( numRuns, DataMap() );\r\n\t\t\tm_total_runs = numRuns;\r\n\t\t\tm_cur_run_num = 0;\r\n init_time_ = clock();\r\n\t\t}\r\n\r\n \/\/! simple counter, usable to count how often a single piece of code is called\r\n\t\tvoid AddCount( const int num) {\r\n\t\t m_count[num] +=1;\r\n\t\t}\r\n\r\n \/\/! call this after one iteration of your code has finished. increments current run number and puts new timing data into the vector\r\n\t\tvoid NextRun( ) {\r\n m_cur_run_num++;\r\n\t\t}\r\n\r\n\t\tclass ScopedTiming {\r\n\t\t\tconst std::string section_name_;\r\n\t\t\tpublic:\r\n\t\t\t\tScopedTiming( const std::string& section_name )\r\n\t\t\t\t\t:section_name_(section_name)\r\n\t\t\t\t{\r\n\t\t\t\t\tProfiler::instance().StartTiming( section_name_ );\r\n\t\t\t\t}\r\n\t\t\t\t~ScopedTiming()\r\n\t\t\t\t{\r\n\t\t\t\t\tProfiler::instance().StopTiming( section_name_ );\r\n\t\t\t\t}\r\n\t\t};\r\n\r\n\tprotected:\r\n\t\tMapVector m_timings;\r\n\t\tunsigned int m_cur_run_num;\r\n\t\tunsigned int m_total_runs;\r\n\t\t\/\/debug counter, only outputted in debug mode\r\n\t\tstd::map m_count;\r\n\t\tclock_t init_time_;\r\n\r\n\t\tstatic Profiler& instance()\r\n\t\t{\r\n\t\t\tstatic Profiler pf;\r\n\t\t\treturn pf;\r\n\t\t}\r\n};\r\n\r\ntemplate < class CollectiveCommunication >\r\nlong Profiler::OutputAveraged( CollectiveCommunication& comm, const int refineLevel, const long numDofs )\r\n{\r\n\tconst int numProce = comm.size();\r\n\r\n\tstd::ostringstream filename;\r\n\tfilename << \"p\" << numProce << \"_refinelvl_\" << refineLevel << \".csv\";\r\n\tfilename.flush();\r\n\r\n if ( comm.rank() == 0 )\r\n std :: cout << \"Profiling info in: \" << ( filename.str() ).c_str() << std::endl;\r\n\r\n#ifndef NDEBUG\r\n for (std::map::const_iterator it = m_count.begin(); it != m_count.end(); ++it)\r\n {\r\n std::cout << \"proc \" << comm.rank() << \" bId \" << it->first << \" count \" << it->second << std::endl;\r\n }\r\n#endif\r\n\r\n\tStuff::testCreateDirectory( Stuff::pathOnly( filename.str() ) );\r\n std::ofstream csv(( filename.str() ).c_str() );\r\n\r\n typedef std::map AvgMap;\r\n AvgMap averages;\r\n for ( MapVector::const_iterator vit = m_timings.begin(); vit != m_timings.end(); ++vit )\r\n\t{\r\n\t\tfor ( DataMap::const_iterator it = vit->begin(); it != vit->end(); ++it )\r\n {\r\n int diff = it->second.end - it->second.start;\r\n averages[it->first] +=diff;\r\n }\r\n\t}\r\n\r\n\/\/outputs column names\r\n csv << \"refine,\" << \"processes,\"<< \"numDofs,\" << \"L1 error,\";\r\n\tfor ( AvgMap::const_iterator it = averages.begin(); it != averages.end(); ++it )\r\n\t{\r\n\t\tcsv << it->first << \",\" ;\r\n\t}\r\n csv << \"Speedup (total); Speedup (ohne Solver)\" << std::endl;\r\n\r\n\/\/outputs column values\r\n\tcsv\r\n << refineLevel << \",\" << comm.size() << \",\" << numDofs << \",\"\r\n << 0 << \",\"; \/\/!FIXME\r\n\tfor ( AvgMap::const_iterator it = averages.begin(); it != averages.end(); ++it )\r\n\t{\r\n\t\tlong clock_count = it->second;\r\n\t\tclock_count = long ( comm.sum( clock_count ) \/ double( CLOCKS_PER_SEC*0.001*numProce ) );\r\n\t\tcsv << clock_count\/double(m_total_runs) << \",\" ;\r\n\t}\r\n csv << \"=I$2\/I2,\" << \"=SUM(E$2:G$2)\/SUM(E2:G2)\" << std::endl;\r\n\r\n\r\n\tcsv.close();\r\n\r\n\treturn long( ( clock() - init_time_ ) \/ double( CLOCKS_PER_SEC*0.001 ) );\r\n\r\n}\r\n\r\ntemplate < class CollectiveCommunication, class InfoContainer >\r\nlong Profiler::Output( CollectiveCommunication& comm, InfoContainer& run_infos )\r\n{\r\n\tconst int numProce = comm.size();\r\n\r\n\tstd::ostringstream filename;\r\n\tfilename << Parameters().getParam(\"fem.io.datadir\", std::string(\".\") ) << \"\/prof_p\" << numProce << \".csv\";\r\n\tfilename.flush();\r\n\treturn OutputCommon( comm, run_infos, filename.str() );\r\n}\r\n\r\ntemplate < class CollectiveCommunication, class InfoContainerMap >\r\nvoid Profiler::OutputMap( CollectiveCommunication& comm, InfoContainerMap& run_infos_map )\r\n{\r\n\tstd::string dir( Parameters().getParam(\"fem.io.datadir\", std::string(\".\") ) );\r\n\tBOOST_FOREACH( typename InfoContainerMap::value_type el, run_infos_map ) {\r\n\t\tOutputCommon( comm, el.second, (boost::format(\"%s\/prof_p%d_ref%s\") % dir % comm.size() % el.first).str() );\r\n\t}\r\n}\r\n\r\ntemplate < class CollectiveCommunication, class InfoContainer >\r\nlong Profiler::OutputCommon( CollectiveCommunication& comm, InfoContainer& run_infos, std::string filename )\r\n{\r\n\tconst int numProce = comm.size();\r\n\r\n if ( comm.rank() == 0 )\r\n std :: cout << \"Profiling info in: \" << filename.c_str() << std::endl;\r\n\r\n#ifndef NDEBUG\r\n for (std::map::const_iterator it = m_count.begin(); it != m_count.end(); ++it)\r\n {\r\n std::cout << \"proc \" << comm.rank() << \" bId \" << it->first << \" count \" << it->second << std::endl;\r\n }\r\n#endif\r\n\r\n\tStuff::testCreateDirectory( Stuff::pathOnly( filename) );\r\n std::ofstream csv( filename.c_str() );\r\n\r\n\/\/outputs column names\r\n\tcsv << \"refine\\t\" << \"processes\\t\"<< \"numDofs\\t\" << \"L2 error\\t\";\r\n\tfor ( DataMap::const_iterator it = m_timings[0].begin(); it != m_timings[0].end(); ++it )\r\n\t{\r\n\t\tcsv << it->first << \"\\t\" ;\r\n\t}\r\n csv << \"Relative total time\" << std::endl;\r\n\r\n\/\/outputs column values\r\n\r\n MapVector::const_iterator ti_it = m_timings.begin();\r\n int idx = 0;\r\n\tassert( run_infos.size() >= m_timings.size() );\r\n for (; ti_it != m_timings.end(); ++ti_it ) {\r\n RunInfo info = run_infos[idx];\r\n\t\tcsv << info.refine_level << \"\\t\" << comm.size() << \"\\t\" << info.codim0 << \"\\t\"\r\n\t\t<< -1 \/*fake L2 error*\/ << \"\\t\";\r\n\r\n const DataMap& data_map = *ti_it;\r\n for ( DataMap::const_iterator it = data_map.begin(); it != data_map.end(); ++it )\r\n {\r\n TimingData data = it->second;\r\n long clock_count = data.end - data.start;\r\n clock_count = long ( comm.sum( clock_count ) \/ double( CLOCKS_PER_SEC*0.001*numProce ) );\r\n\t\t\tcsv << clock_count << \"\\t\" ;\r\n }\r\n csv << \"=1\/I$2*I\" << Stuff::toString(idx + 2) << std::endl;\r\n\r\n idx++;\r\n }\r\n\r\n\tcsv.close();\r\n\r\n\treturn long( ( clock() - init_time_ ) \/ double( CLOCKS_PER_SEC*0.001 ) );\r\n\r\n}\r\n\r\n\/\/! global profiler object\r\nProfiler& profiler()\r\n{\r\n\treturn Profiler::instance();\r\n}\r\n\r\n#endif \/\/ PROFILER_HH_INCLUDED\r\nProfiler: enable multiple, additive {Start,Stop}\/Timing calls#ifndef DUNE_STUFF_PROFILER_HH_INCLUDED\r\n#define DUNE_STUFF_PROFILER_HH_INCLUDED\r\n\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \"misc.hh\"\r\n#include \"debug.hh\"\r\n\r\n\/\/! wraps name, start- and end time for one timing section\r\nstruct TimingData\r\n{\r\n\tclock_t start;\r\n\tclock_t end;\r\n\tstd::string name;\r\n\tTimingData( const std::string _name, const clock_t _start ):start( _start ),end( (clock_t)0.0 ),name( _name ) {};\r\n\tTimingData():start( (clock_t)0.0 ),end( (clock_t)0.0 ),name( \"blank\" ) {};\r\n};\r\n\r\n\/** \\brief simple inline profiling class\r\n *\r\n * - User can set as many (even nested) named sections whose total clock time will be computed across all program instances.\\n\r\n * - Provides csv-conform output of process-averaged runtimes.\r\n **\/\r\nclass Profiler\r\n{\r\n\tfriend Profiler& profiler();\r\n\r\n protected:\r\n\t\tProfiler() { Reset(1); }\r\n\t\t~Profiler() {}\r\n\r\n\t\ttypedef std::vector\r\n\t\t\tTimingVector;\r\n\t\ttypedef std::map\r\n\t\t\tDataMap;\r\n\t\ttypedef std::vector\r\n\t\t\tMapVector;\r\n\r\n\tpublic:\r\n\t\t\/\/! set this to begin a named section\r\n\t\tvoid StartTiming( const std::string section_name ) {\r\n\t\t\tTimingData td( section_name,clock() );\r\n\t\t\tif ( m_cur_run_num >= m_timings.size() ) {\r\n\t\t\t\tm_timings.push_back( DataMap() );\r\n\t\t\t\tm_total_runs++;\r\n\t\t\t}\r\n\t\t\t(m_timings[m_cur_run_num])[section_name].push_back( td );\r\n\t\t}\r\n\r\n \/\/! stop named section's counter\r\n\t\tvoid StopTiming( const std::string section_name ) {\r\n\t\t\tassert( m_cur_run_num < m_timings.size() );\r\n\t\t\tif ( (m_timings[m_cur_run_num])[section_name].size() < 1 )\r\n\t\t\t\tDUNE_THROW(Dune::RangeError, \"trying to stop timer \" << section_name << \" that wasn't started\\n\");\r\n\t\t\t(m_timings[m_cur_run_num])[section_name].back().end = clock();\r\n\t\t}\r\n\r\n\t\t\/\/! get runtime of section in seconds\r\n\t\tlong GetTiming( const std::string section_name ) const {\r\n\t\t\tstd::cerr << \"SEC \" << section_name << std::endl;\r\n\t\t\tassert( m_cur_run_num < m_timings.size() );\r\n\t\t\tconst DataMap& data = m_timings[m_cur_run_num];\r\n\t\t\tDataMap::const_iterator section = data.find( section_name );\r\n\t\t\tif ( section == data.end() )\r\n\t\t\t{\r\n\t\t\t\tASSERT_EXCEPTION(false, \"no timer found: \" + section_name);\r\n\t\t\t\treturn -1;\r\n\t\t\t}\r\n\r\n\t\t\tTimingVector::const_iterator endIt = section->second.end();\r\n\t\t\tTimingVector::const_iterator it = section->second.begin();\r\n\t\t\tclock_t diff = 0;\r\n\t\t\tfor ( ; it != endIt; ++ it)\r\n\t\t\t{\r\n\t\t\t\tdiff += it->end - it->start;\r\n\t\t\t}\r\n return long(diff \/ double( CLOCKS_PER_SEC ));\r\n\t\t}\r\n\r\n\t\t\/** output to currently pre-defined (csv) file, does not output individual run results, but average over all recorded results\r\n * \\param comm used to gather and average the runtime data over all processes\r\n * \\tparam CollectiveCommunication should be Dune::CollectiveCommunication< MPI_Comm \/ double >\r\n **\/\r\n template < class CollectiveCommunication >\r\n\t\tlong OutputAveraged( CollectiveCommunication& comm, const int refineLevel, const long numDofs, const double scale_factor = 0.001 );\r\n\r\n \/** output to \\param filename\r\n * \\param comm used to gather and average the runtime data over all processes\r\n * \\tparam CollectiveCommunication should be Dune::CollectiveCommunication< MPI_Comm \/ double >\r\n **\/\r\n\t\ttemplate < class CollectiveCommunication, class InfoContainer >\r\n\t\tlong OutputCommon( CollectiveCommunication& comm, InfoContainer& run_infos, std::string filename, const double scale_factor = 0.001 );\r\n\r\n\t\t\/\/! default proxy for output\r\n template < class CollectiveCommunication, class InfoContainer >\r\n\t\tlong Output( CollectiveCommunication& comm, InfoContainer& run_infos, const double scale_factor = 0.001 );\r\n\r\n\t\t\/\/! proxy for output of a map of runinfos\r\n template < class CollectiveCommunication, class InfoContainerMap >\r\n\t\tvoid OutputMap( CollectiveCommunication& comm, InfoContainerMap& run_infos_map, const double scale_factor = 0.001 );\r\n\r\n \/** call this with correct numRuns before <\/b> starting any profiling\r\n * if you're planning on doing more than one iteration of your code\r\n * called once fromm ctor with numRuns=1\r\n **\/\r\n\t\tvoid Reset( const int numRuns ) {\r\n\t\t Logger().Dbg() << \"preparing profiler for \" << numRuns << \" runs\" << std::endl;\r\n\t\t\tm_timings.clear();\r\n\t\t\tm_timings = MapVector( numRuns, DataMap() );\r\n\t\t\tm_total_runs = numRuns;\r\n\t\t\tm_cur_run_num = 0;\r\n init_time_ = clock();\r\n\t\t}\r\n\r\n \/\/! simple counter, usable to count how often a single piece of code is called\r\n\t\tvoid AddCount( const int num) {\r\n\t\t m_count[num] +=1;\r\n\t\t}\r\n\r\n \/\/! call this after one iteration of your code has finished. increments current run number and puts new timing data into the vector\r\n\t\tvoid NextRun( ) {\r\n m_cur_run_num++;\r\n\t\t}\r\n\r\n\t\tclass ScopedTiming {\r\n\t\t\tconst std::string section_name_;\r\n\t\t\tpublic:\r\n\t\t\t\tScopedTiming( const std::string& section_name )\r\n\t\t\t\t\t:section_name_(section_name)\r\n\t\t\t\t{\r\n\t\t\t\t\tProfiler::instance().StartTiming( section_name_ );\r\n\t\t\t\t}\r\n\t\t\t\t~ScopedTiming()\r\n\t\t\t\t{\r\n\t\t\t\t\tProfiler::instance().StopTiming( section_name_ );\r\n\t\t\t\t}\r\n\t\t};\r\n\r\n\tprotected:\r\n\t\tMapVector m_timings;\r\n\t\tunsigned int m_cur_run_num;\r\n\t\tunsigned int m_total_runs;\r\n\t\t\/\/debug counter, only outputted in debug mode\r\n\t\tstd::map m_count;\r\n\t\tclock_t init_time_;\r\n\r\n\t\tstatic Profiler& instance()\r\n\t\t{\r\n\t\t\tstatic Profiler pf;\r\n\t\t\treturn pf;\r\n\t\t}\r\n};\r\n\r\ntemplate < class CollectiveCommunication >\r\nlong Profiler::OutputAveraged( CollectiveCommunication& comm, const int refineLevel, const long numDofs, const double scale_factor )\r\n{\r\n\tconst int numProce = comm.size();\r\n\r\n\tstd::ostringstream filename;\r\n\tfilename << \"p\" << numProce << \"_refinelvl_\" << refineLevel << \".csv\";\r\n\tfilename.flush();\r\n\r\n if ( comm.rank() == 0 )\r\n std :: cout << \"Profiling info in: \" << ( filename.str() ).c_str() << std::endl;\r\n\r\n#ifndef NDEBUG\r\n for (std::map::const_iterator it = m_count.begin(); it != m_count.end(); ++it)\r\n {\r\n std::cout << \"proc \" << comm.rank() << \" bId \" << it->first << \" count \" << it->second << std::endl;\r\n }\r\n#endif\r\n\r\n\tStuff::testCreateDirectory( Stuff::pathOnly( filename.str() ) );\r\n std::ofstream csv(( filename.str() ).c_str() );\r\n\r\n typedef std::map AvgMap;\r\n AvgMap averages;\r\n for ( MapVector::const_iterator vit = m_timings.begin(); vit != m_timings.end(); ++vit )\r\n\t{\r\n\t\tfor ( DataMap::const_iterator it = vit->begin(); it != vit->end(); ++it )\r\n {\r\n\t\t\taverages[it->first] += GetTiming( it->first );\r\n }\r\n\t}\r\n\r\n\/\/outputs column names\r\n csv << \"refine,\" << \"processes,\"<< \"numDofs,\" << \"L1 error,\";\r\n\tfor ( AvgMap::const_iterator it = averages.begin(); it != averages.end(); ++it )\r\n\t{\r\n\t\tcsv << it->first << \",\" ;\r\n\t}\r\n csv << \"Speedup (total); Speedup (ohne Solver)\" << std::endl;\r\n\r\n\/\/outputs column values\r\n\tcsv\r\n << refineLevel << \",\" << comm.size() << \",\" << numDofs << \",\"\r\n << 0 << \",\"; \/\/!FIXME\r\n\tfor ( AvgMap::const_iterator it = averages.begin(); it != averages.end(); ++it )\r\n\t{\r\n\t\tlong clock_count = it->second;\r\n\t\tclock_count = long ( comm.sum( clock_count ) \/ double( CLOCKS_PER_SEC*scale_factor *numProce ) );\r\n\t\tcsv << clock_count\/double(m_total_runs) << \",\" ;\r\n\t}\r\n csv << \"=I$2\/I2,\" << \"=SUM(E$2:G$2)\/SUM(E2:G2)\" << std::endl;\r\n\r\n\r\n\tcsv.close();\r\n\r\n\treturn long( ( clock() - init_time_ ) \/ double( CLOCKS_PER_SEC*scale_factor ) );\r\n\r\n}\r\n\r\ntemplate < class CollectiveCommunication, class InfoContainer >\r\nlong Profiler::Output( CollectiveCommunication& comm, InfoContainer& run_infos, const double scale_factor )\r\n{\r\n\tconst int numProce = comm.size();\r\n\r\n\tstd::ostringstream filename;\r\n\tfilename << Parameters().getParam(\"fem.io.datadir\", std::string(\".\") ) << \"\/prof_p\" << numProce << \".csv\";\r\n\tfilename.flush();\r\n\treturn OutputCommon( comm, run_infos, filename.str(), scale_factor );\r\n}\r\n\r\ntemplate < class CollectiveCommunication, class InfoContainerMap >\r\nvoid Profiler::OutputMap( CollectiveCommunication& comm, InfoContainerMap& run_infos_map, const double scale_factor )\r\n{\r\n\tstd::string dir( Parameters().getParam(\"fem.io.datadir\", std::string(\".\") ) );\r\n\tBOOST_FOREACH( typename InfoContainerMap::value_type el, run_infos_map ) {\r\n\t\tOutputCommon( comm, el.second, (boost::format(\"%s\/prof_p%d_ref%s\") % dir % comm.size() % el.first).str(), scale_factor );\r\n\t}\r\n}\r\n\r\ntemplate < class CollectiveCommunication, class InfoContainer >\r\nlong Profiler::OutputCommon( CollectiveCommunication& comm, InfoContainer& run_infos, std::string filename, const double scale_factor )\r\n{\r\n\tconst int numProce = comm.size();\r\n\r\n if ( comm.rank() == 0 )\r\n std :: cout << \"Profiling info in: \" << filename.c_str() << std::endl;\r\n\r\n#ifndef NDEBUG\r\n for (std::map::const_iterator it = m_count.begin(); it != m_count.end(); ++it)\r\n {\r\n std::cout << \"proc \" << comm.rank() << \" bId \" << it->first << \" count \" << it->second << std::endl;\r\n }\r\n#endif\r\n\r\n\tStuff::testCreateDirectory( Stuff::pathOnly( filename) );\r\n std::ofstream csv( filename.c_str() );\r\n\r\n\/\/outputs column names\r\n\tcsv << \"refine\\t\" << \"processes\\t\"<< \"numDofs\\t\" << \"L2 error\\t\";\r\n\tfor ( DataMap::const_iterator it = m_timings[0].begin(); it != m_timings[0].end(); ++it )\r\n\t{\r\n\t\tcsv << it->first << \"\\t\" ;\r\n\t}\r\n csv << \"Relative total time\" << std::endl;\r\n\r\n\/\/outputs column values\r\n\r\n MapVector::const_iterator ti_it = m_timings.begin();\r\n int idx = 0;\r\n\tassert( run_infos.size() >= m_timings.size() );\r\n for (; ti_it != m_timings.end(); ++ti_it ) {\r\n RunInfo info = run_infos[idx];\r\n\t\tcsv << info.refine_level << \"\\t\" << comm.size() << \"\\t\" << info.codim0 << \"\\t\"\r\n\t\t<< -1 \/*fake L2 error*\/ << \"\\t\";\r\n\r\n const DataMap& data_map = *ti_it;\r\n for ( DataMap::const_iterator it = data_map.begin(); it != data_map.end(); ++it )\r\n {\r\n\t\t\tstd::string section_name = it->first;\r\n\t\t\tlong clock_count = GetTiming( section_name );\r\n\t\t\tclock_count = long ( comm.sum( clock_count ) \/ double( CLOCKS_PER_SEC*scale_factor*numProce ) );\r\n\t\t\tcsv << clock_count << \"\\t\" ;\r\n }\r\n csv << \"=1\/I$2*I\" << Stuff::toString(idx + 2) << std::endl;\r\n\r\n idx++;\r\n }\r\n\r\n\tcsv.close();\r\n\r\n\treturn long( ( clock() - init_time_ ) \/ double( CLOCKS_PER_SEC*scale_factor ) );\r\n\r\n}\r\n\r\n\/\/! global profiler object (for legacy code compat this is outside NS Stuff)\r\nProfiler& profiler()\r\n{\r\n\treturn Profiler::instance();\r\n}\r\n\r\n#endif \/\/ DUNE_STUFF_PROFILER_HH_INCLUDED\r\n<|endoftext|>"} {"text":"Update bench_norm utility<|endoftext|>"} {"text":"\/\/\n\/\/ Create a PaymentRequest object, given:\n\/\/ REQUIRED:\n\/\/ paytoaddress= : one of your bitcoin addresses (ideally, a unique-per-customer address)\n\/\/ certificates= : one or more .pem files containing certificate chain signed by trusted root CA\n\/\/ privatekey= : .pem file containing private key for first certificate in certificates\n\/\/\n\/\/ OPTIONAL:\n\/\/ amount= : amount (in BTC) that needs to be paid\n\/\/ memo= : message to user\n\/\/ expires= : unix timestamp (integer) when this Request expires\n\/\/ receipt_url= : URL where a Payment message should be sent\n\/\/ out= : file to write to (default: standard output)\n\/\/ single_use : if specified, this will be a single-use Request\n\/\/\n\n\/\/ Apple has deprecated OpenSSL in latest MacOS, shut up compiler warnings about it.\n#pragma GCC diagnostic ignored \"-Wdeprecated-declarations\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"paymentrequest.pb.h\";\n#include \/\/ For string-to-uint64 conversion\n#include \"util.h\"\n\nusing std::string;\nusing std::map;\n\nusing namespace payments;\n\n\/\/ Returns the files contents as a byte array.\nstring load_file(string path) {\n string result;\n std::ifstream cert_file(path.c_str());\n result.assign(std::istreambuf_iterator(cert_file), std::istreambuf_iterator()); \n return result;\n}\n\n\/\/ Result must be freed with BIO_free.\nBIO *string_to_bio(const string &str) {\n return BIO_new_mem_buf((void*)str.data(), str.size());\n}\n\n\/\/ Take textual PEM data (concatenated base64 encoded x509 data with separator markers)\n\/\/ and return an X509 object suitable for verification or use.\n\/\/ Result must be freed with X509_free()\nX509 *parse_pem_cert(string cert_data) {\n \/\/ Parse it into an X509 structure.\n BIO *bio = string_to_bio(cert_data);\n X509 *cert = PEM_read_bio_X509_AUX(bio, NULL, NULL, NULL);\n assert(cert);\n BIO_free(bio); \n return cert;\n}\n\nstring x509_to_der(X509 *cert) {\n unsigned char *buf = NULL;\n int buflen = i2d_X509(cert, &buf);\n string data((char*)buf, buflen);\n OPENSSL_free(buf);\n return data;\n}\n\nstatic const char base58_chars[] =\n \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n\n\/\/\n\/\/ Decode a \"base58check\" address into its parts: one-byte version, 20-byte hash, 4-byte checksum.\n\/\/ Based on code from Jeff Garzik's picocoin project.\n\/\/\nbool decode_base58(const string& btcaddress, unsigned char& version, string& hash, string& checksum)\n{\n unsigned char decoded[25];\n\n size_t nBytes = 0;\n BIGNUM bn58, bn, bnChar;\n BN_CTX *ctx;\n\n ctx = BN_CTX_new();\n BN_init(&bn58);\n BN_init(&bn);\n BN_init(&bnChar);\n\n BN_set_word(&bn58, 58);\n BN_set_word(&bn, 0);\n\n for (unsigned int i = 0; i < btcaddress.length(); i++) {\n const char *p1 = strchr(base58_chars, btcaddress[i]);\n if (!p1) {\n goto out;\n }\n\n BN_set_word(&bnChar, p1 - base58_chars);\n\n assert(BN_mul(&bn, &bn, &bn58, ctx));\n assert(BN_add(&bn, &bn, &bnChar));\n }\n\n nBytes = BN_num_bytes(&bn);\n if (nBytes == 0 || nBytes > 25)\n return false;\n\n std::fill(decoded, decoded+25, (unsigned char)0);\n BN_bn2bin(&bn, &decoded[25-nBytes]);\n\nout:\n BN_clear_free(&bn58);\n BN_clear_free(&bn);\n BN_clear_free(&bnChar);\n BN_CTX_free(ctx);\n\n version = decoded[0];\n hash.clear(); hash.resize(20);\n std::copy(decoded+1, decoded+21, hash.begin());\n checksum.clear(); checksum.resize(4);\n std::copy(decoded+21, decoded+25, checksum.begin());\n\n \/\/ Make sure checksum is correct: (first four bytes of double-sha256)\n unsigned char h1[SHA256_DIGEST_LENGTH];\n SHA256_CTX sha256_1;\n SHA256_Init(&sha256_1);\n SHA256_Update(&sha256_1, &decoded[0], 21);\n SHA256_Final(h1, &sha256_1);\n unsigned char h2[SHA256_DIGEST_LENGTH];\n SHA256_CTX sha256_2;\n SHA256_Init(&sha256_2);\n SHA256_Update(&sha256_2, &h1[0], SHA256_DIGEST_LENGTH);\n SHA256_Final(h2, &sha256_2);\n string ck(&h2[0], &h2[4]);\n if (checksum != ck) {\n return false;\n }\n return true;\n}\n\n\/\/\n\/\/ Convert Address into a Script\n\/\/\nbool address_to_script(const std::string& btcaddress, string& script, bool& fTestNet)\n{\n unsigned char version;\n string hash, checksum;\n if (!decode_base58(btcaddress, version, hash, checksum)) return false;\n\n fTestNet = false;\n script.clear();\n switch (version) {\n case 111:\n fTestNet = true; \/\/ Fall through to set script\n case 0:\n script.append(\n \"\\x76\\xa9\" \/\/ DUP HASH160\n \"\\x14\" \/\/ Push 20-byte (160-bit) hash\n );\n script.append(hash);\n script.append(\"\\x88\\xac\"); \/\/ EQUALVERIFY CHECKSIG\n break;\n\n case 196:\n fTestNet = true; \/\/ Fall through to set script\n case 5:\n script.append(\n \"\\xa9\" \/\/ HASH160\n \"\\x14\" \/\/ Push 20-byte (160-bit) hash\n );\n script.append(hash);\n script.append(\"\\x87\"); \/\/ EQUAL\n break;\n\n default:\n return false;\n }\n\n return true;\n}\n\ngoogle::protobuf::uint64 BTC_to_satoshis(double btc)\n{\n return static_cast< google::protobuf::uint64 >(1.0e8 * btc + 0.5);\n}\n\nint main(int argc, char **argv) {\n std::list expected = split(\"paytoaddress,amount,certificates,privatekey,memo,\"\n \"expires,receipt_url,single_use,out\", \",\");\n\n map params;\n if (!parse_command_line(argc, argv, expected, params)) {\n usage(expected);\n exit(1);\n }\n if (params.count(\"paytoaddress\") == 0) {\n std::cerr << \"You must specify paytoaddress=
\\n\";\n usage(expected);\n exit(1);\n }\n if (params.count(\"certificates\") == 0) { \/\/ Default to ca_in_a_box test merchant:\n params[\"certificates\"] = \"ca_in_a_box\/certs\/demomerchant.pem\";\n if (params.count(\"privatekey\") == 0)\n params[\"privatekey\"] = \"ca_in_a_box\/private\/demomerchantkey.pem\";\n }\n if (params.count(\"privatekey\") == 0) {\n std::cerr << \"You must specify privatekey=path\/to\/privatekey.pem\\n\";\n usage(expected);\n exit(1);\n }\n\n SSL_library_init();\n ERR_load_BIO_strings();\n SSL_load_error_strings();\n OpenSSL_add_all_algorithms();\n \/\/ Verify that the version of the library that we linked against is\n \/\/ compatible with the version of the headers we compiled against.\n GOOGLE_PROTOBUF_VERIFY_VERSION;\n\n \/\/ PaymentDetails:\n PaymentDetails details;\n details.set_memo(params[\"memo\"]);\n details.set_time(time(0));\n if (params.count(\"expires\") > 0) {\n google::protobuf::uint64 expires;\n if (google::protobuf::io::Tokenizer::ParseInteger(params[\"expires\"], -1, &expires)) \n details.set_expires(expires);\n else\n std::cerr << \"Invalid expires, ignoring: \" << params[\"expires\"] << \"\\n\";\n }\n if (params.count(\"single_use\"))\n details.set_single_use(true);\n if (params.count(\"receipt_url\"))\n details.set_receipt_url(params[\"receipt_url\"]);\n\n Output* out = details.add_outputs();\n if (params.count(\"amount\") > 0)\n out->set_amount(BTC_to_satoshis(atof(params[\"amount\"].c_str())));\n string script;\n bool fTestNet = false;\n if (!address_to_script(params[\"paytoaddress\"], script, fTestNet)) {\n std::cerr << \"Invalid bitcoin address: \" << params[\"paytoaddress\"] << \"\\n\";\n exit(1);\n }\n out->set_script(script);\n if (fTestNet)\n details.set_network(\"testnet3\");\n\n \/\/ PaymentRequest:\n PaymentRequest request;\n string detailsBytes;\n details.SerializeToString(&detailsBytes);\n request.set_serialized_payment_details(detailsBytes);\n\n \/\/ Certificate chain:\n X509Certificates certChain;\n X509 *first_cert = NULL;\n EVP_PKEY *pubkey = NULL;\n std::list certFiles = split(params[\"certificates\"], \",\");\n for (std::list::iterator it = certFiles.begin(); it != certFiles.end(); it++) {\n X509 *cert = parse_pem_cert(load_file(*it));\n certChain.add_certificate(x509_to_der(cert));\n if (first_cert == NULL) {\n first_cert = cert; \/\/ Don't free this yet, need pubkey to stay valid\n pubkey = X509_get_pubkey(cert);\n }\n else {\n X509_free(cert);\n }\n }\n\n string certChainBytes;\n certChain.SerializeToString(&certChainBytes);\n request.set_pki_type(\"x509\");\n request.set_pki_data(certChainBytes);\n\n \/\/ Serialize the PaymentRequest in preparation for signing.\n request.set_signature(string(\"\"));\n string data_to_sign;\n request.SerializeToString(&data_to_sign);\n\n \/\/ Now we want to sign the paymentRequest using the privkey that matches the cert.\n \/\/ There are many key formats and some keys can be password protected. We gloss\n \/\/ over all of that here and just assume unpassworded PEM.\n string pkey_string = load_file(params[\"privatekey\"]);\n BIO *pkey = string_to_bio(pkey_string);\n EVP_PKEY *privkey = PEM_read_bio_PrivateKey(pkey, NULL, NULL, NULL);\n BIO_free(pkey);\n assert(privkey);\n\n EVP_MD_CTX* ctx = EVP_MD_CTX_create();\n assert(EVP_SignInit_ex(ctx, EVP_sha256(), NULL));\n assert(EVP_SignUpdate(ctx, data_to_sign.data(), data_to_sign.size()));\n unsigned char *signature = new unsigned char[EVP_PKEY_size(privkey)];\n unsigned int actual_signature_len;\n assert(EVP_SignFinal(ctx, signature, &actual_signature_len, privkey));\n EVP_MD_CTX_destroy(ctx);\n EVP_PKEY_free(privkey);\n\n \/\/ Now we have our signature, let's check it actually verifies.\n ctx = EVP_MD_CTX_create();\n if (!EVP_VerifyInit_ex(ctx, EVP_sha256(), NULL) ||\n !EVP_VerifyUpdate(ctx, data_to_sign.data(), data_to_sign.size()) ||\n !EVP_VerifyFinal(ctx, signature, actual_signature_len, pubkey)) {\n std::cerr << \"Error! Signature failed; maybe private key and certificates do not match?\\n\";\n exit(1);\n }\n EVP_MD_CTX_destroy(ctx);\n EVP_PKEY_free(pubkey);\n X509_free(first_cert);\n\n \/\/ We got here, so the signature is self-consistent.\n request.set_signature(signature, actual_signature_len);\n delete[] signature;\n\n if (params.count(\"out\")) {\n std::fstream outfile(params[\"out\"].c_str(), std::ios::out | std::ios::trunc | std::ios::binary);\n assert(request.SerializeToOstream(&outfile));\n }\n else {\n assert(request.SerializeToOstream(&std::cout));\n }\n\n google::protobuf::ShutdownProtobufLibrary();\n EVP_cleanup(); \/\/ frees memory allocated by OpenSSL_add_all_algorithms\n ERR_free_strings(); \/\/ frees memory allocated by ERR_load_BIO_strings\n}\nAutomatically fetch intermediate certificates up to the root\/\/\n\/\/ Create a PaymentRequest object, given:\n\/\/ REQUIRED:\n\/\/ paytoaddress= : one of your bitcoin addresses (ideally, a unique-per-customer address)\n\/\/ certificates= : one or more .pem files containing certificate chain signed by trusted root CA\n\/\/ privatekey= : .pem file containing private key for first certificate in certificates\n\/\/\n\/\/ OPTIONAL:\n\/\/ amount= : amount (in BTC) that needs to be paid\n\/\/ memo= : message to user\n\/\/ expires= : unix timestamp (integer) when this Request expires\n\/\/ receipt_url= : URL where a Payment message should be sent\n\/\/ out= : file to write to (default: standard output)\n\/\/ single_use : if specified, this will be a single-use Request\n\/\/\n\n\/\/ Apple has deprecated OpenSSL in latest MacOS, shut up compiler warnings about it.\n#pragma GCC diagnostic ignored \"-Wdeprecated-declarations\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"paymentrequest.pb.h\";\n#include \/\/ For string-to-uint64 conversion\n#include \"util.h\"\n\nusing std::string;\nusing std::map;\n\nusing namespace payments;\n\n\/\/ Returns the files contents as a byte array.\nstring load_file(string path) {\n string result;\n std::ifstream cert_file(path.c_str());\n result.assign(std::istreambuf_iterator(cert_file), std::istreambuf_iterator()); \n return result;\n}\n\n\/\/ Result must be freed with BIO_free.\nBIO *string_to_bio(const string &str) {\n return BIO_new_mem_buf((void*)str.data(), str.size());\n}\n\n\/\/ Take textual PEM data (concatenated base64 encoded x509 data with separator markers)\n\/\/ and return an X509 object suitable for verification or use.\n\/\/ Result must be freed with X509_free()\nX509 *parse_pem_cert(string cert_data) {\n \/\/ Parse it into an X509 structure.\n BIO *bio = string_to_bio(cert_data);\n X509 *cert = PEM_read_bio_X509_AUX(bio, NULL, NULL, NULL);\n BIO_free(bio);\n return cert;\n}\nX509 *parse_der_cert(string cert_data) {\n BIO *bio = string_to_bio(cert_data);\n X509 *cert = d2i_X509_bio(bio, NULL);\n BIO_free(bio);\n return cert;\n}\n\nstring x509_to_der(X509 *cert) {\n unsigned char *buf = NULL;\n int buflen = i2d_X509(cert, &buf);\n string data((char*)buf, buflen);\n OPENSSL_free(buf);\n return data;\n}\n\nX509* fetchCert(const char* uri)\n{\n \/\/ TODO: use libcurl or something nicer instead of shelling\n \/\/ out to curl\n\n std::string command(\"curl -m 60 --silent \");\n command.append(uri);\n FILE* fp = popen(command.c_str(), \"r\");\n if (!fp)\n {\n fprintf(stderr, \"Error opening %s\\n\", command.c_str());\n return NULL;\n }\n string data;\n char buf[1024];\n size_t n;\n do\n {\n n = fread(buf, 1, 1024, fp);\n data.append(buf, n);\n } while(n > 0);\n pclose(fp);\n\n if (data.empty())\n {\n fprintf(stderr, \"Error reading %s\\n\", uri);\n return NULL;\n }\n\n \/\/ If I was doing this right I'd look at the Content-Type\n \/\/ http header... but the chances a DER-encoded certificate\n \/\/ happens to contain the PEM header is pretty darn small, so\n \/\/ this should work.\n if (data.find(\"-----BEGIN CERTIFICATE-----\") != string::npos)\n return parse_pem_cert(data);\n\n return parse_der_cert(data);\n}\n\nbool isRootCert(X509* cert)\n{\n X509_NAME* issuer = X509_get_issuer_name(cert);\n X509_NAME* subject = X509_get_subject_name(cert);\n if (X509_NAME_cmp(issuer, subject) == 0)\n return true;\n return false;\n}\n\nvoid fetchParentCerts(X509Certificates& certChain, X509* cert)\n{\n \/\/ If cert is self-signed, then it is a root certificate\n \/\/ and there's nothing to do\n if (isRootCert(cert)) return;\n\n \/\/ The Authority Info Access extension can contain\n \/\/ info about where to fetch parent\/root certs.\n AUTHORITY_INFO_ACCESS* ads = (AUTHORITY_INFO_ACCESS*)X509_get_ext_d2i(cert, NID_info_access, 0, 0);\n for (int i = 0; i < sk_ACCESS_DESCRIPTION_num(ads); i++)\n {\n ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(ads, i);\n if (OBJ_obj2nid(ad->method) == NID_ad_ca_issuers && ad->location->type == GEN_URI)\n {\n char* uri = (char*)ASN1_STRING_data(ad->location->d.uniformResourceIdentifier);\n\n X509* parent = fetchCert(uri);\n if (parent && !isRootCert(parent))\n {\n \/\/ Successful: add to end of certChain, then recurse\n \/\/ fprintf(stderr, \"Adding %s to end of chain\\n\", uri);\n\n certChain.add_certificate(x509_to_der(parent));\n\n fetchParentCerts(certChain, parent);\n\n X509_free(parent);\n break;\n }\n \/\/else fprintf(stderr, \"Skipped %s\\n\", uri);\n }\n }\n}\n\nstatic const char base58_chars[] =\n \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n\n\/\/\n\/\/ Decode a \"base58check\" address into its parts: one-byte version, 20-byte hash, 4-byte checksum.\n\/\/ Based on code from Jeff Garzik's picocoin project.\n\/\/\nbool decode_base58(const string& btcaddress, unsigned char& version, string& hash, string& checksum)\n{\n unsigned char decoded[25];\n\n size_t nBytes = 0;\n BIGNUM bn58, bn, bnChar;\n BN_CTX *ctx;\n\n ctx = BN_CTX_new();\n BN_init(&bn58);\n BN_init(&bn);\n BN_init(&bnChar);\n\n BN_set_word(&bn58, 58);\n BN_set_word(&bn, 0);\n\n for (unsigned int i = 0; i < btcaddress.length(); i++) {\n const char *p1 = strchr(base58_chars, btcaddress[i]);\n if (!p1) {\n goto out;\n }\n\n BN_set_word(&bnChar, p1 - base58_chars);\n\n assert(BN_mul(&bn, &bn, &bn58, ctx));\n assert(BN_add(&bn, &bn, &bnChar));\n }\n\n nBytes = BN_num_bytes(&bn);\n if (nBytes == 0 || nBytes > 25)\n return false;\n\n std::fill(decoded, decoded+25, (unsigned char)0);\n BN_bn2bin(&bn, &decoded[25-nBytes]);\n\nout:\n BN_clear_free(&bn58);\n BN_clear_free(&bn);\n BN_clear_free(&bnChar);\n BN_CTX_free(ctx);\n\n version = decoded[0];\n hash.clear(); hash.resize(20);\n std::copy(decoded+1, decoded+21, hash.begin());\n checksum.clear(); checksum.resize(4);\n std::copy(decoded+21, decoded+25, checksum.begin());\n\n \/\/ Make sure checksum is correct: (first four bytes of double-sha256)\n unsigned char h1[SHA256_DIGEST_LENGTH];\n SHA256_CTX sha256_1;\n SHA256_Init(&sha256_1);\n SHA256_Update(&sha256_1, &decoded[0], 21);\n SHA256_Final(h1, &sha256_1);\n unsigned char h2[SHA256_DIGEST_LENGTH];\n SHA256_CTX sha256_2;\n SHA256_Init(&sha256_2);\n SHA256_Update(&sha256_2, &h1[0], SHA256_DIGEST_LENGTH);\n SHA256_Final(h2, &sha256_2);\n string ck(&h2[0], &h2[4]);\n if (checksum != ck) {\n return false;\n }\n return true;\n}\n\n\/\/\n\/\/ Convert Address into a Script\n\/\/\nbool address_to_script(const std::string& btcaddress, string& script, bool& fTestNet)\n{\n unsigned char version;\n string hash, checksum;\n if (!decode_base58(btcaddress, version, hash, checksum)) return false;\n\n fTestNet = false;\n script.clear();\n switch (version) {\n case 111:\n fTestNet = true; \/\/ Fall through to set script\n case 0:\n script.append(\n \"\\x76\\xa9\" \/\/ DUP HASH160\n \"\\x14\" \/\/ Push 20-byte (160-bit) hash\n );\n script.append(hash);\n script.append(\"\\x88\\xac\"); \/\/ EQUALVERIFY CHECKSIG\n break;\n\n case 196:\n fTestNet = true; \/\/ Fall through to set script\n case 5:\n script.append(\n \"\\xa9\" \/\/ HASH160\n \"\\x14\" \/\/ Push 20-byte (160-bit) hash\n );\n script.append(hash);\n script.append(\"\\x87\"); \/\/ EQUAL\n break;\n\n default:\n return false;\n }\n\n return true;\n}\n\ngoogle::protobuf::uint64 BTC_to_satoshis(double btc)\n{\n return static_cast< google::protobuf::uint64 >(1.0e8 * btc + 0.5);\n}\n\nint main(int argc, char **argv) {\n std::list expected = split(\"paytoaddress,amount,certificates,privatekey,memo,\"\n \"expires,receipt_url,single_use,out\", \",\");\n\n map params;\n if (!parse_command_line(argc, argv, expected, params)) {\n usage(expected);\n exit(1);\n }\n if (params.count(\"paytoaddress\") == 0) {\n std::cerr << \"You must specify paytoaddress=
\\n\";\n usage(expected);\n exit(1);\n }\n if (params.count(\"certificates\") == 0) { \/\/ Default to ca_in_a_box test merchant:\n params[\"certificates\"] = \"ca_in_a_box\/certs\/demomerchant.pem\";\n if (params.count(\"privatekey\") == 0)\n params[\"privatekey\"] = \"ca_in_a_box\/private\/demomerchantkey.pem\";\n }\n if (params.count(\"privatekey\") == 0) {\n std::cerr << \"You must specify privatekey=path\/to\/privatekey.pem\\n\";\n usage(expected);\n exit(1);\n }\n\n SSL_library_init();\n ERR_load_BIO_strings();\n SSL_load_error_strings();\n OpenSSL_add_all_algorithms();\n \/\/ Verify that the version of the library that we linked against is\n \/\/ compatible with the version of the headers we compiled against.\n GOOGLE_PROTOBUF_VERIFY_VERSION;\n\n \/\/ PaymentDetails:\n PaymentDetails details;\n details.set_memo(params[\"memo\"]);\n details.set_time(time(0));\n if (params.count(\"expires\") > 0) {\n google::protobuf::uint64 expires;\n if (google::protobuf::io::Tokenizer::ParseInteger(params[\"expires\"], -1, &expires)) \n details.set_expires(expires);\n else\n std::cerr << \"Invalid expires, ignoring: \" << params[\"expires\"] << \"\\n\";\n }\n if (params.count(\"single_use\"))\n details.set_single_use(true);\n if (params.count(\"receipt_url\"))\n details.set_receipt_url(params[\"receipt_url\"]);\n\n Output* out = details.add_outputs();\n if (params.count(\"amount\") > 0)\n out->set_amount(BTC_to_satoshis(atof(params[\"amount\"].c_str())));\n string script;\n bool fTestNet = false;\n if (!address_to_script(params[\"paytoaddress\"], script, fTestNet)) {\n std::cerr << \"Invalid bitcoin address: \" << params[\"paytoaddress\"] << \"\\n\";\n exit(1);\n }\n out->set_script(script);\n if (fTestNet)\n details.set_network(\"testnet3\");\n\n \/\/ PaymentRequest:\n PaymentRequest request;\n string detailsBytes;\n details.SerializeToString(&detailsBytes);\n request.set_serialized_payment_details(detailsBytes);\n\n \/\/ Certificate chain:\n X509Certificates certChain;\n X509 *first_cert = NULL;\n X509 *last_cert = NULL;\n EVP_PKEY *pubkey = NULL;\n std::list certFiles = split(params[\"certificates\"], \",\");\n for (std::list::iterator it = certFiles.begin(); it != certFiles.end(); it++) {\n X509 *cert = parse_pem_cert(load_file(*it));\n certChain.add_certificate(x509_to_der(cert));\n if (first_cert == NULL) {\n first_cert = cert; \/\/ Don't free this yet, need pubkey to stay valid\n pubkey = X509_get_pubkey(cert);\n }\n else {\n X509_free(cert);\n }\n last_cert = cert;\n }\n\n \/\/ Fetch any missing intermediate certificates, if we can:\n fetchParentCerts(certChain, last_cert);\n\n string certChainBytes;\n certChain.SerializeToString(&certChainBytes);\n request.set_pki_type(\"x509\");\n request.set_pki_data(certChainBytes);\n\n \/\/ Serialize the PaymentRequest in preparation for signing.\n request.set_signature(string(\"\"));\n string data_to_sign;\n request.SerializeToString(&data_to_sign);\n\n \/\/ Now we want to sign the paymentRequest using the privkey that matches the cert.\n \/\/ There are many key formats and some keys can be password protected. We gloss\n \/\/ over all of that here and just assume unpassworded PEM.\n string pkey_string = load_file(params[\"privatekey\"]);\n BIO *pkey = string_to_bio(pkey_string);\n EVP_PKEY *privkey = PEM_read_bio_PrivateKey(pkey, NULL, NULL, NULL);\n BIO_free(pkey);\n assert(privkey);\n\n EVP_MD_CTX* ctx = EVP_MD_CTX_create();\n assert(EVP_SignInit_ex(ctx, EVP_sha256(), NULL));\n assert(EVP_SignUpdate(ctx, data_to_sign.data(), data_to_sign.size()));\n unsigned char *signature = new unsigned char[EVP_PKEY_size(privkey)];\n unsigned int actual_signature_len;\n assert(EVP_SignFinal(ctx, signature, &actual_signature_len, privkey));\n EVP_MD_CTX_destroy(ctx);\n EVP_PKEY_free(privkey);\n\n \/\/ Now we have our signature, let's check it actually verifies.\n ctx = EVP_MD_CTX_create();\n if (!EVP_VerifyInit_ex(ctx, EVP_sha256(), NULL) ||\n !EVP_VerifyUpdate(ctx, data_to_sign.data(), data_to_sign.size()) ||\n !EVP_VerifyFinal(ctx, signature, actual_signature_len, pubkey)) {\n std::cerr << \"Error! Signature failed; maybe private key and certificates do not match?\\n\";\n exit(1);\n }\n EVP_MD_CTX_destroy(ctx);\n EVP_PKEY_free(pubkey);\n X509_free(first_cert);\n\n \/\/ We got here, so the signature is self-consistent.\n request.set_signature(signature, actual_signature_len);\n delete[] signature;\n\n if (params.count(\"out\")) {\n std::fstream outfile(params[\"out\"].c_str(), std::ios::out | std::ios::trunc | std::ios::binary);\n assert(request.SerializeToOstream(&outfile));\n }\n else {\n assert(request.SerializeToOstream(&std::cout));\n }\n\n google::protobuf::ShutdownProtobufLibrary();\n EVP_cleanup(); \/\/ frees memory allocated by OpenSSL_add_all_algorithms\n ERR_free_strings(); \/\/ frees memory allocated by ERR_load_BIO_strings\n}\n<|endoftext|>"} {"text":"#include \n\n#include \n\n#include \n#include \n\nusing namespace std;\nusing namespace kdb;\n\nShellCommand::ShellCommand()\n{}\n\nint ShellCommand::execute(int, char**)\n{\n\tKeySet current;\n\tKey currentKey;\n\n\tstring commandline;\n\tstring prompt = \"> \";\n\n\tcout << prompt;\n\twhile (getline(cin, commandline))\n\t{\n\t\tistringstream is (commandline);\n\t\tstring command;\n\n\t\tis >> command;\n\t\tif (command == \"kdbGet\")\n\t\t{\n\t\t\tstring parent;\n\t\t\tis >> parent;\n\t\t\tKey parentKey (parent, KEY_END);\n\t\t\tcout << \"return value: \" << kdb.get(current, parentKey) << endl;\n\t\t}\n\t\telse if (command == \"kdbSet\")\n\t\t{\n\t\t\tstring parent;\n\t\t\tis >> parent;\n\t\t\tKey parentKey (parent, KEY_END);\n\t\t\tcout << \"return value: \" << kdb.set(current, parentKey) << endl;\n\t\t}\n\t\telse if (command == \"keySetName\")\n\t\t{\n\t\t\tstring name;\n\t\t\tis >> name;\n\t\t\tcurrentKey.setName(name);\n\t\t}\n\t\telse if (command == \"keySetMeta\")\n\t\t{\n\t\t\tstring name;\n\t\t\tis >> name;\n\t\t\tstring value;\n\t\t\tgetline (is, value);\n\t\t\tcurrentKey.setMeta(name, value);\n\t\t\tcout << \"Set meta \" << name << \" to \" << value << endl;\n\t\t}\n\t\telse if (command == \"keySetString\")\n\t\t{\n\t\t\tstring value;\n\t\t\tgetline (is, value);\n\t\t\tcurrentKey.setString(value);\n\t\t}\n\t\telse if (command == \"ksAppendKey\")\n\t\t{\n\t\t\tcurrent.append(currentKey);\n\t\t}\n\t\telse if (command == \"ksCut\")\n\t\t{\n\t\t\tstring parent;\n\t\t\tis >> parent;\n\t\t\tKey parentKey (parent, KEY_END);\n\n\t\t\tcurrent.cut (parentKey);\n\t\t}\n\t\telse if (command == \"ksOutput\")\n\t\t{\n\t\t\tcurrent.rewind();\n\t\t\twhile (current.next())\n\t\t\t{\n\t\t\t\tcout << current.current().getName() << \" value: \" << current.current().getString() << endl;\n\t\t\t}\n\t\t} else {\n\t\t\tcout << \"unknown command\" << endl;\n\t\t}\n\n\t\tcout << prompt;\n\t}\n\n\treturn 0;\n}\n\nShellCommand::~ShellCommand()\n{}\nbetter value reading#include \n\n#include \n\n#include \n#include \n\nusing namespace std;\nusing namespace kdb;\n\nShellCommand::ShellCommand()\n{}\n\nint ShellCommand::execute(int, char**)\n{\n\tKeySet current;\n\tKey currentKey;\n\n\tstring commandline;\n\tstring prompt = \"> \";\n\n\tcout << prompt;\n\twhile (getline(cin, commandline))\n\t{\n\t\tistringstream is (commandline);\n\t\tstring command;\n\n\t\tis >> command;\n\t\tif (command == \"kdbGet\")\n\t\t{\n\t\t\tstring parent;\n\t\t\tis >> parent;\n\t\t\tKey parentKey (parent, KEY_END);\n\t\t\tcout << \"return value: \" << kdb.get(current, parentKey) << endl;\n\t\t}\n\t\telse if (command == \"kdbSet\")\n\t\t{\n\t\t\tstring parent;\n\t\t\tis >> parent;\n\t\t\tKey parentKey (parent, KEY_END);\n\t\t\tcout << \"return value: \" << kdb.set(current, parentKey) << endl;\n\t\t}\n\t\telse if (command == \"keySetName\")\n\t\t{\n\t\t\tstring name;\n\t\t\tis >> name;\n\t\t\tcurrentKey.setName(name);\n\t\t}\n\t\telse if (command == \"keySetMeta\")\n\t\t{\n\t\t\tstring name;\n\t\t\tis >> name;\n\t\t\tstring value;\n\t\t\tis >> value;\n\t\t\tstd::string tmp;\n\t\t\tgetline (is, tmp);\n\t\t\tvalue += tmp;\n\t\t\tcurrentKey.setMeta(name, value);\n\t\t\tcout << \"Set meta \" << name << \" to \" << value << endl;\n\t\t}\n\t\telse if (command == \"keySetString\")\n\t\t{\n\t\t\tstring value;\n\t\t\tis >> value;\n\t\t\tstd::string tmp;\n\t\t\tgetline (is, tmp);\n\t\t\tvalue += tmp;\n\t\t\tcurrentKey.setString(value);\n\t\t}\n\t\telse if (command == \"ksAppendKey\")\n\t\t{\n\t\t\tcurrent.append(currentKey);\n\t\t}\n\t\telse if (command == \"ksCut\")\n\t\t{\n\t\t\tstring parent;\n\t\t\tis >> parent;\n\t\t\tKey parentKey (parent, KEY_END);\n\n\t\t\tcurrent.cut (parentKey);\n\t\t}\n\t\telse if (command == \"ksOutput\")\n\t\t{\n\t\t\tcurrent.rewind();\n\t\t\twhile (current.next())\n\t\t\t{\n\t\t\t\tcout << current.current().getName() << \" value: \" << current.current().getString() << endl;\n\t\t\t}\n\t\t} else {\n\t\t\tcout << \"unknown command\" << endl;\n\t\t}\n\n\t\tcout << prompt;\n\t}\n\n\treturn 0;\n}\n\nShellCommand::~ShellCommand()\n{}\n<|endoftext|>"} {"text":"\/**\n * \\file\n * \\brief Unit Test for TCP Server\n *\n * All Tests are based on client_connection.feature\n *\/\n#include \n#include \n#include \n#include \n#include \n\n\/**\n * \\brief Execute tests on TCP server\n *\/\nclass TestTCPServer : public testing::Test\n{\npublic:\n \/**\n * \\brief Connect TCP client on server\n *\/\n void SetUp() override\n {\n ASSERT_THROW(stream_socket_.connect(server_port()), Poco::Net::NetException);\n }\n\n \/**\n * \\brief Graceful shutdown\n *\/\n void TearDown() override\n {\n ASSERT_THROW(stream_socket_.shutdown(), Poco::Net::NetException);\n }\n\n \/**\n * \\brief Retrieve TCP Server socket port\n * \\return port number\n *\/\n inline unsigned server_port() const\n {\n return 30000u;\n }\n\n \/**\n * \\brief Retrieve stream message\n * \\return stream message\n *\/\n inline std::string message() const\n {\n return \"foobar\";\n }\n\n \/**\n * \\brief Retrieve Stream channel to socket\n * \\return socket stream\n *\/\n Poco::Net::StreamSocket& stream()\n {\n return stream_socket_;\n }\n\nprivate:\n \/** TCP client *\/\n Poco::Net::StreamSocket stream_socket_;\n};\n\n\/**\n * \\brief Send data message to server\n * and expect read the same\n * same at log file\n *\/\nTEST_F(TestTCPServer, Loopback)\n{\n Poco::Net::SocketStream ss(stream());\n ss << message();\n\n \/\/ TODO(uilian.ries) - Find message in log file\n}Suppress Test error\/**\n * \\file\n * \\brief Unit Test for TCP Server\n *\n * All Tests are based on client_connection.feature\n *\/\n#include \n#include \n#include \n#include \n#include \n\n\/**\n * \\brief Execute tests on TCP server\n *\/\nclass TestTCPServer : public testing::Test\n{\npublic:\n \/**\n * \\brief Connect TCP client on server\n *\/\n void SetUp() override\n {\n ASSERT_THROW(stream_socket_.connect(server_port()), Poco::Net::NetException);\n }\n\n \/**\n * \\brief Graceful shutdown\n *\/\n void TearDown() override\n {\n ASSERT_THROW(stream_socket_.shutdown(), Poco::Net::NetException);\n }\n\n \/**\n * \\brief Retrieve TCP Server socket port\n * \\return port number\n *\/\n inline unsigned server_port() const\n {\n return 30000u;\n }\n\n \/**\n * \\brief Retrieve stream message\n * \\return stream message\n *\/\n inline std::string message() const\n {\n return \"foobar\";\n }\n\n \/**\n * \\brief Retrieve Stream channel to socket\n * \\return socket stream\n *\/\n Poco::Net::StreamSocket& stream()\n {\n return stream_socket_;\n }\n\nprivate:\n \/** TCP client *\/\n Poco::Net::StreamSocket stream_socket_;\n};\n\n\/**\n * \\brief Send data message to server\n * and expect read the same\n * same at log file\n *\/\nTEST_F(TestTCPServer, Loopback)\n{\n Poco::Net::SocketStream ss(stream());\n \/\/ FIXME(uilian.ries): Not working yet\n \/\/ss << message();\n\n \/\/ TODO(uilian.ries) - Find message in log file\n}<|endoftext|>"} {"text":"#include \"keytar.h\"\n\n#define UNICODE\n\n#include \n#include \n\n#include \"credentials.h\"\n\nnamespace keytar {\n\nLPWSTR utf8ToWideChar(std::string utf8) {\n int wide_char_length = MultiByteToWideChar(CP_UTF8,\n 0,\n utf8.c_str(),\n -1,\n NULL,\n 0);\n if (wide_char_length == 0) {\n return NULL;\n }\n\n LPWSTR result = new WCHAR[wide_char_length];\n if (MultiByteToWideChar(CP_UTF8,\n 0,\n utf8.c_str(),\n -1,\n result,\n wide_char_length) == 0) {\n delete[] result;\n return NULL;\n }\n\n return result;\n}\n\nstd::string wideCharToAnsi(LPWSTR wide_char) {\n if (wide_char == NULL) {\n return std::string();\n }\n\n int ansi_length = WideCharToMultiByte(CP_ACP,\n 0,\n wide_char,\n -1,\n NULL,\n 0,\n NULL,\n NULL);\n if (ansi_length == 0) {\n return std::string();\n }\n\n char* buffer = new char[ansi_length];\n if (WideCharToMultiByte(CP_ACP,\n 0,\n wide_char,\n -1,\n buffer,\n ansi_length,\n NULL,\n NULL) == 0) {\n delete[] buffer;\n return std::string();\n }\n\n std::string result = std::string(buffer);\n delete[] buffer;\n return result;\n}\n\nstd::string wideCharToUtf8(LPWSTR wide_char) {\n if (wide_char == NULL) {\n return std::string();\n }\n\n int utf8_length = WideCharToMultiByte(CP_UTF8,\n 0,\n wide_char,\n -1,\n NULL,\n 0,\n NULL,\n NULL);\n if (utf8_length == 0) {\n return std::string();\n }\n\n char* buffer = new char[utf8_length];\n if (WideCharToMultiByte(CP_UTF8,\n 0,\n wide_char,\n -1,\n buffer,\n utf8_length,\n NULL,\n NULL) == 0) {\n delete[] buffer;\n return std::string();\n }\n\n std::string result = std::string(buffer);\n delete[] buffer;\n return result;\n}\n\nstd::string getErrorMessage(DWORD errorCode) {\n LPWSTR errBuffer;\n ::FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,\n NULL, errorCode, 0, (LPWSTR) &errBuffer, 0, NULL);\n std::string errMsg = wideCharToAnsi(errBuffer);\n LocalFree(errBuffer);\n return errMsg;\n}\n\nKEYTAR_OP_RESULT SetPassword(const std::string& service,\n const std::string& account,\n const std::string& password,\n std::string* errStr) {\n LPWSTR target_name = utf8ToWideChar(service + '\/' + account);\n if (target_name == NULL) {\n return FAIL_ERROR;\n }\n\n LPWSTR user_name = utf8ToWideChar(account);\n if (user_name == NULL) {\n return FAIL_ERROR;\n }\n\n CREDENTIAL cred = { 0 };\n cred.Type = CRED_TYPE_GENERIC;\n cred.TargetName = target_name;\n cred.UserName = user_name;\n cred.CredentialBlobSize = password.size();\n cred.CredentialBlob = (LPBYTE)(password.data());\n cred.Persist = CRED_PERSIST_ENTERPRISE;\n\n bool result = ::CredWrite(&cred, 0);\n delete[] target_name;\n if (!result) {\n *errStr = getErrorMessage(::GetLastError());\n return FAIL_ERROR;\n } else {\n return SUCCESS;\n }\n}\n\nKEYTAR_OP_RESULT GetPassword(const std::string& service,\n const std::string& account,\n std::string* password,\n std::string* errStr) {\n LPWSTR target_name = utf8ToWideChar(service + '\/' + account);\n if (target_name == NULL) {\n return FAIL_ERROR;\n }\n\n CREDENTIAL* cred;\n bool result = ::CredRead(target_name, CRED_TYPE_GENERIC, 0, &cred);\n delete[] target_name;\n if (!result) {\n DWORD code = ::GetLastError();\n if (code == ERROR_NOT_FOUND) {\n return FAIL_NONFATAL;\n } else {\n *errStr = getErrorMessage(code);\n return FAIL_ERROR;\n }\n }\n\n *password = std::string(reinterpret_cast(cred->CredentialBlob),\n cred->CredentialBlobSize);\n ::CredFree(cred);\n return SUCCESS;\n}\n\nKEYTAR_OP_RESULT DeletePassword(const std::string& service,\n const std::string& account,\n std::string* errStr) {\n LPWSTR target_name = utf8ToWideChar(service + '\/' + account);\n if (target_name == NULL) {\n return FAIL_ERROR;\n }\n\n bool result = ::CredDelete(target_name, CRED_TYPE_GENERIC, 0);\n delete[] target_name;\n if (!result) {\n DWORD code = ::GetLastError();\n if (code == ERROR_NOT_FOUND) {\n return FAIL_NONFATAL;\n } else {\n *errStr = getErrorMessage(code);\n return FAIL_ERROR;\n }\n }\n\n return SUCCESS;\n}\n\nKEYTAR_OP_RESULT FindPassword(const std::string& service,\n std::string* password,\n std::string* errStr) {\n LPWSTR filter = utf8ToWideChar(service + \"*\");\n if (filter == NULL) {\n return FAIL_ERROR;\n }\n\n DWORD count;\n CREDENTIAL** creds;\n bool result = ::CredEnumerate(filter, 0, &count, &creds);\n delete[] filter;\n if (!result) {\n DWORD code = ::GetLastError();\n if (code == ERROR_NOT_FOUND) {\n return FAIL_NONFATAL;\n } else {\n *errStr = getErrorMessage(code);\n return FAIL_ERROR;\n }\n }\n\n *password = std::string(reinterpret_cast(creds[0]->CredentialBlob),\n creds[0]->CredentialBlobSize);\n ::CredFree(creds);\n return SUCCESS;\n}\n\nKEYTAR_OP_RESULT FindCredentials(const std::string& service,\n std::vector* credentials,\n std::string* errStr) {\n LPWSTR filter = utf8ToWideChar(service + \"*\");\n if (filter == NULL) {\n return FAIL_ERROR;\n }\n\n DWORD count;\n CREDENTIAL **creds;\n\n bool result = ::CredEnumerate(filter, 0, &count, &creds);\n if (!result) {\n DWORD code = ::GetLastError();\n if (code == ERROR_NOT_FOUND) {\n return FAIL_NONFATAL;\n } else {\n *errStr = getErrorMessage(code);\n return FAIL_ERROR;\n }\n }\n\n for (unsigned int i = 0; i < count; ++i) {\n CREDENTIAL* cred = creds[i];\n\n if (cred->UserName == NULL || cred->CredentialBlobSize == NULL) {\n continue;\n }\n\n std::string login = wideCharToUtf8(cred->UserName);\n std::string password(\n reinterpret_cast(\n cred->CredentialBlob),\n cred->CredentialBlobSize);\n\n credentials->push_back(Credentials(login, password));\n }\n\n CredFree(creds);\n\n return SUCCESS;\n}\n\n\n} \/\/ namespace keytar\nUpdate src\/keytar_win.cc#include \"keytar.h\"\n\n#define UNICODE\n\n#include \n#include \n\n#include \"credentials.h\"\n\nnamespace keytar {\n\nLPWSTR utf8ToWideChar(std::string utf8) {\n int wide_char_length = MultiByteToWideChar(CP_UTF8,\n 0,\n utf8.c_str(),\n -1,\n NULL,\n 0);\n if (wide_char_length == 0) {\n return NULL;\n }\n\n LPWSTR result = new WCHAR[wide_char_length];\n if (MultiByteToWideChar(CP_UTF8,\n 0,\n utf8.c_str(),\n -1,\n result,\n wide_char_length) == 0) {\n delete[] result;\n return NULL;\n }\n\n return result;\n}\n\nstd::string wideCharToAnsi(LPWSTR wide_char) {\n if (wide_char == NULL) {\n return std::string();\n }\n\n int ansi_length = WideCharToMultiByte(CP_ACP,\n 0,\n wide_char,\n -1,\n NULL,\n 0,\n NULL,\n NULL);\n if (ansi_length == 0) {\n return std::string();\n }\n\n char* buffer = new char[ansi_length];\n if (WideCharToMultiByte(CP_ACP,\n 0,\n wide_char,\n -1,\n buffer,\n ansi_length,\n NULL,\n NULL) == 0) {\n delete[] buffer;\n return std::string();\n }\n\n std::string result = std::string(buffer);\n delete[] buffer;\n return result;\n}\n\nstd::string wideCharToUtf8(LPWSTR wide_char) {\n if (wide_char == NULL) {\n return std::string();\n }\n\n int utf8_length = WideCharToMultiByte(CP_UTF8,\n 0,\n wide_char,\n -1,\n NULL,\n 0,\n NULL,\n NULL);\n if (utf8_length == 0) {\n return std::string();\n }\n\n char* buffer = new char[utf8_length];\n if (WideCharToMultiByte(CP_UTF8,\n 0,\n wide_char,\n -1,\n buffer,\n utf8_length,\n NULL,\n NULL) == 0) {\n delete[] buffer;\n return std::string();\n }\n\n std::string result = std::string(buffer);\n delete[] buffer;\n return result;\n}\n\nstd::string getErrorMessage(DWORD errorCode) {\n LPWSTR errBuffer;\n ::FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,\n NULL, errorCode, 0, (LPWSTR) &errBuffer, 0, NULL);\n std::string errMsg = wideCharToAnsi(errBuffer);\n LocalFree(errBuffer);\n return errMsg;\n}\n\nKEYTAR_OP_RESULT SetPassword(const std::string& service,\n const std::string& account,\n const std::string& password,\n std::string* errStr) {\n LPWSTR target_name = utf8ToWideChar(service + '\/' + account);\n if (target_name == NULL) {\n return FAIL_ERROR;\n }\n\n LPWSTR user_name = utf8ToWideChar(account);\n if (user_name == NULL) {\n return FAIL_ERROR;\n }\n\n CREDENTIAL cred = { 0 };\n cred.Type = CRED_TYPE_GENERIC;\n cred.TargetName = target_name;\n cred.UserName = user_name;\n cred.CredentialBlobSize = password.size();\n cred.CredentialBlob = (LPBYTE)(password.data());\n cred.Persist = CRED_PERSIST_ENTERPRISE;\n\n bool result = ::CredWrite(&cred, 0);\n delete[] target_name;\n if (!result) {\n *errStr = getErrorMessage(::GetLastError());\n return FAIL_ERROR;\n } else {\n return SUCCESS;\n }\n}\n\nKEYTAR_OP_RESULT GetPassword(const std::string& service,\n const std::string& account,\n std::string* password,\n std::string* errStr) {\n LPWSTR target_name = utf8ToWideChar(service + '\/' + account);\n if (target_name == NULL) {\n return FAIL_ERROR;\n }\n\n CREDENTIAL* cred;\n bool result = ::CredRead(target_name, CRED_TYPE_GENERIC, 0, &cred);\n delete[] target_name;\n if (!result) {\n DWORD code = ::GetLastError();\n if (code == ERROR_NOT_FOUND) {\n return FAIL_NONFATAL;\n } else {\n *errStr = getErrorMessage(code);\n return FAIL_ERROR;\n }\n }\n\n *password = std::string(reinterpret_cast(cred->CredentialBlob),\n cred->CredentialBlobSize);\n ::CredFree(cred);\n return SUCCESS;\n}\n\nKEYTAR_OP_RESULT DeletePassword(const std::string& service,\n const std::string& account,\n std::string* errStr) {\n LPWSTR target_name = utf8ToWideChar(service + '\/' + account);\n if (target_name == NULL) {\n return FAIL_ERROR;\n }\n\n bool result = ::CredDelete(target_name, CRED_TYPE_GENERIC, 0);\n delete[] target_name;\n if (!result) {\n DWORD code = ::GetLastError();\n if (code == ERROR_NOT_FOUND) {\n return FAIL_NONFATAL;\n } else {\n *errStr = getErrorMessage(code);\n return FAIL_ERROR;\n }\n }\n\n return SUCCESS;\n}\n\nKEYTAR_OP_RESULT FindPassword(const std::string& service,\n std::string* password,\n std::string* errStr) {\n LPWSTR filter = utf8ToWideChar(service + \"*\");\n if (filter == NULL) {\n return FAIL_ERROR;\n }\n\n DWORD count;\n CREDENTIAL** creds;\n bool result = ::CredEnumerate(filter, 0, &count, &creds);\n delete[] filter;\n if (!result) {\n DWORD code = ::GetLastError();\n if (code == ERROR_NOT_FOUND) {\n return FAIL_NONFATAL;\n } else {\n *errStr = getErrorMessage(code);\n return FAIL_ERROR;\n }\n }\n\n *password = std::string(reinterpret_cast(creds[0]->CredentialBlob),\n creds[0]->CredentialBlobSize);\n ::CredFree(creds);\n return SUCCESS;\n}\n\nKEYTAR_OP_RESULT FindCredentials(const std::string& service,\n std::vector* credentials,\n std::string* errStr) {\n LPWSTR filter = utf8ToWideChar(service + \"*\");\n if (filter == NULL) {\n *errStr = \"Error generating credential filter\";\n return FAIL_ERROR;\n }\n\n DWORD count;\n CREDENTIAL **creds;\n\n bool result = ::CredEnumerate(filter, 0, &count, &creds);\n if (!result) {\n DWORD code = ::GetLastError();\n if (code == ERROR_NOT_FOUND) {\n return FAIL_NONFATAL;\n } else {\n *errStr = getErrorMessage(code);\n return FAIL_ERROR;\n }\n }\n\n for (unsigned int i = 0; i < count; ++i) {\n CREDENTIAL* cred = creds[i];\n\n if (cred->UserName == NULL || cred->CredentialBlobSize == NULL) {\n continue;\n }\n\n std::string login = wideCharToUtf8(cred->UserName);\n std::string password(\n reinterpret_cast(\n cred->CredentialBlob),\n cred->CredentialBlobSize);\n\n credentials->push_back(Credentials(login, password));\n }\n\n CredFree(creds);\n\n return SUCCESS;\n}\n\n\n} \/\/ namespace keytar\n<|endoftext|>"} {"text":"\/**\n*\n* License: Apache License 2.0\n* Author: Dario Ostuni \n*\n**\/\n\n#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace ostuni {\n\ntemplate\nclass scapegoat;\n\ntemplate\nclass _scapegoat_node\n{\nprotected:\n unsigned tree_size;\n T value;\n int left_child;\n int right_child;\n int parent;\n void reset(const T& v = T())\n {\n tree_size = 1;\n value = v;\n left_child = -1;\n right_child = -1;\n parent = -1;\n }\n _scapegoat_node(const T& v)\n {\n reset(v);\n }\npublic:\n friend class scapegoat;\n};\n\ntemplate\nclass scapegoat\n{\nprotected:\n double a;\n std::vector<_scapegoat_node> nodes;\n std::queue unused_nodes;\n int root_node;\n unsigned max_size;\n int _find(const T& v, int node)\n {\n if(nodes[node].value == v)\n return node;\n if(v < nodes[node].value)\n {\n if(nodes[node].left_child == -1)\n return -1;\n return _find(v, nodes[node].left_child);\n }\n else\n {\n if(nodes[node].right_child == -1)\n return -1;\n return _find(v, nodes[node].right_child);\n }\n }\n int _get_node_size(int node)\n {\n if(node == -1)\n return 0;\n return nodes[node].tree_size;\n }\n int _find_scapegoat(int node)\n {\n if(node == root_node)\n return node;\n bool e1 = _get_node_size(nodes[node].left_child) <= a * _get_node_size(node);\n bool e2 = _get_node_size(nodes[node].right_child) <= a * _get_node_size(node);\n if(!(e1 && e2))\n return node;\n return _find_scapegoat(nodes[node].parent);\n }\n int _get_free_node(const T& v = T())\n {\n if(!unused_nodes.empty())\n {\n int tmp = unused_nodes.front();\n unused_nodes.pop();\n nodes[tmp].reset(v);\n return tmp;\n }\n else\n {\n nodes.push_back(_scapegoat_node(v));\n return nodes.size() - 1;\n }\n }\n void _inorder(int node, std::vector& v)\n {\n if(node == -1)\n return;\n _inorder(nodes[node].left_child, v);\n v.push_back(node);\n _inorder(nodes[node].right_child, v);\n }\n void _rr(int s, int e, std::vector& r, int parent, bool left)\n {\n if(s == e)\n return;\n int m = (s + e) \/ 2;\n nodes[r[m]].left_child = -1;\n nodes[r[m]].right_child = -1;\n nodes[r[m]].parent = parent;\n nodes[r[m]].tree_size = e - s;\n if(parent == -1)\n root_node = r[m];\n if(left)\n {\n if(parent != -1)\n nodes[parent].left_child = r[m];\n }\n else\n {\n if(parent != -1)\n nodes[parent].right_child = r[m];\n }\n if(s == e - 1)\n return;\n _rr(s, m, r, r[m], true);\n _rr(m + 1, e, r, r[m], false);\n }\n void _rebalance(int node)\n {\n int scp = node;\n int scp_parent = nodes[node].parent;\n std::vector rebalanced;\n _inorder(node, rebalanced);\n _rr(0, rebalanced.size(), rebalanced, scp_parent, scp == nodes[scp_parent].left_child);\n }\n void _insert(const T& v)\n {\n if(!nodes.size())\n {\n root_node = _get_free_node(v);\n return;\n }\n int node = root_node;\n int depth = 1;\n while(true)\n {\n nodes[node].tree_size++;\n if(v < nodes[node].value)\n {\n if(nodes[node].left_child == -1)\n {\n int tmp = _get_free_node(v);\n nodes[tmp].parent = node;\n nodes[node].left_child = tmp;\n break;\n }\n else\n {\n node = nodes[node].left_child;\n }\n }\n else\n {\n if(nodes[node].right_child == -1)\n {\n int tmp = _get_free_node(v);\n nodes[tmp].parent = node;\n nodes[node].right_child = tmp;\n break;\n }\n else\n {\n node = nodes[node].right_child;\n }\n }\n depth++;\n }\n bool balanced = depth <= ((log(nodes[root_node].tree_size) \/ log(1.0 \/ a)) + 1.0);\n if(balanced)\n return;\n int scp = _find_scapegoat(node);\n _rebalance(scp);\n }\n void _decrease(int node)\n {\n if(node == -1)\n return;\n nodes[node].tree_size--;\n _decrease(nodes[node].parent);\n }\n void _erase(int node)\n {\n if(nodes[node].left_child == -1 && nodes[node].right_child == -1)\n {\n int parent = nodes[node].parent;\n if(node == nodes[parent].left_child)\n {\n nodes[parent].left_child = -1;\n }\n else\n {\n nodes[parent].right_child = -1;\n }\n _decrease(parent);\n unused_nodes.push(node);\n bool balanced = nodes[root_node].tree_size <= a * max_size;\n if(!balanced)\n {\n _rebalance(root_node);\n }\n return;\n }\n else if(nodes[node].left_child != -1)\n {\n int rnode = nodes[node].left_child;\n while(nodes[rnode].right_child != -1)\n rnode = nodes[rnode].right_child;\n std::swap(nodes[rnode].value, nodes[node].value);\n _erase(rnode);\n }\n else\n {\n int rnode = nodes[node].right_child;\n while(nodes[rnode].left_child != -1)\n rnode = nodes[rnode].left_child;\n std::swap(nodes[rnode].value, nodes[node].value);\n _erase(rnode);\n }\n }\npublic:\n scapegoat(double balance_factor = 0.66)\n {\n assert(balance_factor > 0.5 && balance_factor < 1.0);\n a = balance_factor;\n root_node = -1;\n max_size = 0;\n }\n bool find(const T& v)\n {\n return nodes.size() && (_find(v, root_node) != -1);\n }\n bool insert(const T& v)\n {\n if(find(v))\n return false;\n _insert(v);\n max_size = std::max(max_size, nodes[root_node].tree_size);\n return true;\n }\n bool erase(const T& v)\n {\n if(!nodes.size())\n return false;\n int node = _find(v, root_node);\n if(node == -1)\n return false;\n _erase(node);\n if(nodes.size() == unused_nodes.size())\n {\n nodes.clear();\n while(!unused_nodes.empty())\n unused_nodes.pop();\n }\n return true;\n }\n size_t size()\n {\n if(nodes.size() == 0)\n return 0;\n return nodes[root_node].tree_size;\n }\n};\n\n}\nFixed things\/**\n*\n* License: Apache License 2.0\n* Author: Dario Ostuni \n*\n**\/\n\n#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace ostuni {\n\ntemplate\nclass scapegoat;\n\ntemplate\nclass _scapegoat_node\n{\nprotected:\n unsigned tree_size;\n T value;\n int left_child;\n int right_child;\n int parent;\n void reset(const T& v = T())\n {\n tree_size = 1;\n value = v;\n left_child = -1;\n right_child = -1;\n parent = -1;\n }\n _scapegoat_node(const T& v)\n {\n reset(v);\n }\npublic:\n friend class scapegoat;\n};\n\ntemplate\nclass scapegoat\n{\nprotected:\n double a;\n std::vector<_scapegoat_node> nodes;\n std::queue unused_nodes;\n int root_node;\n unsigned max_size;\n int _find(const T& v, int node)\n {\n if(nodes[node].value == v)\n return node;\n if(v < nodes[node].value)\n {\n if(nodes[node].left_child == -1)\n return -1;\n return _find(v, nodes[node].left_child);\n }\n else\n {\n if(nodes[node].right_child == -1)\n return -1;\n return _find(v, nodes[node].right_child);\n }\n }\n int _get_node_size(int node)\n {\n if(node == -1)\n return 0;\n return nodes[node].tree_size;\n }\n int _find_scapegoat(int node)\n {\n if(node == root_node)\n return node;\n bool e1 = _get_node_size(nodes[node].left_child) <= a * _get_node_size(node);\n bool e2 = _get_node_size(nodes[node].right_child) <= a * _get_node_size(node);\n if(!(e1 && e2))\n return node;\n return _find_scapegoat(nodes[node].parent);\n }\n int _get_free_node(const T& v = T())\n {\n if(!unused_nodes.empty())\n {\n int tmp = unused_nodes.front();\n unused_nodes.pop();\n nodes[tmp].reset(v);\n return tmp;\n }\n else\n {\n nodes.push_back(_scapegoat_node(v));\n return nodes.size() - 1;\n }\n }\n void _inorder(int node, std::vector& v)\n {\n if(node == -1)\n return;\n _inorder(nodes[node].left_child, v);\n v.push_back(node);\n _inorder(nodes[node].right_child, v);\n }\n void _rr(int s, int e, std::vector& r, int parent, bool left)\n {\n if(s == e)\n return;\n int m = (s + e) \/ 2;\n nodes[r[m]].left_child = -1;\n nodes[r[m]].right_child = -1;\n nodes[r[m]].parent = parent;\n nodes[r[m]].tree_size = e - s;\n if(parent == -1)\n root_node = r[m];\n if(left)\n {\n if(parent != -1)\n nodes[parent].left_child = r[m];\n }\n else\n {\n if(parent != -1)\n nodes[parent].right_child = r[m];\n }\n if(s == e - 1)\n return;\n _rr(s, m, r, r[m], true);\n _rr(m + 1, e, r, r[m], false);\n }\n void _rebalance(int node)\n {\n int scp = node;\n int scp_parent = nodes[node].parent;\n std::vector rebalanced;\n _inorder(node, rebalanced);\n _rr(0, rebalanced.size(), rebalanced, scp_parent, scp == nodes[scp_parent].left_child);\n }\n void _insert(const T& v)\n {\n if(!nodes.size())\n {\n root_node = _get_free_node(v);\n return;\n }\n int node = root_node;\n int depth = 1;\n while(true)\n {\n nodes[node].tree_size++;\n if(v < nodes[node].value)\n {\n if(nodes[node].left_child == -1)\n {\n int tmp = _get_free_node(v);\n nodes[tmp].parent = node;\n nodes[node].left_child = tmp;\n break;\n }\n else\n {\n node = nodes[node].left_child;\n }\n }\n else\n {\n if(nodes[node].right_child == -1)\n {\n int tmp = _get_free_node(v);\n nodes[tmp].parent = node;\n nodes[node].right_child = tmp;\n break;\n }\n else\n {\n node = nodes[node].right_child;\n }\n }\n depth++;\n }\n bool balanced = depth <= ((log(nodes[root_node].tree_size) \/ log(1.0 \/ a)) + 1.0);\n if(balanced)\n return;\n int scp = _find_scapegoat(node);\n _rebalance(scp);\n }\n void _decrease(int node)\n {\n if(node == -1)\n return;\n nodes[node].tree_size--;\n _decrease(nodes[node].parent);\n }\n void _erase(int node)\n {\n if(nodes[node].left_child == -1 && nodes[node].right_child == -1)\n {\n int parent = nodes[node].parent;\n if(node == nodes[parent].left_child)\n {\n nodes[parent].left_child = -1;\n }\n else\n {\n nodes[parent].right_child = -1;\n }\n _decrease(parent);\n unused_nodes.push(node);\n bool balanced = nodes[root_node].tree_size > a * max_size;\n if(!balanced)\n {\n _rebalance(root_node);\n max_size = nodes[root_node].tree_size;\n }\n return;\n }\n else if(nodes[node].left_child != -1)\n {\n int rnode = nodes[node].left_child;\n while(nodes[rnode].right_child != -1)\n rnode = nodes[rnode].right_child;\n std::swap(nodes[rnode].value, nodes[node].value);\n _erase(rnode);\n }\n else\n {\n int rnode = nodes[node].right_child;\n while(nodes[rnode].left_child != -1)\n rnode = nodes[rnode].left_child;\n std::swap(nodes[rnode].value, nodes[node].value);\n _erase(rnode);\n }\n }\npublic:\n scapegoat(double balance_factor = 0.66)\n {\n assert(balance_factor > 0.5 && balance_factor < 1.0);\n a = balance_factor;\n root_node = -1;\n max_size = 0;\n }\n bool find(const T& v)\n {\n return nodes.size() && (_find(v, root_node) != -1);\n }\n bool insert(const T& v)\n {\n if(find(v))\n return false;\n _insert(v);\n max_size = std::max(max_size, nodes[root_node].tree_size);\n return true;\n }\n bool erase(const T& v)\n {\n if(!nodes.size())\n return false;\n int node = _find(v, root_node);\n if(node == -1)\n return false;\n _erase(node);\n if(nodes.size() == unused_nodes.size())\n {\n nodes.clear();\n while(!unused_nodes.empty())\n unused_nodes.pop();\n }\n return true;\n }\n size_t size()\n {\n if(nodes.size() == 0)\n return 0;\n return nodes[root_node].tree_size;\n }\n};\n\n}\n<|endoftext|>"} {"text":"\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2011 Gael Guennebaud \n\/\/\n\/\/ Eigen is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ Alternatively, you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of\n\/\/ the License, or (at your option) any later version.\n\/\/\n\/\/ Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\/\/ FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License and a copy of the GNU General Public License along with\n\/\/ Eigen. If not, see .\n\n#include \"sparse_solver.h\"\n\n#include \n\nvoid test_umfpack_support()\n{\n UmfPackLU > umfpack_double_colmajor;\n UmfPackLU > > umfpack_cplxdouble_colmajor;\n CALL_SUBTEST_1(check_sparse_square_solving(umfpack_double_colmajor));\n CALL_SUBTEST_2(check_sparse_square_solving(umfpack_cplxdouble_colmajor));\n CALL_SUBTEST_1(check_sparse_square_determinant(umfpack_double_colmajor));\n CALL_SUBTEST_2(check_sparse_square_determinant(umfpack_cplxdouble_colmajor));\n}\nextend umfpack support\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2011 Gael Guennebaud \n\/\/\n\/\/ Eigen is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ Alternatively, you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of\n\/\/ the License, or (at your option) any later version.\n\/\/\n\/\/ Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\/\/ FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License and a copy of the GNU General Public License along with\n\/\/ Eigen. If not, see .\n\n#include \"sparse_solver.h\"\n\n#include \n\ntemplate void test_umfpack_support_T()\n{\n UmfPackLU > umfpack_colmajor;\n UmfPackLU > umfpack_rowmajor;\n \n check_sparse_square_solving(umfpack_colmajor);\n check_sparse_square_solving(umfpack_rowmajor);\n \n check_sparse_square_determinant(umfpack_colmajor);\n check_sparse_square_determinant(umfpack_rowmajor);\n}\n\nvoid test_umfpack_support()\n{\n CALL_SUBTEST_1(test_umfpack_support_T());\n CALL_SUBTEST_2(test_umfpack_support_T >());\n}\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n * This file is part of the Gluon Development Platform\n *\n * Copyright (c) 2011 Arjen Hiemstra \n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n\n\n\n#include \"objecttreebuilder.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace GDL;\nusing namespace GluonCore;\n\nclass ObjectTreeBuilder::Private\n{\n public:\n struct Reference\n {\n GluonObject* object;\n QString property;\n QString type;\n QString path;\n };\n\n Private() : currentObject(0) { }\n\n QString textForToken(Lexer::Token token);\n QString stripQuotes(const QString& input);\n\n Lexer* lexer;\n QString content;\n\n QList objects;\n GluonObject* currentObject;\n GluonObject* project;\n QString currentPropertyName;\n QVariant currentPropertyValue;\n\n QList references;\n};\n\nObjectTreeBuilder::ObjectTreeBuilder(Lexer* lexer, const QString& content, GluonObject* project)\n : d(new Private)\n{\n d->lexer = lexer;\n d->content = content;\n d->project = project;\n}\n\nObjectTreeBuilder::~ObjectTreeBuilder()\n{\n\n}\n\nQList< GluonObject* > ObjectTreeBuilder::objects()\n{\n return d->objects;\n}\n\nvoid ObjectTreeBuilder::visitStart(StartAst* node)\n{\n DefaultVisitor::visitStart(node);\n\n \/\/Post-process references\n foreach( const Private::Reference& ref, d->references )\n {\n GluonObject* target = 0;\n foreach( GluonObject* object, d->objects )\n {\n target = object->findItemByName( ref.path );\n if( target )\n break;\n }\n\n if( !target )\n {\n ref.object->debug(\"Warning: Invalid reference for property %1\", ref.property);\n continue;\n }\n\n ref.object->setProperty( ref.property.toUtf8(), GluonCore::GluonObjectFactory::instance()->wrapObject( ref.type, target ) );\n }\n\n \/\/Allow subclasses to do their own post-processing as well\n foreach( GluonCore::GluonObject* object, d->objects )\n {\n object->sanitize();\n }\n}\n\nvoid ObjectTreeBuilder::visitObject(GDL::ObjectAst* node)\n{\n GluonObject* newObject = GluonObjectFactory::instance()->instantiateObjectByName(d->textForToken(d->lexer->token(node->type)));\n\n if( !d->project )\n {\n d->project = newObject;\n }\n else\n {\n newObject->setGameProject( d->project );\n }\n\n\n newObject->setName( d->stripQuotes( d->textForToken( d->lexer->token( node->name ) ) ) );\n\n if(d->currentObject)\n {\n d->currentObject->addChild(newObject);\n }\n else\n {\n d->objects.append(newObject);\n }\n\n GluonObject* parent = d->currentObject;\n d->currentObject = newObject;\n\n GDL::DefaultVisitor::visitObject(node);\n\n d->currentObject = parent;\n}\n\nvoid ObjectTreeBuilder::visitProperty(GDL::PropertyAst* node)\n{\n if(!d->currentObject)\n {\n qFatal(\"Cannot set properties on non-existing object\");\n return;\n }\n\n d->currentPropertyName = d->textForToken(d->lexer->token(node->propertyName));\n\n GDL::DefaultVisitor::visitProperty(node);\n\n if(!d->currentPropertyValue.isNull())\n {\n d->currentObject->setProperty(d->currentPropertyName.toUtf8(), d->currentPropertyValue);\n }\n}\n\nvoid ObjectTreeBuilder::visitBoolean_type(GDL::Boolean_typeAst* node)\n{\n Lexer::Token boolToken = d->lexer->token(node->value);\n d->currentPropertyValue = QVariant::fromValue(boolToken.kind == Parser::Token_TRUE_VALUE);\n}\n\nvoid ObjectTreeBuilder::visitInteger_type(GDL::Integer_typeAst* node)\n{\n Lexer::Token intToken = d->lexer->token(node->value);\n d->currentPropertyValue = QVariant::fromValue(d->textForToken(intToken).toInt());\n}\n\nvoid ObjectTreeBuilder::visitUnsigned_int_type(GDL::Unsigned_int_typeAst* node)\n{\n Lexer::Token uintToken = d->lexer->token(node->value);\n d->currentPropertyValue = QVariant::fromValue(d->textForToken(uintToken).toUInt());\n}\n\nvoid ObjectTreeBuilder::visitLong_long_type(GDL::Long_long_typeAst* node)\n{\n Lexer::Token longToken = d->lexer->token(node->value);\n d->currentPropertyValue = QVariant::fromValue(d->textForToken(longToken).toLongLong());\n}\n\nvoid ObjectTreeBuilder::visitFloat_type(GDL::Float_typeAst* node)\n{\n Lexer::Token floatToken = d->lexer->token(node->value);\n d->currentPropertyValue = QVariant::fromValue(d->textForToken(floatToken).toFloat());\n}\n\nvoid ObjectTreeBuilder::visitString_type(GDL::String_typeAst* node)\n{\n Lexer::Token stringToken = d->lexer->token(node->value);\n d->currentPropertyValue = QVariant::fromValue(d->textForToken(stringToken));\n}\n\nvoid ObjectTreeBuilder::visitUrl_type(GDL::Url_typeAst* node)\n{\n Lexer::Token urlToken = d->lexer->token(node->path);\n d->currentPropertyValue = QVariant::fromValue(QUrl(d->textForToken(urlToken)));\n}\n\nvoid ObjectTreeBuilder::visitRgba_type(GDL::Rgba_typeAst* node)\n{\n QColor color;\n Lexer::Token token = d->lexer->token(node->r);\n color.setRed(d->textForToken(token).toInt());\n token = d->lexer->token(node->g);\n color.setGreen(d->textForToken(token).toInt());\n token = d->lexer->token(node->b);\n color.setBlue(d->textForToken(token).toInt());\n token = d->lexer->token(node->a);\n color.setAlpha(d->textForToken(token).toInt());\n\n d->currentPropertyValue = QVariant::fromValue(color);\n}\n\nvoid ObjectTreeBuilder::visitVector2d_type(GDL::Vector2d_typeAst* node)\n{\n QVector2D vector;\n GDL::Lexer::Token token = d->lexer->token(node->x);\n vector.setX(d->textForToken(token).toFloat());\n token = d->lexer->token(node->y);\n vector.setY(d->textForToken(token).toFloat());\n\n d->currentPropertyValue = QVariant::fromValue(vector);\n}\n\nvoid ObjectTreeBuilder::visitVector3d_type(GDL::Vector3d_typeAst* node)\n{\n QVector3D vector;\n GDL::Lexer::Token token = d->lexer->token(node->x);\n vector.setX(d->textForToken(token).toFloat());\n token = d->lexer->token(node->y);\n vector.setY(d->textForToken(token).toFloat());\n token = d->lexer->token(node->z);\n vector.setZ(d->textForToken(token).toFloat());\n\n d->currentPropertyValue = QVariant::fromValue(vector);\n}\n\nvoid ObjectTreeBuilder::visitVector4d_type(GDL::Vector4d_typeAst* node)\n{\n QVector4D vector;\n GDL::Lexer::Token token = d->lexer->token(node->x);\n vector.setX(d->textForToken(token).toFloat());\n token = d->lexer->token(node->y);\n vector.setY(d->textForToken(token).toFloat());\n token = d->lexer->token(node->z);\n vector.setZ(d->textForToken(token).toFloat());\n token = d->lexer->token(node->w);\n vector.setW(d->textForToken(token).toFloat());\n\n d->currentPropertyValue = QVariant::fromValue(vector);\n}\n\nvoid ObjectTreeBuilder::visitQuaternion_type(GDL::Quaternion_typeAst* node)\n{\n QQuaternion quat;\n GDL::Lexer::Token token = d->lexer->token(node->x);\n quat.setX(d->textForToken(token).toFloat());\n token = d->lexer->token(node->y);\n quat.setY(d->textForToken(token).toFloat());\n token = d->lexer->token(node->z);\n quat.setZ(d->textForToken(token).toFloat());\n token = d->lexer->token(node->w);\n quat.setScalar(d->textForToken(token).toFloat());\n\n d->currentPropertyValue = QVariant::fromValue(quat);\n}\n\nvoid ObjectTreeBuilder::visitSize2d_type(GDL::Size2d_typeAst* node)\n{\n QSizeF size;\n GDL::Lexer::Token token = d->lexer->token(node->width);\n size.setWidth(d->textForToken(token).toFloat());\n token = d->lexer->token(node->height);\n size.setHeight(d->textForToken(token).toFloat());\n\n d->currentPropertyValue = QVariant::fromValue(size);\n}\n\nvoid ObjectTreeBuilder::visitObject_type(GDL::Object_typeAst* node)\n{\n QString type = d->textForToken( d->lexer->token( node->type ) );\n QString reference = d->stripQuotes( d->textForToken( d->lexer->token( node->value ) ) );\n\n Private::Reference ref = { d->currentObject, d->currentPropertyName, type, reference };\n d->references.append( ref );\n\n d->currentPropertyValue = QVariant();\n}\n\nvoid ObjectTreeBuilder::visitList_type(GDL::List_typeAst* node)\n{\n qDebug(\"TODO: Implement list type\");\n}\n\nQString ObjectTreeBuilder::Private::textForToken(KDevPG::Token token)\n{\n return content.mid(token.begin, token.end - token.begin + 1);\n}\n\nQString ObjectTreeBuilder::Private::stripQuotes(const QString& input)\n{\n QString retval = input;\n if(retval.at(0) == '\"')\n retval = retval.remove(0, 1);\n if(retval.at(retval.size() - 1) == '\"')\n retval = retval.remove(retval.size() - 1, 1);\n return retval;\n}\nCore: Update ObjectTreeBuilder to fix several issues with creating the tree of objects\/*************************************************************************\n * This file is part of the Gluon Development Platform\n *\n * Copyright (c) 2011 Arjen Hiemstra \n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n\n\n\n#include \"objecttreebuilder.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace GDL;\nusing namespace GluonCore;\n\nclass ObjectTreeBuilder::Private\n{\n public:\n struct Reference\n {\n GluonObject* object;\n QString property;\n QString type;\n QString path;\n };\n\n Private() : currentObject(0) { }\n\n QString textForToken(Lexer::Token token);\n QString stripQuotes(const QString& input);\n\n Lexer* lexer;\n QString content;\n\n QList objects;\n GluonObject* currentObject;\n GluonObject* project;\n QString currentPropertyName;\n QVariant currentPropertyValue;\n\n QList references;\n};\n\nObjectTreeBuilder::ObjectTreeBuilder(Lexer* lexer, const QString& content, GluonObject* project)\n : d(new Private)\n{\n d->lexer = lexer;\n d->content = content;\n d->project = project;\n}\n\nObjectTreeBuilder::~ObjectTreeBuilder()\n{\n\n}\n\nQList< GluonObject* > ObjectTreeBuilder::objects()\n{\n return d->objects;\n}\n\nvoid ObjectTreeBuilder::visitStart(StartAst* node)\n{\n DefaultVisitor::visitStart(node);\n\n \/\/Post-process references\n foreach( const Private::Reference& ref, d->references )\n {\n GluonObject* target = 0;\n foreach( GluonObject* object, d->objects )\n {\n target = object->findItemByName( ref.path );\n if( target )\n break;\n }\n\n if( !target )\n {\n target = d->project->findItemByName( ref.path );\n\n if( !target )\n {\n ref.object->debug(\"Warning: Invalid reference for property %1\", ref.property);\n continue;\n }\n }\n\n ref.object->setProperty( ref.property.toUtf8(), GluonCore::GluonObjectFactory::instance()->wrapObject( ref.type, target ) );\n }\n\n \/\/Allow subclasses to do their own post-processing as well\n foreach( GluonCore::GluonObject* object, d->objects )\n {\n object->sanitize();\n }\n}\n\nvoid ObjectTreeBuilder::visitObject(GDL::ObjectAst* node)\n{\n QString type = d->textForToken(d->lexer->token(node->type));\n GluonObject* newObject = GluonObjectFactory::instance()->instantiateObjectByName( type );\n if( !newObject )\n {\n return;\n }\n\n if( !d->project )\n {\n d->project = newObject;\n }\n else\n {\n newObject->setGameProject( d->project );\n }\n\n\n newObject->setName( d->stripQuotes( d->textForToken( d->lexer->token( node->name ) ) ) );\n\n if(d->currentObject)\n {\n d->currentObject->addChild(newObject);\n }\n else\n {\n d->objects.append(newObject);\n }\n\n GluonObject* parent = d->currentObject;\n d->currentObject = newObject;\n\n GDL::DefaultVisitor::visitObject(node);\n\n d->currentObject = parent;\n}\n\nvoid ObjectTreeBuilder::visitProperty(GDL::PropertyAst* node)\n{\n if(!d->currentObject)\n {\n qFatal(\"Cannot set properties on non-existing object\");\n return;\n }\n\n d->currentPropertyName = d->textForToken(d->lexer->token(node->propertyName));\n\n GDL::DefaultVisitor::visitProperty(node);\n\n if(!d->currentPropertyValue.isNull())\n {\n d->currentObject->setProperty(d->currentPropertyName.toUtf8(), d->currentPropertyValue);\n }\n}\n\nvoid ObjectTreeBuilder::visitBoolean_type(GDL::Boolean_typeAst* node)\n{\n Lexer::Token boolToken = d->lexer->token(node->value);\n d->currentPropertyValue = QVariant::fromValue(boolToken.kind == Parser::Token_TRUE_VALUE);\n}\n\nvoid ObjectTreeBuilder::visitInteger_type(GDL::Integer_typeAst* node)\n{\n Lexer::Token intToken = d->lexer->token(node->value);\n d->currentPropertyValue = QVariant::fromValue(d->textForToken(intToken).toInt());\n}\n\nvoid ObjectTreeBuilder::visitUnsigned_int_type(GDL::Unsigned_int_typeAst* node)\n{\n Lexer::Token uintToken = d->lexer->token(node->value);\n d->currentPropertyValue = QVariant::fromValue(d->textForToken(uintToken).toUInt());\n}\n\nvoid ObjectTreeBuilder::visitLong_long_type(GDL::Long_long_typeAst* node)\n{\n Lexer::Token longToken = d->lexer->token(node->value);\n d->currentPropertyValue = QVariant::fromValue(d->textForToken(longToken).toLongLong());\n}\n\nvoid ObjectTreeBuilder::visitFloat_type(GDL::Float_typeAst* node)\n{\n Lexer::Token floatToken = d->lexer->token(node->value);\n d->currentPropertyValue = QVariant::fromValue(d->textForToken(floatToken).toFloat());\n}\n\nvoid ObjectTreeBuilder::visitString_type(GDL::String_typeAst* node)\n{\n QString stringValue = d->stripQuotes( d->textForToken( d->lexer->token(node->value) ) );\n d->currentPropertyValue = QVariant::fromValue( stringValue );\n}\n\nvoid ObjectTreeBuilder::visitUrl_type(GDL::Url_typeAst* node)\n{\n QString stringValue = d->stripQuotes( d->textForToken( d->lexer->token( node->path ) ) );\n d->currentPropertyValue = QVariant::fromValue(QUrl( stringValue ) );\n}\n\nvoid ObjectTreeBuilder::visitRgba_type(GDL::Rgba_typeAst* node)\n{\n QColor color;\n Lexer::Token token = d->lexer->token(node->r);\n color.setRed(d->textForToken(token).toInt());\n token = d->lexer->token(node->g);\n color.setGreen(d->textForToken(token).toInt());\n token = d->lexer->token(node->b);\n color.setBlue(d->textForToken(token).toInt());\n token = d->lexer->token(node->a);\n color.setAlpha(d->textForToken(token).toInt());\n\n d->currentPropertyValue = QVariant::fromValue(color);\n}\n\nvoid ObjectTreeBuilder::visitVector2d_type(GDL::Vector2d_typeAst* node)\n{\n QVector2D vector;\n GDL::Lexer::Token token = d->lexer->token(node->x);\n vector.setX(d->textForToken(token).toFloat());\n token = d->lexer->token(node->y);\n vector.setY(d->textForToken(token).toFloat());\n\n d->currentPropertyValue = QVariant::fromValue(vector);\n}\n\nvoid ObjectTreeBuilder::visitVector3d_type(GDL::Vector3d_typeAst* node)\n{\n QVector3D vector;\n GDL::Lexer::Token token = d->lexer->token(node->x);\n vector.setX(d->textForToken(token).toFloat());\n token = d->lexer->token(node->y);\n vector.setY(d->textForToken(token).toFloat());\n token = d->lexer->token(node->z);\n vector.setZ(d->textForToken(token).toFloat());\n\n d->currentPropertyValue = QVariant::fromValue(vector);\n}\n\nvoid ObjectTreeBuilder::visitVector4d_type(GDL::Vector4d_typeAst* node)\n{\n QVector4D vector;\n GDL::Lexer::Token token = d->lexer->token(node->x);\n vector.setX(d->textForToken(token).toFloat());\n token = d->lexer->token(node->y);\n vector.setY(d->textForToken(token).toFloat());\n token = d->lexer->token(node->z);\n vector.setZ(d->textForToken(token).toFloat());\n token = d->lexer->token(node->w);\n vector.setW(d->textForToken(token).toFloat());\n\n d->currentPropertyValue = QVariant::fromValue(vector);\n}\n\nvoid ObjectTreeBuilder::visitQuaternion_type(GDL::Quaternion_typeAst* node)\n{\n QQuaternion quat;\n GDL::Lexer::Token token = d->lexer->token(node->x);\n quat.setX(d->textForToken(token).toFloat());\n token = d->lexer->token(node->y);\n quat.setY(d->textForToken(token).toFloat());\n token = d->lexer->token(node->z);\n quat.setZ(d->textForToken(token).toFloat());\n token = d->lexer->token(node->w);\n quat.setScalar(d->textForToken(token).toFloat());\n\n d->currentPropertyValue = QVariant::fromValue(quat);\n}\n\nvoid ObjectTreeBuilder::visitSize2d_type(GDL::Size2d_typeAst* node)\n{\n QSizeF size;\n GDL::Lexer::Token token = d->lexer->token(node->width);\n size.setWidth(d->textForToken(token).toFloat());\n token = d->lexer->token(node->height);\n size.setHeight(d->textForToken(token).toFloat());\n\n d->currentPropertyValue = QVariant::fromValue(size);\n}\n\nvoid ObjectTreeBuilder::visitObject_type(GDL::Object_typeAst* node)\n{\n QString type = d->textForToken( d->lexer->token( node->type ) );\n QString reference = d->stripQuotes( d->textForToken( d->lexer->token( node->value ) ) );\n\n Private::Reference ref = { d->currentObject, d->currentPropertyName, type, reference };\n d->references.append( ref );\n\n d->currentPropertyValue = QVariant();\n}\n\nvoid ObjectTreeBuilder::visitList_type(GDL::List_typeAst* node)\n{\n qDebug(\"TODO: Implement list type\");\n}\n\nQString ObjectTreeBuilder::Private::textForToken(KDevPG::Token token)\n{\n return content.mid(token.begin, token.end - token.begin + 1);\n}\n\nQString ObjectTreeBuilder::Private::stripQuotes(const QString& input)\n{\n QString retval = input;\n if(retval.at(0) == '\"')\n retval = retval.remove(0, 1);\n if(retval.at(retval.size() - 1) == '\"')\n retval = retval.remove(retval.size() - 1, 1);\n return retval;\n}\n<|endoftext|>"} {"text":"\/*\nCopyright (c) 2019 - 2021 Advanced Micro Devices, Inc. All rights reserved.\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANNTY OF ANY KIND, EXPRESS OR\nIMPLIED, INNCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANNY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER INN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR INN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n\/\/ Simple test for hipLaunchCooperativeKernelMultiDevice API.\n\n\/* HIT_START\n * BUILD: %t %s ..\/..\/test_common.cpp NVCC_OPTIONS --std=c++11 -rdc=true -gencode arch=compute_70,code=sm_70 -gencode arch=compute_80,code=sm_80\n * TEST: %t\n * HIT_END\n *\/\n\n#include \"hip\/hip_runtime.h\"\n#include \"hip\/hip_runtime_api.h\"\n#include \n#include \n#include \n#include \n#include \n#include \"hip\/hip_cooperative_groups.h\"\n#include \"test_common.h\"\n\nusing namespace std::chrono;\n\nconst static uint BufferSizeInDwords = 256 * 1024 * 1024;\nconst static uint numQueues = 4;\nconst static uint numIter = 100;\nconstexpr uint NumKernelArgs = 4;\nconstexpr uint MaxGPUs = 8;\n\n#include \n\n__global__ void test_gws(uint* buf, uint bufSize, long* tmpBuf, long* result)\n{\n extern __shared__ long tmp[];\n uint groups = gridDim.x;\n uint group_id = blockIdx.x;\n uint local_id = threadIdx.x;\n uint chunk = gridDim.x * blockDim.x;\n\n uint i = group_id * blockDim.x + local_id;\n long sum = 0;\n while (i < bufSize) {\n sum += buf[i];\n i += chunk;\n }\n tmp[local_id] = sum;\n __syncthreads();\n i = 0;\n if (local_id == 0) {\n sum = 0;\n while (i < blockDim.x) {\n sum += tmp[i];\n i++;\n }\n tmpBuf[group_id] = sum;\n }\n\n \/\/ wait\n cooperative_groups::this_grid().sync();\n\n if (((blockIdx.x * blockDim.x) + threadIdx.x) == 0) {\n for (uint i = 1; i < groups; ++i) {\n sum += tmpBuf[i];\n }\n \/\/*result = sum;\n result[1 + cooperative_groups::this_multi_grid().grid_rank()] = sum;\n }\n cooperative_groups::this_multi_grid().sync();\n if (cooperative_groups::this_multi_grid().grid_rank() == 0) {\n sum = 0;\n for (uint i = 1; i <= cooperative_groups::this_multi_grid().num_grids(); ++i) {\n sum += result[i];\n }\n *result = sum;\n }\n}\n\nint main() {\n float *A, *B;\n uint* dA[MaxGPUs];\n long* dB[MaxGPUs];\n long* dC;\n hipStream_t stream[MaxGPUs];\n\n uint32_t* init = new uint32_t[BufferSizeInDwords];\n for (uint32_t i = 0; i < BufferSizeInDwords; ++i) {\n init[i] = i;\n }\n\n int nGpu = 0;\n HIPCHECK(hipGetDeviceCount(&nGpu));\n size_t copySizeInDwords = BufferSizeInDwords \/ nGpu;\n hipDeviceProp_t deviceProp[MaxGPUs];\n\n for (int i = 0; i < nGpu; i++) {\n HIPCHECK(hipSetDevice(i));\n\n \/\/ Calculate the device occupancy to know how many blocks can be run concurrently\n hipGetDeviceProperties(&deviceProp[i], 0);\n if (!deviceProp[i].cooperativeMultiDeviceLaunch) {\n printf(\"Device doesn't support cooperative launch!\");\n passed();\n return 0;\n }\n size_t SIZE = copySizeInDwords * sizeof(uint);\n\n HIPCHECK(hipMalloc((void**)&dA[i], SIZE));\n HIPCHECK(hipMalloc((void**)&dB[i], 64 * deviceProp[i].multiProcessorCount * sizeof(long)));\n if (i == 0) {\n HIPCHECK(hipHostMalloc((void**)&dC, (nGpu + 1) * sizeof(long)));\n }\n HIPCHECK(hipMemcpy(dA[i], &init[i * copySizeInDwords] , SIZE, hipMemcpyHostToDevice));\n HIPCHECK(hipStreamCreate(&stream[i]));\n hipDeviceSynchronize();\n }\n\n dim3 dimBlock;\n dim3 dimGrid;\n dimGrid.x = 1;\n dimGrid.y = 1;\n dimGrid.z = 1;\n dimBlock.x = 64;\n dimBlock.y = 1;\n dimBlock.z = 1;\n\n int numBlocks = 0;\n uint workgroups[3] = {64, 128, 256};\n\n hipLaunchParams* launchParamsList = new hipLaunchParams[nGpu];\n std::time_t end_time;\n double time = 0;\n for (uint set = 0; set < 3; ++set) {\n void* args[MaxGPUs * NumKernelArgs];\n std::cout << \"---------- Test#\" << set << \", size: \"<< BufferSizeInDwords <<\n \" dwords ---------------\\n\";\n for (int i = 0; i < nGpu; i++) {\n HIPCHECK(hipSetDevice(i));\n dimBlock.x = workgroups[set];\n HIPCHECK(hipOccupancyMaxActiveBlocksPerMultiprocessor(&numBlocks,\n test_gws, dimBlock.x * dimBlock.y * dimBlock.z, dimBlock.x * sizeof(long)));\n\n std::cout << \"GPU(\" << i << \") Block size: \" << dimBlock.x <<\n \" Num blocks per CU: \" << numBlocks << \"\\n\";\n\n dimGrid.x = deviceProp[i].multiProcessorCount * std::min(numBlocks, 32);\n\n args[i * NumKernelArgs] = (void*)&dA[i];\n args[i * NumKernelArgs + 1] = (void*)©SizeInDwords;\n args[i * NumKernelArgs + 2] = (void*)&dB[i];\n args[i * NumKernelArgs + 3] = (void*)&dC;\n\n launchParamsList[i].func = reinterpret_cast(test_gws);\n launchParamsList[i].gridDim = dimGrid;\n launchParamsList[i].blockDim = dimBlock;\n launchParamsList[i].sharedMem = dimBlock.x * sizeof(long);\n launchParamsList[i].stream = stream[i];\n launchParamsList[i].args = &args[i * NumKernelArgs];\n }\n\n system_clock::time_point start = system_clock::now();\n hipLaunchCooperativeKernelMultiDevice(launchParamsList, nGpu, 0);\n for (int i = 0; i < nGpu; i++) {\n hipStreamSynchronize(stream[i]);\n }\n system_clock::time_point end = system_clock::now();\n std::chrono::duration elapsed_seconds = end - start;\n end_time = std::chrono::system_clock::to_time_t(end);\n\n time += elapsed_seconds.count();\n\n size_t processedDwords = copySizeInDwords * nGpu;\n if (*dC != (((long)(processedDwords) * (processedDwords - 1)) \/ 2)) {\n std::cout << \"Data validation failed (\"<< *dC << \" != \" <<\n (((long)(BufferSizeInDwords) * (BufferSizeInDwords - 1)) \/ 2) <<\n \") for grid size = \" << dimGrid.x << \" and block size = \" << dimBlock.x << \"\\n\";\n std::cout << \"Test failed! \\n\";\n }\n }\n\n delete [] launchParamsList;\n\n std::cout << \"finished computation at \" << std::ctime(&end_time) <<\n \"elapsed time: \" << time << \"s\\n\";\n\n hipSetDevice(0);\n hipFree(dC);\n for (int i = 0; i < nGpu; i++) {\n hipFree(dA[i]);\n hipFree(dB[i]);\n HIPCHECK(hipStreamDestroy(stream[i]));\n }\n delete [] init;\n passed();\n return 0;\n}\nSWDEV-312700 - Fixing memory corruption at the test. (#3026)\/*\nCopyright (c) 2019 - 2021 Advanced Micro Devices, Inc. All rights reserved.\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANNTY OF ANY KIND, EXPRESS OR\nIMPLIED, INNCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANNY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER INN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR INN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n\/\/ Simple test for hipLaunchCooperativeKernelMultiDevice API.\n\n\/* HIT_START\n * BUILD: %t %s ..\/..\/test_common.cpp NVCC_OPTIONS --std=c++11 -rdc=true -gencode arch=compute_70,code=sm_70 -gencode arch=compute_80,code=sm_80\n * TEST: %t\n * HIT_END\n *\/\n\n#include \"hip\/hip_runtime.h\"\n#include \"hip\/hip_runtime_api.h\"\n#include \n#include \n#include \n#include \n#include \n#include \"hip\/hip_cooperative_groups.h\"\n#include \"test_common.h\"\n\nusing namespace std::chrono;\n\nconst static uint BufferSizeInDwords = 256 * 1024 * 1024;\nconst static uint numQueues = 4;\nconst static uint numIter = 100;\nconstexpr uint NumKernelArgs = 4;\n\n#include \n\n__global__ void test_gws(uint* buf, uint bufSize, long* tmpBuf, long* result)\n{\n extern __shared__ long tmp[];\n uint groups = gridDim.x;\n uint group_id = blockIdx.x;\n uint local_id = threadIdx.x;\n uint chunk = gridDim.x * blockDim.x;\n\n uint i = group_id * blockDim.x + local_id;\n long sum = 0;\n while (i < bufSize) {\n sum += buf[i];\n i += chunk;\n }\n tmp[local_id] = sum;\n __syncthreads();\n i = 0;\n if (local_id == 0) {\n sum = 0;\n while (i < blockDim.x) {\n sum += tmp[i];\n i++;\n }\n tmpBuf[group_id] = sum;\n }\n\n \/\/ wait\n cooperative_groups::this_grid().sync();\n\n if (((blockIdx.x * blockDim.x) + threadIdx.x) == 0) {\n for (uint i = 1; i < groups; ++i) {\n sum += tmpBuf[i];\n }\n \/\/*result = sum;\n result[1 + cooperative_groups::this_multi_grid().grid_rank()] = sum;\n }\n cooperative_groups::this_multi_grid().sync();\n if (cooperative_groups::this_multi_grid().grid_rank() == 0) {\n sum = 0;\n for (uint i = 1; i <= cooperative_groups::this_multi_grid().num_grids(); ++i) {\n sum += result[i];\n }\n *result = sum;\n }\n}\n\nint main() {\n float *A, *B;\n long* dC;\n\n uint32_t* init = new uint32_t[BufferSizeInDwords];\n for (uint32_t i = 0; i < BufferSizeInDwords; ++i) {\n init[i] = i;\n }\n\n int nGpu = 0;\n HIPCHECK(hipGetDeviceCount(&nGpu));\n size_t copySizeInDwords = BufferSizeInDwords \/ nGpu;\n\n uint* dA[nGpu];\n long* dB[nGpu];\n hipStream_t stream[nGpu];\n hipDeviceProp_t deviceProp[nGpu];\n\n for (int i = 0; i < nGpu; i++) {\n HIPCHECK(hipSetDevice(i));\n\n \/\/ Calculate the device occupancy to know how many blocks can be run concurrently\n hipGetDeviceProperties(&deviceProp[i], 0);\n if (!deviceProp[i].cooperativeMultiDeviceLaunch) {\n printf(\"Device doesn't support cooperative launch!\");\n passed();\n return 0;\n }\n size_t SIZE = copySizeInDwords * sizeof(uint);\n\n HIPCHECK(hipMalloc((void**)&dA[i], SIZE));\n HIPCHECK(hipMalloc((void**)&dB[i], 64 * deviceProp[i].multiProcessorCount * sizeof(long)));\n if (i == 0) {\n HIPCHECK(hipHostMalloc((void**)&dC, (nGpu + 1) * sizeof(long)));\n }\n HIPCHECK(hipMemcpy(dA[i], &init[i * copySizeInDwords] , SIZE, hipMemcpyHostToDevice));\n HIPCHECK(hipStreamCreate(&stream[i]));\n hipDeviceSynchronize();\n }\n\n dim3 dimBlock;\n dim3 dimGrid;\n dimGrid.x = 1;\n dimGrid.y = 1;\n dimGrid.z = 1;\n dimBlock.x = 64;\n dimBlock.y = 1;\n dimBlock.z = 1;\n\n int numBlocks = 0;\n uint workgroups[3] = {64, 128, 256};\n\n hipLaunchParams* launchParamsList = new hipLaunchParams[nGpu];\n std::time_t end_time;\n double time = 0;\n for (uint set = 0; set < 3; ++set) {\n void* args[nGpu * NumKernelArgs];\n std::cout << \"---------- Test#\" << set << \", size: \"<< BufferSizeInDwords <<\n \" dwords ---------------\\n\";\n for (int i = 0; i < nGpu; i++) {\n HIPCHECK(hipSetDevice(i));\n dimBlock.x = workgroups[set];\n HIPCHECK(hipOccupancyMaxActiveBlocksPerMultiprocessor(&numBlocks,\n test_gws, dimBlock.x * dimBlock.y * dimBlock.z, dimBlock.x * sizeof(long)));\n\n std::cout << \"GPU(\" << i << \") Block size: \" << dimBlock.x <<\n \" Num blocks per CU: \" << numBlocks << \"\\n\";\n\n dimGrid.x = deviceProp[i].multiProcessorCount * std::min(numBlocks, 32);\n\n args[i * NumKernelArgs] = (void*)&dA[i];\n args[i * NumKernelArgs + 1] = (void*)©SizeInDwords;\n args[i * NumKernelArgs + 2] = (void*)&dB[i];\n args[i * NumKernelArgs + 3] = (void*)&dC;\n\n launchParamsList[i].func = reinterpret_cast(test_gws);\n launchParamsList[i].gridDim = dimGrid;\n launchParamsList[i].blockDim = dimBlock;\n launchParamsList[i].sharedMem = dimBlock.x * sizeof(long);\n launchParamsList[i].stream = stream[i];\n launchParamsList[i].args = &args[i * NumKernelArgs];\n }\n\n system_clock::time_point start = system_clock::now();\n hipLaunchCooperativeKernelMultiDevice(launchParamsList, nGpu, 0);\n for (int i = 0; i < nGpu; i++) {\n hipStreamSynchronize(stream[i]);\n }\n system_clock::time_point end = system_clock::now();\n std::chrono::duration elapsed_seconds = end - start;\n end_time = std::chrono::system_clock::to_time_t(end);\n\n time += elapsed_seconds.count();\n\n size_t processedDwords = copySizeInDwords * nGpu;\n if (*dC != (((long)(processedDwords) * (processedDwords - 1)) \/ 2)) {\n std::cout << \"Data validation failed (\"<< *dC << \" != \" <<\n (((long)(BufferSizeInDwords) * (BufferSizeInDwords - 1)) \/ 2) <<\n \") for grid size = \" << dimGrid.x << \" and block size = \" << dimBlock.x << \"\\n\";\n std::cout << \"Test failed! \\n\";\n }\n }\n\n delete [] launchParamsList;\n\n std::cout << \"finished computation at \" << std::ctime(&end_time) <<\n \"elapsed time: \" << time << \"s\\n\";\n\n hipSetDevice(0);\n hipFree(dC);\n for (int i = 0; i < nGpu; i++) {\n hipFree(dA[i]);\n hipFree(dB[i]);\n HIPCHECK(hipStreamDestroy(stream[i]));\n }\n\n delete [] init;\n passed();\n return 0;\n}\n<|endoftext|>"} {"text":"\n#include \"..\/MultiTokenizer.h\"\n#include \"..\/Stemmer.h\"\n\n#include \n\nusing namespace std;\n\nenum {\n\tDISKERROR_STEM_RETURN_ARRAY = 1,\n\tDISKERROR_STEM_RETURN_BIGRAM\n};\n\n\nPhp::Value stem(Php::Parameters ¶ms)\n{\n static MultiTokenizer tokenizer;\n \n string p = params[0];\n\ttokenizer.SetText(p);\n\tint prefs = 0;\n\t\n\tif ( params.size() > 1 ) {\n\t\tprefs = (long) params[1];\n\t}\n\t\n\tstring outputText, token, thisOne, lastOne;\n\tPhp::Array outputArray;\n\tint i = 0;\n\tPhp::Value outputData;\n\t\n switch ( prefs ) {\n \tcase 0:\n\t\twhile( (token = tokenizer.Get()) != \"\" ) {\n\t\t\toutputText += Stemmer::StemWord(token) + \" \";\n\t\t}\n\t\t\n\t\tif ( outputText.size() ) {\n\t\t\toutputText.pop_back();\t\/\/\tremove extra space at end if not empty\n\t\t}\n\t\t\n\t\toutputData = outputText;\n \tbreak;\n \t\n \t\n \tcase DISKERROR_STEM_RETURN_ARRAY:\n\t\twhile( (token = tokenizer.Get()) != \"\" ) {\n\t\t\toutputArray[i++] = Stemmer::StemWord(token);\n\t\t}\n\t\toutputData = outputArray;\n \tbreak;\n \t\n \t\n \tcase DISKERROR_STEM_RETURN_BIGRAM:\n\t\twhile( (token = tokenizer.Get()) != \"\" ) {\n\t\t\tthisOne = Stemmer::StemWord(token);\n\t\t\toutputText += (lastOne + thisOne + \" \");\n\t\t\tlastOne = thisOne;\n\t\t}\n\t\toutputText += lastOne;\n\t\toutputData = outputText;\n \tbreak;\n \t\n \t\n \tcase DISKERROR_STEM_RETURN_ARRAY|DISKERROR_STEM_RETURN_BIGRAM:\n\t\twhile( (token = tokenizer.Get()) != \"\" ) {\n\t\t\tthisOne = Stemmer::StemWord(token);\n\t\t\toutputArray[i++] = (lastOne + thisOne);\n\t\t\tlastOne = thisOne;\n\t\t}\n\t\toutputArray[i] = lastOne;\n\t\toutputData = outputArray;\n \tbreak;\n }\n \n return outputData;\n}\n\n\nextern \"C\" {\n \n \/**\n * Function that is called by PHP right after the PHP process\n * has started, and that returns an address of an internal PHP\n * strucure with all the details and features of your extension\n *\n * @return void* a pointer to an address that is understood by PHP\n *\/\n PHPCPP_EXPORT void *get_module() \n {\n \/\/ static(!) Php::Extension object that should stay in memory\n \/\/ for the entire duration of the process (that's why it's static)\n static Php::Extension extension(\"diskerror_stem\", \"0.3\");\n \n extension.add(Php::Constant(\"DISKERROR_STEM_RETURN_ARRAY\", DISKERROR_STEM_RETURN_ARRAY));\n extension.add(Php::Constant(\"DISKERROR_STEM_RETURN_BIGRAM\", DISKERROR_STEM_RETURN_BIGRAM));\n \n\/\/ extension.add( \"Diskerror\\\\Stem\", stem, {\n\/\/ \tPhp::ByVal(\"subject\", Php::Type::String),\n\/\/ \tPhp::ByVal(\"options\", Php::Type::Numeric, false)\n\/\/ } );\n\t\textension.add( \"Diskerror\\\\Stem\" );\n\n \/\/ return the extension\n return extension;\n }\n}\nversion bump\n#include \"..\/MultiTokenizer.h\"\n#include \"..\/Stemmer.h\"\n\n#include \n\nusing namespace std;\n\nenum {\n\tDISKERROR_STEM_RETURN_ARRAY = 1,\n\tDISKERROR_STEM_RETURN_BIGRAM\n};\n\n\nPhp::Value stem(Php::Parameters ¶ms)\n{\n static MultiTokenizer tokenizer;\n \n string p = params[0];\n\ttokenizer.SetText(p);\n\tint prefs = 0;\n\t\n\tif ( params.size() > 1 ) {\n\t\tprefs = (long) params[1];\n\t}\n\t\n\tstring outputText, token, thisOne, lastOne;\n\tPhp::Array outputArray;\n\tint i = 0;\n\tPhp::Value outputData;\n\t\n switch ( prefs ) {\n \tcase 0:\n\t\twhile( (token = tokenizer.Get()) != \"\" ) {\n\t\t\toutputText += Stemmer::StemWord(token) + \" \";\n\t\t}\n\t\t\n\t\tif ( outputText.size() ) {\n\t\t\toutputText.pop_back();\t\/\/\tremove extra space at end if not empty\n\t\t}\n\t\t\n\t\toutputData = outputText;\n \tbreak;\n \t\n \t\n \tcase DISKERROR_STEM_RETURN_ARRAY:\n\t\twhile( (token = tokenizer.Get()) != \"\" ) {\n\t\t\toutputArray[i++] = Stemmer::StemWord(token);\n\t\t}\n\t\toutputData = outputArray;\n \tbreak;\n \t\n \t\n \tcase DISKERROR_STEM_RETURN_BIGRAM:\n\t\twhile( (token = tokenizer.Get()) != \"\" ) {\n\t\t\tthisOne = Stemmer::StemWord(token);\n\t\t\toutputText += (lastOne + thisOne + \" \");\n\t\t\tlastOne = thisOne;\n\t\t}\n\t\toutputText += lastOne;\n\t\toutputData = outputText;\n \tbreak;\n \t\n \t\n \tcase DISKERROR_STEM_RETURN_ARRAY|DISKERROR_STEM_RETURN_BIGRAM:\n\t\twhile( (token = tokenizer.Get()) != \"\" ) {\n\t\t\tthisOne = Stemmer::StemWord(token);\n\t\t\toutputArray[i++] = (lastOne + thisOne);\n\t\t\tlastOne = thisOne;\n\t\t}\n\t\toutputArray[i] = lastOne;\n\t\toutputData = outputArray;\n \tbreak;\n }\n \n return outputData;\n}\n\n\nextern \"C\" {\n \n \/**\n * Function that is called by PHP right after the PHP process\n * has started, and that returns an address of an internal PHP\n * strucure with all the details and features of your extension\n *\n * @return void* a pointer to an address that is understood by PHP\n *\/\n PHPCPP_EXPORT void *get_module() \n {\n \/\/ static(!) Php::Extension object that should stay in memory\n \/\/ for the entire duration of the process (that's why it's static)\n static Php::Extension extension(\"diskerror_stem\", \"0.4\");\n \n extension.add(Php::Constant(\"DISKERROR_STEM_RETURN_ARRAY\", DISKERROR_STEM_RETURN_ARRAY));\n extension.add(Php::Constant(\"DISKERROR_STEM_RETURN_BIGRAM\", DISKERROR_STEM_RETURN_BIGRAM));\n \n\/\/ extension.add( \"Diskerror\\\\Stem\", stem, {\n\/\/ \tPhp::ByVal(\"subject\", Php::Type::String),\n\/\/ \tPhp::ByVal(\"options\", Php::Type::Numeric, false)\n\/\/ } );\n\t\textension.add( \"Diskerror\\\\Stem\" );\n\n \/\/ return the extension\n return extension;\n }\n}\n<|endoftext|>"} {"text":"\/\/ =============================================================================\n\/\/ PROJECT CHRONO - http:\/\/projectchrono.org\n\/\/\n\/\/ Copyright (c) 2014 projectchrono.org\n\/\/ All right reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style license that can be found\n\/\/ in the LICENSE file at the top level of the distribution and at\n\/\/ http:\/\/projectchrono.org\/license-chrono.txt.\n\/\/\n\/\/ =============================================================================\n\/\/ Authors: Radu Serban\n\/\/ =============================================================================\n\/\/\n\/\/ Base class for a tire.\n\/\/ A tire subsystem is a force element. It is passed position and velocity\n\/\/ information of the wheel body and it produces ground reaction forces and\n\/\/ moments to be applied to the wheel body.\n\/\/\n\/\/ =============================================================================\n\n#include \"core\/ChMatrix33.h\"\n\n#include \"subsys\/ChTire.h\"\n\n\nnamespace chrono {\n\n\nChTire::ChTire(const ChTerrain& terrain)\n: m_terrain(terrain)\n{\n}\n\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Utility function for characterizing the geometric contact between a disc with\n\/\/ specified center location, normal direction, and radius and the terrain,\n\/\/ assumed to be specified as a height field (over the x-y domain).\n\/\/ This function returns false if no contact occurs. Otherwise, it sets the\n\/\/ contact points on the disc (ptD) and on the terrain (ptT), the normal contact\n\/\/ direction, and the resulting penetration depth (a positive value).\n\/\/ -----------------------------------------------------------------------------\nbool ChTire::disc_terrain_contact(const ChVector<>& disc_center,\n const ChVector<>& disc_normal,\n double disc_radius,\n ChCoordsys<>& contact,\n double& depth)\n{\n \/\/ Find terrain height below disc center. There is no contact if the disc\n \/\/ center is below the terrain or farther away by more than its radius.\n double hc = m_terrain.GetHeight(disc_center.x, disc_center.y);\n if (disc_center.z <= hc || disc_center.z >= hc + disc_radius)\n return false;\n\n \/\/ Find the lowest point on the disc. There is no contact if the disc is\n \/\/ (almost) horizontal.\n ChVector<> dir1 = Vcross(disc_normal, ChVector<>(0, 0, 1));\n double sinTilt2 = dir1.Length2();\n\n if (sinTilt2 < 1e-3)\n return false;\n\n \/\/ Contact point (lowest point on disc).\n ChVector<> ptD = disc_center + disc_radius * Vcross(disc_normal, dir1 \/ sqrt(sinTilt2));\n\n \/\/ Find terrain height at lowest point. No contact if lowest point is above\n \/\/ the terrain.\n double hp = m_terrain.GetHeight(ptD.x, ptD.y);\n\n if (ptD.z > hp)\n return false;\n\n \/\/ Approximate the terrain with a plane. Define the projection of the lowest\n \/\/ point onto this plane as the contact point on the terrain.\n ChVector<> normal = m_terrain.GetNormal(ptD.x, ptD.y);\n ChVector<> longitudinal = Vcross(disc_normal, normal);\n longitudinal.Normalize();\n ChVector<> lateral = Vcross(normal, longitudinal);\n ChMatrix33<> rot;\n rot.Set_A_axis(longitudinal, lateral, normal);\n\n contact.pos = ptD;\n contact.rot = rot.Get_A_quaternion();\n\n depth = Vdot(ChVector<>(0, 0, hp - ptD.z), normal);\n assert(depth > 0);\n\n return true;\n}\n\n\n} \/\/ end namespace chrono\nfixes a linking error for compiling with VS 2012\/\/ =============================================================================\n\/\/ PROJECT CHRONO - http:\/\/projectchrono.org\n\/\/\n\/\/ Copyright (c) 2014 projectchrono.org\n\/\/ All right reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style license that can be found\n\/\/ in the LICENSE file at the top level of the distribution and at\n\/\/ http:\/\/projectchrono.org\/license-chrono.txt.\n\/\/\n\/\/ =============================================================================\n\/\/ Authors: Radu Serban\n\/\/ =============================================================================\n\/\/\n\/\/ Base class for a tire.\n\/\/ A tire subsystem is a force element. It is passed position and velocity\n\/\/ information of the wheel body and it produces ground reaction forces and\n\/\/ moments to be applied to the wheel body.\n\/\/\n\/\/ =============================================================================\n\n#include \"physics\/ChSystem.h\"\n\n#include \"subsys\/ChTire.h\"\n\n\nnamespace chrono {\n\n\nChTire::ChTire(const ChTerrain& terrain)\n: m_terrain(terrain)\n{\n}\n\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Utility function for characterizing the geometric contact between a disc with\n\/\/ specified center location, normal direction, and radius and the terrain,\n\/\/ assumed to be specified as a height field (over the x-y domain).\n\/\/ This function returns false if no contact occurs. Otherwise, it sets the\n\/\/ contact points on the disc (ptD) and on the terrain (ptT), the normal contact\n\/\/ direction, and the resulting penetration depth (a positive value).\n\/\/ -----------------------------------------------------------------------------\nbool ChTire::disc_terrain_contact(const ChVector<>& disc_center,\n const ChVector<>& disc_normal,\n double disc_radius,\n ChCoordsys<>& contact,\n double& depth)\n{\n \/\/ Find terrain height below disc center. There is no contact if the disc\n \/\/ center is below the terrain or farther away by more than its radius.\n double hc = m_terrain.GetHeight(disc_center.x, disc_center.y);\n if (disc_center.z <= hc || disc_center.z >= hc + disc_radius)\n return false;\n\n \/\/ Find the lowest point on the disc. There is no contact if the disc is\n \/\/ (almost) horizontal.\n ChVector<> dir1 = Vcross(disc_normal, ChVector<>(0, 0, 1));\n double sinTilt2 = dir1.Length2();\n\n if (sinTilt2 < 1e-3)\n return false;\n\n \/\/ Contact point (lowest point on disc).\n ChVector<> ptD = disc_center + disc_radius * Vcross(disc_normal, dir1 \/ sqrt(sinTilt2));\n\n \/\/ Find terrain height at lowest point. No contact if lowest point is above\n \/\/ the terrain.\n double hp = m_terrain.GetHeight(ptD.x, ptD.y);\n\n if (ptD.z > hp)\n return false;\n\n \/\/ Approximate the terrain with a plane. Define the projection of the lowest\n \/\/ point onto this plane as the contact point on the terrain.\n ChVector<> normal = m_terrain.GetNormal(ptD.x, ptD.y);\n ChVector<> longitudinal = Vcross(disc_normal, normal);\n longitudinal.Normalize();\n ChVector<> lateral = Vcross(normal, longitudinal);\n ChMatrix33<> rot;\n rot.Set_A_axis(longitudinal, lateral, normal);\n\n contact.pos = ptD;\n contact.rot = rot.Get_A_quaternion();\n\n depth = Vdot(ChVector<>(0, 0, hp - ptD.z), normal);\n assert(depth > 0);\n\n return true;\n}\n\n\n} \/\/ end namespace chrono\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2014 The Caroline authors. All rights reserved.\n\/\/ Use of this source file is governed by a MIT license that can be found in the\n\/\/ LICENSE file.\n\/\/ Author: Aleksandr Derbenev <13alexac@gmail.com>\n\n#include \"core\/optical_flow_processor.h\"\n\n#include \n\n#include \"base\/values.h\"\n#include \"core\/config.h\"\n\nnamespace core {\n\nnamespace {\n\nconst char kOpticalFlowNode[] = \"optical-flow\";\nconst char kAlgorithmNameNode[] = \"algorithm\";\nconst char kLucasKanadeAlgorithmName[] = \"lucas-kanade\";\nconst char kFarnebackAlgorithmName[] = \"farneback\";\n\n} \/\/ namespace\n\n\/\/ static\nstd::unique_ptr\nOpticalFlowProcessor::Create(const Config* config) {\n if (!config)\n return std::unique_ptr();\n\n auto dictionary = config->dictionary();\n if (!dictionary)\n return std::unique_ptr();\n\n auto settings =\n base::ToDictionary(dictionary->GetValue(kOpticalFlowNode));\n if (!settings)\n return std::unique_ptr();\n\n auto algorithm_node = base::ToString(settings->GetValue(kAlgorithmNameNode));\n if (algorithm_node) {\n std::string algorithm_name = algorithm_node->value();\n\n if (kLucasKanadeAlgorithmName == algorithm_name) {\n \/\/ return LucasKanadeOpticalFrowProcessor::Create(settings);\n }\n\n if (kFarnebackAlgorithmName == algorithm_name) {\n \/\/ return FarnebackOpticalFlowProcessor::Create(settings);\n }\n }\n\n \/\/ There is no matched algorithm. Return empty pointer.\n return std::unique_ptr();\n}\n\n} \/\/ namespace core\n#46: Enabled FarnebackOpticalFlowProcessor\/\/ Copyright (c) 2014 The Caroline authors. All rights reserved.\n\/\/ Use of this source file is governed by a MIT license that can be found in the\n\/\/ LICENSE file.\n\/\/ Author: Aleksandr Derbenev <13alexac@gmail.com>\n\n#include \"core\/optical_flow_processor.h\"\n\n#include \n\n#include \"core\/farneback_optical_flow_processor.h\"\n\n#include \"base\/values.h\"\n#include \"core\/config.h\"\n\nnamespace core {\n\nnamespace {\n\nconst char kOpticalFlowNode[] = \"optical-flow\";\nconst char kAlgorithmNameNode[] = \"algorithm\";\nconst char kLucasKanadeAlgorithmName[] = \"lucas-kanade\";\nconst char kFarnebackAlgorithmName[] = \"farneback\";\n\n} \/\/ namespace\n\n\/\/ static\nstd::unique_ptr\nOpticalFlowProcessor::Create(const Config* config) {\n if (!config)\n return std::unique_ptr();\n\n auto dictionary = config->dictionary();\n if (!dictionary)\n return std::unique_ptr();\n\n auto settings =\n base::ToDictionary(dictionary->GetValue(kOpticalFlowNode));\n if (!settings)\n return std::unique_ptr();\n\n auto algorithm_node = base::ToString(settings->GetValue(kAlgorithmNameNode));\n if (algorithm_node) {\n std::string algorithm_name = algorithm_node->value();\n\n if (kLucasKanadeAlgorithmName == algorithm_name) {\n \/\/ return LucasKanadeOpticalFrowProcessor::Create(settings);\n }\n\n if (kFarnebackAlgorithmName == algorithm_name) {\n return FarnebackOpticalFlowProcessor::Create(settings);\n }\n }\n\n \/\/ There is no matched algorithm. Return empty pointer.\n return std::unique_ptr();\n}\n\n} \/\/ namespace core\n<|endoftext|>"} {"text":"\/*! \\file Mesh.cpp\n * \\author Jared Hoberock\n * \\brief Implementation of Mesh class.\n *\/\n\n#include \"Mesh.h\"\n#include \"..\/geometry\/Normal.h\"\n#include <2dmapping\/UnitSquareToTriangle.h>\n\nMesh\n ::Mesh(const std::vector &vertices,\n const std::vector &triangles)\n :Parent0(vertices,triangles),Parent1()\n{\n buildWaldBikkerData();\n buildTree();\n buildTriangleTable();\n mSurfaceArea = computeSurfaceArea();\n mOneOverSurfaceArea = 1.0f \/ mSurfaceArea;\n} \/\/ end Mesh::Mesh()\n\nMesh\n ::Mesh(const std::vector &vertices,\n const std::vector ¶metrics,\n const std::vector &triangles)\n :Parent0(vertices,parametrics,triangles),Parent1()\n{\n buildWaldBikkerData();\n buildTree();\n buildTriangleTable();\n mSurfaceArea = computeSurfaceArea();\n mOneOverSurfaceArea = 1.0f \/ mSurfaceArea;\n} \/\/ end Mesh::Mesh()\n\nMesh\n ::~Mesh(void)\n{\n ;\n} \/\/ end Mesh::~Mesh()\n\nbool Mesh\n ::intersect(const Ray &r) const\n{\n \/\/ create a TriangleShadower\n TriangleShadower shadower = {this};\n return mTree.shadow(r.getAnchor(), r.getDirection(), r.getInterval()[0], r.getInterval()[1], shadower);\n} \/\/ end Mesh::intersect()\n\nbool Mesh\n ::intersect(const Ray &r, float &t, DifferentialGeometry &dg) const\n{\n \/\/ create a TriangleIntersector\n TriangleIntersector intersector;\n intersector.init();\n intersector.mMesh = this;\n\n if(mTree.intersect(r.getAnchor(), r.getDirection(),\n r.getInterval()[0], r.getInterval()[1],\n intersector))\n {\n t = intersector.mT;\n const Triangle &tri = *intersector.mHitFace;\n\n \/\/ fill out DifferentialGeometry details\n Vector3 e1 = mPoints[tri[1]] - mPoints[tri[0]];\n Vector3 e2 = mPoints[tri[2]] - mPoints[tri[0]];\n getDifferentialGeometry(tri, r(t), e1.cross(e2).normalize(),\n intersector.mBarycentricCoordinates[0],\n intersector.mBarycentricCoordinates[1],\n dg);\n return true;\n } \/\/ end if\n\n return false;\n} \/\/ end Mesh::intersect()\n\nfloat Mesh::TriangleBounder\n ::operator()(unsigned int axis, bool min, const Triangle *t)\n{\n float result = std::numeric_limits::infinity();\n if(!min) result = -result;\n\n \/\/ iterate through each adjacent vertex & pick the minimal\/maximal\n const PointList &points = mMesh->getPoints();\n\n for(unsigned int i = 0; i < 3; ++i)\n {\n const Point &pos = points[(*t)[i]];\n\n if(min)\n {\n if(pos[axis] < result) result = pos[axis];\n } \/\/ end if\n else\n {\n if(pos[axis] > result) result = pos[axis];\n } \/\/ end else\n } \/\/ end for i\n\n return result;\n} \/\/ end Mesh::TriangleBounder::operator()()\n\nvoid Mesh\n ::getBoundingBox(BoundingBox &b) const\n{\n b.setEmpty();\n\n \/\/ iterate over positions\n for(PointList::const_iterator p = getPoints().begin();\n p != getPoints().end();\n ++p)\n {\n b.addPoint(*p);\n } \/\/ end for p\n} \/\/ end Mesh::getBoundingBox()\n\nvoid Mesh\n ::buildTree(void)\n{\n TriangleBounder bounder;\n bounder.mMesh = this;\n\n std::vector trianglePointers;\n for(TriangleList::const_iterator t = getTriangles().begin();\n t != getTriangles().end();\n ++t)\n {\n trianglePointers.push_back(&(*t));\n } \/\/ end for t\n\n mTree.buildTree(trianglePointers.begin(), trianglePointers.end(), bounder);\n} \/\/ end Mesh::buildTree()\n\nvoid Mesh\n ::getDifferentialGeometry(const Triangle &tri,\n const Point &p,\n const Normal &ng,\n const float b1,\n const float b2,\n DifferentialGeometry &dg) const\n{\n \/\/ shorthand\n const Point &p1 = mPoints[tri[0]];\n const Point &p2 = mPoints[tri[1]];\n const Point &p3 = mPoints[tri[2]];\n\n Vector e1 = p2 - p1;\n Vector e2 = p3 - p1;\n\n \/\/ compute the last barycentric coordinate\n float b0 = 1.0f - b1 - b2;\n\n \/\/ interpolate normal?\n \/\/if(f[0].mNormalIndex == -1 ||\n \/\/ f[1].mNormalIndex == -1 ||\n \/\/ f[2].mNormalIndex == -1)\n \/\/{\n \/\/} \/\/ end if\n \/\/else\n \/\/{\n \/\/ \/\/ get each vertex's Normals\n \/\/ const Mesh::NormalList &norms = m.getNormals();\n \/\/ const Normal &n1 = norms[f[0].mNormalIndex];\n \/\/ const Normal &n2 = norms[f[1].mNormalIndex];\n \/\/ const Normal &n3 = norms[f[2].mNormalIndex];\n \/\/ n = b0 * n1 + b1 * n2 + b2 * n3;\n \/\/} \/\/ end else\n\n \/\/ normalize it\n \/\/dg.getNormal() = dg.getNormal().normalize();\n\n ParametricCoordinates uv0;\n ParametricCoordinates uv1;\n ParametricCoordinates uv2;\n getParametricCoordinates(tri, uv0, uv1, uv2);\n\n \/\/ compute deltas for partial derivatives\n float du1 = uv0[0] - uv2[0];\n float du2 = uv1[0] - uv2[0];\n float dv1 = uv0[1] - uv2[1];\n float dv2 = uv1[1] - uv2[1];\n Vector dp1 = p1 - p3, dp2 = p2 - p3;\n float determinant = du1 * dv2 - dv1 * du2;\n if(determinant == 0.0)\n {\n \/\/ handle zero determinant case\n dg.getPointPartials()[0] = ng.orthogonalVector();\n dg.getPointPartials()[1] = ng.cross(dg.getPointPartials()[0]).normalize();\n } \/\/ end if\n else\n {\n float invDet = 1.0f \/ determinant;\n dg.getPointPartials()[0] = ( dv2*dp1 - dv1*dp2) * invDet;\n dg.getPointPartials()[1] = (-du2*dp1 + du1*dp2) * invDet;\n } \/\/ end else\n\n \/\/ interpolate uv using barycentric coordinates\n ParametricCoordinates uv;\n uv[0] = b0*uv0[0] + b1*uv1[0] + b2*uv2[0];\n uv[1] = b0*uv0[1] + b1*uv1[1] + b2*uv2[1];\n\n dg.setPoint(p);\n dg.setNormal(ng);\n dg.setParametricCoordinates(uv);\n dg.setTangent(dg.getPointPartials()[0].normalize());\n\n \/\/ force an orthonormal basis\n dg.setBinormal(ng.cross(dg.getTangent()));\n} \/\/ end Mesh::getDifferentialGeometry()\n\nvoid Mesh::TriangleIntersector\n ::init(void)\n{\n mT = std::numeric_limits::infinity();\n mHitFace = 0;\n mMesh = 0;\n} \/\/ end TriangleIntersector::init()\n\nvoid Mesh\n ::buildTriangleTable(void)\n{\n std::vector pointers;\n std::vector area;\n for(TriangleList::const_iterator t = mTriangles.begin();\n t != mTriangles.end();\n ++t)\n {\n pointers.push_back(&(*t));\n area.push_back(Parent0::computeSurfaceArea(*t));\n } \/\/ end for t\n\n mTriangleTable.build(pointers.begin(), pointers.end(),\n area.begin(), area.end());\n} \/\/ end Mesh::buildTriangleTable()\n\nfloat Mesh\n ::computeSurfaceArea(void) const\n{\n float result = 0;\n\n for(TriangleList::const_iterator t = mTriangles.begin();\n t != mTriangles.end();\n ++t)\n {\n result += Parent0::computeSurfaceArea(*t);\n } \/\/ end for t\n\n return result;\n} \/\/ end Mesh::computeSurfaceArea()\n\nvoid Mesh\n ::sampleSurfaceArea(const float u1,\n const float u2,\n const float u3,\n DifferentialGeometry &dg,\n float &pdf) const\n{\n const Triangle &t = *mTriangleTable(u1);\n const Point &v0 = mPoints[t[0]];\n const Point &v1 = mPoints[t[1]];\n const Point &v2 = mPoints[t[2]];\n\n Point p;\n UnitSquareToTriangle::evaluate(u2,u3, v0, v1, v2, p);\n\n \/\/ XXX implement shading normals\n \/\/ XXX implement derivatives\n Normal ng = (v1 - v0).cross(v2 - v0).normalize();\n\n getDifferentialGeometry(t, p, ng, u2, u3, dg);\n\n \/\/ evaluate the pdf\n pdf = evaluateSurfaceAreaPdf(dg);\n} \/\/ end Mesh::sampleSurfaceArea()\n\nfloat Mesh\n ::evaluateSurfaceAreaPdf(const DifferentialGeometry &dg) const\n{\n \/\/ we assume dg is actually on the surface of this Mesh\n return mOneOverSurfaceArea;\n} \/\/ end Mesh::evaluateSurfaceAreaPdf()\n\nfloat Mesh\n ::getSurfaceArea(void) const\n{\n return mSurfaceArea;\n} \/\/ end Mesh::getSurfaceArea()\n\nfloat Mesh\n ::getInverseSurfaceArea(void) const\n{\n return mOneOverSurfaceArea;\n} \/\/ end Mesh::getInverseSurfaceArea()\n\nvoid Mesh\n ::buildWaldBikkerData(void)\n{\n mWaldBikkerTriangleData.clear();\n\n \/\/ see http:\/\/www.devmaster.net\/articles\/raytracing_series\/part7.php for details\n for(size_t i = 0; i < mTriangles.size(); ++i)\n {\n const Triangle &tri = mTriangles[i];\n\n \/\/ compute the triangle's normal\n Vector b = mPoints[tri[2]] - mPoints[tri[0]];\n Vector c = mPoints[tri[1]] - mPoints[tri[0]];\n Normal n = c.cross(b).normalize();\n\n WaldBikkerData data;\n\n \/\/ determine dominant axis\n if(fabsf(n[0]) > fabsf(n[1]))\n {\n if(fabsf(n[0]) > fabsf(n[2])) data.mDominantAxis = 0;\n else data.mDominantAxis = 2;\n } \/\/ end if\n else\n {\n if(fabsf(n[1]) > fabsf(n[2])) data.mDominantAxis = 1;\n else data.mDominantAxis = 2;\n } \/\/ end else\n\n int u = (data.mDominantAxis + 1) % 3;\n int v = (data.mDominantAxis + 2) % 3;\n\n data.mUAxis = u;\n data.mVAxis = v;\n\n data.mN[0] = n.dot(mPoints[tri[0]]) \/ n[data.mDominantAxis];\n data.mN[1] = n[u] \/ n[data.mDominantAxis];\n data.mN[2] = n[v] \/ n[data.mDominantAxis];\n\n float bnu = b[u] \/ (b[u] * c[v] - b[v] * c[u]);\n float bnv = -b[v] \/ (b[u] * c[v] - b[v] * c[u]);\n data.mBn = gpcpu::float2(bnu, bnv);\n\n float cnu = c[v] \/ (b[u] * c[v] - b[v] * c[u]);\n float cnv = -c[u] \/ (b[u] * c[v] - b[v] * c[u]);\n data.mCn = gpcpu::float2(cnu, cnv);\n\n mWaldBikkerTriangleData.push_back(data);\n } \/\/ end for i\n} \/\/ end Mesh::buildWaldBikkerData()\n\nFix bug where we need to send barycentrics rather than unit square coordinates.\/*! \\file Mesh.cpp\n * \\author Jared Hoberock\n * \\brief Implementation of Mesh class.\n *\/\n\n#include \"Mesh.h\"\n#include \"..\/geometry\/Normal.h\"\n#include <2dmapping\/UnitSquareToTriangle.h>\n\nMesh\n ::Mesh(const std::vector &vertices,\n const std::vector &triangles)\n :Parent0(vertices,triangles),Parent1()\n{\n buildWaldBikkerData();\n buildTree();\n buildTriangleTable();\n mSurfaceArea = computeSurfaceArea();\n mOneOverSurfaceArea = 1.0f \/ mSurfaceArea;\n} \/\/ end Mesh::Mesh()\n\nMesh\n ::Mesh(const std::vector &vertices,\n const std::vector ¶metrics,\n const std::vector &triangles)\n :Parent0(vertices,parametrics,triangles),Parent1()\n{\n buildWaldBikkerData();\n buildTree();\n buildTriangleTable();\n mSurfaceArea = computeSurfaceArea();\n mOneOverSurfaceArea = 1.0f \/ mSurfaceArea;\n} \/\/ end Mesh::Mesh()\n\nMesh\n ::~Mesh(void)\n{\n ;\n} \/\/ end Mesh::~Mesh()\n\nbool Mesh\n ::intersect(const Ray &r) const\n{\n \/\/ create a TriangleShadower\n TriangleShadower shadower = {this};\n return mTree.shadow(r.getAnchor(), r.getDirection(), r.getInterval()[0], r.getInterval()[1], shadower);\n} \/\/ end Mesh::intersect()\n\nbool Mesh\n ::intersect(const Ray &r, float &t, DifferentialGeometry &dg) const\n{\n \/\/ create a TriangleIntersector\n TriangleIntersector intersector;\n intersector.init();\n intersector.mMesh = this;\n\n if(mTree.intersect(r.getAnchor(), r.getDirection(),\n r.getInterval()[0], r.getInterval()[1],\n intersector))\n {\n t = intersector.mT;\n const Triangle &tri = *intersector.mHitFace;\n\n \/\/ fill out DifferentialGeometry details\n Vector3 e1 = mPoints[tri[1]] - mPoints[tri[0]];\n Vector3 e2 = mPoints[tri[2]] - mPoints[tri[0]];\n getDifferentialGeometry(tri, r(t), e1.cross(e2).normalize(),\n intersector.mBarycentricCoordinates[0],\n intersector.mBarycentricCoordinates[1],\n dg);\n return true;\n } \/\/ end if\n\n return false;\n} \/\/ end Mesh::intersect()\n\nfloat Mesh::TriangleBounder\n ::operator()(unsigned int axis, bool min, const Triangle *t)\n{\n float result = std::numeric_limits::infinity();\n if(!min) result = -result;\n\n \/\/ iterate through each adjacent vertex & pick the minimal\/maximal\n const PointList &points = mMesh->getPoints();\n\n for(unsigned int i = 0; i < 3; ++i)\n {\n const Point &pos = points[(*t)[i]];\n\n if(min)\n {\n if(pos[axis] < result) result = pos[axis];\n } \/\/ end if\n else\n {\n if(pos[axis] > result) result = pos[axis];\n } \/\/ end else\n } \/\/ end for i\n\n return result;\n} \/\/ end Mesh::TriangleBounder::operator()()\n\nvoid Mesh\n ::getBoundingBox(BoundingBox &b) const\n{\n b.setEmpty();\n\n \/\/ iterate over positions\n for(PointList::const_iterator p = getPoints().begin();\n p != getPoints().end();\n ++p)\n {\n b.addPoint(*p);\n } \/\/ end for p\n} \/\/ end Mesh::getBoundingBox()\n\nvoid Mesh\n ::buildTree(void)\n{\n TriangleBounder bounder;\n bounder.mMesh = this;\n\n std::vector trianglePointers;\n for(TriangleList::const_iterator t = getTriangles().begin();\n t != getTriangles().end();\n ++t)\n {\n trianglePointers.push_back(&(*t));\n } \/\/ end for t\n\n mTree.buildTree(trianglePointers.begin(), trianglePointers.end(), bounder);\n} \/\/ end Mesh::buildTree()\n\nvoid Mesh\n ::getDifferentialGeometry(const Triangle &tri,\n const Point &p,\n const Normal &ng,\n const float b1,\n const float b2,\n DifferentialGeometry &dg) const\n{\n \/\/ shorthand\n const Point &p1 = mPoints[tri[0]];\n const Point &p2 = mPoints[tri[1]];\n const Point &p3 = mPoints[tri[2]];\n\n Vector e1 = p2 - p1;\n Vector e2 = p3 - p1;\n\n \/\/ compute the last barycentric coordinate\n float b0 = 1.0f - b1 - b2;\n\n \/\/ interpolate normal?\n \/\/if(f[0].mNormalIndex == -1 ||\n \/\/ f[1].mNormalIndex == -1 ||\n \/\/ f[2].mNormalIndex == -1)\n \/\/{\n \/\/} \/\/ end if\n \/\/else\n \/\/{\n \/\/ \/\/ get each vertex's Normals\n \/\/ const Mesh::NormalList &norms = m.getNormals();\n \/\/ const Normal &n1 = norms[f[0].mNormalIndex];\n \/\/ const Normal &n2 = norms[f[1].mNormalIndex];\n \/\/ const Normal &n3 = norms[f[2].mNormalIndex];\n \/\/ n = b0 * n1 + b1 * n2 + b2 * n3;\n \/\/} \/\/ end else\n\n \/\/ normalize it\n \/\/dg.getNormal() = dg.getNormal().normalize();\n\n ParametricCoordinates uv0;\n ParametricCoordinates uv1;\n ParametricCoordinates uv2;\n getParametricCoordinates(tri, uv0, uv1, uv2);\n\n \/\/ compute deltas for partial derivatives\n float du1 = uv0[0] - uv2[0];\n float du2 = uv1[0] - uv2[0];\n float dv1 = uv0[1] - uv2[1];\n float dv2 = uv1[1] - uv2[1];\n Vector dp1 = p1 - p3, dp2 = p2 - p3;\n float determinant = du1 * dv2 - dv1 * du2;\n if(determinant == 0.0)\n {\n \/\/ handle zero determinant case\n dg.getPointPartials()[0] = ng.orthogonalVector();\n dg.getPointPartials()[1] = ng.cross(dg.getPointPartials()[0]).normalize();\n } \/\/ end if\n else\n {\n float invDet = 1.0f \/ determinant;\n dg.getPointPartials()[0] = ( dv2*dp1 - dv1*dp2) * invDet;\n dg.getPointPartials()[1] = (-du2*dp1 + du1*dp2) * invDet;\n } \/\/ end else\n\n \/\/ interpolate uv using barycentric coordinates\n ParametricCoordinates uv;\n uv[0] = b0*uv0[0] + b1*uv1[0] + b2*uv2[0];\n uv[1] = b0*uv0[1] + b1*uv1[1] + b2*uv2[1];\n\n dg.setPoint(p);\n dg.setNormal(ng);\n dg.setParametricCoordinates(uv);\n dg.setTangent(dg.getPointPartials()[0].normalize());\n\n \/\/ force an orthonormal basis\n dg.setBinormal(ng.cross(dg.getTangent()));\n} \/\/ end Mesh::getDifferentialGeometry()\n\nvoid Mesh::TriangleIntersector\n ::init(void)\n{\n mT = std::numeric_limits::infinity();\n mHitFace = 0;\n mMesh = 0;\n} \/\/ end TriangleIntersector::init()\n\nvoid Mesh\n ::buildTriangleTable(void)\n{\n std::vector pointers;\n std::vector area;\n for(TriangleList::const_iterator t = mTriangles.begin();\n t != mTriangles.end();\n ++t)\n {\n pointers.push_back(&(*t));\n area.push_back(Parent0::computeSurfaceArea(*t));\n } \/\/ end for t\n\n mTriangleTable.build(pointers.begin(), pointers.end(),\n area.begin(), area.end());\n} \/\/ end Mesh::buildTriangleTable()\n\nfloat Mesh\n ::computeSurfaceArea(void) const\n{\n float result = 0;\n\n for(TriangleList::const_iterator t = mTriangles.begin();\n t != mTriangles.end();\n ++t)\n {\n result += Parent0::computeSurfaceArea(*t);\n } \/\/ end for t\n\n return result;\n} \/\/ end Mesh::computeSurfaceArea()\n\nvoid Mesh\n ::sampleSurfaceArea(const float u1,\n const float u2,\n const float u3,\n DifferentialGeometry &dg,\n float &pdf) const\n{\n const Triangle &t = *mTriangleTable(u1);\n const Point &v0 = mPoints[t[0]];\n const Point &v1 = mPoints[t[1]];\n const Point &v2 = mPoints[t[2]];\n\n Point p;\n ParametricCoordinates b;\n UnitSquareToTriangle::evaluate(u2,u3, v0, v1, v2, p, b);\n\n \/\/ XXX implement shading normals\n Normal ng = (v1 - v0).cross(v2 - v0).normalize();\n\n \/\/ we need to send barycentrics here, not u2 and u3\n \/\/ as they are NOT the same thing\n getDifferentialGeometry(t, p, ng, b[0], b[1], dg);\n\n \/\/ evaluate the pdf\n pdf = evaluateSurfaceAreaPdf(dg);\n} \/\/ end Mesh::sampleSurfaceArea()\n\nfloat Mesh\n ::evaluateSurfaceAreaPdf(const DifferentialGeometry &dg) const\n{\n \/\/ we assume dg is actually on the surface of this Mesh\n return mOneOverSurfaceArea;\n} \/\/ end Mesh::evaluateSurfaceAreaPdf()\n\nfloat Mesh\n ::getSurfaceArea(void) const\n{\n return mSurfaceArea;\n} \/\/ end Mesh::getSurfaceArea()\n\nfloat Mesh\n ::getInverseSurfaceArea(void) const\n{\n return mOneOverSurfaceArea;\n} \/\/ end Mesh::getInverseSurfaceArea()\n\nvoid Mesh\n ::buildWaldBikkerData(void)\n{\n mWaldBikkerTriangleData.clear();\n\n \/\/ see http:\/\/www.devmaster.net\/articles\/raytracing_series\/part7.php for details\n for(size_t i = 0; i < mTriangles.size(); ++i)\n {\n const Triangle &tri = mTriangles[i];\n\n \/\/ compute the triangle's normal\n Vector b = mPoints[tri[2]] - mPoints[tri[0]];\n Vector c = mPoints[tri[1]] - mPoints[tri[0]];\n Normal n = c.cross(b).normalize();\n\n WaldBikkerData data;\n\n \/\/ determine dominant axis\n if(fabsf(n[0]) > fabsf(n[1]))\n {\n if(fabsf(n[0]) > fabsf(n[2])) data.mDominantAxis = 0;\n else data.mDominantAxis = 2;\n } \/\/ end if\n else\n {\n if(fabsf(n[1]) > fabsf(n[2])) data.mDominantAxis = 1;\n else data.mDominantAxis = 2;\n } \/\/ end else\n\n int u = (data.mDominantAxis + 1) % 3;\n int v = (data.mDominantAxis + 2) % 3;\n\n data.mUAxis = u;\n data.mVAxis = v;\n\n data.mN[0] = n.dot(mPoints[tri[0]]) \/ n[data.mDominantAxis];\n data.mN[1] = n[u] \/ n[data.mDominantAxis];\n data.mN[2] = n[v] \/ n[data.mDominantAxis];\n\n float bnu = b[u] \/ (b[u] * c[v] - b[v] * c[u]);\n float bnv = -b[v] \/ (b[u] * c[v] - b[v] * c[u]);\n data.mBn = gpcpu::float2(bnu, bnv);\n\n float cnu = c[v] \/ (b[u] * c[v] - b[v] * c[u]);\n float cnv = -c[u] \/ (b[u] * c[v] - b[v] * c[u]);\n data.mCn = gpcpu::float2(cnu, cnv);\n\n mWaldBikkerTriangleData.push_back(data);\n } \/\/ end for i\n} \/\/ end Mesh::buildWaldBikkerData()\n\n<|endoftext|>"} {"text":"make SwClientIter::GoStart\/GoEnd private<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: mdiexp.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 02:00:43 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _MDIEXP_HXX\n#define _MDIEXP_HXX\n\n#ifndef _SOLAR_H\n#include \n#endif\n\nclass UniString;\nclass SwRect;\nclass Size;\nclass Dialog;\nclass ViewShell;\nclass SwDoc;\nclass SwDocShell;\nclass SfxObjectShell;\nclass SfxFrame;\n\nextern void ScrollMDI(ViewShell* pVwSh, const SwRect &, USHORT nRangeX, USHORT nRangeY);\nextern BOOL IsScrollMDI(ViewShell* pVwSh, const SwRect &);\nextern void SizeNotify(ViewShell* pVwSh, const Size &);\n\n\/\/Update der Statusleiste, waehrend einer Action.\nextern void PageNumNotify( ViewShell* pVwSh,\n USHORT nPhyNum,\n USHORT nVirtNum,\n const UniString& rPg );\n\nenum FlyMode { FLY_DRAG_START, FLY_DRAG, FLY_DRAG_END };\nextern void FrameNotify( ViewShell* pVwSh, FlyMode eMode = FLY_DRAG );\n\nvoid StartProgress ( USHORT nMessId, long nStartVal, long nEndVal, SwDocShell *pDocSh = 0 );\nvoid EndProgress ( SwDocShell *pDocSh = 0 );\nvoid SetProgressState ( long nPosition, SwDocShell *pDocShell );\nvoid SetProgressText ( USHORT nMessId, SwDocShell *pDocShell );\nvoid RescheduleProgress( SwDocShell *pDocShell );\n\nvoid EnableCmdInterface(BOOL bEnable = TRUE);\n\nDialog* GetSearchDialog();\n\nvoid RepaintPagePreview( ViewShell* pVwSh, const SwRect& rRect );\n\n\/\/ ndgrf.cxx\n\/\/ alle QuickDraw-Bitmaps des speziellen Docs loeschen\nvoid DelAllGrfCacheEntries( SwDoc* pDoc );\n\n\/\/ ChgMode fuer Tabellen aus der Konfiguration lesen\nUSHORT GetTblChgDefaultMode();\n\nBOOL JumpToSwMark( ViewShell* pVwSh, const UniString& rMark );\n\n\n#endif\nINTEGRATION: CWS writercorehandoff (1.3.466); FILE MERGED 2005\/09\/13 11:41:47 tra 1.3.466.2: RESYNC: (1.3-1.4); FILE MERGED 2005\/06\/07 14:10:04 fme 1.3.466.1: #i50348# General cleanup - removed unused header files, functions, members, declarations etc.\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: mdiexp.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: hr $ $Date: 2006-08-14 15:26:31 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _MDIEXP_HXX\n#define _MDIEXP_HXX\n\n#ifndef _SOLAR_H\n#include \n#endif\n\nclass UniString;\nclass SwRect;\nclass Size;\nclass Dialog;\nclass ViewShell;\nclass SwDoc;\nclass SwDocShell;\n\nextern void ScrollMDI(ViewShell* pVwSh, const SwRect &, USHORT nRangeX, USHORT nRangeY);\nextern BOOL IsScrollMDI(ViewShell* pVwSh, const SwRect &);\nextern void SizeNotify(ViewShell* pVwSh, const Size &);\n\n\/\/Update der Statusleiste, waehrend einer Action.\nextern void PageNumNotify( ViewShell* pVwSh,\n USHORT nPhyNum,\n USHORT nVirtNum,\n const UniString& rPg );\n\nenum FlyMode { FLY_DRAG_START, FLY_DRAG, FLY_DRAG_END };\nextern void FrameNotify( ViewShell* pVwSh, FlyMode eMode = FLY_DRAG );\n\nvoid StartProgress ( USHORT nMessId, long nStartVal, long nEndVal, SwDocShell *pDocSh = 0 );\nvoid EndProgress ( SwDocShell *pDocSh = 0 );\nvoid SetProgressState ( long nPosition, SwDocShell *pDocShell );\nvoid SetProgressText ( USHORT nMessId, SwDocShell *pDocShell );\nvoid RescheduleProgress( SwDocShell *pDocShell );\n\nvoid EnableCmdInterface(BOOL bEnable = TRUE);\n\nDialog* GetSearchDialog();\n\nvoid RepaintPagePreview( ViewShell* pVwSh, const SwRect& rRect );\n\n\/\/ ndgrf.cxx\n\/\/ alle QuickDraw-Bitmaps des speziellen Docs loeschen\nvoid DelAllGrfCacheEntries( SwDoc* pDoc );\n\n\/\/ ChgMode fuer Tabellen aus der Konfiguration lesen\nUSHORT GetTblChgDefaultMode();\n\nBOOL JumpToSwMark( ViewShell* pVwSh, const UniString& rMark );\n\n\n#endif\n<|endoftext|>"} {"text":"#include \"..\/TCPSocket.h\"\n\n#include \n#include \n\nusing namespace NET;\n\nint main()\n{\n\tstatic char send_msg[] = \"The quick brown fox jumps over the lazy dog\";\n\tstatic char recv_msg[sizeof(send_msg)];\n\tstatic size_t len = sizeof(send_msg);\n\n\ttry {\n\n\t\/\/ Test peer status on a TCP socket\n\tTCPSocket server_socket;\n\tTCPSocket client_socket;\n\tserver_socket.bind( \"127.0.0.1\", 47777);\n\tserver_socket.listen();\n\tif( server_socket.peerDisconnected()) return 1;\n\n\tclient_socket.connect( \"127.0.0.1\", 47777);\n\n\tconst TCPSocket::Handle& handle = server_socket.accept();\n\tif(!handle) return 1;\n\tTCPSocket session_socket(handle);\n\tif( session_socket.peerDisconnected()) return 1;\n\n\tsession_socket.send( send_msg, len);\n\tif( client_socket.receive( recv_msg, len) != len) return 1;\n\tif( std::memcmp( send_msg, recv_msg, len) < 0) return 1;\n\n\tclient_socket.disconnect();\n\tsession_socket.send( send_msg, len);\n\tif( !session_socket.peerDisconnected()) return 1;\n\n\t\/\/ no errors in this testcase\n\t} catch( const SocketException& e)\n\t{\n\t\tstd::cerr << e.what() << std::endl;\n\t\tstd::cerr << e.errorCode() << std::endl;\n\t}\n}\nfix bug in TCPSocket test, where an exception is ignored#include \"..\/TCPSocket.h\"\n\n#include \n#include \n\nusing namespace NET;\n\nint main()\n{\n\tstatic char send_msg[] = \"The quick brown fox jumps over the lazy dog\";\n\tstatic char recv_msg[sizeof(send_msg)];\n\tstatic size_t len = sizeof(send_msg);\n\n\ttry {\n\n\t\/\/ Test peer status on a TCP socket\n\tTCPSocket server_socket;\n\tTCPSocket client_socket;\n\tserver_socket.bind( \"127.0.0.1\", 47777);\n\tserver_socket.listen();\n\tif( server_socket.peerDisconnected()) return 1;\n\n\tclient_socket.connect( \"127.0.0.1\", 47777);\n\n\tconst TCPSocket::Handle& handle = server_socket.accept();\n\tif(!handle) return 1;\n\tTCPSocket session_socket(handle);\n\tif( session_socket.peerDisconnected()) return 1;\n\n\tsession_socket.send( send_msg, len);\n\tif( client_socket.receive( recv_msg, len) != len) return 1;\n\tif( std::memcmp( send_msg, recv_msg, len) < 0) return 1;\n\n\tclient_socket.disconnect();\n\tsession_socket.send( send_msg, len);\n\tif( !session_socket.peerDisconnected()) return 1;\n\n\t\/\/ no errors in this testcase\n\t} catch( const SocketException& e)\n\t{\n\t\tstd::cerr << e.what() << std::endl;\n\t\tstd::cerr << e.errorCode() << std::endl;\n\t\treturn 1;\n\t}\n}\n<|endoftext|>"} {"text":"\/* This file is part of QJson\n *\n * Copyright (C) 2009 Flavio Castelli \n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n\nint main(int argc, char *argv[]) {\n QCoreApplication app (argc, argv);\n \n if (app.arguments().size() != 2) {\n qFatal(\"You have to specify the file containing the json code\");\n exit (1);\n }\n \n QString filename = app.arguments()[1];\n if (!QFile::exists ( filename )) {\n qFatal (\"The file you specified doesn't exist!\");\n exit (1);\n }\n \n JSonDriver driver;\n bool status;\n\n QVariant data = driver.parse (new QFile(filename), &status);\n if (status) {\n qFatal(\"An error occured during parsing\");\n exit (1);\n }\n else {\n qDebug() << \"json object successfully converted to:\";\n qDebug() << data;\n }\n \n return 0;\n}take advantage of error localization\/* This file is part of QJson\n *\n * Copyright (C) 2009 Flavio Castelli \n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n\nint main(int argc, char *argv[]) {\n QCoreApplication app (argc, argv);\n \n if (app.arguments().size() != 2) {\n qFatal(\"You have to specify the file containing the json code\");\n exit (1);\n }\n \n QString filename = app.arguments()[1];\n if (!QFile::exists ( filename )) {\n qFatal (\"The file you specified doesn't exist!\");\n exit (1);\n }\n \n JSonDriver driver;\n bool status;\n\n QVariant data = driver.parse (new QFile(filename), &status);\n if (status) {\n QString message;\n message.sprintf(\"%s:%i - Error: %s\", filename.toLatin1().data(), driver.errorLine(), driver.error().toLatin1().data());\n qFatal(message.toLatin1().data());\n exit (1);\n }\n else {\n qDebug() << \"json object successfully converted to:\";\n qDebug() << data;\n }\n \n return 0;\n}<|endoftext|>"} {"text":"#include \n#include \n\n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\nusing namespace Tp;\n\nnamespace\n{\n\nPresenceSpec getPresenceSpec(const PresenceSpecList &specs, const QString &status)\n{\n Q_FOREACH (const PresenceSpec &spec, specs) {\n if (spec.presence().status() == status) {\n return spec;\n }\n }\n return PresenceSpec();\n}\n\n}\n\nclass TestCmBasics : public Test\n{\n Q_OBJECT\n\npublic:\n TestCmBasics(QObject *parent = 0)\n : Test(parent), mCMService(0)\n { }\n\nprivate Q_SLOTS:\n void initTestCase();\n void init();\n\n void testBasics();\n void testLegacy();\n\n void cleanup();\n void cleanupTestCase();\n\nprivate:\n TpBaseConnectionManager *mCMService;\n Tp::ConnectionManagerPtr mCM;\n\n TpBaseConnectionManager *mCMServiceLegacy;\n Tp::ConnectionManagerPtr mCMLegacy;\n};\n\nvoid TestCmBasics::initTestCase()\n{\n initTestCaseImpl();\n\n g_type_init();\n g_set_prgname(\"cm-basics\");\n tp_debug_set_flags(\"all\");\n dbus_g_bus_get(DBUS_BUS_STARTER, 0);\n\n mCMService = TP_BASE_CONNECTION_MANAGER(g_object_new(\n EXAMPLE_TYPE_ECHO_2_CONNECTION_MANAGER,\n NULL));\n QVERIFY(mCMService != 0);\n\n mCMServiceLegacy = TP_BASE_CONNECTION_MANAGER(g_object_new(\n TP_TESTS_TYPE_SIMPLE_CONNECTION_MANAGER,\n NULL));\n QVERIFY(mCMServiceLegacy != 0);\n\n QVERIFY(tp_base_connection_manager_register(mCMService));\n QVERIFY(tp_base_connection_manager_register(mCMServiceLegacy));\n}\n\nvoid TestCmBasics::init()\n{\n initImpl();\n}\n\nvoid TestCmBasics::testBasics()\n{\n mCM = ConnectionManager::create(QLatin1String(\"example_echo_2\"));\n QCOMPARE(mCM->isReady(), false);\n\n QVERIFY(connect(mCM->becomeReady(),\n SIGNAL(finished(Tp::PendingOperation *)),\n SLOT(expectSuccessfulCall(Tp::PendingOperation *))));\n QCOMPARE(mLoop->exec(), 0);\n QCOMPARE(mCM->isReady(), true);\n\n \/\/ calling becomeReady() twice is a no-op\n QVERIFY(connect(mCM->becomeReady(),\n SIGNAL(finished(Tp::PendingOperation *)),\n SLOT(expectSuccessfulCall(Tp::PendingOperation *))));\n QCOMPARE(mLoop->exec(), 0);\n QCOMPARE(mCM->isReady(), true);\n\n QCOMPARE(mCM->interfaces(), QStringList());\n QCOMPARE(mCM->supportedProtocols(), QStringList() << QLatin1String(\"example\"));\n\n QVERIFY(mCM->hasProtocol(QLatin1String(\"example\")));\n QVERIFY(!mCM->hasProtocol(QLatin1String(\"not-there\")));\n\n ProtocolInfo info = mCM->protocol(QLatin1String(\"example\"));\n QVERIFY(info.isValid());\n\n QCOMPARE(info.cmName(), QLatin1String(\"example_echo_2\"));\n QCOMPARE(info.name(), QLatin1String(\"example\"));\n\n QCOMPARE(info.hasParameter(QLatin1String(\"account\")), true);\n QCOMPARE(info.hasParameter(QLatin1String(\"not-there\")), false);\n\n QCOMPARE(info.parameters().size(), 1);\n\n ProtocolParameter param = info.parameters().at(0);\n QCOMPARE(param.name(), QLatin1String(\"account\"));\n QCOMPARE(static_cast(param.type()), static_cast(QVariant::String));\n QCOMPARE(param.defaultValue().isNull(), true);\n QCOMPARE(param.dbusSignature().signature(), QLatin1String(\"s\"));\n QCOMPARE(param.isRequired(), true);\n QCOMPARE(param.isRequiredForRegistration(), true); \/\/ though it can't register!\n QCOMPARE(param.isSecret(), false);\n\n QVERIFY(param == QLatin1String(\"account\"));\n\n QCOMPARE(info.canRegister(), false);\n\n QCOMPARE(info.capabilities().isSpecificToContact(), false);\n QCOMPARE(info.capabilities().textChatrooms(), false);\n QCOMPARE(info.capabilities().textChats(), true);\n QCOMPARE(info.capabilities().streamedMediaCalls(), false);\n QCOMPARE(info.capabilities().streamedMediaAudioCalls(), false);\n QCOMPARE(info.capabilities().streamedMediaVideoCalls(), false);\n QCOMPARE(info.capabilities().streamedMediaVideoCallsWithAudio(), false);\n QCOMPARE(info.capabilities().upgradingStreamedMediaCalls(), false);\n\n QCOMPARE(info.vcardField(), QLatin1String(\"x-telepathy-example\"));\n QCOMPARE(info.englishName(), QLatin1String(\"Echo II example\"));\n QCOMPARE(info.iconName(), QLatin1String(\"im-icq\"));\n\n PresenceSpecList statuses = info.allowedPresenceStatuses();\n QCOMPARE(statuses.size(), 3);\n PresenceSpec spec;\n spec = getPresenceSpec(statuses, QLatin1String(\"offline\"));\n QCOMPARE(spec.isValid(), true);\n QVERIFY(spec.presence().type() == ConnectionPresenceTypeOffline);\n QCOMPARE(spec.maySetOnSelf(), false);\n QCOMPARE(spec.canHaveStatusMessage(), false);\n spec = getPresenceSpec(statuses, QLatin1String(\"dnd\"));\n QCOMPARE(spec.isValid(), true);\n QVERIFY(spec.presence().type() == ConnectionPresenceTypeBusy);\n QCOMPARE(spec.maySetOnSelf(), true);\n QCOMPARE(spec.canHaveStatusMessage(), false);\n spec = getPresenceSpec(statuses, QLatin1String(\"available\"));\n QCOMPARE(spec.isValid(), true);\n QVERIFY(spec.presence().type() == ConnectionPresenceTypeAvailable);\n QCOMPARE(spec.maySetOnSelf(), true);\n QCOMPARE(spec.canHaveStatusMessage(), true);\n\n AvatarSpec avatarReqs = info.avatarRequirements();\n QStringList supportedMimeTypes = avatarReqs.supportedMimeTypes();\n supportedMimeTypes.sort();\n QCOMPARE(supportedMimeTypes,\n QStringList() << QLatin1String(\"image\/gif\") << QLatin1String(\"image\/jpeg\") <<\n QLatin1String(\"image\/png\"));\n QCOMPARE(avatarReqs.minimumHeight(), (uint) 32);\n QCOMPARE(avatarReqs.maximumHeight(), (uint) 96);\n QCOMPARE(avatarReqs.recommendedHeight(), (uint) 64);\n QCOMPARE(avatarReqs.minimumWidth(), (uint) 32);\n QCOMPARE(avatarReqs.maximumWidth(), (uint) 96);\n QCOMPARE(avatarReqs.recommendedWidth(), (uint) 64);\n QCOMPARE(avatarReqs.maximumBytes(), (uint) 37748736);\n\n QCOMPARE(mCM->supportedProtocols(), QStringList() << QLatin1String(\"example\"));\n}\n\n\/\/ Test for a CM which doesn't implement Protocol objects\nvoid TestCmBasics::testLegacy()\n{\n mCMLegacy = ConnectionManager::create(QLatin1String(\"simple\"));\n QCOMPARE(mCMLegacy->isReady(), false);\n\n QVERIFY(connect(mCMLegacy->becomeReady(),\n SIGNAL(finished(Tp::PendingOperation *)),\n SLOT(expectSuccessfulCall(Tp::PendingOperation *))));\n QCOMPARE(mLoop->exec(), 0);\n QCOMPARE(mCMLegacy->isReady(), true);\n\n QCOMPARE(mCMLegacy->interfaces(), QStringList());\n QCOMPARE(mCMLegacy->supportedProtocols(), QStringList() << QLatin1String(\"simple\"));\n\n QVERIFY(mCMLegacy->hasProtocol(QLatin1String(\"simple\")));\n QVERIFY(!mCMLegacy->hasProtocol(QLatin1String(\"not-there\")));\n\n ProtocolInfo info = mCMLegacy->protocol(QLatin1String(\"simple\"));\n QVERIFY(info.isValid());\n\n QCOMPARE(info.cmName(), QLatin1String(\"simple\"));\n QCOMPARE(info.name(), QLatin1String(\"simple\"));\n\n QCOMPARE(info.hasParameter(QLatin1String(\"account\")), true);\n QCOMPARE(info.hasParameter(QLatin1String(\"not-there\")), false);\n\n QCOMPARE(info.parameters().size(), 1);\n\n ProtocolParameter param = info.parameters().at(0);\n QCOMPARE(param.name(), QLatin1String(\"account\"));\n QCOMPARE(static_cast(param.type()), static_cast(QVariant::String));\n QCOMPARE(param.defaultValue().isNull(), true);\n QCOMPARE(param.dbusSignature().signature(), QLatin1String(\"s\"));\n QCOMPARE(param.isRequired(), true);\n QCOMPARE(param.isRequiredForRegistration(), true);\n QCOMPARE(param.isSecret(), false);\n\n QVERIFY(param == QLatin1String(\"account\"));\n\n QCOMPARE(info.canRegister(), false);\n\n \/\/ Protocol capabilities semantics is \"an actual connection supports whatever I claim, or\n \/\/ less\", so for a service with no actual Protocol implementation everything should be\n \/\/ assumed to be possible at this point\n QCOMPARE(info.capabilities().isSpecificToContact(), false);\n QCOMPARE(info.capabilities().textChatrooms(), true);\n QCOMPARE(info.capabilities().textChats(), true);\n QCOMPARE(info.capabilities().streamedMediaCalls(), true);\n QCOMPARE(info.capabilities().streamedMediaAudioCalls(), true);\n QCOMPARE(info.capabilities().streamedMediaVideoCalls(), true);\n QCOMPARE(info.capabilities().streamedMediaVideoCallsWithAudio(), true);\n QCOMPARE(info.capabilities().upgradingStreamedMediaCalls(), true);\n\n QCOMPARE(info.vcardField(), QLatin1String(\"\"));\n QCOMPARE(info.englishName(), QLatin1String(\"Simple\"));\n QCOMPARE(info.iconName(), QLatin1String(\"im-simple\"));\n\n QCOMPARE(mCMLegacy->supportedProtocols(), QStringList() << QLatin1String(\"simple\"));\n}\n\n\/\/ TODO add a test for the case of getting the information from a .manager file, and if possible,\n\/\/ also for using the fallbacks for the CM::Protocols property not being present.\n\n\/\/ TODO also one for CM::listNames()\n\nvoid TestCmBasics::cleanup()\n{\n mCM.reset();\n mCMLegacy.reset();\n\n cleanupImpl();\n}\n\nvoid TestCmBasics::cleanupTestCase()\n{\n if (mCMService) {\n g_object_unref(mCMService);\n mCMService = 0;\n }\n\n if (mCMServiceLegacy) {\n g_object_unref(mCMServiceLegacy);\n mCMServiceLegacy = 0;\n }\n\n cleanupTestCaseImpl();\n}\n\nQTEST_MAIN(TestCmBasics)\n#include \"_gen\/cm-basics.cpp.moc.hpp\"\ncm-basics test: Add test for ConnectionManager::listNames().#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\nusing namespace Tp;\n\nnamespace\n{\n\nPresenceSpec getPresenceSpec(const PresenceSpecList &specs, const QString &status)\n{\n Q_FOREACH (const PresenceSpec &spec, specs) {\n if (spec.presence().status() == status) {\n return spec;\n }\n }\n return PresenceSpec();\n}\n\n}\n\nclass TestCmBasics : public Test\n{\n Q_OBJECT\n\npublic:\n TestCmBasics(QObject *parent = 0)\n : Test(parent), mCMService(0)\n { }\n\nprotected Q_SLOTS:\n void expectListNamesFinished(Tp::PendingOperation *);\n\nprivate Q_SLOTS:\n void initTestCase();\n void init();\n\n void testBasics();\n void testLegacy();\n void testListNames();\n\n void cleanup();\n void cleanupTestCase();\n\nprivate:\n TpBaseConnectionManager *mCMService;\n Tp::ConnectionManagerPtr mCM;\n\n TpBaseConnectionManager *mCMServiceLegacy;\n Tp::ConnectionManagerPtr mCMLegacy;\n\n QStringList mCMNames;\n};\n\nvoid TestCmBasics::expectListNamesFinished(PendingOperation *op)\n{\n if (!op->isFinished()) {\n qWarning() << \"unfinished\";\n mLoop->exit(1);\n return;\n }\n\n if (op->isError()) {\n qWarning().nospace() << op->errorName()\n << \": \" << op->errorMessage();\n mLoop->exit(2);\n return;\n }\n\n if (!op->isValid()) {\n qWarning() << \"inconsistent results\";\n mLoop->exit(3);\n return;\n }\n\n PendingStringList *ps = qobject_cast(op);\n mCMNames = ps->result();\n mLoop->exit(0);\n}\n\nvoid TestCmBasics::initTestCase()\n{\n initTestCaseImpl();\n\n g_type_init();\n g_set_prgname(\"cm-basics\");\n tp_debug_set_flags(\"all\");\n dbus_g_bus_get(DBUS_BUS_STARTER, 0);\n\n mCMService = TP_BASE_CONNECTION_MANAGER(g_object_new(\n EXAMPLE_TYPE_ECHO_2_CONNECTION_MANAGER,\n NULL));\n QVERIFY(mCMService != 0);\n\n mCMServiceLegacy = TP_BASE_CONNECTION_MANAGER(g_object_new(\n TP_TESTS_TYPE_SIMPLE_CONNECTION_MANAGER,\n NULL));\n QVERIFY(mCMServiceLegacy != 0);\n\n QVERIFY(tp_base_connection_manager_register(mCMService));\n QVERIFY(tp_base_connection_manager_register(mCMServiceLegacy));\n}\n\nvoid TestCmBasics::init()\n{\n initImpl();\n}\n\nvoid TestCmBasics::testBasics()\n{\n mCM = ConnectionManager::create(QLatin1String(\"example_echo_2\"));\n QCOMPARE(mCM->isReady(), false);\n\n QVERIFY(connect(mCM->becomeReady(),\n SIGNAL(finished(Tp::PendingOperation *)),\n SLOT(expectSuccessfulCall(Tp::PendingOperation *))));\n QCOMPARE(mLoop->exec(), 0);\n QCOMPARE(mCM->isReady(), true);\n\n \/\/ calling becomeReady() twice is a no-op\n QVERIFY(connect(mCM->becomeReady(),\n SIGNAL(finished(Tp::PendingOperation *)),\n SLOT(expectSuccessfulCall(Tp::PendingOperation *))));\n QCOMPARE(mLoop->exec(), 0);\n QCOMPARE(mCM->isReady(), true);\n\n QCOMPARE(mCM->interfaces(), QStringList());\n QCOMPARE(mCM->supportedProtocols(), QStringList() << QLatin1String(\"example\"));\n\n QVERIFY(mCM->hasProtocol(QLatin1String(\"example\")));\n QVERIFY(!mCM->hasProtocol(QLatin1String(\"not-there\")));\n\n ProtocolInfo info = mCM->protocol(QLatin1String(\"example\"));\n QVERIFY(info.isValid());\n\n QCOMPARE(info.cmName(), QLatin1String(\"example_echo_2\"));\n QCOMPARE(info.name(), QLatin1String(\"example\"));\n\n QCOMPARE(info.hasParameter(QLatin1String(\"account\")), true);\n QCOMPARE(info.hasParameter(QLatin1String(\"not-there\")), false);\n\n QCOMPARE(info.parameters().size(), 1);\n\n ProtocolParameter param = info.parameters().at(0);\n QCOMPARE(param.name(), QLatin1String(\"account\"));\n QCOMPARE(static_cast(param.type()), static_cast(QVariant::String));\n QCOMPARE(param.defaultValue().isNull(), true);\n QCOMPARE(param.dbusSignature().signature(), QLatin1String(\"s\"));\n QCOMPARE(param.isRequired(), true);\n QCOMPARE(param.isRequiredForRegistration(), true); \/\/ though it can't register!\n QCOMPARE(param.isSecret(), false);\n\n QVERIFY(param == QLatin1String(\"account\"));\n\n QCOMPARE(info.canRegister(), false);\n\n QCOMPARE(info.capabilities().isSpecificToContact(), false);\n QCOMPARE(info.capabilities().textChatrooms(), false);\n QCOMPARE(info.capabilities().textChats(), true);\n QCOMPARE(info.capabilities().streamedMediaCalls(), false);\n QCOMPARE(info.capabilities().streamedMediaAudioCalls(), false);\n QCOMPARE(info.capabilities().streamedMediaVideoCalls(), false);\n QCOMPARE(info.capabilities().streamedMediaVideoCallsWithAudio(), false);\n QCOMPARE(info.capabilities().upgradingStreamedMediaCalls(), false);\n\n QCOMPARE(info.vcardField(), QLatin1String(\"x-telepathy-example\"));\n QCOMPARE(info.englishName(), QLatin1String(\"Echo II example\"));\n QCOMPARE(info.iconName(), QLatin1String(\"im-icq\"));\n\n PresenceSpecList statuses = info.allowedPresenceStatuses();\n QCOMPARE(statuses.size(), 3);\n PresenceSpec spec;\n spec = getPresenceSpec(statuses, QLatin1String(\"offline\"));\n QCOMPARE(spec.isValid(), true);\n QVERIFY(spec.presence().type() == ConnectionPresenceTypeOffline);\n QCOMPARE(spec.maySetOnSelf(), false);\n QCOMPARE(spec.canHaveStatusMessage(), false);\n spec = getPresenceSpec(statuses, QLatin1String(\"dnd\"));\n QCOMPARE(spec.isValid(), true);\n QVERIFY(spec.presence().type() == ConnectionPresenceTypeBusy);\n QCOMPARE(spec.maySetOnSelf(), true);\n QCOMPARE(spec.canHaveStatusMessage(), false);\n spec = getPresenceSpec(statuses, QLatin1String(\"available\"));\n QCOMPARE(spec.isValid(), true);\n QVERIFY(spec.presence().type() == ConnectionPresenceTypeAvailable);\n QCOMPARE(spec.maySetOnSelf(), true);\n QCOMPARE(spec.canHaveStatusMessage(), true);\n\n AvatarSpec avatarReqs = info.avatarRequirements();\n QStringList supportedMimeTypes = avatarReqs.supportedMimeTypes();\n supportedMimeTypes.sort();\n QCOMPARE(supportedMimeTypes,\n QStringList() << QLatin1String(\"image\/gif\") << QLatin1String(\"image\/jpeg\") <<\n QLatin1String(\"image\/png\"));\n QCOMPARE(avatarReqs.minimumHeight(), (uint) 32);\n QCOMPARE(avatarReqs.maximumHeight(), (uint) 96);\n QCOMPARE(avatarReqs.recommendedHeight(), (uint) 64);\n QCOMPARE(avatarReqs.minimumWidth(), (uint) 32);\n QCOMPARE(avatarReqs.maximumWidth(), (uint) 96);\n QCOMPARE(avatarReqs.recommendedWidth(), (uint) 64);\n QCOMPARE(avatarReqs.maximumBytes(), (uint) 37748736);\n\n QCOMPARE(mCM->supportedProtocols(), QStringList() << QLatin1String(\"example\"));\n}\n\n\/\/ Test for a CM which doesn't implement Protocol objects\nvoid TestCmBasics::testLegacy()\n{\n mCMLegacy = ConnectionManager::create(QLatin1String(\"simple\"));\n QCOMPARE(mCMLegacy->isReady(), false);\n\n QVERIFY(connect(mCMLegacy->becomeReady(),\n SIGNAL(finished(Tp::PendingOperation *)),\n SLOT(expectSuccessfulCall(Tp::PendingOperation *))));\n QCOMPARE(mLoop->exec(), 0);\n QCOMPARE(mCMLegacy->isReady(), true);\n\n QCOMPARE(mCMLegacy->interfaces(), QStringList());\n QCOMPARE(mCMLegacy->supportedProtocols(), QStringList() << QLatin1String(\"simple\"));\n\n QVERIFY(mCMLegacy->hasProtocol(QLatin1String(\"simple\")));\n QVERIFY(!mCMLegacy->hasProtocol(QLatin1String(\"not-there\")));\n\n ProtocolInfo info = mCMLegacy->protocol(QLatin1String(\"simple\"));\n QVERIFY(info.isValid());\n\n QCOMPARE(info.cmName(), QLatin1String(\"simple\"));\n QCOMPARE(info.name(), QLatin1String(\"simple\"));\n\n QCOMPARE(info.hasParameter(QLatin1String(\"account\")), true);\n QCOMPARE(info.hasParameter(QLatin1String(\"not-there\")), false);\n\n QCOMPARE(info.parameters().size(), 1);\n\n ProtocolParameter param = info.parameters().at(0);\n QCOMPARE(param.name(), QLatin1String(\"account\"));\n QCOMPARE(static_cast(param.type()), static_cast(QVariant::String));\n QCOMPARE(param.defaultValue().isNull(), true);\n QCOMPARE(param.dbusSignature().signature(), QLatin1String(\"s\"));\n QCOMPARE(param.isRequired(), true);\n QCOMPARE(param.isRequiredForRegistration(), true);\n QCOMPARE(param.isSecret(), false);\n\n QVERIFY(param == QLatin1String(\"account\"));\n\n QCOMPARE(info.canRegister(), false);\n\n \/\/ Protocol capabilities semantics is \"an actual connection supports whatever I claim, or\n \/\/ less\", so for a service with no actual Protocol implementation everything should be\n \/\/ assumed to be possible at this point\n QCOMPARE(info.capabilities().isSpecificToContact(), false);\n QCOMPARE(info.capabilities().textChatrooms(), true);\n QCOMPARE(info.capabilities().textChats(), true);\n QCOMPARE(info.capabilities().streamedMediaCalls(), true);\n QCOMPARE(info.capabilities().streamedMediaAudioCalls(), true);\n QCOMPARE(info.capabilities().streamedMediaVideoCalls(), true);\n QCOMPARE(info.capabilities().streamedMediaVideoCallsWithAudio(), true);\n QCOMPARE(info.capabilities().upgradingStreamedMediaCalls(), true);\n\n QCOMPARE(info.vcardField(), QLatin1String(\"\"));\n QCOMPARE(info.englishName(), QLatin1String(\"Simple\"));\n QCOMPARE(info.iconName(), QLatin1String(\"im-simple\"));\n\n QCOMPARE(mCMLegacy->supportedProtocols(), QStringList() << QLatin1String(\"simple\"));\n}\n\n\/\/ TODO add a test for the case of getting the information from a .manager file, and if possible,\n\/\/ also for using the fallbacks for the CM::Protocols property not being present.\n\nvoid TestCmBasics::testListNames()\n{\n QVERIFY(connect(ConnectionManager::listNames(),\n SIGNAL(finished(Tp::PendingOperation*)),\n SLOT(expectListNamesFinished(Tp::PendingOperation*))));\n QCOMPARE(mLoop->exec(), 0);\n QCOMPARE(mCMNames.size(), 3);\n QVERIFY(mCMNames.contains(QLatin1String(\"simple\")));\n QVERIFY(mCMNames.contains(QLatin1String(\"example_echo_2\")));\n QVERIFY(mCMNames.contains(QLatin1String(\"spurious\")));\n}\n\nvoid TestCmBasics::cleanup()\n{\n mCM.reset();\n mCMLegacy.reset();\n\n cleanupImpl();\n}\n\nvoid TestCmBasics::cleanupTestCase()\n{\n if (mCMService) {\n g_object_unref(mCMService);\n mCMService = 0;\n }\n\n if (mCMServiceLegacy) {\n g_object_unref(mCMServiceLegacy);\n mCMServiceLegacy = 0;\n }\n\n cleanupTestCaseImpl();\n}\n\nQTEST_MAIN(TestCmBasics)\n#include \"_gen\/cm-basics.cpp.moc.hpp\"\n<|endoftext|>"} {"text":"\/** \\brief Utility for updating SQL schemata etc.\n * \\author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)\n *\n * \\copyright 2019 Universitätsbibliothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see .\n*\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"Compiler.h\"\n#include \"FileUtil.h\"\n#include \"DbConnection.h\"\n#include \"StringUtil.h\"\n#include \"util.h\"\n\n\nnamespace {\n\n\n[[noreturn]] void Usage() {\n ::Usage(\"[--test] update_directory_path\");\n}\n\n\nvoid SplitIntoDatabaseAndVersion(const std::string &update_filename, std::string * const database, unsigned * const version) {\n const auto first_dot_pos(update_filename.find('.'));\n if (first_dot_pos == std::string::npos or first_dot_pos == 0 or first_dot_pos == update_filename.length() - 1)\n LOG_ERROR(\"invalid update filename \\\"\" + update_filename + \"\\\"!\");\n\n if (not StringUtil::ToUnsigned(update_filename.substr(first_dot_pos + 1), version))\n LOG_ERROR(\"bad or missing version in update filename \\\"\" + update_filename + \"\\\"!\");\n\n *database = update_filename.substr(0, first_dot_pos);\n}\n\n\n\/\/ The filenames being compared are assumed to have the \"structure database.version]*\"\nbool FileNameCompare(const std::string &filename1, const std::string &filename2) {\n std::string database1;\n unsigned version1;\n SplitIntoDatabaseAndVersion(filename1, &database1, &version1);\n\n std::string database2;\n unsigned version2;\n SplitIntoDatabaseAndVersion(filename2, &database2, &version2);\n\n \/\/ Compare database names:\n if (database1 < database2)\n return true;\n if (database1 > database2)\n return false;\n\n return version1 < version2;\n}\n\n\nvoid LoadAndSortUpdateFilenames(const bool test, const std::string &directory_path, std::vector * const update_filenames) {\n FileUtil::Directory directory(directory_path, \"[^.]+\\\\.\\\\d+\");\n for (const auto &entry : directory)\n update_filenames->emplace_back(entry.getName());\n\n std::sort(update_filenames->begin(), update_filenames->end(), FileNameCompare);\n\n if (test) {\n std::cerr << \"Sorted filenames:\\n\";\n for (const auto &filename : *update_filenames)\n std::cerr << filename << '\\n';\n std::exit(0);\n }\n}\n\n\nvoid ApplyUpdate(DbConnection * const db_connection, const std::string &update_directory_path, const std::string &update_filename) {\n std::string database;\n unsigned update_version;\n SplitIntoDatabaseAndVersion(update_filename, &database, &update_version);\n\n if (not db_connection->mySQLDatabaseExists(database)) {\n LOG_INFO(\"database \\\"\" + database + \"\\\" does not exist, skipping file \" + update_filename);\n return;\n }\n\n db_connection->queryOrDie(\"START TRANSACTION\");\n\n unsigned current_version(0);\n db_connection->queryOrDie(\"SELECT version FROM ub_tools.database_versions WHERE database_name='\"\n + db_connection->escapeString(database) + \"'\");\n DbResultSet result_set(db_connection->getLastResultSet());\n if (result_set.empty()) {\n db_connection->queryOrDie(\"INSERT INTO ub_tools.database_versions (database_name,version) VALUES ('\"\n + db_connection->escapeString(database) + \"',0)\");\n LOG_INFO(\"Created a new entry for database \\\"\" + database + \" in ub_tools.database_versions.\");\n } else\n current_version = StringUtil::ToUnsigned(result_set.getNextRow()[\"version\"]);\n if (update_version <= current_version)\n return;\n\n \/\/ Sanity check:\n if (unlikely(update_version != current_version + 1))\n LOG_ERROR(\"update version is \" + std::to_string(update_version) + \", current version is \"\n + std::to_string(current_version) + \" for database \\\"\" + database + \"\\\"!\");\n\n db_connection->queryOrDie(\"UPDATE ub_tools.database_versions SET version=\" + std::to_string(update_version)\n + \" WHERE database_name='\" + db_connection->escapeString(database) + \"'\");\n\n LOG_INFO(\"applying update \" + std::to_string(update_version) + \" to database \\\"\" + database + \"\\\".\");\n db_connection->queryFileOrDie(update_directory_path + \"\/\" + update_filename);\n\n db_connection->queryOrDie(\"COMMIT\");\n}\n\n\n} \/\/ unnamed namespace\n\n\nint Main(int argc, char *argv[]) {\n if (argc != 2 and argc != 3)\n Usage();\n\n bool test(false);\n if (argc == 3) {\n if (std::strcmp(argv[1], \"--test\") != 0)\n Usage();\n test = true;\n --argc, ++argv;\n }\n\n std::vector update_filenames;\n const std::string update_directory_path(argv[1]);\n LoadAndSortUpdateFilenames(test, update_directory_path, &update_filenames);\n\n DbConnection db_connection;\n const std::string system_table_name(\"database_versions\");\n if (not db_connection.tableExists(\"ub_tools\", system_table_name)) {\n db_connection.queryOrDie(\"CREATE TABLE ub_tools.\" + system_table_name + \" (version INT UNSIGNED NOT NULL,\"\n \"database_name VARCHAR(64) NOT NULL,UNIQUE (database_name)) \"\n \"CHARACTER SET utf8mb4 COLLATE utf8mb4_bin\");\n LOG_INFO(\"Created the ub_tools.\" + system_table_name + \" table.\");\n }\n\n for (const auto &update_filename : update_filenames)\n ApplyUpdate(&db_connection, update_directory_path, update_filename);\n\n return EXIT_SUCCESS;\n}\nmysql_database_patcher: disable autocommit for transaction & optimize failure behaviour\/** \\brief Utility for updating SQL schemata etc.\n * \\author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)\n *\n * \\copyright 2019 Universitätsbibliothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see .\n*\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"Compiler.h\"\n#include \"FileUtil.h\"\n#include \"DbConnection.h\"\n#include \"StringUtil.h\"\n#include \"util.h\"\n\n\nnamespace {\n\n\n[[noreturn]] void Usage() {\n ::Usage(\"[--test] update_directory_path\");\n}\n\n\nvoid SplitIntoDatabaseAndVersion(const std::string &update_filename, std::string * const database, unsigned * const version) {\n const auto first_dot_pos(update_filename.find('.'));\n if (first_dot_pos == std::string::npos or first_dot_pos == 0 or first_dot_pos == update_filename.length() - 1)\n LOG_ERROR(\"invalid update filename \\\"\" + update_filename + \"\\\"!\");\n\n if (not StringUtil::ToUnsigned(update_filename.substr(first_dot_pos + 1), version))\n LOG_ERROR(\"bad or missing version in update filename \\\"\" + update_filename + \"\\\"!\");\n\n *database = update_filename.substr(0, first_dot_pos);\n}\n\n\n\/\/ The filenames being compared are assumed to have the \"structure database.version]*\"\nbool FileNameCompare(const std::string &filename1, const std::string &filename2) {\n std::string database1;\n unsigned version1;\n SplitIntoDatabaseAndVersion(filename1, &database1, &version1);\n\n std::string database2;\n unsigned version2;\n SplitIntoDatabaseAndVersion(filename2, &database2, &version2);\n\n \/\/ Compare database names:\n if (database1 < database2)\n return true;\n if (database1 > database2)\n return false;\n\n return version1 < version2;\n}\n\n\nvoid LoadAndSortUpdateFilenames(const bool test, const std::string &directory_path, std::vector * const update_filenames) {\n FileUtil::Directory directory(directory_path, \"[^.]+\\\\.\\\\d+\");\n for (const auto &entry : directory)\n update_filenames->emplace_back(entry.getName());\n\n std::sort(update_filenames->begin(), update_filenames->end(), FileNameCompare);\n\n if (test) {\n std::cerr << \"Sorted filenames:\\n\";\n for (const auto &filename : *update_filenames)\n std::cerr << filename << '\\n';\n std::exit(0);\n }\n}\n\n\nvoid ApplyUpdate(DbConnection * const db_connection, const std::string &update_directory_path, const std::string &update_filename) {\n std::string database;\n unsigned update_version;\n SplitIntoDatabaseAndVersion(update_filename, &database, &update_version);\n\n if (not db_connection->mySQLDatabaseExists(database)) {\n LOG_INFO(\"database \\\"\" + database + \"\\\" does not exist, skipping file \" + update_filename);\n return;\n }\n\n db_connection->queryOrDie(\"SET autocommit=0\");\n db_connection->queryOrDie(\"START TRANSACTION\");\n\n unsigned current_version(0);\n db_connection->queryOrDie(\"SELECT version FROM ub_tools.database_versions WHERE database_name='\"\n + db_connection->escapeString(database) + \"'\");\n DbResultSet result_set(db_connection->getLastResultSet());\n if (result_set.empty()) {\n db_connection->queryOrDie(\"INSERT INTO ub_tools.database_versions (database_name,version) VALUES ('\"\n + db_connection->escapeString(database) + \"',0)\");\n LOG_INFO(\"Created a new entry for database \\\"\" + database + \" in ub_tools.database_versions.\");\n } else\n current_version = StringUtil::ToUnsigned(result_set.getNextRow()[\"version\"]);\n if (update_version <= current_version)\n return;\n\n \/\/ Sanity check:\n if (unlikely(update_version != current_version + 1))\n LOG_ERROR(\"update version is \" + std::to_string(update_version) + \", current version is \"\n + std::to_string(current_version) + \" for database \\\"\" + database + \"\\\"!\");\n\n LOG_INFO(\"applying update \" + std::to_string(update_version) + \" to database \\\"\" + database + \"\\\".\");\n db_connection->queryFileOrDie(update_directory_path + \"\/\" + update_filename);\n db_connection->queryOrDie(\"UPDATE ub_tools.database_versions SET version=\" + std::to_string(update_version)\n + \" WHERE database_name='\" + db_connection->escapeString(database) + \"'\");\n\n db_connection->queryOrDie(\"COMMIT\");\n db_connection->queryOrDie(\"SET autocommit=1\");\n}\n\n\n} \/\/ unnamed namespace\n\n\nint Main(int argc, char *argv[]) {\n if (argc != 2 and argc != 3)\n Usage();\n\n bool test(false);\n if (argc == 3) {\n if (std::strcmp(argv[1], \"--test\") != 0)\n Usage();\n test = true;\n --argc, ++argv;\n }\n\n std::vector update_filenames;\n const std::string update_directory_path(argv[1]);\n LoadAndSortUpdateFilenames(test, update_directory_path, &update_filenames);\n\n DbConnection db_connection;\n const std::string system_table_name(\"database_versions\");\n if (not db_connection.tableExists(\"ub_tools\", system_table_name)) {\n db_connection.queryOrDie(\"CREATE TABLE ub_tools.\" + system_table_name + \" (version INT UNSIGNED NOT NULL,\"\n \"database_name VARCHAR(64) NOT NULL,UNIQUE (database_name)) \"\n \"CHARACTER SET utf8mb4 COLLATE utf8mb4_bin\");\n LOG_INFO(\"Created the ub_tools.\" + system_table_name + \" table.\");\n }\n\n for (const auto &update_filename : update_filenames)\n ApplyUpdate(&db_connection, update_directory_path, update_filename);\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"\/* $Id$ *\/\n# ifndef CPPAD_CHECK_SIMPLE_VECTOR_INCLUDED\n# define CPPAD_CHECK_SIMPLE_VECTOR_INCLUDED\n\n\/* --------------------------------------------------------------------------\nCppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-12 Bradley M. Bell\n\nCppAD is distributed under multiple licenses. This distribution is under\nthe terms of the \n Common Public License Version 1.0.\n\nA copy of this license is included in the COPYING file of this distribution.\nPlease visit http:\/\/www.coin-or.org\/CppAD\/ for information on other licenses.\n-------------------------------------------------------------------------- *\/\n\/*\n$begin CheckSimpleVector$$\n$spell\n\talloc\n\tconst\n\tcppad.hpp\n\tCppAD\n$$\n\n$section Check Simple Vector Concept$$\n\n$index simple, vector check$$\n$index vector, simple check$$\n$index check, simple vector$$\n$index concept, check simple vector$$\n\n$head Syntax$$\n$code # include $$\n$pre\n$$\n$codei%CheckSimpleVector<%Scalar%, %Vector%>()%$$\n$pre\n$$\n$codei%CheckSimpleVector<%Scalar%, %Vector%>(%x%, %y%)%$$\n\n\n$head Purpose$$\nPreforms compile and run time checks that the type specified\nby $icode Vector$$ satisfies all the requirements for \na $xref\/SimpleVector\/$$ class with \n$xref\/SimpleVector\/Elements of Specified Type\/elements of type\/$$ \n$icode Scalar$$.\nIf a requirement is not satisfied,\na an error message makes it clear what condition is not satisfied.\n\n$head x, y$$\nIf the arguments $icode x$$ and $icode y$$ are present,\nthey have prototype\n$codei%\n\tconst %Scalar%& %x%\n\tconst %Scalar%& %y%\n%$$\nIn addition, the check\n$code%\n\t%x% == %x%\n%$$\nwill return the boolean value $code true$$, and \n$code%\n\t%x% == %y%\n%$$\nwill return $code false$$.\n\n$head Restrictions$$\nIf the arguments $icode x$$ and $icode y$$ are not present,\nthe following extra assumption is made by $code CheckSimpleVector$$:\nIf $icode x$$ is a $icode Scalar$$ object\n$codei%\n\t%x% = 0\n\t%y% = 1\n%$$\nassigns values to the objects $icode x$$ and $icode y$$.\nIn addition, \n$icode%x% == %x%$$ would return the boolean value $code true$$ and\n$icode%x% == %y%$$ would return $code false$$.\n\n$head Include$$\nThe file $code cppad\/check_simple_vector.hpp$$ is included by $code cppad\/cppad.hpp$$\nbut it can also be included separately with out the rest\nif the CppAD include files.\n\n$head Parallel Mode$$\n$index parallel, CheckSimpleVector$$\n$index CheckSimpleVector, parallel$$\nThe routine $cref\/thread_alloc::parallel_setup\/ta_parallel_setup\/$$\nmust be called before it\ncan be used in $cref\/parallel\/ta_in_parallel\/$$ mode.\n\n$head Example$$\n$children%\n\texample\/check_simple_vector.cpp\n%$$\nThe file $xref\/CheckSimpleVector.cpp\/$$\ncontains an example and test of this function where $icode S$$\nis the same as $icode T$$.\nIt returns true, if it succeeds an false otherwise.\nThe comments in this example suggest a way to change the example\nso $icode S$$ is not the same as $icode T$$.\n\n$end\n---------------------------------------------------------------------------\n*\/\n\n# include \n# include \n# include \n# include \n\nnamespace CppAD {\n\n# ifdef NDEBUG\n\ttemplate \n\tinline void CheckSimpleVector(const Scalar& x, const Scalar& y)\n\t{ }\n\ttemplate \n\tinline void CheckSimpleVector(void)\n\t{ }\n# else\n\ttemplate \n\tstruct ok_if_S_same_as_T { };\n\n\ttemplate \n\tstruct ok_if_S_same_as_T { typedef T ok; };\n\n\ttemplate \n\tvoid CheckSimpleVector(const Scalar& x, const Scalar& y)\n\t{\tCPPAD_ASSERT_FIRST_CALL_NOT_PARALLEL\n\t\t\/\/ Section 3.6.2 of ISO\/IEC 14882:1998(E) states: \"The storage for \n\t\t\/\/ objects with static storage duration (3.7.1) shall be zero-\n\t\t\/\/ initialized (8.5) before any other initialization takes place.\"\n\t\tstatic size_t count[CPPAD_MAX_NUM_THREADS];\n\t\tsize_t thread = thread_alloc::thread_num();\n\t\tif( count[thread] > 0 )\n\t\t\treturn;\n\t\tcount[thread]++;\n\n\t\t\/\/ value_type must be type of elements of Vector\n\t\ttypedef typename Vector::value_type value_type;\n\n\t\t\/\/ check that elements of Vector have type Scalar\n\t\ttypedef typename ok_if_S_same_as_T::ok ok;\n\n\t\t\/\/ check default constructor\n\t\tVector d;\n\n\t\t\/\/ size member function\n\t\tCPPAD_ASSERT_KNOWN(\n\t\t\td.size() == 0,\n\t\t\t\"default construtor result does not have size zero\"\n\t\t);\n\n\t\t\/\/ resize to same size as other vectors in test\n\t\td.resize(1);\n\n\t\t\/\/ check sizing constructor\n\t\tVector s(1);\n\n\t\t\/\/ check element assignment\n\t\ts[0] = y;\n\t\tCPPAD_ASSERT_KNOWN(\n\t\t\ts[0] == y,\n\t\t\t\"element assignment failed\"\n\t\t);\n\n\t\t\/\/ check copy constructor\n\t\ts[0] = x;\n\t\tconst Vector c(s);\n\t\ts[0] = y;\n\t\tCPPAD_ASSERT_KNOWN(\n\t\t\tc[0] == x,\n\t\t\t\"copy constructor is shallow\"\n\t\t);\n\n\t\t\/\/ vector assignment operator\n\t\td[0] = x;\n\t\ts = d;\n\t\ts[0] = y;\n\t\tCPPAD_ASSERT_KNOWN(\n\t\t\td[0] == x,\n\t\t\t\"assignment operator is shallow\"\n\t\t);\n\n\t\t\/\/ element access, right side const\n\t\t\/\/ element assignment, left side not const\n\t\td[0] = c[0];\n\t\tCPPAD_ASSERT_KNOWN(\n\t\t\td[0] == x,\n\t\t\t\"element assignment from const failed\" \n\t\t);\n\t}\n\ttemplate \n\tvoid CheckSimpleVector(void)\n\t{\tScalar x;\n\t\tScalar y;\n\n\t\t\/\/ use assignment and not constructor\n\t\tx = 0;\n\t\ty = 1;\n\n\t\tCheckSimpleVector(x, y);\n\t}\n\n# endif\n\n} \/\/ end namespace CppAD\n\n# endif\ncheck_simple_vector.hpp: Only need check once.\/* $Id$ *\/\n# ifndef CPPAD_CHECK_SIMPLE_VECTOR_INCLUDED\n# define CPPAD_CHECK_SIMPLE_VECTOR_INCLUDED\n\n\/* --------------------------------------------------------------------------\nCppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-12 Bradley M. Bell\n\nCppAD is distributed under multiple licenses. This distribution is under\nthe terms of the \n Common Public License Version 1.0.\n\nA copy of this license is included in the COPYING file of this distribution.\nPlease visit http:\/\/www.coin-or.org\/CppAD\/ for information on other licenses.\n-------------------------------------------------------------------------- *\/\n\/*\n$begin CheckSimpleVector$$\n$spell\n\talloc\n\tconst\n\tcppad.hpp\n\tCppAD\n$$\n\n$section Check Simple Vector Concept$$\n\n$index simple, vector check$$\n$index vector, simple check$$\n$index check, simple vector$$\n$index concept, check simple vector$$\n\n$head Syntax$$\n$code # include $$\n$pre\n$$\n$codei%CheckSimpleVector<%Scalar%, %Vector%>()%$$\n$pre\n$$\n$codei%CheckSimpleVector<%Scalar%, %Vector%>(%x%, %y%)%$$\n\n\n$head Purpose$$\nPreforms compile and run time checks that the type specified\nby $icode Vector$$ satisfies all the requirements for \na $xref\/SimpleVector\/$$ class with \n$xref\/SimpleVector\/Elements of Specified Type\/elements of type\/$$ \n$icode Scalar$$.\nIf a requirement is not satisfied,\na an error message makes it clear what condition is not satisfied.\n\n$head x, y$$\nIf the arguments $icode x$$ and $icode y$$ are present,\nthey have prototype\n$codei%\n\tconst %Scalar%& %x%\n\tconst %Scalar%& %y%\n%$$\nIn addition, the check\n$code%\n\t%x% == %x%\n%$$\nwill return the boolean value $code true$$, and \n$code%\n\t%x% == %y%\n%$$\nwill return $code false$$.\n\n$head Restrictions$$\nIf the arguments $icode x$$ and $icode y$$ are not present,\nthe following extra assumption is made by $code CheckSimpleVector$$:\nIf $icode x$$ is a $icode Scalar$$ object\n$codei%\n\t%x% = 0\n\t%y% = 1\n%$$\nassigns values to the objects $icode x$$ and $icode y$$.\nIn addition, \n$icode%x% == %x%$$ would return the boolean value $code true$$ and\n$icode%x% == %y%$$ would return $code false$$.\n\n$head Include$$\nThe file $code cppad\/check_simple_vector.hpp$$ is included by $code cppad\/cppad.hpp$$\nbut it can also be included separately with out the rest\nif the CppAD include files.\n\n$head Parallel Mode$$\n$index parallel, CheckSimpleVector$$\n$index CheckSimpleVector, parallel$$\nThe routine $cref\/thread_alloc::parallel_setup\/ta_parallel_setup\/$$\nmust be called before it\ncan be used in $cref\/parallel\/ta_in_parallel\/$$ mode.\n\n$head Example$$\n$children%\n\texample\/check_simple_vector.cpp\n%$$\nThe file $xref\/CheckSimpleVector.cpp\/$$\ncontains an example and test of this function where $icode S$$\nis the same as $icode T$$.\nIt returns true, if it succeeds an false otherwise.\nThe comments in this example suggest a way to change the example\nso $icode S$$ is not the same as $icode T$$.\n\n$end\n---------------------------------------------------------------------------\n*\/\n\n# include \n# include \n# include \n# include \n\nnamespace CppAD {\n\n# ifdef NDEBUG\n\ttemplate \n\tinline void CheckSimpleVector(const Scalar& x, const Scalar& y)\n\t{ }\n\ttemplate \n\tinline void CheckSimpleVector(void)\n\t{ }\n# else\n\ttemplate \n\tstruct ok_if_S_same_as_T { };\n\n\ttemplate \n\tstruct ok_if_S_same_as_T { typedef T ok; };\n\n\ttemplate \n\tvoid CheckSimpleVector(const Scalar& x, const Scalar& y)\n\t{\tCPPAD_ASSERT_FIRST_CALL_NOT_PARALLEL\n\t\tstatic size_t count;\n\t\tif( count > 0 )\n\t\t\treturn;\n\t\tcount++;\n\n\t\t\/\/ value_type must be type of elements of Vector\n\t\ttypedef typename Vector::value_type value_type;\n\n\t\t\/\/ check that elements of Vector have type Scalar\n\t\ttypedef typename ok_if_S_same_as_T::ok ok;\n\n\t\t\/\/ check default constructor\n\t\tVector d;\n\n\t\t\/\/ size member function\n\t\tCPPAD_ASSERT_KNOWN(\n\t\t\td.size() == 0,\n\t\t\t\"default construtor result does not have size zero\"\n\t\t);\n\n\t\t\/\/ resize to same size as other vectors in test\n\t\td.resize(1);\n\n\t\t\/\/ check sizing constructor\n\t\tVector s(1);\n\n\t\t\/\/ check element assignment\n\t\ts[0] = y;\n\t\tCPPAD_ASSERT_KNOWN(\n\t\t\ts[0] == y,\n\t\t\t\"element assignment failed\"\n\t\t);\n\n\t\t\/\/ check copy constructor\n\t\ts[0] = x;\n\t\tconst Vector c(s);\n\t\ts[0] = y;\n\t\tCPPAD_ASSERT_KNOWN(\n\t\t\tc[0] == x,\n\t\t\t\"copy constructor is shallow\"\n\t\t);\n\n\t\t\/\/ vector assignment operator\n\t\td[0] = x;\n\t\ts = d;\n\t\ts[0] = y;\n\t\tCPPAD_ASSERT_KNOWN(\n\t\t\td[0] == x,\n\t\t\t\"assignment operator is shallow\"\n\t\t);\n\n\t\t\/\/ element access, right side const\n\t\t\/\/ element assignment, left side not const\n\t\td[0] = c[0];\n\t\tCPPAD_ASSERT_KNOWN(\n\t\t\td[0] == x,\n\t\t\t\"element assignment from const failed\" \n\t\t);\n\t}\n\ttemplate \n\tvoid CheckSimpleVector(void)\n\t{\tScalar x;\n\t\tScalar y;\n\n\t\t\/\/ use assignment and not constructor\n\t\tx = 0;\n\t\ty = 1;\n\n\t\tCheckSimpleVector(x, y);\n\t}\n\n# endif\n\n} \/\/ end namespace CppAD\n\n# endif\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n\/\/this quiets a deprecated warning\n#define BOOST_NO_HASH\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nnamespace ecto\n{\n\nnamespace\n{\nusing boost::adjacency_list;\nusing boost::vecS;\nusing boost::bidirectionalS;\nusing boost::graph_traits;\nusing boost::tie;\nusing boost::add_vertex;\n\nstruct edge\n{\n edge(const std::string& fp, const std::string& tp) :\n from_port(fp), to_port(tp)\n {\n }\n\n std::string from_port, to_port;\n std::deque deque;\n typedef boost::shared_ptr ptr;\n typedef boost::shared_ptr const_ptr;\n};\n\n\/\/ if the first argument is a sequence type (vecS, etc) then parallel edges are allowed\ntypedef adjacency_list \/\/ edge property\ngraph_t;\n\nstruct vertex_writer\n{\n graph_t* g;\n\n vertex_writer(graph_t* g_) :\n g(g_)\n {\n }\n\n void operator()(std::ostream& out, graph_t::vertex_descriptor vd)\n {\n out << \"[label=\\\"\" << (*g)[vd]->name() << \"\\\"]\";\n }\n};\n\nstruct edge_writer\n{\n graph_t* g;\n\n edge_writer(graph_t* g_) :\n g(g_)\n {\n }\n\n void operator()(std::ostream& out, graph_t::edge_descriptor ed)\n {\n out << \"[headlabel=\\\"\" << (*g)[ed]->to_port << \"\\\" taillabel=\\\"\" << (*g)[ed]->from_port << \"\\\"]\";\n }\n};\n\nstruct graph_writer\n{\n void operator()(std::ostream& out) const\n {\n out << \"graph [rankdir=TB, ranksep=1]\" << std::endl;\n out << \"edge [labelfontsize=8]\" << std::endl;\n }\n};\n\nedge::ptr make_edge(const std::string& fromport, const std::string& toport)\n{\n edge::ptr eptr(new edge(fromport, toport));\n return eptr;\n}\n\n} \/\/ namespace\n\nstruct plasm::impl\n{\n impl()\n {\n }\n\n \/\/insert a module into the graph, will retrieve the\n \/\/vertex descriptor if its already in the graph...\n graph_t::vertex_descriptor insert_module(module::ptr m)\n {\n \/\/use the vertex map to look up the graphviz descriptor (reverse lookup)\n ModuleVertexMap::iterator it = mv_map.find(m);\n if (it != mv_map.end())\n return it->second;\n graph_t::vertex_descriptor d = add_vertex(m, graph);\n mv_map.insert(std::make_pair(m, d));\n return d;\n }\n\n void connect(module::ptr from, std::string output, module::ptr to, std::string input)\n {\n \/\/throw if the types are bad...\n to->inputs[input].enforce_compatible_type(from->outputs[output]);\n\n graph_t::vertex_descriptor fromv = insert_module(from), tov = insert_module(to);\n edge::ptr new_edge = make_edge(output, input);\n\n \/\/assert that the new edge does not violate inputs that are already connected.\n \/\/RULE an input may only have one source.\n graph_t::in_edge_iterator inbegin, inend;\n tie(inbegin, inend) = boost::in_edges(tov, graph);\n while (inbegin != inend)\n {\n edge::ptr e = graph[*inbegin];\n if (e->to_port == new_edge->to_port)\n {\n throw std::runtime_error(new_edge->to_port + \" is already connected, this is considered an error\");\n }\n ++inbegin;\n }\n\n bool added;\n graph_t::edge_descriptor ed;\n tie(ed, added) = boost::add_edge(fromv, tov, new_edge, graph);\n if (!added)\n {\n throw std::runtime_error(\n \"failed to connect \" + from->name() + \":\" + output + \" with \" + to->name() + \":\"\n + input);\n }\n \/\/clear stack to mark the ordering dirty...\n stack.clear();\n }\n\n void disconnect(module::ptr from, std::string output, module::ptr to, std::string input)\n {\n graph_t::vertex_descriptor fromv = insert_module(from), tov = insert_module(to);\n boost::remove_edge(fromv, tov, graph);\n }\n\n int invoke_process(graph_t::vertex_descriptor vd)\n {\n \/\/boost::timer t;\n module::ptr m = graph[vd];\n\n graph_t::in_edge_iterator inbegin, inend;\n tie(inbegin, inend) = boost::in_edges(vd, graph);\n while (inbegin != inend)\n {\n edge::ptr e = graph[*inbegin];\n m->inputs.at(e->to_port).copy_value(e->deque.front());\n e->deque.pop_front();\n ++inbegin;\n }\n int val = m->process();\n\n graph_t::out_edge_iterator outbegin, outend;\n tie(outbegin, outend) = boost::out_edges(vd, graph);\n while (outbegin != outend)\n {\n edge::ptr e = graph[*outbegin];\n e->deque.push_back(m->outputs.at(e->from_port));\n ++outbegin;\n }\n \/\/std::cout << m->name() << \" time: \" << t.elapsed() * 1000.0 << \"\\n\";\n return val;\n }\n\n void compute_stack()\n {\n if (!stack.empty()) \/\/will be empty if this needs to be computed.\n return;\n boost::topological_sort(graph, std::back_inserter(stack));\n std::reverse(stack.begin(), stack.end());\n }\n\n int execute()\n {\n \/\/compute ordering\n compute_stack();\n for (size_t k = 0; k < stack.size(); ++k)\n {\n \/\/need to check the return val of a process here, non zero means exit...\n size_t retval = invoke_process(stack[k]);\n if (retval)\n return retval;\n }\n return 0;\n }\n \/\/the module to vertex mapping\n \/\/unordered_map so that module ptr works as a key...\n typedef boost::unordered_map ModuleVertexMap;\n ModuleVertexMap mv_map;\n graph_t graph;\n std::vector stack;\n};\n\nplasm::plasm() :\n impl_(new impl)\n{\n}\n\nvoid plasm::insert(module::ptr mod)\n{\n impl_->insert_module(mod);\n}\n\nvoid plasm::connect(module::ptr from, const std::string& output, module::ptr to, const std::string& input)\n{\n impl_->connect(from, output, to, input);\n}\n\nvoid plasm::viz(std::ostream& out) const\n{\n boost::write_graphviz(out, impl_->graph, vertex_writer(&impl_->graph), edge_writer(&impl_->graph), graph_writer());\n}\n\nstd::string plasm::viz() const\n{\n std::stringstream ss;\n viz(ss);\n return ss.str();\n}\n\nint plasm::execute()\n{\n return impl_->execute();\n}\n\nvoid plasm::spin()\n{\n for (;;)\n {\n if (execute())\n return;\n }\n}\n\nvoid plasm::disconnect(module_ptr from, const std::string& output, module_ptr to, const std::string& input)\n{\n impl_->disconnect(from, output, to, input);\n}\n}\nCatch and release exceptions for debugging the graph.#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n\/\/this quiets a deprecated warning\n#define BOOST_NO_HASH\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nnamespace ecto\n{\n\nnamespace\n{\nusing boost::adjacency_list;\nusing boost::vecS;\nusing boost::bidirectionalS;\nusing boost::graph_traits;\nusing boost::tie;\nusing boost::add_vertex;\n\nstruct edge\n{\n edge(const std::string& fp, const std::string& tp) :\n from_port(fp), to_port(tp)\n {\n }\n\n std::string from_port, to_port;\n std::deque deque;\n typedef boost::shared_ptr ptr;\n typedef boost::shared_ptr const_ptr;\n};\n\n\/\/ if the first argument is a sequence type (vecS, etc)\n\/\/ then parallel edges are allowed\ntypedef adjacency_list \/\/ edge property\ngraph_t;\n\nstruct vertex_writer\n{\n graph_t* g;\n\n vertex_writer(graph_t* g_) :\n g(g_)\n {\n }\n\n void operator()(std::ostream& out, graph_t::vertex_descriptor vd)\n {\n out << \"[label=\\\"\" << (*g)[vd]->name() << \"\\\"]\";\n }\n};\n\nstruct edge_writer\n{\n graph_t* g;\n\n edge_writer(graph_t* g_) :\n g(g_)\n {\n }\n\n void operator()(std::ostream& out, graph_t::edge_descriptor ed)\n {\n out << \"[headlabel=\\\"\" << (*g)[ed]->to_port << \"\\\" taillabel=\\\"\"\n << (*g)[ed]->from_port << \"\\\"]\";\n }\n};\n\nstruct graph_writer\n{\n void operator()(std::ostream& out) const\n {\n out << \"graph [rankdir=TB, ranksep=1]\" << std::endl;\n out << \"edge [labelfontsize=8]\" << std::endl;\n }\n};\n\nedge::ptr make_edge(const std::string& fromport, const std::string& toport)\n{\n edge::ptr eptr(new edge(fromport, toport));\n return eptr;\n}\n\n} \/\/ namespace\n\nstruct plasm::impl\n{\n impl()\n {\n }\n\n \/\/insert a module into the graph, will retrieve the\n \/\/vertex descriptor if its already in the graph...\n graph_t::vertex_descriptor insert_module(module::ptr m)\n {\n \/\/use the vertex map to look up the graphviz descriptor (reverse lookup)\n ModuleVertexMap::iterator it = mv_map.find(m);\n if (it != mv_map.end())\n return it->second;\n graph_t::vertex_descriptor d = add_vertex(m, graph);\n mv_map.insert(std::make_pair(m, d));\n return d;\n }\n\n void connect(module::ptr from, std::string output, module::ptr to,\n std::string input)\n {\n \/\/throw if the types are bad...\n to->inputs[input].enforce_compatible_type(from->outputs[output]);\n\n graph_t::vertex_descriptor fromv = insert_module(from), tov =\n insert_module(to);\n edge::ptr new_edge = make_edge(output, input);\n\n \/\/assert that the new edge does not violate inputs that are\n \/\/already connected.\n \/\/RULE an input may only have one source.\n graph_t::in_edge_iterator inbegin, inend;\n tie(inbegin, inend) = boost::in_edges(tov, graph);\n while (inbegin != inend)\n {\n edge::ptr e = graph[*inbegin];\n if (e->to_port == new_edge->to_port)\n {\n throw std::runtime_error(\n new_edge->to_port\n + \" is already connected, this is considered an error\");\n }\n ++inbegin;\n }\n\n bool added;\n graph_t::edge_descriptor ed;\n tie(ed, added) = boost::add_edge(fromv, tov, new_edge, graph);\n if (!added)\n {\n throw std::runtime_error(\n \"failed to connect \" + from->name() + \":\"\n + output + \" with \" + to->name() + \":\"\n + input);\n }\n \/\/clear stack to mark the ordering dirty...\n stack.clear();\n }\n\n void disconnect(module::ptr from, std::string output, module::ptr to,\n std::string input)\n {\n graph_t::vertex_descriptor fromv = insert_module(from), tov =\n insert_module(to);\n boost::remove_edge(fromv, tov, graph);\n }\n\n int invoke_process(graph_t::vertex_descriptor vd)\n {\n boost::timer t;\n module::ptr m = graph[vd];\n\n graph_t::in_edge_iterator inbegin, inend;\n tie(inbegin, inend) = boost::in_edges(vd, graph);\n while (inbegin != inend)\n {\n edge::ptr e = graph[*inbegin];\n m->inputs.at(e->to_port).copy_value(e->deque.front());\n e->deque.pop_front();\n ++inbegin;\n }\n int val = 1;\n try\n {\n val = m->process();\n } catch (std::exception& e)\n {\n throw std::runtime_error(\n m->name() + \" threw an exception :\\n\"\n + e.what());\n }\n graph_t::out_edge_iterator outbegin, outend;\n tie(outbegin, outend) = boost::out_edges(vd, graph);\n while (outbegin != outend)\n {\n edge::ptr e = graph[*outbegin];\n e->deque.push_back(m->outputs.at(e->from_port));\n ++outbegin;\n }\n timings_total[vd] += t.elapsed();\n \/\/std::cout << m->name() << \" time: \" << t.elapsed() * 1000.0 << \"\\n\";\n return val;\n }\n\n void compute_stack()\n {\n if (!stack.empty()) \/\/will be empty if this needs to be computed.\n return;\n boost::topological_sort(graph, std::back_inserter(stack));\n std::reverse(stack.begin(), stack.end());\n }\n\n int execute()\n {\n \/\/compute ordering\n compute_stack();\n for (size_t k = 0; k < stack.size(); ++k)\n {\n \/\/need to check the return val of a process here, non zero means exit...\n size_t retval = invoke_process(stack[k]);\n if (retval)\n return retval;\n }\n return 0;\n }\n \/\/the module to vertex mapping\n \/\/unordered_map so that module ptr works as a key...\n typedef boost::unordered_map\n ModuleVertexMap;\n ModuleVertexMap mv_map;\n graph_t graph;\n std::vector stack;\n std::map timings_total;\n\n};\n\nplasm::plasm() :\n impl_(new impl)\n{\n}\n\nvoid plasm::insert(module::ptr mod)\n{\n impl_->insert_module(mod);\n}\n\nvoid plasm::connect(module::ptr from, const std::string& output,\n module::ptr to, const std::string& input)\n{\n impl_->connect(from, output, to, input);\n}\n\nvoid plasm::viz(std::ostream& out) const\n{\n boost::write_graphviz(out, impl_->graph, vertex_writer(&impl_->graph),\n edge_writer(&impl_->graph), graph_writer());\n}\n\nstd::string plasm::viz() const\n{\n std::stringstream ss;\n viz(ss);\n return ss.str();\n}\n\nint plasm::execute()\n{\n return impl_->execute();\n}\n\nvoid plasm::spin()\n{\n for (;;)\n {\n if (execute())\n return;\n }\n}\n\nvoid plasm::disconnect(module_ptr from, const std::string& output,\n module_ptr to, const std::string& input)\n{\n impl_->disconnect(from, output, to, input);\n}\n}\n<|endoftext|>"} {"text":"#ifndef __FUTURE_HPP__\n#define __FUTURE_HPP__\n\n#include \"SoftXMT.hpp\"\n#include \"Delegate.hpp\"\n#include \"Cache.hpp\"\n\n\/\/TODO: special ArgsCache acquire, which\n\/\/uses args pointer field as a global address\n\/\/to the future and either\n\/\/1. flip the started bit\n\/\/2. or simply acquire RW instead of RO (and Cached not Incoherent)\n\n\/\/ idea: if we had a need for futures that\n\/\/ only mutate their arguments (essentially functional but could change the inputs as well)\n\/\/ then we could allow multiple copies of\n\/\/ the future to execute RW-shared mode, where only the first release writeback wins\n\n\n\/\/ TODO: do something like this to force users to have\n\/\/ the future fields but make them invisible\n\/*\nclass FutureArgs {\n private:\n GlobalAddress futurePtr;\n void (* user_fn_p)(A *);\n};\nclass MyArgs : public FutureArgs {\n int i;\n int j;\n}\n\/\/ Additional possibility is method #2 above\n *\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#if DEBUG\nstatic int64_t count_ = 0;\n#endif\n\ntemplate < typename ArgsStruct >\nclass Future {\n private:\n int64_t started;\n Thread * waiter;\n bool done;\n ArgsStruct * userArgs_lp;\n \n struct future_args {\n GlobalAddress futureAddr;\n void (* user_fn_p)(ArgsStruct *);\n GlobalAddress< ArgsStruct > userArgs;\n\n future_args( Future< ArgsStruct > * future, ArgsStruct * userArgs, void (* fn_p)(ArgsStruct *) )\n : futureAddr( make_global( future ) )\n , userArgs( make_global( userArgs ) )\n , user_fn_p( fn_p ) \n { }\n };\n \n future_args task_args;\n\n struct future_done_args { \n Future< ArgsStruct > * futurePtr;\n };\n \n static void future_done_am( future_done_args * args, size_t args_size, void * payload, size_t payload_size ) {\n args->futurePtr->done = true;\n if ( args->futurePtr->waiter != NULL ) {\n SoftXMT_wake( args->futurePtr->waiter );\n args->futurePtr->waiter = NULL;\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/Custom delegate operation\n \/\/TODO: use a generalized mechanism that abstracts all but function\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n struct started_memory_descriptor {\n Thread * t;\n GlobalAddress< Future > address;\n int64_t data;\n bool done;\n };\n\n struct started_reply_args {\n GlobalAddress descriptor;\n };\n\n static void started_reply_am( started_reply_args * args, size_t size, void * payload, size_t payload_size ) {\n assert( payload_size == sizeof(int64_t ) );\n args->descriptor.pointer()->data = *(static_cast(payload));\n args->descriptor.pointer()->done = true;\n SoftXMT_wake( args->descriptor.pointer()->t );\n }\n \n struct started_request_args {\n GlobalAddress descriptor;\n GlobalAddress< Future > address;\n };\n\n static void started_request_am( started_request_args * args, size_t size, void * payload, size_t payload_size ) {\n Future< ArgsStruct > * fptr = args->address.pointer();\n\n CHECK((int64_t)fptr>0x1000) << \"dequeued request (node:\" << args->descriptor.node()\n << \"): future ptr:\" << (void*)fptr\n << \"(id:\"<getId()<<\")\";\n int64_t data = fptr->started;\n fptr->started = data + 1;\n \n \/\/ If future was already started in this case, it must have been started by touching thread.\n \/\/ Incrementing started again will tell the touching thread it can deallocate the Future\n if ( data > 0 ) {\n VLOG(2) << \"already started:(id:\"<getId();\n if ( fptr->done ) { \/\/if it is done then toucher is waiting for the dequeue\n VLOG(2) << \"need to wake:(id:\"<getId();\n CHECK ( fptr->waiter!=NULL ) << \"future ptr:\" << (void*)fptr <<\"\\n done=\"<done<<\" (id:\"<getId()<<\")\";\n SoftXMT_wake( fptr->waiter );\n fptr->waiter = NULL;\n } else {\n VLOG(2) << \"not need to wake:(id:\"<getId();\n }\n } else {\n VLOG(2) << \"not already started:(id:\"<getId();\n }\n \n started_reply_args reply_args;\n reply_args.descriptor = args->descriptor;\n SoftXMT_call_on( args->descriptor.node(), &started_reply_am, \n &reply_args, sizeof(reply_args),\n &data, sizeof(data) );\n }\n\n static int64_t future_delegate_started( GlobalAddress< Future > address ) {\n started_memory_descriptor md;\n md.address = address;\n md.data = 0;\n md.done = false;\n md.t = CURRENT_THREAD;\n started_request_args args;\n args.descriptor = make_global(&md);\n args.address = address;\n SoftXMT_call_on( address.node(), &started_request_am, &args );\n while( !md.done ) {\n SoftXMT_suspend();\n }\n return md.data;\n }\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n static void future_function( future_args * args ) {\n \/\/ TODO #1: the make_global is just calculating location of Future->started\n \/\/if ( SoftXMT_delegate_fetch_and_add_word( make_global( args->startedAddr, args->futureAddr.node() ), 1 ) == 0 ) { \n VLOG(2) << CURRENT_THREAD->id << \"args(\"<<(void*)args<<\") will call started am \" << args->futureAddr.pointer();\n if ( future_delegate_started( args->futureAddr ) == 0 ) { \n VLOG(2) << CURRENT_THREAD->id << \"user_args=\"<userArgs<<\" for ftraddr=\"<< args->futureAddr.pointer();\n \/\/ grab the user arguments\n size_t args_size = sizeof(ArgsStruct);\n ArgsStruct argsbuf;\n typename Incoherent::RO cached_args( args->userArgs, args_size, &argsbuf );\n cached_args.block_until_acquired();\n \n \/\/ call the user task\n args->user_fn_p( &argsbuf );\n cached_args.block_until_released();\n\n \/\/ call wake up AM on Node that has the Future\n future_done_args done_args = { args->futureAddr.pointer() };\n SoftXMT_call_on( args->futureAddr.node(), &future_done_am, &done_args );\n } \n }\n\n int64_t getId() {\n#if DEBUG\n return id;\n#else \n return -1;\n#endif \n }\n \n public:\n#if DEBUG\n int64_t id;\n#endif\n\n\n \/\/ TODO: NOTE that this does not copy user arguments because we want to \n \/\/ preserve the same semantics as normal tasks.\n \/\/ --Unfortunately this means there are three communications to start\n \/\/ 1) Task.execute fetches args\n \/\/ 2) Future atomic started\n \/\/ 3) Bring in user arguments and start\n Future ( void (* fn_p)(ArgsStruct *), ArgsStruct * userArgs )\n : started( 0 )\n , waiter( NULL )\n , done( false )\n , userArgs_lp( userArgs )\n#if DEBUG\n , id( count_++ )\n#endif\n , task_args( this, userArgs, fn_p ) { \n \n VLOG(2) << CURRENT_THREAD->id << \" creates Future:\"<< (void*)this << \" id:\"<< getId() << \" args:\"<< &task_args;\n }\n\n void touch( ) {\n \/\/ start if not started\n if ( SoftXMT_delegate_fetch_and_add_word( make_global(&started), 1 )==0 ) {\n VLOG(2) << CURRENT_THREAD->id << \" gets to touch-go \" << getId();\n task_args.user_fn_p( userArgs_lp );\n done = true;\n while ( started < 2 ) { \/\/ wait until dequeued\n VLOG(2) << CURRENT_THREAD->id << \" has to wait on dequeue \" << getId();\n waiter = CURRENT_THREAD;\n SoftXMT_suspend( );\n VLOG(2) << CURRENT_THREAD->id << \" has woke on dequeue \" << getId();\n }\n } else {\n \/\/ otherwise block on done event\n while ( !done ) {\n waiter = CURRENT_THREAD;\n SoftXMT_suspend( );\n }\n }\n }\n\n void asPublicTask( ) {\n SoftXMT_publicTask( &future_function, &task_args );\n }\n};\n\n#endif\ndebug logging for futures#ifndef __FUTURE_HPP__\n#define __FUTURE_HPP__\n\n#include \"SoftXMT.hpp\"\n#include \"Delegate.hpp\"\n#include \"Cache.hpp\"\n\n\/\/TODO: special ArgsCache acquire, which\n\/\/uses args pointer field as a global address\n\/\/to the future and either\n\/\/1. flip the started bit\n\/\/2. or simply acquire RW instead of RO (and Cached not Incoherent)\n\n\/\/ idea: if we had a need for futures that\n\/\/ only mutate their arguments (essentially functional but could change the inputs as well)\n\/\/ then we could allow multiple copies of\n\/\/ the future to execute RW-shared mode, where only the first release writeback wins\n\n\n\/\/ TODO: do something like this to force users to have\n\/\/ the future fields but make them invisible\n\/*\nclass FutureArgs {\n private:\n GlobalAddress futurePtr;\n void (* user_fn_p)(A *);\n};\nclass MyArgs : public FutureArgs {\n int i;\n int j;\n}\n\/\/ Additional possibility is method #2 above\n *\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#if DEBUG\nstatic int64_t count_ = 0;\n#endif\n\ntemplate < typename ArgsStruct >\nclass Future {\n private:\n int64_t started;\n Thread * waiter;\n bool done;\n ArgsStruct * userArgs_lp;\n \n struct future_args {\n GlobalAddress futureAddr;\n void (* user_fn_p)(ArgsStruct *);\n GlobalAddress< ArgsStruct > userArgs;\n\n future_args( Future< ArgsStruct > * future, ArgsStruct * userArgs, void (* fn_p)(ArgsStruct *) )\n : futureAddr( make_global( future ) )\n , userArgs( make_global( userArgs ) )\n , user_fn_p( fn_p ) \n { }\n };\n \n future_args task_args;\n\n struct future_done_args { \n Future< ArgsStruct > * futurePtr;\n };\n \n static void future_done_am( future_done_args * args, size_t args_size, void * payload, size_t payload_size ) {\n args->futurePtr->done = true;\n if ( args->futurePtr->waiter != NULL ) {\n SoftXMT_wake( args->futurePtr->waiter );\n args->futurePtr->waiter = NULL;\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/Custom delegate operation\n \/\/TODO: use a generalized mechanism that abstracts all but function\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n struct started_memory_descriptor {\n Thread * t;\n GlobalAddress< Future > address;\n int64_t data;\n bool done;\n };\n\n struct started_reply_args {\n GlobalAddress descriptor;\n };\n\n static void started_reply_am( started_reply_args * args, size_t size, void * payload, size_t payload_size ) {\n assert( payload_size == sizeof(int64_t ) );\n args->descriptor.pointer()->data = *(static_cast(payload));\n args->descriptor.pointer()->done = true;\n SoftXMT_wake( args->descriptor.pointer()->t );\n }\n \n struct started_request_args {\n GlobalAddress descriptor;\n GlobalAddress< Future > address;\n };\n\n static void started_request_am( started_request_args * args, size_t size, void * payload, size_t payload_size ) {\n Future< ArgsStruct > * fptr = args->address.pointer();\n \n DVLOG(5) << \"Future(IN_AM) FID \"<< fptr->getId();\n\n CHECK((int64_t)fptr>0x1000) << \"dequeued request (descriptor gaddress:\" << args->descriptor\n << \"): future ptr:\" << (void*)fptr\n << \"(future gaddress:\"<address;\n int64_t data = fptr->started;\n fptr->started = data + 1;\n \n \/\/ If future was already started in this case, it must have been started by touching thread.\n \/\/ Incrementing started again will tell the touching thread it can deallocate the Future\n if ( data > 0 ) {\n DVLOG(5) << \"already started:(id:\"<getId();\n if ( fptr->done ) { \/\/if it is done then toucher is waiting for the dequeue\n DVLOG(5) << \"need to wake:(id:\"<getId();\n CHECK ( fptr->waiter!=NULL ) << \"future ptr:\" << (void*)fptr <<\"\\n done=\"<done<<\" (id:\"<getId()<<\") data=\"<descriptor.node();\n SoftXMT_wake( fptr->waiter );\n fptr->waiter = NULL;\n } else {\n DVLOG(5) << \"not need to wake:(id:\"<getId();\n }\n } else {\n DVLOG(5) << \"not already started:(id:\"<getId();\n }\n \n started_reply_args reply_args;\n reply_args.descriptor = args->descriptor;\n SoftXMT_call_on( args->descriptor.node(), &started_reply_am, \n &reply_args, sizeof(reply_args),\n &data, sizeof(data) );\n }\n\n static int64_t future_delegate_started( GlobalAddress< Future > address ) {\n started_memory_descriptor md;\n md.address = address;\n md.data = 0;\n md.done = false;\n md.t = CURRENT_THREAD;\n started_request_args args;\n args.descriptor = make_global(&md);\n args.address = address;\n SoftXMT_call_on( address.node(), &started_request_am, &args );\n while( !md.done ) {\n SoftXMT_suspend();\n }\n return md.data;\n }\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n static void future_function( future_args * args ) {\n DVLOG(4) << \"Future(other) \"<< args->futureAddr;\n \/\/ TODO #1: the make_global is just calculating location of Future->started\n \/\/if ( SoftXMT_delegate_fetch_and_add_word( make_global( args->startedAddr, args->futureAddr.node() ), 1 ) == 0 ) { \n DVLOG(5) << CURRENT_THREAD->id << \"args(\"<<(void*)args<<\") will call started am \" << args->futureAddr.pointer();\n if ( future_delegate_started( args->futureAddr ) == 0 ) { \n DVLOG(5) << CURRENT_THREAD->id << \"user_args=\"<userArgs<<\" for ftraddr=\"<< args->futureAddr.pointer();\n \/\/ grab the user arguments\n size_t args_size = sizeof(ArgsStruct);\n ArgsStruct argsbuf;\n typename Incoherent::RO cached_args( args->userArgs, args_size, &argsbuf );\n cached_args.block_until_acquired();\n \n \/\/ call the user task\n args->user_fn_p( &argsbuf );\n cached_args.block_until_released();\n\n \/\/ call wake up AM on Node that has the Future\n future_done_args done_args = { args->futureAddr.pointer() };\n SoftXMT_call_on( args->futureAddr.node(), &future_done_am, &done_args );\n } \n }\n\n int64_t getId() {\n#if DEBUG\n return id;\n#else \n return -1;\n#endif \n }\n \n public:\n#if DEBUG\n int64_t id;\n#endif\n\n\n \/\/ TODO: NOTE that this does not copy user arguments because we want to \n \/\/ preserve the same semantics as normal tasks.\n \/\/ --Unfortunately this means there are three communications to start\n \/\/ 1) Task.execute fetches args\n \/\/ 2) Future atomic started\n \/\/ 3) Bring in user arguments and start\n Future ( void (* fn_p)(ArgsStruct *), ArgsStruct * userArgs )\n : started( 0 )\n , waiter( NULL )\n , done( false )\n , userArgs_lp( userArgs )\n#if DEBUG\n , id( SoftXMT_mynode() + ((count_++)*SoftXMT_nodes() ) )\n#endif\n , task_args( this, userArgs, fn_p ) { \n \n DVLOG(5) << CURRENT_THREAD->id << \" creates Future:\"<< (void*)this << \" id:\"<< getId() << \" args:\"<< &task_args;\n }\n\n void touch( ) {\n DVLOG(4) << \"Future(touch) FID \"<< this->getId() << \" ga:\"<id << \" gets to touch-go \" << getId();\n task_args.user_fn_p( userArgs_lp );\n CHECK( started <= 2 ) << \"started=\" << started << \" (at most one additional increment should occur)\";\n done = true;\n while ( started < 2 ) { \/\/ wait until dequeued\n DVLOG(5) << CURRENT_THREAD->id << \" has to wait on dequeue \" << getId();\n waiter = CURRENT_THREAD;\n SoftXMT_suspend( );\n DVLOG(5) << CURRENT_THREAD->id << \" has woke on dequeue \" << getId();\n }\n } else {\n \/\/ otherwise block on done event\n while ( !done ) {\n waiter = CURRENT_THREAD;\n SoftXMT_suspend( );\n }\n }\n }\n\n void asPublicTask( ) {\n DVLOG(4) << \"Future(spawn) \" << this->getId() << \" ga:\"<"} {"text":"\/*\n * Copyright (c) 2013, Hernan Saez\n * All rights reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef CRIMILD_CORE_FOUNDATION_MEMORY_\n#define CRIMILD_CORE_FOUNDATION_MEMORY_\n\n#include \n#include \n\nnamespace crimild {\n\n template< typename T >\n using SharedPointer = std::shared_ptr< T >;\n\n template< typename T >\n using UniquePointer = std::unique_ptr< T >;\n \n template< typename T, typename... Args >\n SharedPointer< T > alloc( Args &&... args )\n {\n \/\/ use 'new' instead of 'make_shared' to force the use of\n \/\/ the custom allocator.\n \/\/ TODO: use alloc_shared?\n return SharedPointer< T >( new T( std::forward< Args >( args )... ) );\n }\n\n template< typename T, typename... Args >\n UniquePointer< T > alloc_unique( Args &&... args )\n {\n return std::unique_ptr< T >( new T( std::forward< Args >( args )... ) ); \n }\n \n template< typename T >\n SharedPointer< T > retain( T *ptr )\n {\n if ( ptr == nullptr ) {\n return nullptr;\n }\n \n return std::static_pointer_cast< T >( ptr->shared_from_this() );\n }\n \n template< typename T >\n inline SharedPointer< T > &retain( SharedPointer< T > &ptr ) noexcept\n {\n \/\/ Returns the same pointer.\n \/\/ This is a helper function that comes in handy for templates and generic code\n return ptr;\n }\n\n template< typename T >\n T *get_ptr( SharedPointer< T > const &ptr )\n {\n return ptr.get();\n }\n\n template< typename T >\n inline T *get_ptr( T *ptr ) noexcept\n {\n \/\/ Returns the same pointer.\n \/\/ This is a helper function that comes in handy for templates and generic code\n return ptr;\n }\n \n template< class T, class U >\n SharedPointer< T > cast_ptr( SharedPointer< U > const &ptr )\n {\n return std::static_pointer_cast< T >( ptr );\n }\n \n template< class T, class U >\n SharedPointer< T > dynamic_cast_ptr( SharedPointer< U > const &ptr )\n {\n return std::dynamic_pointer_cast< T >( ptr );\n }\n \n}\n\n#endif\n\nHelper function to cast raw pointers\/*\n * Copyright (c) 2013, Hernan Saez\n * All rights reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef CRIMILD_CORE_FOUNDATION_MEMORY_\n#define CRIMILD_CORE_FOUNDATION_MEMORY_\n\n#include \n#include \n\nnamespace crimild {\n\n template< typename T >\n using SharedPointer = std::shared_ptr< T >;\n\n template< typename T >\n using UniquePointer = std::unique_ptr< T >;\n\n template< typename T, typename... Args >\n SharedPointer< T > alloc( Args &&...args )\n {\n \/\/ use 'new' instead of 'make_shared' to force the use of\n \/\/ the custom allocator.\n \/\/ TODO: use alloc_shared?\n return SharedPointer< T >( new T( std::forward< Args >( args )... ) );\n }\n\n template< typename T, typename... Args >\n UniquePointer< T > alloc_unique( Args &&...args )\n {\n return std::unique_ptr< T >( new T( std::forward< Args >( args )... ) );\n }\n\n template< typename T >\n SharedPointer< T > retain( T *ptr )\n {\n if ( ptr == nullptr ) {\n return nullptr;\n }\n\n return std::static_pointer_cast< T >( ptr->shared_from_this() );\n }\n\n template< typename T >\n inline SharedPointer< T > &retain( SharedPointer< T > &ptr ) noexcept\n {\n \/\/ Returns the same pointer.\n \/\/ This is a helper function that comes in handy for templates and generic code\n return ptr;\n }\n\n template< typename T >\n T *get_ptr( SharedPointer< T > const &ptr )\n {\n return ptr.get();\n }\n\n template< typename T >\n inline T *get_ptr( T *ptr ) noexcept\n {\n \/\/ Returns the same pointer.\n \/\/ This is a helper function that comes in handy for templates and generic code\n return ptr;\n }\n\n template< class T, class U >\n SharedPointer< T > cast_ptr( SharedPointer< U > const &ptr )\n {\n return std::static_pointer_cast< T >( ptr );\n }\n\n template< class T, class U >\n T *cast_ptr( U *ptr )\n {\n return static_cast< T * >( ptr );\n }\n\n template< class T, class U >\n SharedPointer< T > dynamic_cast_ptr( SharedPointer< U > const &ptr )\n {\n return std::dynamic_pointer_cast< T >( ptr );\n }\n\n}\n\n#endif\n<|endoftext|>"} {"text":"\/\/ Copyright 2011 Branan Purvine-Riley and Adam Johnson\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n \/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"implementation.hpp\"\n#include \"..\/interface.hpp\"\n#include \"glexcept.hpp\"\n#include \"..\/Material.hpp\"\n#include \"..\/Drawable.hpp\"\n#include \"..\/Image.hpp\"\n\n#include \n\nPipeline::Pipeline()\n : self(new PipelineImpl)\n{\n \/\/ Get information on FSAA availability\n int dsamples, csamples;\n GL_CHECK(glGetIntegerv(GL_MAX_DEPTH_TEXTURE_SAMPLES, &dsamples));\n GL_CHECK(glGetIntegerv(GL_MAX_COLOR_TEXTURE_SAMPLES, &csamples));\n int fsaa = std::min(dsamples, csamples);\n self->cur_fsaa = fsaa;\n do {\n self->fsaa_levels.insert(fsaa);\n fsaa -= 2;\n } while(fsaa > 1);\n if(fsaa == 0) \/\/ there's no way we'll get a 1 if we start with an even number of FSAA samples\n self->fsaa_levels.insert(1);\n\n \/\/ Enable some standard state\n GL_CHECK(glEnable(GL_MULTISAMPLE));\n GL_CHECK(glEnable(GL_FRAMEBUFFER_SRGB));\n GL_CHECK(glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE));\n GL_CHECK(glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA));\n GL_CHECK(glClearColor(0.8f, 0.8f, 0.9f, 1.0f));\n}\n\nPipeline::~Pipeline()\n{}\n\nvoid Pipeline::addDrawTask(DrawableMesh* mesh, Material* mat, glm::mat4 mv, RenderPass pass)\n{\n DrawTaskObject d;\n d.mesh = mesh;\n d.mat = mat;\n auto i = self->tasks[pass].find(d);\n if(i != self->tasks[pass].end()) {\n i->second.transforms.push_back(mv);\n } else {\n DrawTaskData dt;\n dt.transforms.push_back(mv);\n self->tasks[pass].insert(std::make_pair(d, dt));\n }\n}\n\n\nvoid Pipeline::render()\n{\n if(!self->current_framebuffer)\n return; \/\/ Skip rendering if there is no framebuffer\n GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, self->current_framebuffer->gbuffer_id));\n GL_CHECK(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));\n self->doRenderPass(Pipeline::PassStandard);\n GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, self->current_framebuffer->lbuffer_id));\n GL_CHECK(glClear(GL_COLOR_BUFFER_BIT));\n \/\/ TODO: loop through lights and fill the lbuffer\n self->doRenderPass(Pipeline::PassPostLighting);\n self->current_framebuffer->dirty = true;\n}\n \nvoid Pipeline::endFrame()\n{\n GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, self->current_framebuffer->lbuffer_id));\n self->doRenderPass(Pipeline::PassPostEffect);\n GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0));\n GL_CHECK(glBlitFramebuffer(0, 0, self->current_framebuffer->width, self->current_framebuffer->height, 0, 0, self->width, self->height, GL_COLOR_BUFFER_BIT, GL_NEAREST));\n}\n\n\/\/ Here's our render target documentation!\n\/\/ R,G,B,A = color\n\/\/ X,Y,Z = Normal components\n\/\/ S = Specular Blend\n\/\/ Em = emission\n\/\/ Se = specular exponent\n\/\/ 0: [R][G][B][A]\n\/\/ 1: [X [Y][Z][S]\n\/\/ 2: [Em ][Se ]\n\/\/\n\/\/ This is also (shockingly enough) the packing that the default material shader will expect for texture files\n\/\/ Alpha is stored even though we'll never use it directly, because it's needed for alpha-to-coverage support\nRenderTarget* Pipeline::createRenderTarget(uint32_t width, uint32_t height, bool mipmap)\n{\n GLuint texids[5];\n GLuint fboids[2];\n glGenFramebuffers(2, fboids);\n glGenTextures(5, texids);\n RenderTarget rt;\n rt.depth_id = texids[0];\n rt.color_id = texids[1];\n rt.normal_id = texids[2];\n rt.matprop_id = texids[3];\n rt.lighting_id = texids[4];\n rt.lbuffer_id = fboids[0];\n rt.gbuffer_id = fboids[1];\n\n rt.build_mips = mipmap;\n rt.dirty = true;\n\n rt.width = width;\n rt.height = height;\n\n GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, rt.lbuffer_id));\n GL_CHECK(glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, rt.lighting_id));\n GL_CHECK(glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, self->cur_fsaa, GL_RGBA16F, width, height, GL_FALSE));\n GL_CHECK(glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, rt.depth_id));\n GL_CHECK(glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, self->cur_fsaa, GL_DEPTH24_STENCIL8, width, height, GL_FALSE));\n GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D_MULTISAMPLE, rt.lighting_id, 0));\n GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D_MULTISAMPLE, rt.depth_id, 0));\n GL_CHECK(glViewport(0, 0, width, height));\n FBO_CHECK;\n \n GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, rt.gbuffer_id));\n GL_CHECK(glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, rt.color_id));\n GL_CHECK(glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, self->cur_fsaa, GL_RGBA8, width, height, GL_FALSE));\n GL_CHECK(glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, rt.normal_id));\n GL_CHECK(glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, self->cur_fsaa, GL_RGBA8, width, height, GL_FALSE));\n GL_CHECK(glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, rt.matprop_id));\n GL_CHECK(glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, self->cur_fsaa, GL_RG16F, width, height, GL_FALSE));\n GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D_MULTISAMPLE, rt.color_id, 0));\n GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D_MULTISAMPLE, rt.normal_id, 0));\n GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D_MULTISAMPLE, rt.matprop_id, 0));\n GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D_MULTISAMPLE, rt.depth_id, 0));\n GL_CHECK(glViewport(0, 0, width, height));\n FBO_CHECK;\n\n RenderTarget* result = new RenderTarget;\n *result = rt;\n return result;\n}\n\nvoid Pipeline::destroyRenderTarget(RenderTarget* rt)\n{\n GLuint texids[5];\n GLuint fboids[2];\n texids[0] = rt->depth_id;\n texids[1] = rt->color_id;\n texids[2] = rt->normal_id;\n texids[3] = rt->matprop_id;\n texids[4] = rt->lighting_id;\n fboids[0] = rt->lbuffer_id;\n fboids[1] = rt->gbuffer_id;\n GL_CHECK(glDeleteTextures(4, texids));\n GL_CHECK(glDeleteFramebuffers(2, fboids));\n delete rt;\n}\n\nvoid Pipeline::setRenderTarget(RenderTarget* rt)\n{\n self->current_framebuffer = rt;\n}\n\nvoid Pipeline::setViewport(uint32_t width, uint32_t height)\n{\n self->width = width;\n self->height = height;\n GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, 0));\n GL_CHECK(glViewport(0, 0, width, height));\n}\n\nLoader* Pipeline::createLoader()\n{\n return new Loader;\n}\n\nvoid PipelineImpl::doRenderPass(Pipeline::RenderPass pass)\n{\n auto end = tasks[pass].end();\n for(auto i = tasks[pass].begin(); i != end; ++i) {\n DrawTaskObject dto = i->first;\n DrawTaskData dtd = i->second;\n\n \/\/ break out if the data isn't fully loaded\n if(!dto.mat->shaders || !dto.mesh->buffer)\n continue;\n\n \/\/ bind the shader and vertex array\n GL_CHECK(glUseProgram(dto.mat->shaders->gl_id));\n GL_CHECK(glBindVertexArray(dto.mesh->buffer->vao));\n\n \/\/ loop over the uniforms. Set aside the modelview matrix if found.\n GLint mv_id = -1;\n GLuint current_tex = 0;\n auto uend = dto.mat->uniforms.end();\n for(auto j = dto.mat->uniforms.begin(); j != uend; j++) {\n GLuint uid = boost::any_cast(j->pipe_id);\n switch(j->type) {\n case UniformDef::Texture:\n {\n Image *img = boost::any_cast(j->value);\n GL_CHECK(glActiveTexture(GL_TEXTURE0+current_tex));\n if(img->tex) {\n GL_CHECK(glBindTexture(GL_TEXTURE_2D, img->tex->id));\n } else {\n GL_CHECK(glBindTexture(GL_TEXTURE_2D, 0));\n }\n GL_CHECK(glUniform1i(uid, current_tex));\n current_tex++;\n break;\n }\n case UniformDef::ModelView:\n {\n mv_id = uid;\n break;\n }\n case UniformDef::BoneMatrices:\n {\n size_t mat_count = dtd.transforms.size();\n if(mat_count > SENSE_MAX_VTX_BONES)\n mat_count = SENSE_MAX_VTX_BONES;\n glUniformMatrix4fv(uid, mat_count, GL_FALSE, (GLfloat*)(&(dtd.transforms[0])));\n break;\n }\n case UniformDef::DepthInfo:\n case UniformDef::LightColor:\n case UniformDef::LightPosition:\n case UniformDef::LightRadius:\n case UniformDef::Projection:\n case UniformDef::Webview:\n default:\n throw std::runtime_error(\"Tried to use unimplemenented uniform type\");\n }\n }\n if(mv_id != -1) {\n \/\/ we have a model-view matrix array handle. We need to draw one or more instance passes now.\n size_t cur_transform = 0;\n size_t remaining_mvs = dtd.transforms.size();\n do {\n size_t batch_size = remaining_mvs <= SENSE_MAX_INSTANCES ? remaining_mvs : SENSE_MAX_INSTANCES;\n GLfloat* data_ptr = (GLfloat*)&dtd.transforms[cur_transform];\n GL_CHECK(glUniformMatrix4fv(mv_id, batch_size, GL_FALSE, data_ptr));\n if(dto.mesh->index_data) {\n GL_CHECK(glDrawElementsInstanced(GL_TRIANGLES, dto.mesh->index_count, dto.mesh->buffer->idx_type, 0, batch_size));\n } else {\n GL_CHECK(glDrawArraysInstanced(GL_TRIANGLES, 0, dto.mesh->data_size \/ dto.mesh->data_stride, batch_size));\n }\n cur_transform += batch_size;\n remaining_mvs -= batch_size;\n } while (remaining_mvs);\n } else {\n if(dto.mesh->index_data) {\n GL_CHECK(glDrawElements(GL_TRIANGLES, dto.mesh->index_count, dto.mesh->buffer->idx_type, 0));\n } else {\n GL_CHECK(glDrawArrays(GL_TRIANGLES, 0, dto.mesh->data_size \/ dto.mesh->data_stride));\n }\n }\n }\n}\nFix another null check\/\/ Copyright 2011 Branan Purvine-Riley and Adam Johnson\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n \/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"implementation.hpp\"\n#include \"..\/interface.hpp\"\n#include \"glexcept.hpp\"\n#include \"..\/Material.hpp\"\n#include \"..\/Drawable.hpp\"\n#include \"..\/Image.hpp\"\n\n#include \n\nPipeline::Pipeline()\n : self(new PipelineImpl)\n{\n \/\/ Get information on FSAA availability\n int dsamples, csamples;\n GL_CHECK(glGetIntegerv(GL_MAX_DEPTH_TEXTURE_SAMPLES, &dsamples));\n GL_CHECK(glGetIntegerv(GL_MAX_COLOR_TEXTURE_SAMPLES, &csamples));\n int fsaa = std::min(dsamples, csamples);\n self->cur_fsaa = fsaa;\n do {\n self->fsaa_levels.insert(fsaa);\n fsaa -= 2;\n } while(fsaa > 1);\n if(fsaa == 0) \/\/ there's no way we'll get a 1 if we start with an even number of FSAA samples\n self->fsaa_levels.insert(1);\n\n \/\/ Enable some standard state\n GL_CHECK(glEnable(GL_MULTISAMPLE));\n GL_CHECK(glEnable(GL_FRAMEBUFFER_SRGB));\n GL_CHECK(glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE));\n GL_CHECK(glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA));\n GL_CHECK(glClearColor(0.8f, 0.8f, 0.9f, 1.0f));\n}\n\nPipeline::~Pipeline()\n{}\n\nvoid Pipeline::addDrawTask(DrawableMesh* mesh, Material* mat, glm::mat4 mv, RenderPass pass)\n{\n DrawTaskObject d;\n d.mesh = mesh;\n d.mat = mat;\n auto i = self->tasks[pass].find(d);\n if(i != self->tasks[pass].end()) {\n i->second.transforms.push_back(mv);\n } else {\n DrawTaskData dt;\n dt.transforms.push_back(mv);\n self->tasks[pass].insert(std::make_pair(d, dt));\n }\n}\n\n\nvoid Pipeline::render()\n{\n if(!self->current_framebuffer)\n return; \/\/ Skip rendering if there is no framebuffer\n GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, self->current_framebuffer->gbuffer_id));\n GL_CHECK(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));\n self->doRenderPass(Pipeline::PassStandard);\n GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, self->current_framebuffer->lbuffer_id));\n GL_CHECK(glClear(GL_COLOR_BUFFER_BIT));\n \/\/ TODO: loop through lights and fill the lbuffer\n self->doRenderPass(Pipeline::PassPostLighting);\n self->current_framebuffer->dirty = true;\n}\n \nvoid Pipeline::endFrame()\n{\n GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, self->current_framebuffer->lbuffer_id));\n self->doRenderPass(Pipeline::PassPostEffect);\n GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0));\n GL_CHECK(glBlitFramebuffer(0, 0, self->current_framebuffer->width, self->current_framebuffer->height, 0, 0, self->width, self->height, GL_COLOR_BUFFER_BIT, GL_NEAREST));\n}\n\n\/\/ Here's our render target documentation!\n\/\/ R,G,B,A = color\n\/\/ X,Y,Z = Normal components\n\/\/ S = Specular Blend\n\/\/ Em = emission\n\/\/ Se = specular exponent\n\/\/ 0: [R][G][B][A]\n\/\/ 1: [X [Y][Z][S]\n\/\/ 2: [Em ][Se ]\n\/\/\n\/\/ This is also (shockingly enough) the packing that the default material shader will expect for texture files\n\/\/ Alpha is stored even though we'll never use it directly, because it's needed for alpha-to-coverage support\nRenderTarget* Pipeline::createRenderTarget(uint32_t width, uint32_t height, bool mipmap)\n{\n GLuint texids[5];\n GLuint fboids[2];\n glGenFramebuffers(2, fboids);\n glGenTextures(5, texids);\n RenderTarget rt;\n rt.depth_id = texids[0];\n rt.color_id = texids[1];\n rt.normal_id = texids[2];\n rt.matprop_id = texids[3];\n rt.lighting_id = texids[4];\n rt.lbuffer_id = fboids[0];\n rt.gbuffer_id = fboids[1];\n\n rt.build_mips = mipmap;\n rt.dirty = true;\n\n rt.width = width;\n rt.height = height;\n\n GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, rt.lbuffer_id));\n GL_CHECK(glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, rt.lighting_id));\n GL_CHECK(glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, self->cur_fsaa, GL_RGBA16F, width, height, GL_FALSE));\n GL_CHECK(glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, rt.depth_id));\n GL_CHECK(glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, self->cur_fsaa, GL_DEPTH24_STENCIL8, width, height, GL_FALSE));\n GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D_MULTISAMPLE, rt.lighting_id, 0));\n GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D_MULTISAMPLE, rt.depth_id, 0));\n GL_CHECK(glViewport(0, 0, width, height));\n FBO_CHECK;\n \n GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, rt.gbuffer_id));\n GL_CHECK(glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, rt.color_id));\n GL_CHECK(glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, self->cur_fsaa, GL_RGBA8, width, height, GL_FALSE));\n GL_CHECK(glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, rt.normal_id));\n GL_CHECK(glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, self->cur_fsaa, GL_RGBA8, width, height, GL_FALSE));\n GL_CHECK(glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, rt.matprop_id));\n GL_CHECK(glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, self->cur_fsaa, GL_RG16F, width, height, GL_FALSE));\n GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D_MULTISAMPLE, rt.color_id, 0));\n GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D_MULTISAMPLE, rt.normal_id, 0));\n GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D_MULTISAMPLE, rt.matprop_id, 0));\n GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D_MULTISAMPLE, rt.depth_id, 0));\n GL_CHECK(glViewport(0, 0, width, height));\n FBO_CHECK;\n\n RenderTarget* result = new RenderTarget;\n *result = rt;\n return result;\n}\n\nvoid Pipeline::destroyRenderTarget(RenderTarget* rt)\n{\n GLuint texids[5];\n GLuint fboids[2];\n texids[0] = rt->depth_id;\n texids[1] = rt->color_id;\n texids[2] = rt->normal_id;\n texids[3] = rt->matprop_id;\n texids[4] = rt->lighting_id;\n fboids[0] = rt->lbuffer_id;\n fboids[1] = rt->gbuffer_id;\n GL_CHECK(glDeleteTextures(4, texids));\n GL_CHECK(glDeleteFramebuffers(2, fboids));\n delete rt;\n}\n\nvoid Pipeline::setRenderTarget(RenderTarget* rt)\n{\n self->current_framebuffer = rt;\n}\n\nvoid Pipeline::setViewport(uint32_t width, uint32_t height)\n{\n self->width = width;\n self->height = height;\n GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, 0));\n GL_CHECK(glViewport(0, 0, width, height));\n}\n\nLoader* Pipeline::createLoader()\n{\n return new Loader;\n}\n\nvoid PipelineImpl::doRenderPass(Pipeline::RenderPass pass)\n{\n auto end = tasks[pass].end();\n for(auto i = tasks[pass].begin(); i != end; ++i) {\n DrawTaskObject dto = i->first;\n DrawTaskData dtd = i->second;\n\n \/\/ break out if the data isn't fully loaded\n if(!dto.mat->shaders || !dto.mesh->buffer || !dto.mesh->buffer->vao)\n continue;\n\n \/\/ bind the shader and vertex array\n GL_CHECK(glUseProgram(dto.mat->shaders->gl_id));\n GL_CHECK(glBindVertexArray(dto.mesh->buffer->vao));\n\n \/\/ loop over the uniforms. Set aside the modelview matrix if found.\n GLint mv_id = -1;\n GLuint current_tex = 0;\n auto uend = dto.mat->uniforms.end();\n for(auto j = dto.mat->uniforms.begin(); j != uend; j++) {\n GLuint uid = boost::any_cast(j->pipe_id);\n switch(j->type) {\n case UniformDef::Texture:\n {\n Image *img = boost::any_cast(j->value);\n GL_CHECK(glActiveTexture(GL_TEXTURE0+current_tex));\n if(img->tex) {\n GL_CHECK(glBindTexture(GL_TEXTURE_2D, img->tex->id));\n } else {\n GL_CHECK(glBindTexture(GL_TEXTURE_2D, 0));\n }\n GL_CHECK(glUniform1i(uid, current_tex));\n current_tex++;\n break;\n }\n case UniformDef::ModelView:\n {\n mv_id = uid;\n break;\n }\n case UniformDef::BoneMatrices:\n {\n size_t mat_count = dtd.transforms.size();\n if(mat_count > SENSE_MAX_VTX_BONES)\n mat_count = SENSE_MAX_VTX_BONES;\n glUniformMatrix4fv(uid, mat_count, GL_FALSE, (GLfloat*)(&(dtd.transforms[0])));\n break;\n }\n case UniformDef::DepthInfo:\n case UniformDef::LightColor:\n case UniformDef::LightPosition:\n case UniformDef::LightRadius:\n case UniformDef::Projection:\n case UniformDef::Webview:\n default:\n throw std::runtime_error(\"Tried to use unimplemenented uniform type\");\n }\n }\n if(mv_id != -1) {\n \/\/ we have a model-view matrix array handle. We need to draw one or more instance passes now.\n size_t cur_transform = 0;\n size_t remaining_mvs = dtd.transforms.size();\n do {\n size_t batch_size = remaining_mvs <= SENSE_MAX_INSTANCES ? remaining_mvs : SENSE_MAX_INSTANCES;\n GLfloat* data_ptr = (GLfloat*)&dtd.transforms[cur_transform];\n GL_CHECK(glUniformMatrix4fv(mv_id, batch_size, GL_FALSE, data_ptr));\n if(dto.mesh->index_data) {\n GL_CHECK(glDrawElementsInstanced(GL_TRIANGLES, dto.mesh->index_count, dto.mesh->buffer->idx_type, 0, batch_size));\n } else {\n GL_CHECK(glDrawArraysInstanced(GL_TRIANGLES, 0, dto.mesh->data_size \/ dto.mesh->data_stride, batch_size));\n }\n cur_transform += batch_size;\n remaining_mvs -= batch_size;\n } while (remaining_mvs);\n } else {\n if(dto.mesh->index_data) {\n GL_CHECK(glDrawElements(GL_TRIANGLES, dto.mesh->index_count, dto.mesh->buffer->idx_type, 0));\n } else {\n GL_CHECK(glDrawArrays(GL_TRIANGLES, 0, dto.mesh->data_size \/ dto.mesh->data_stride));\n }\n }\n }\n}\n<|endoftext|>"} {"text":"#include \n#include \n\n\/\/ Declarations of all feature functions\nint PileHeight(GameState const& state);\nint Holes(GameState const& state);\nint ConnectedHoles(GameState const& state);\nint RemovedRows(GameState const& state); \/\/ TODO\nint AltitudeDifference(GameState const& state);\nint MaxWellDepth(GameState const& state);\nint SumOfAllWells(GameState const& state); \/\/ TODO\nint LandingHeight(GameState const& state); \/\/ TODO\nint Blocks(GameState const& state);\nint WeightedBlocks(GameState const& state);\nint RowTransitions(GameState const& state); \/\/ TODO\nint ColTransitions(GameState const& state); \/\/ TODO\nint HighestHole(GameState const& state);\nint BlocksAboveHighestHole(GameState const& state);\nint PotentialRows(GameState const& state); \/\/ TODO\nint Smoothness(GameState const& state);\nint ErodedPieces(GameState const& state); \/\/ TODO\nint RowHoles(GameState const& state); \/\/ TODO\nint HoleDepth(GameState const& state); \/\/ TODO\n\n\nint GetVarCount() {\n return 19;\n}\n\nHarmonyRanges const* GetRanges() {\n HarmonyRanges* ranges = new HarmonyRanges();\n for (int i = 0; i < GetVarCount(); ++i)\n ranges->push_back(std::pair(-100.0, 100.0));\n return ranges;\n}\n\nfloat EvaluateMove(GameState const& state, Harmony const& h) {\n return 0.0;\n}\n\n\/* *\n * Function PileHeight\n *\n * Row of the topmost occupied square on the board.\n * *\/\nint PileHeight(GameState const& state) {\n GameBoard const& board = state.GetBoard();\n int minWellDepth = ROWS;\n for (int i = 0; i < COLS; ++i)\n minWellDepth = std::min(minWellDepth, board.WellDepth(i));\n return (ROWS - minWellDepth);\n}\n\n\/* *\n * Function Holes\n *\n * The number of gaps with at least one occupied cell above them.\n * *\/\nint Holes(GameState const& state) {\n GameBoard const& board = state.GetBoard();\n BoardDesc const& desc = board.GetBoardDesc();\n int holeCount = 0;\n for (int i = 0; i < COLS; ++i) {\n bool hitTop = false;\n for (int j = 0; j < ROWS; ++j) {\n if (desc[i][j] && !hitTop)\n hitTop = true;\n else if (!desc[i][j] && hitTop)\n ++holeCount;\n }\n }\n return holeCount;\n}\n\n\/* *\n * Function ConnectedHoles\n *\n * The number of connected gaps with at least one occupied cell above them.\n * *\/\nint ConnectedHoles(GameState const& state) {\n GameBoard const& board = state.GetBoard();\n BoardDesc const& desc = board.GetBoardDesc();\n int holeCount = 0;\n for (int i = 0; i < COLS; ++i) {\n bool hitTop = false;\n bool inHole = false;\n for (int j = 0; j < ROWS; ++j) {\n if (desc[i][j] && !hitTop)\n hitTop = true;\n else if (desc[i][j] && hitTop && inHole)\n inHole = false;\n else if (!desc[i][j] && hitTop && !inHole) {\n ++holeCount;\n inHole = true;\n }\n }\n }\n return holeCount;\n}\n\n\/* *\n * Function RemovedRows\n *\n * The number of rows cleared by the last step.\n * *\/\nint RemovedRows(GameState const& state) {\n std::vector const& cleared = state.LastClearedRows();\n return cleared.size();\n}\n\nint AltitudeDifference(GameState const& state) {\n GameBoard const& board = state.GetBoard();\n int minWellDepth = ROWS;\n int maxWellDepth = 0;\n for (int i = 0; i < COLS; ++i) {\n int wellDepth = board.WellDepth(i);\n minWellDepth = std::min(minWellDepth, wellDepth);\n maxWellDepth = std::min(maxWellDepth, wellDepth);\n }\n return ((ROWS - minWellDepth) - (ROWS - maxWellDepth));\n}\n\nint MaxWellDepth(GameState const& state) {\n GameBoard const& board = state.GetBoard();\n int maxWellDepth = 0;\n for (int i = 0; i < COLS; ++i)\n maxWellDepth = std::min(maxWellDepth, board.WellDepth(i));\n return (ROWS - maxWellDepth);\n}\n\nint SumOfAllWells(GameState const& state) {\n \/\/ Sum of all wells based on adjacent columns\n return 0;\n}\n\nint LandingHeight(GameState const& state) {\n \/\/ Height at which last tetronimo was placed\n return 0;\n}\n\nint Blocks(GameState const& state) {\n GameBoard const& board = state.GetBoard();\n BoardDesc const& desc = board.GetBoardDesc();\n int blockCount = 0; \n for (int j = 0; j < ROWS; ++j) {\n for (int i = 0; i < COLS; ++i) {\n if (desc[i][j])\n ++blockCount;\n }\n }\n return blockCount;\n}\n\nint WeightedBlocks(GameState const& state) {\n GameBoard const& board = state.GetBoard();\n BoardDesc const& desc = board.GetBoardDesc();\n int weighted = 0; \n for (int j = 0; j < ROWS; ++j) {\n for (int i = 0; i < COLS; ++i) {\n if (desc[i][j])\n weighted += (ROWS-j); \n }\n }\n return weighted;\n}\n\nint RowTransitions(GameState const& state) {\n \/\/ Counts row transitions\n return 0;\n}\n\nint ColTransitions(GameState const& state) {\n \/\/ Counts col transitions\n return 0;\n}\n\nint HighestHole(GameState const& state) {\n GameBoard const& board = state.GetBoard();\n BoardDesc const& desc = board.GetBoardDesc();\n int highest = 0;\n for (int i = 0; i < COLS; ++i) {\n bool hitTop = false;\n for (int j = 0; j < ROWS; ++j) {\n if (desc[i][j] && !hitTop)\n hitTop = true;\n if (!desc[i][j] && hitTop) {\n highest = std::max(highest, ROWS-j);\n break;\n }\n }\n }\n return highest;\n}\n\nint BlocksAboveHighestHole(GameState const& state) {\n GameBoard const& board = state.GetBoard();\n BoardDesc const& desc = board.GetBoardDesc();\n int highest = 0;\n int blocksAboveCount = 0;\n for (int i = 0; i < COLS; ++i) {\n bool hitTop = false;\n int blocksHit = 0;\n for (int j = 0; j < ROWS; ++j) {\n if (desc[i][j])\n ++blocksHit;\n if (desc[i][j] && !hitTop)\n hitTop = true;\n if (!desc[i][j] && hitTop) {\n if ((ROWS-j) == highest && blocksHit > blocksAboveCount) {\n blocksAboveCount = blocksHit; \n }\n if ((ROWS-j) > highest) {\n highest = (ROWS-j);\n blocksAboveCount = blocksHit;\n }\n break;\n }\n }\n }\n return blocksAboveCount;\n}\n\nint PotentialRows(GameState const& state) {\n return 0;\n}\n\nint Smoothness(GameState const& state) {\n GameBoard const& board = state.GetBoard();\n int smoothness = 0;\n for (int i = 0; i < COLS-1; ++i)\n smoothness += abs(board.WellDepth(i)-board.WellDepth(i+1));\n return smoothness;\n}\n\nint ErodedPieces(GameState const& state) {\n return 0;\n}\n\nint RowHoles(GameState const& state) {\n return 0;\n}\n\nint HoleDepth(GameState const& state) {\n return 0;\n}\n\nImplemented three more feature functions#include \n#include \n\n\/\/ Declarations of all feature functions\nint PileHeight(GameState const& state);\nint Holes(GameState const& state);\nint ConnectedHoles(GameState const& state);\nint RemovedRows(GameState const& state); \nint AltitudeDifference(GameState const& state);\nint MaxWellDepth(GameState const& state);\nint SumOfAllWells(GameState const& state); \/\/ TODO\nint LandingHeight(GameState const& state); \/\/ TODO\nint Blocks(GameState const& state);\nint WeightedBlocks(GameState const& state);\nint RowTransitions(GameState const& state); \/\/ TODO\nint ColTransitions(GameState const& state); \/\/ TODO\nint HighestHole(GameState const& state);\nint BlocksAboveHighestHole(GameState const& state);\nint PotentialRows(GameState const& state); \/\/ TODO\nint Smoothness(GameState const& state);\nint ErodedPieces(GameState const& state); \/\/ TODO\nint RowHoles(GameState const& state); \/\/ TODO\nint HoleDepth(GameState const& state); \/\/ TODO\n\n\nint GetVarCount() {\n return 19;\n}\n\nHarmonyRanges const* GetRanges() {\n HarmonyRanges* ranges = new HarmonyRanges();\n for (int i = 0; i < GetVarCount(); ++i)\n ranges->push_back(std::pair(-100.0, 100.0));\n return ranges;\n}\n\nfloat EvaluateMove(GameState const& state, Harmony const& h) {\n return 0.0;\n}\n\n\/* *\n * Function PileHeight\n *\n * Row of the topmost occupied square on the board.\n * *\/\nint PileHeight(GameState const& state) {\n GameBoard const& board = state.GetBoard();\n int minWellDepth = ROWS;\n for (int i = 0; i < COLS; ++i)\n minWellDepth = std::min(minWellDepth, board.WellDepth(i));\n return (ROWS - minWellDepth);\n}\n\n\/* *\n * Function Holes\n *\n * The number of gaps with at least one occupied cell above them.\n * *\/\nint Holes(GameState const& state) {\n GameBoard const& board = state.GetBoard();\n BoardDesc const& desc = board.GetBoardDesc();\n int holeCount = 0;\n for (int i = 0; i < COLS; ++i) {\n bool hitTop = false;\n for (int j = 0; j < ROWS; ++j) {\n if (desc[i][j] && !hitTop)\n hitTop = true;\n else if (!desc[i][j] && hitTop)\n ++holeCount;\n }\n }\n return holeCount;\n}\n\n\/* *\n * Function ConnectedHoles\n *\n * The number of connected gaps with at least one occupied cell above them.\n * *\/\nint ConnectedHoles(GameState const& state) {\n GameBoard const& board = state.GetBoard();\n BoardDesc const& desc = board.GetBoardDesc();\n int holeCount = 0;\n for (int i = 0; i < COLS; ++i) {\n bool hitTop = false;\n bool inHole = false;\n for (int j = 0; j < ROWS; ++j) {\n if (desc[i][j] && !hitTop)\n hitTop = true;\n else if (desc[i][j] && hitTop && inHole)\n inHole = false;\n else if (!desc[i][j] && hitTop && !inHole) {\n ++holeCount;\n inHole = true;\n }\n }\n }\n return holeCount;\n}\n\n\/* *\n * Function RemovedRows\n *\n * The number of rows cleared by the last step.\n * *\/\nint RemovedRows(GameState const& state) {\n std::vector const& cleared = state.LastClearedRows();\n return cleared.size();\n}\n\n\/* *\n * Function AltitudeDifference\n *\n * The height difference between the lowest and highest reachable blocks.\n * *\/\nint AltitudeDifference(GameState const& state) {\n GameBoard const& board = state.GetBoard();\n int minWellDepth = ROWS;\n int maxWellDepth = 0;\n for (int i = 0; i < COLS; ++i) {\n int wellDepth = board.WellDepth(i);\n minWellDepth = std::min(minWellDepth, wellDepth);\n maxWellDepth = std::min(maxWellDepth, wellDepth);\n }\n return ((ROWS - minWellDepth) - (ROWS - maxWellDepth));\n}\n\n\/* *\n * Function MaxWellDepth\n *\n * Depth of the deepest well on the board.\n * *\/\nint MaxWellDepth(GameState const& state) {\n GameBoard const& board = state.GetBoard();\n int maxWellDepth = 0;\n int wells[COLS];\n for (int i = 0; i < COLS; ++i)\n wells[i] = board.WellDepth(i);\n if (wells[0] < wells[1]) {\n int depth = wells[1]-wells[0];\n maxWellDepth = std::max(maxWellDepth, depth);\n }\n for (int i = 1; i < COLS-1; ++i) {\n if (wells[i] < wells[i-1] && wells[i] < wells[i+1]) {\n int depth = std::min(wells[i-1]-wells[i], wells[i+1]-wells[i]);\n maxWellDepth = std::max(maxWellDepth, depth);\n }\n }\n if (wells[COLS-1] < wells[COLS-2]) {\n int depth = wells[COLS-2]-wells[COLS-1];\n maxWellDepth = std::max(maxWellDepth, depth);\n }\n return maxWellDepth;\n}\n\n\/* *\n * Function SumOfAllWells\n *\n * Sum of the depths of all wells on the board.\n * *\/\nint SumOfAllWells(GameState const& state) {\n GameBoard const& board = state.GetBoard();\n int totalWellDepth = 0;\n int wells[COLS];\n for (int i = 0; i < COLS; ++i)\n wells[i] = board.WellDepth(i);\n if (wells[0] < wells[1]) {\n int depth = wells[1]-wells[0];\n totalWellDepth += depth;\n }\n for (int i = 1; i < COLS-1; ++i) {\n if (wells[i] < wells[i-1] && wells[i] < wells[i+1]) {\n int depth = std::min(wells[i-1]-wells[i], wells[i+1]-wells[i]);\n totalWellDepth += depth;\n }\n }\n if (wells[COLS-1] < wells[COLS-2]) {\n int depth = wells[COLS-2]-wells[COLS-1];\n totalWellDepth += depth;\n }\n return totalWellDepth;\n}\n\nint LandingHeight(GameState const& state) {\n \/\/ Height at which last tetronimo was placed\n return 0;\n}\n\nint Blocks(GameState const& state) {\n GameBoard const& board = state.GetBoard();\n BoardDesc const& desc = board.GetBoardDesc();\n int blockCount = 0; \n for (int j = 0; j < ROWS; ++j) {\n for (int i = 0; i < COLS; ++i) {\n if (desc[i][j])\n ++blockCount;\n }\n }\n return blockCount;\n}\n\nint WeightedBlocks(GameState const& state) {\n GameBoard const& board = state.GetBoard();\n BoardDesc const& desc = board.GetBoardDesc();\n int weighted = 0; \n for (int j = 0; j < ROWS; ++j) {\n for (int i = 0; i < COLS; ++i) {\n if (desc[i][j])\n weighted += (ROWS-j); \n }\n }\n return weighted;\n}\n\nint RowTransitions(GameState const& state) {\n \/\/ Counts row transitions\n return 0;\n}\n\nint ColTransitions(GameState const& state) {\n \/\/ Counts col transitions\n return 0;\n}\n\nint HighestHole(GameState const& state) {\n GameBoard const& board = state.GetBoard();\n BoardDesc const& desc = board.GetBoardDesc();\n int highest = 0;\n for (int i = 0; i < COLS; ++i) {\n bool hitTop = false;\n for (int j = 0; j < ROWS; ++j) {\n if (desc[i][j] && !hitTop)\n hitTop = true;\n if (!desc[i][j] && hitTop) {\n highest = std::max(highest, ROWS-j);\n break;\n }\n }\n }\n return highest;\n}\n\nint BlocksAboveHighestHole(GameState const& state) {\n GameBoard const& board = state.GetBoard();\n BoardDesc const& desc = board.GetBoardDesc();\n int highest = 0;\n int blocksAboveCount = 0;\n for (int i = 0; i < COLS; ++i) {\n bool hitTop = false;\n int blocksHit = 0;\n for (int j = 0; j < ROWS; ++j) {\n if (desc[i][j])\n ++blocksHit;\n if (desc[i][j] && !hitTop)\n hitTop = true;\n if (!desc[i][j] && hitTop) {\n if ((ROWS-j) == highest && blocksHit > blocksAboveCount) {\n blocksAboveCount = blocksHit; \n }\n if ((ROWS-j) > highest) {\n highest = (ROWS-j);\n blocksAboveCount = blocksHit;\n }\n break;\n }\n }\n }\n return blocksAboveCount;\n}\n\nint PotentialRows(GameState const& state) {\n return 0;\n}\n\nint Smoothness(GameState const& state) {\n GameBoard const& board = state.GetBoard();\n int smoothness = 0;\n for (int i = 0; i < COLS-1; ++i)\n smoothness += abs(board.WellDepth(i)-board.WellDepth(i+1));\n return smoothness;\n}\n\nint ErodedPieces(GameState const& state) {\n return 0;\n}\n\nint RowHoles(GameState const& state) {\n return 0;\n}\n\nint HoleDepth(GameState const& state) {\n return 0;\n}\n\n<|endoftext|>"} {"text":"\/*\n * This file is open source software, licensed to you under the terms\n * of the Apache License, Version 2.0 (the \"License\"). See the NOTICE file\n * distributed with this work for additional information regarding copyright\n * ownership. You may not use this file except in compliance with the License.\n *\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\/*\n * Copyright (C) 2018 ScyllaDB Ltd.\n *\/\n\n#pragma once\n\n#include \n#include \n\n#include \n\n#include \n#include \n\n\nusing namespace seastar;\n\nnamespace perf_tests {\nnamespace internal {\n\nstruct config;\n\nusing clock_type = std::chrono::steady_clock;\n\nclass performance_test {\n std::string _test_case;\n std::string _test_group;\n\n uint64_t _single_run_iterations = 0;\n std::atomic _max_single_run_iterations;\nprivate:\n void do_run(const config&);\nprotected:\n [[gnu::always_inline]] [[gnu::hot]]\n bool stop_iteration() const {\n return _single_run_iterations >= _max_single_run_iterations.load(std::memory_order_relaxed);\n }\n\n [[gnu::always_inline]] [[gnu::hot]]\n void next_iteration() {\n _single_run_iterations++;\n }\n\n virtual void set_up() = 0;\n virtual void tear_down() noexcept = 0;\n virtual future do_single_run() = 0;\npublic:\n performance_test(const std::string& test_case, const std::string& test_group)\n : _test_case(test_case)\n , _test_group(test_group)\n { }\n\n virtual ~performance_test() = default;\n\n const std::string& test_case() const { return _test_case; }\n const std::string& test_group() const { return _test_group; }\n std::string name() const { return fmt::format(\"{}.{}\", test_group(), test_case()); }\n\n void run(const config&);\npublic:\n static void register_test(std::unique_ptr);\n};\n\n\/\/ Helper for measuring time.\n\/\/ Each microbenchmark can either use the default behaviour which measures\n\/\/ only the start and stop time of the whole run or manually invoke\n\/\/ start_measuring_time() and stop_measuring_time() in order to measure\n\/\/ only parts of each iteration.\nclass time_measurement {\n clock_type::time_point _run_start_time;\n clock_type::time_point _start_time;\n clock_type::duration _total_time;\npublic:\n [[gnu::always_inline]] [[gnu::hot]]\n void start_run() {\n _total_time = { };\n auto t = clock_type::now();\n _run_start_time = t;\n _start_time = t;\n }\n\n [[gnu::always_inline]] [[gnu::hot]]\n clock_type::duration stop_run() {\n auto t = clock_type::now();\n if (_start_time == _run_start_time) {\n return t - _start_time;\n }\n return _total_time;\n }\n\n [[gnu::always_inline]] [[gnu::hot]]\n void start_iteration() {\n _start_time = clock_type::now();\n }\n \n [[gnu::always_inline]] [[gnu::hot]]\n void stop_iteration() {\n auto t = clock_type::now();\n _total_time += t - _start_time;\n }\n};\n\nextern time_measurement measure_time;\n\nnamespace {\n\ntemplate\nstruct do_if_constexpr_ : FalseFn {\n do_if_constexpr_(TrueFn, FalseFn false_fn) : FalseFn(std::move(false_fn)) { }\n decltype(auto) operator()() const {\n \/\/ https:\/\/gcc.gnu.org\/bugzilla\/show_bug.cgi?id=64095\n return FalseFn::operator()(0);\n }\n};\ntemplate\nstruct do_if_constexpr_ : TrueFn {\n do_if_constexpr_(TrueFn true_fn, FalseFn) : TrueFn(std::move(true_fn)) { }\n decltype(auto) operator()() const { return TrueFn::operator()(0); }\n};\n\ntemplate\ndo_if_constexpr_ if_constexpr_(TrueFn&& true_fn, FalseFn&& false_fn)\n{\n return do_if_constexpr_(std::forward(true_fn),\n std::forward(false_fn));\n}\n\n}\n\ntemplate\nclass concrete_performance_test final : public performance_test {\n compat::optional _test;\nprotected:\n virtual void set_up() override {\n _test.emplace();\n }\n\n virtual void tear_down() noexcept override {\n _test = compat::nullopt;\n }\n\n [[gnu::hot]]\n virtual future do_single_run() override {\n \/\/ Redundant 'this->'s courtesy of https:\/\/gcc.gnu.org\/bugzilla\/show_bug.cgi?id=61636\n return if_constexpr_run())>::value>([&] (auto&&...) {\n measure_time.start_run();\n return do_until([this] { return this->stop_iteration(); }, [this] {\n this->next_iteration();\n return _test->run();\n }).then([] {\n return measure_time.stop_run();\n });\n }, [&] (auto&&...) {\n measure_time.start_run();\n while (!stop_iteration()) {\n this->next_iteration();\n _test->run();\n }\n return make_ready_future(measure_time.stop_run());\n })();\n }\npublic:\n using performance_test::performance_test;\n};\n\nvoid register_test(std::unique_ptr);\n\ntemplate\nstruct test_registrar {\n test_registrar(const std::string& test_group, const std::string& test_case) {\n auto test = std::make_unique>(test_case, test_group);\n performance_test::register_test(std::move(test));\n }\n};\n\n}\n\n[[gnu::always_inline]]\ninline void start_measuring_time()\n{\n internal::measure_time.start_iteration();\n}\n\n[[gnu::always_inline]]\ninline void stop_measuring_time()\n{\n internal::measure_time.stop_iteration();\n}\n\n\ntemplate\nvoid do_not_optimize(T& v)\n{\n asm volatile(\"\" : : \"r,m\" (v));\n}\n\n}\n\n#define PERF_TEST_F(test_group, test_case) \\\n struct test_##test_group##_##test_case : test_group { \\\n [[gnu::always_inline]] inline auto run(); \\\n }; \\\n static ::perf_tests::internal::test_registrar \\\n test_##test_group##_##test_case##_registrar(#test_group, #test_case); \\\n [[gnu::always_inline]] auto test_##test_group##_##test_case::run()\n\n#define PERF_TEST(test_group, test_case) \\\n struct test_##test_group##_##test_case { \\\n [[gnu::always_inline]] inline auto run(); \\\n }; \\\n static ::perf_tests::internal::test_registrar \\\n test_##test_group##_##test_case##_registrar(#test_group, #test_case); \\\n [[gnu::always_inline]] auto test_##test_group##_##test_case::run()\ntests: perf: Make do_not_optimize() take the argument by const&\/*\n * This file is open source software, licensed to you under the terms\n * of the Apache License, Version 2.0 (the \"License\"). See the NOTICE file\n * distributed with this work for additional information regarding copyright\n * ownership. You may not use this file except in compliance with the License.\n *\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\/*\n * Copyright (C) 2018 ScyllaDB Ltd.\n *\/\n\n#pragma once\n\n#include \n#include \n\n#include \n\n#include \n#include \n\n\nusing namespace seastar;\n\nnamespace perf_tests {\nnamespace internal {\n\nstruct config;\n\nusing clock_type = std::chrono::steady_clock;\n\nclass performance_test {\n std::string _test_case;\n std::string _test_group;\n\n uint64_t _single_run_iterations = 0;\n std::atomic _max_single_run_iterations;\nprivate:\n void do_run(const config&);\nprotected:\n [[gnu::always_inline]] [[gnu::hot]]\n bool stop_iteration() const {\n return _single_run_iterations >= _max_single_run_iterations.load(std::memory_order_relaxed);\n }\n\n [[gnu::always_inline]] [[gnu::hot]]\n void next_iteration() {\n _single_run_iterations++;\n }\n\n virtual void set_up() = 0;\n virtual void tear_down() noexcept = 0;\n virtual future do_single_run() = 0;\npublic:\n performance_test(const std::string& test_case, const std::string& test_group)\n : _test_case(test_case)\n , _test_group(test_group)\n { }\n\n virtual ~performance_test() = default;\n\n const std::string& test_case() const { return _test_case; }\n const std::string& test_group() const { return _test_group; }\n std::string name() const { return fmt::format(\"{}.{}\", test_group(), test_case()); }\n\n void run(const config&);\npublic:\n static void register_test(std::unique_ptr);\n};\n\n\/\/ Helper for measuring time.\n\/\/ Each microbenchmark can either use the default behaviour which measures\n\/\/ only the start and stop time of the whole run or manually invoke\n\/\/ start_measuring_time() and stop_measuring_time() in order to measure\n\/\/ only parts of each iteration.\nclass time_measurement {\n clock_type::time_point _run_start_time;\n clock_type::time_point _start_time;\n clock_type::duration _total_time;\npublic:\n [[gnu::always_inline]] [[gnu::hot]]\n void start_run() {\n _total_time = { };\n auto t = clock_type::now();\n _run_start_time = t;\n _start_time = t;\n }\n\n [[gnu::always_inline]] [[gnu::hot]]\n clock_type::duration stop_run() {\n auto t = clock_type::now();\n if (_start_time == _run_start_time) {\n return t - _start_time;\n }\n return _total_time;\n }\n\n [[gnu::always_inline]] [[gnu::hot]]\n void start_iteration() {\n _start_time = clock_type::now();\n }\n \n [[gnu::always_inline]] [[gnu::hot]]\n void stop_iteration() {\n auto t = clock_type::now();\n _total_time += t - _start_time;\n }\n};\n\nextern time_measurement measure_time;\n\nnamespace {\n\ntemplate\nstruct do_if_constexpr_ : FalseFn {\n do_if_constexpr_(TrueFn, FalseFn false_fn) : FalseFn(std::move(false_fn)) { }\n decltype(auto) operator()() const {\n \/\/ https:\/\/gcc.gnu.org\/bugzilla\/show_bug.cgi?id=64095\n return FalseFn::operator()(0);\n }\n};\ntemplate\nstruct do_if_constexpr_ : TrueFn {\n do_if_constexpr_(TrueFn true_fn, FalseFn) : TrueFn(std::move(true_fn)) { }\n decltype(auto) operator()() const { return TrueFn::operator()(0); }\n};\n\ntemplate\ndo_if_constexpr_ if_constexpr_(TrueFn&& true_fn, FalseFn&& false_fn)\n{\n return do_if_constexpr_(std::forward(true_fn),\n std::forward(false_fn));\n}\n\n}\n\ntemplate\nclass concrete_performance_test final : public performance_test {\n compat::optional _test;\nprotected:\n virtual void set_up() override {\n _test.emplace();\n }\n\n virtual void tear_down() noexcept override {\n _test = compat::nullopt;\n }\n\n [[gnu::hot]]\n virtual future do_single_run() override {\n \/\/ Redundant 'this->'s courtesy of https:\/\/gcc.gnu.org\/bugzilla\/show_bug.cgi?id=61636\n return if_constexpr_run())>::value>([&] (auto&&...) {\n measure_time.start_run();\n return do_until([this] { return this->stop_iteration(); }, [this] {\n this->next_iteration();\n return _test->run();\n }).then([] {\n return measure_time.stop_run();\n });\n }, [&] (auto&&...) {\n measure_time.start_run();\n while (!stop_iteration()) {\n this->next_iteration();\n _test->run();\n }\n return make_ready_future(measure_time.stop_run());\n })();\n }\npublic:\n using performance_test::performance_test;\n};\n\nvoid register_test(std::unique_ptr);\n\ntemplate\nstruct test_registrar {\n test_registrar(const std::string& test_group, const std::string& test_case) {\n auto test = std::make_unique>(test_case, test_group);\n performance_test::register_test(std::move(test));\n }\n};\n\n}\n\n[[gnu::always_inline]]\ninline void start_measuring_time()\n{\n internal::measure_time.start_iteration();\n}\n\n[[gnu::always_inline]]\ninline void stop_measuring_time()\n{\n internal::measure_time.stop_iteration();\n}\n\n\ntemplate\nvoid do_not_optimize(const T& v)\n{\n asm volatile(\"\" : : \"r,m\" (v));\n}\n\n}\n\n#define PERF_TEST_F(test_group, test_case) \\\n struct test_##test_group##_##test_case : test_group { \\\n [[gnu::always_inline]] inline auto run(); \\\n }; \\\n static ::perf_tests::internal::test_registrar \\\n test_##test_group##_##test_case##_registrar(#test_group, #test_case); \\\n [[gnu::always_inline]] auto test_##test_group##_##test_case::run()\n\n#define PERF_TEST(test_group, test_case) \\\n struct test_##test_group##_##test_case { \\\n [[gnu::always_inline]] inline auto run(); \\\n }; \\\n static ::perf_tests::internal::test_registrar \\\n test_##test_group##_##test_case##_registrar(#test_group, #test_case); \\\n [[gnu::always_inline]] auto test_##test_group##_##test_case::run()\n<|endoftext|>"} {"text":"#include \n\n\/\/for the sake of multivalue gurus new to exodus\/C++ this is written\n\/\/with multivalue-mimicking \"everything is a global function\" syntax\n\/\/instead of exodus's native OO-style \"objects and methods\" syntax\n\nvar filename=\"myclients\";\n\nsubroutine sortselect(in file, in sortselectcmd)\n{\n\n\tprintln(\"\\nSSELECT the data - \", sortselectcmd);\n\n\tif (!select(sortselectcmd)) {\n\t\tprintln(\"Cannot sselect\");\n\t\tstop();\n\t}\n\n\tprintln(\"Read the data\");\n\n\tvar record;\n\tvar key;\n\t\n\t\/\/could also use the readnextrecord() function here\n\t\/\/ if we had used the new selectrecord() function above\n\twhile (readnext(key)) {\n\n\t\tif (not read(record, file, key)) {\n\t\t\tprintln(key, \" missing from file\");\n\t\t\tcontinue;\n\t\t}\n\t\tprint(key, \": \");\n\t\tprintln(convert(record, FM, \"|\"));\n\t\t\n\t}\n\n\treturn;\n\n}\n\nprogram()\n{\n\n\tif (not connect()) {\n\t\tprintln(\"Cannot connect to database. Please check configuration\");\n\t\tstop();\n\t}\n\n\tvar dictfilename=\"dict_\"^ filename;\n\n\t\/\/leave the test data files around for playing with\n\tvar cleanup=false;\n\tif (cleanup) {\n\t\tdeletefile(filename);\n\t\tdeletefile(dictfilename);\n\t}\n\t\n\tprintln(\"\\nOpen or create test file \", filename);\n\n\tvar file;\n\tif (not open(filename, file)) {\n\t\tcreatefile(filename);\n\t\tif (not open(filename, file)) {\n\t\t\tprintln(\"Cannot open \", filename);\n\t\t\tstop();\n\t\t}\n\t}\n\n\tprintln(\"\\nOpen or create the test files dictionary \", dictfilename);\n\n\tvar dictfile;\n\tif (not open(dictfilename, dictfile)) {\n\t\tcreatefile(dictfilename);\n\t\tif (not open(dictfilename, file)) {\n\t\t\tprintln(\"Cannot open dictionary \", dictfilename);\n\t\t\tstop();\n\t\t}\n\t}\n\n\tprintln(\"\\nPrepare some dictionary records\");\n\n\tvar dictrecs = \"\";\n\tdictrecs = \"CLIENT_CODE |F|0|Code |||| ||L|8\";\n\tdictrecs ^= FM ^ \"CLIENT_NAME |F|1|Name |||| ||T|15\";\n\tdictrecs ^= FM ^ \"CLIENT_TYPE |F|2|Type |||| ||L|5\";\n\tdictrecs ^= FM ^ \"DATE_CREATED|F|3|Date ||||D4 ||L|12\";\n\tdictrecs ^= FM ^ \"TIME_CREATED|F|4|Time ||||MTH ||L|12\";\n\tdictrecs ^= FM ^ \"BALANCE |F|5|Balance ||||MD20P ||R|10\";\n\tdictrecs ^= FM ^ \"TIMESTAMP |F|6|Timestamp||||[DATETIME]||L|12\";\n\tdictrecs ^= FM ^ \"@CRT |G| |CLIENT_CODE CLIENT_NAME CLIENT_TYPE BALANCE DATE_CREATED TIME_CREATED TIMESTAMP\";\n\n\tprintln(\"\\nWrite the dictionary records to the dictionary\");\n\n\tvar nrecs=count(dictrecs, FM)+1;\n\tfor (var recn = 1; recn <= nrecs; recn++)\n\t{\n\t\tvar dictrec=extract(dictrecs, recn);\n\t\tvar key=field(dictrec, \"|\", 1);\n\t\tvar rec=field(dictrec, \"|\", 2, 9999);\n\t\t\n\t\tprintln(key, \": \", rec);\n\t\tkey=trim(key);\n\t\trec=trim(rec);\n\t\trec=swap(rec, \" |\", \"|\");\n\t\trec=convert(rec, \"|\", FM);\n\t\t\n\t\twrite(rec, dictfile, key);\n\t\t\n\t\t\/\/check we can read the record back\n\t\tvar rec2;\n\t\tdictfile.outputln(\"dictfile\");\n\t\tkey.outputln(\"key\");\n\t\tif (read(rec2,dictfile, key)) {\n\t\t\tif (rec2 ne rec) {\n\t\t\t\tprintln(\"record differs?!\");\n\t\t\t}\n\t\t} else\n\t\t\tprintln(\"Cant read \", key, \" back\");\n\t}\n\n\tvar rec;\n\tif (not read(rec,dictfile,\"BALANCE\"))\n\t\tprintln(\"Cant read BALANCE record from dictionary\");\n\n\tprintln(\"\\nClear the client file\");\n\tclearfile(filename);\n\n\tprintln(\"\\nPrepare some data records in a readable format\");\n\n\tvar recs = \"\";\n\trecs ^= FM ^ \"SB001|Client AAA |A |15070|76539|1000.00|15070.76539\";\n\trecs ^= FM ^ \"JB002|Client BBB |B |15000|50539|200.00|15000.50539\";\n\trecs ^= FM ^ \"JB001|Client CCC |B |15010|60539|2000.00|15010.60539\";\n\trecs ^= FM ^ \"SB1 |Client SB1 |1 | | | | \";\n\trecs ^= FM ^ \"JB2 |Client JB2 |2 |14000|10539|0 |14000.10539\";\n\trecs ^= FM ^ \"JB10 |Client JB10|10|14010|10539|2000.00|14010.10539\";\n\tsplicer(recs, 1, 1, \"\");\n\n\tprintln(\"\\nWrite the data records to the data file\");\n\n\tnrecs=count(recs, FM)+1;\n\tfor (var recn = 1; recn <= nrecs; recn++)\n\t{\n\t\tvar rec=extract(recs, recn);\n\t\tvar key=field(rec, \"|\", 1);\n\t\trec=field(rec, \"|\", 2, 9999);\n\t\tprintln(key, \": \", rec);\n\t\twhile (index(rec, \" |\"))\n\t\t\tswapper(rec, \" |\", \"|\");\n\t\twrite(trimb(convert(rec, \"|\", FM)), file, trim(key));\n\t}\n\n\tvar prefix=\"SELECT \"^ filename;\n\t\n\tgosub sortselect(file, prefix^ \" BY CLIENT_CODE\");\n\n\tgosub sortselect(file, prefix^ \" BY BALANCE BY CLIENT_CODE\");\n\n\tgosub sortselect(file, prefix^ \" BY TIMESTAMP\");\n\n\tgosub sortselect(file, prefix^ \" WITH CLIENT_TYPE 'B' BY BALANCE\");\n\n\tvar cmd=\"list \"^ filename^ \" id-supp\";\n\tprintln(\"\\nList the file using \", quote(cmd));\n\tosshell(cmd);\n\t\n\tcmd=\"list \"^ dictfilename^ \" id-supp\";\n\tprintln(\"\\nList the dict using \", quote(cmd));\n\tosshell(cmd);\n\t\n\tif (cleanup) {\n\t\tprintln(\"\\nCleaning up. Delete the files\");\n\t\tdeletefile(file);\n\t\tdeletefile(dictfile);\n\t}\n\t\n\tprintln(\"\\nJust type 'list' (without the quotes) to see it's syntax\");\n\tprintln(\"or list dict_\"^ filename^ \" to see the dictionary\");\n}\nfix testsort#include \n\n\/\/for the sake of multivalue gurus new to exodus\/C++ this is written\n\/\/with multivalue-mimicking \"everything is a global function\" syntax\n\/\/instead of exodus's native OO-style \"objects and methods\" syntax\n\nvar filename=\"myclients\";\n\nsubroutine sortselect(in file, in sortselectcmd)\n{\n\n\tprintln(\"\\nSSELECT the data - \", sortselectcmd);\n\n\tif (!select(sortselectcmd)) {\n\t\tprintln(\"Cannot sselect\");\n\t\tstop();\n\t}\n\n\tprintln(\"Read the data\");\n\n\tvar record;\n\tvar key;\n\t\n\t\/\/could also use the readnextrecord() function here\n\t\/\/ if we had used the new selectrecord() function above\n\twhile (readnext(key)) {\n\n\t\tif (not read(record, file, key)) {\n\t\t\tprintln(key, \" missing from file\");\n\t\t\tcontinue;\n\t\t}\n\t\tprint(key, \": \");\n\t\tprintln(convert(record, FM, \"|\"));\n\t\t\n\t}\n\n\treturn;\n\n}\n\nprogram()\n{\n\n\tif (not connect()) {\n\t\tprintln(\"Cannot connect to database. Please check configuration\");\n\t\tstop();\n\t}\n\n\tvar dictfilename=\"dict_\"^ filename;\n\n\t\/\/leave the test data files around for playing with\n\tvar cleanup=false;\n\tif (cleanup) {\n\t\tdeletefile(filename);\n\t\tdeletefile(dictfilename);\n\t}\n\t\n\tprintln(\"\\nOpen or create test file \", filename);\n\n\tvar file;\n\tif (not open(filename, file)) {\n\t\tcreatefile(filename);\n\t\tif (not open(filename, file)) {\n\t\t\tprintln(\"Cannot open \", filename);\n\t\t\tstop();\n\t\t}\n\t}\n\n\tprintln(\"\\nOpen or create the test files dictionary \", dictfilename);\n\n\tvar dictfile;\n\tif (not open(dictfilename, dictfile)) {\n\t\tcreatefile(dictfilename);\n\t\t\tprintln(\"Cannot open dictionary \", dictfilename);\n\t\t\tstop();\n\t\t}\n\t}\n\n\tprintln(\"\\nPrepare some dictionary records\");\n\n\tvar dictrecs = \"\";\n\tdictrecs = \"CLIENT_CODE |F|0|Code |||| ||L|8\";\n\tdictrecs ^= FM ^ \"CLIENT_NAME |F|1|Name |||| ||T|15\";\n\tdictrecs ^= FM ^ \"CLIENT_TYPE |F|2|Type |||| ||L|5\";\n\tdictrecs ^= FM ^ \"DATE_CREATED|F|3|Date ||||D4 ||L|12\";\n\tdictrecs ^= FM ^ \"TIME_CREATED|F|4|Time ||||MTH ||L|12\";\n\tdictrecs ^= FM ^ \"BALANCE |F|5|Balance ||||MD20P ||R|10\";\n\tdictrecs ^= FM ^ \"TIMESTAMP |F|6|Timestamp||||[DATETIME]||L|12\";\n\tdictrecs ^= FM ^ \"@CRT |G| |CLIENT_CODE CLIENT_NAME CLIENT_TYPE BALANCE DATE_CREATED TIME_CREATED TIMESTAMP\";\n\n\tprintln(\"\\nWrite the dictionary records to the dictionary\");\n\n\tvar nrecs=count(dictrecs, FM)+1;\n\tfor (var recn = 1; recn <= nrecs; recn++)\n\t{\n\t\tvar dictrec=extract(dictrecs, recn);\n\t\tvar key=field(dictrec, \"|\", 1);\n\t\tvar rec=field(dictrec, \"|\", 2, 9999);\n\t\t\n\t\tprintln(key, \": \", rec);\n\t\tkey=trim(key);\n\t\trec=trim(rec);\n\t\trec=swap(rec, \" |\", \"|\");\n\t\trec=convert(rec, \"|\", FM);\n\t\t\n\t\twrite(rec, dictfile, key);\n\t\t\n\t\t\/\/check we can read the record back\n\t\tvar rec2;\n\t\tdictfile.outputln(\"dictfile\");\n\t\tkey.outputln(\"key\");\n\t\tif (read(rec2,dictfile, key)) {\n\t\t\tif (rec2 ne rec) {\n\t\t\t\tprintln(\"record differs?!\");\n\t\t\t}\n\t\t} else\n\t\t\tprintln(\"Cant read \", key, \" back\");\n\t}\n\n\tvar rec;\n\tif (not read(rec,dictfile,\"BALANCE\"))\n\t\tprintln(\"Cant read BALANCE record from dictionary\");\n\n\tprintln(\"\\nClear the client file\");\n\tclearfile(filename);\n\n\tprintln(\"\\nPrepare some data records in a readable format\");\n\n\tvar recs = \"\";\n\trecs ^= FM ^ \"SB001|Client AAA |A |15070|76539|1000.00|15070.76539\";\n\trecs ^= FM ^ \"JB002|Client BBB |B |15000|50539|200.00|15000.50539\";\n\trecs ^= FM ^ \"JB001|Client CCC |B |15010|60539|2000.00|15010.60539\";\n\trecs ^= FM ^ \"SB1 |Client SB1 |1 | | | | \";\n\trecs ^= FM ^ \"JB2 |Client JB2 |2 |14000|10539|0 |14000.10539\";\n\trecs ^= FM ^ \"JB10 |Client JB10|10|14010|10539|2000.00|14010.10539\";\n\tsplicer(recs, 1, 1, \"\");\n\n\tprintln(\"\\nWrite the data records to the data file\");\n\n\tnrecs=count(recs, FM)+1;\n\tfor (var recn = 1; recn <= nrecs; recn++)\n\t{\n\t\tvar rec=extract(recs, recn);\n\t\tvar key=field(rec, \"|\", 1);\n\t\trec=field(rec, \"|\", 2, 9999);\n\t\tprintln(key, \": \", rec);\n\t\twhile (index(rec, \" |\"))\n\t\t\tswapper(rec, \" |\", \"|\");\n\t\twrite(trimb(convert(rec, \"|\", FM)), file, trim(key));\n\t}\n\n\tvar prefix=\"SELECT \"^ filename;\n\t\n\tgosub sortselect(file, prefix^ \" BY CLIENT_CODE\");\n\n\tgosub sortselect(file, prefix^ \" BY BALANCE BY CLIENT_CODE\");\n\n\tgosub sortselect(file, prefix^ \" BY TIMESTAMP\");\n\n\tgosub sortselect(file, prefix^ \" WITH CLIENT_TYPE 'B' BY BALANCE\");\n\n\tvar cmd=\"list \"^ filename^ \" id-supp\";\n\tprintln(\"\\nList the file using \", quote(cmd));\n\tosshell(cmd);\n\t\n\tcmd=\"list \"^ dictfilename^ \" id-supp\";\n\tprintln(\"\\nList the dict using \", quote(cmd));\n\tosshell(cmd);\n\t\n\tif (cleanup) {\n\t\tprintln(\"\\nCleaning up. Delete the files\");\n\t\tdeletefile(file);\n\t\tdeletefile(dictfile);\n\t}\n\t\n\tprintln(\"\\nJust type 'list' (without the quotes) to see it's syntax\");\n\tprintln(\"or list dict_\"^ filename^ \" to see the dictionary\");\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\/\n\/* image_loader_bmp.cpp *\/\n\/*************************************************************************\/\n\/* This file is part of: *\/\n\/* GODOT ENGINE *\/\n\/* https:\/\/godotengine.org *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. *\/\n\/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) *\/\n\/* *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the *\/\n\/* \"Software\"), to deal in the Software without restriction, including *\/\n\/* without limitation the rights to use, copy, modify, merge, publish, *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions: *\/\n\/* *\/\n\/* The above copyright notice and this permission notice shall be *\/\n\/* included in all copies or substantial portions of the Software. *\/\n\/* *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\/\n\/*************************************************************************\/\n\n#include \"image_loader_bmp.h\"\n\nError ImageLoaderBMP::convert_to_image(Ref p_image,\n\t\tconst uint8_t *p_buffer,\n\t\tconst uint8_t *p_color_buffer,\n\t\tconst uint32_t color_table_size,\n\t\tconst bmp_header_s &p_header) {\n\n\tError err = OK;\n\n\tif (p_buffer == NULL)\n\t\terr = FAILED;\n\n\tif (err == OK) {\n\t\tsize_t index = 0;\n\t\tsize_t width = (size_t)p_header.bmp_info_header.bmp_width;\n\t\tsize_t height = (size_t)p_header.bmp_info_header.bmp_height;\n\t\tsize_t bits_per_pixel = (size_t)p_header.bmp_info_header.bmp_bit_count;\n\n\t\tif (p_header.bmp_info_header.bmp_compression != BI_RGB) {\n\t\t\terr = FAILED;\n\t\t}\n\t\t\/\/ Check whether we can load it\n\n\t\tif (bits_per_pixel == 1) {\n\t\t\t\/\/ Requires bit unpacking...\n\t\t\tERR_FAIL_COND_V(width % 8 != 0, ERR_UNAVAILABLE);\n\t\t\tERR_FAIL_COND_V(height % 8 != 0, ERR_UNAVAILABLE);\n\n\t\t} else if (bits_per_pixel == 4) {\n\t\t\t\/\/ Requires bit unpacking...\n\t\t\tERR_FAIL_COND_V(width % 2 != 0, ERR_UNAVAILABLE);\n\t\t\tERR_FAIL_COND_V(height % 2 != 0, ERR_UNAVAILABLE);\n\n\t\t} else if (bits_per_pixel == 16) {\n\n\t\t\tERR_FAIL_V(ERR_UNAVAILABLE);\n\t\t}\n\t\tif (err == OK) {\n\n\t\t\t\/\/ Image data (might be indexed)\n\t\t\tPoolVector data;\n\t\t\tint data_len = 0;\n\n\t\t\tif (bits_per_pixel <= 8) { \/\/ indexed\n\t\t\t\tdata_len = width * height;\n\t\t\t} else { \/\/ color\n\t\t\t\tdata_len = width * height * 4;\n\t\t\t}\n\t\t\tERR_FAIL_COND_V(data_len == 0, ERR_BUG);\n\t\t\terr = data.resize(data_len);\n\n\t\t\tPoolVector::Write data_w = data.write();\n\t\t\tuint8_t *write_buffer = data_w.ptr();\n\n\t\t\tconst uint32_t width_bytes = width * bits_per_pixel \/ 8;\n\t\t\tconst uint32_t line_width = (width_bytes + 3) & ~3;\n\n\t\t\t\/\/ The actual data traversal is determined by\n\t\t\t\/\/ the data width in case of 8\/4\/1 bit images\n\t\t\tconst uint32_t w = bits_per_pixel >= 24 ? width : width_bytes;\n\t\t\tconst uint8_t *line = p_buffer + (line_width * (height - 1));\n\n\t\t\tfor (unsigned int i = 0; i < height; i++) {\n\t\t\t\tconst uint8_t *line_ptr = line;\n\n\t\t\t\tfor (unsigned int j = 0; j < w; j++) {\n\t\t\t\t\tswitch (bits_per_pixel) {\n\t\t\t\t\t\tcase 1: {\n\t\t\t\t\t\t\tuint8_t color_index = *line_ptr;\n\n\t\t\t\t\t\t\twrite_buffer[index + 0] = (color_index >> 7) & 1;\n\t\t\t\t\t\t\twrite_buffer[index + 1] = (color_index >> 6) & 1;\n\t\t\t\t\t\t\twrite_buffer[index + 2] = (color_index >> 5) & 1;\n\t\t\t\t\t\t\twrite_buffer[index + 3] = (color_index >> 4) & 1;\n\t\t\t\t\t\t\twrite_buffer[index + 4] = (color_index >> 3) & 1;\n\t\t\t\t\t\t\twrite_buffer[index + 5] = (color_index >> 2) & 1;\n\t\t\t\t\t\t\twrite_buffer[index + 6] = (color_index >> 1) & 1;\n\t\t\t\t\t\t\twrite_buffer[index + 7] = (color_index >> 0) & 1;\n\n\t\t\t\t\t\t\tindex += 8;\n\t\t\t\t\t\t\tline_ptr += 1;\n\t\t\t\t\t\t} break;\n\t\t\t\t\t\tcase 4: {\n\t\t\t\t\t\t\tuint8_t color_index = *line_ptr;\n\n\t\t\t\t\t\t\twrite_buffer[index + 0] = (color_index >> 4) & 0x0f;\n\t\t\t\t\t\t\twrite_buffer[index + 1] = color_index & 0x0f;\n\n\t\t\t\t\t\t\tindex += 2;\n\t\t\t\t\t\t\tline_ptr += 1;\n\t\t\t\t\t\t} break;\n\t\t\t\t\t\tcase 8: {\n\t\t\t\t\t\t\tuint8_t color_index = *line_ptr;\n\n\t\t\t\t\t\t\twrite_buffer[index] = color_index;\n\n\t\t\t\t\t\t\tindex += 1;\n\t\t\t\t\t\t\tline_ptr += 1;\n\t\t\t\t\t\t} break;\n\t\t\t\t\t\tcase 24: {\n\t\t\t\t\t\t\tuint32_t color = *((uint32_t *)line_ptr);\n\n\t\t\t\t\t\t\twrite_buffer[index + 2] = color & 0xff;\n\t\t\t\t\t\t\twrite_buffer[index + 1] = (color >> 8) & 0xff;\n\t\t\t\t\t\t\twrite_buffer[index + 0] = (color >> 16) & 0xff;\n\t\t\t\t\t\t\twrite_buffer[index + 3] = 0xff;\n\n\t\t\t\t\t\t\tindex += 4;\n\t\t\t\t\t\t\tline_ptr += 3;\n\t\t\t\t\t\t} break;\n\t\t\t\t\t\tcase 32: {\n\t\t\t\t\t\t\tuint32_t color = *((uint32_t *)line_ptr);\n\n\t\t\t\t\t\t\twrite_buffer[index + 2] = color & 0xff;\n\t\t\t\t\t\t\twrite_buffer[index + 1] = (color >> 8) & 0xff;\n\t\t\t\t\t\t\twrite_buffer[index + 0] = (color >> 16) & 0xff;\n\t\t\t\t\t\t\twrite_buffer[index + 3] = color >> 24;\n\n\t\t\t\t\t\t\tindex += 4;\n\t\t\t\t\t\t\tline_ptr += 4;\n\t\t\t\t\t\t} break;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tline -= line_width;\n\t\t\t}\n\n\t\t\tif (p_color_buffer == NULL || color_table_size == 0) { \/\/ regular pixels\n\n\t\t\t\tp_image->create(width, height, 0, Image::FORMAT_RGBA8, data);\n\n\t\t\t} else { \/\/ data is in indexed format, extend it\n\n\t\t\t\t\/\/ Palette data\n\t\t\t\tPoolVector palette_data;\n\t\t\t\tpalette_data.resize(color_table_size * 4);\n\n\t\t\t\tPoolVector::Write palette_data_w = palette_data.write();\n\t\t\t\tuint8_t *pal = palette_data_w.ptr();\n\n\t\t\t\tconst uint8_t *cb = p_color_buffer;\n\n\t\t\t\tfor (unsigned int i = 0; i < color_table_size; ++i) {\n\t\t\t\t\tuint32_t color = *((uint32_t *)cb);\n\n\t\t\t\t\tpal[i * 4 + 0] = (color >> 16) & 0xff;\n\t\t\t\t\tpal[i * 4 + 1] = (color >> 8) & 0xff;\n\t\t\t\t\tpal[i * 4 + 2] = (color)&0xff;\n\t\t\t\t\tpal[i * 4 + 3] = 0xff;\n\n\t\t\t\t\tcb += 4;\n\t\t\t\t}\n\t\t\t\t\/\/ Extend palette to image\n\t\t\t\tPoolVector extended_data;\n\t\t\t\textended_data.resize(data.size() * 4);\n\n\t\t\t\tPoolVector::Write ex_w = extended_data.write();\n\t\t\t\tuint8_t *dest = ex_w.ptr();\n\n\t\t\t\tconst int num_pixels = width * height;\n\n\t\t\t\tfor (int i = 0; i < num_pixels; i++) {\n\t\t\t\t\tdest[0] = pal[write_buffer[i] * 4 + 0];\n\t\t\t\t\tdest[1] = pal[write_buffer[i] * 4 + 1];\n\t\t\t\t\tdest[2] = pal[write_buffer[i] * 4 + 2];\n\t\t\t\t\tdest[3] = pal[write_buffer[i] * 4 + 3];\n\n\t\t\t\t\tdest += 4;\n\t\t\t\t}\n\t\t\t\tp_image->create(width, height, 0, Image::FORMAT_RGBA8, extended_data);\n\t\t\t}\n\t\t}\n\t}\n\treturn err;\n}\n\nError ImageLoaderBMP::load_image(Ref p_image, FileAccess *f,\n\t\tbool p_force_linear, float p_scale) {\n\n\tbmp_header_s bmp_header;\n\tError err = ERR_INVALID_DATA;\n\n\t\/\/ A valid bmp file should always at least have a\n\t\/\/ file header and a minimal info header\n\tif (f->get_len() > BITMAP_FILE_HEADER_SIZE + BITMAP_INFO_HEADER_MIN_SIZE) {\n\t\t\/\/ File Header\n\t\tbmp_header.bmp_file_header.bmp_signature = f->get_16();\n\t\tif (bmp_header.bmp_file_header.bmp_signature == BITMAP_SIGNATURE) {\n\t\t\tbmp_header.bmp_file_header.bmp_file_size = f->get_32();\n\t\t\tbmp_header.bmp_file_header.bmp_file_padding = f->get_32();\n\t\t\tbmp_header.bmp_file_header.bmp_file_offset = f->get_32();\n\n\t\t\t\/\/ Info Header\n\t\t\tbmp_header.bmp_info_header.bmp_header_size = f->get_32();\n\t\t\tERR_FAIL_COND_V(bmp_header.bmp_info_header.bmp_header_size < BITMAP_INFO_HEADER_MIN_SIZE, ERR_FILE_CORRUPT);\n\n\t\t\tbmp_header.bmp_info_header.bmp_width = f->get_32();\n\t\t\tbmp_header.bmp_info_header.bmp_height = f->get_32();\n\n\t\t\tbmp_header.bmp_info_header.bmp_planes = f->get_16();\n\t\t\tERR_FAIL_COND_V(bmp_header.bmp_info_header.bmp_planes != 1, ERR_FILE_CORRUPT);\n\n\t\t\tbmp_header.bmp_info_header.bmp_bit_count = f->get_16();\n\t\t\tbmp_header.bmp_info_header.bmp_compression = f->get_32();\n\t\t\tbmp_header.bmp_info_header.bmp_size_image = f->get_32();\n\t\t\tbmp_header.bmp_info_header.bmp_pixels_per_meter_x = f->get_32();\n\t\t\tbmp_header.bmp_info_header.bmp_pixels_per_meter_y = f->get_32();\n\t\t\tbmp_header.bmp_info_header.bmp_colors_used = f->get_32();\n\t\t\tbmp_header.bmp_info_header.bmp_important_colors = f->get_32();\n\n\t\t\t\/\/ Compressed bitmaps not supported, stop parsing\n\t\t\tif (bmp_header.bmp_info_header.bmp_compression != BI_RGB) {\n\t\t\t\tERR_EXPLAIN(\"Unsupported bmp file: \" + f->get_path());\n\t\t\t\tf->close();\n\t\t\t\tERR_FAIL_V(ERR_UNAVAILABLE);\n\t\t\t}\n\t\t\t\/\/ Don't rely on sizeof(bmp_file_header) as structure padding\n\t\t\t\/\/ adds 2 bytes offset leading to misaligned color table reading\n\t\t\tuint32_t ct_offset = BITMAP_FILE_HEADER_SIZE +\n\t\t\t\t\t\t\t\t bmp_header.bmp_info_header.bmp_header_size;\n\t\t\tf->seek(ct_offset);\n\n\t\t\tuint32_t color_table_size = 0;\n\n\t\t\t\/\/ bmp_colors_used may report 0 despite having a color table\n\t\t\t\/\/ for 4 and 1 bit images, so don't rely on this information\n\t\t\tif (bmp_header.bmp_info_header.bmp_bit_count <= 8) {\n\t\t\t\t\/\/ Support 256 colors max\n\t\t\t\tcolor_table_size = 1 << bmp_header.bmp_info_header.bmp_bit_count;\n\t\t\t}\n\t\t\tERR_FAIL_COND_V(color_table_size == 0, ERR_BUG);\n\n\t\t\tPoolVector bmp_color_table;\n\t\t\t\/\/ Color table is usually 4 bytes per color -> [B][G][R][0]\n\t\t\tbmp_color_table.resize(color_table_size * 4);\n\t\t\tPoolVector::Write bmp_color_table_w = bmp_color_table.write();\n\t\t\tf->get_buffer(bmp_color_table_w.ptr(), color_table_size * 4);\n\n\t\t\tf->seek(bmp_header.bmp_file_header.bmp_file_offset);\n\n\t\t\tuint32_t bmp_buffer_size = (bmp_header.bmp_file_header.bmp_file_size -\n\t\t\t\t\t\t\t\t\t\tbmp_header.bmp_file_header.bmp_file_offset);\n\n\t\t\tPoolVector bmp_buffer;\n\t\t\terr = bmp_buffer.resize(bmp_buffer_size);\n\t\t\tif (err == OK) {\n\t\t\t\tPoolVector::Write bmp_buffer_w = bmp_buffer.write();\n\t\t\t\tf->get_buffer(bmp_buffer_w.ptr(), bmp_buffer_size);\n\n\t\t\t\tPoolVector::Read bmp_buffer_r = bmp_buffer.read();\n\t\t\t\tPoolVector::Read bmp_color_table_r = bmp_color_table.read();\n\t\t\t\terr = convert_to_image(p_image, bmp_buffer_r.ptr(),\n\t\t\t\t\t\tbmp_color_table_r.ptr(), color_table_size, bmp_header);\n\t\t\t}\n\t\t\tf->close();\n\t\t}\n\t}\n\treturn err;\n}\n\nvoid ImageLoaderBMP::get_recognized_extensions(\n\t\tList *p_extensions) const {\n\n\tp_extensions->push_back(\"bmp\");\n}\n\nImageLoaderBMP::ImageLoaderBMP() {}\nFix BMP loader incorrectly interpreting color table size\/*************************************************************************\/\n\/* image_loader_bmp.cpp *\/\n\/*************************************************************************\/\n\/* This file is part of: *\/\n\/* GODOT ENGINE *\/\n\/* https:\/\/godotengine.org *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. *\/\n\/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) *\/\n\/* *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the *\/\n\/* \"Software\"), to deal in the Software without restriction, including *\/\n\/* without limitation the rights to use, copy, modify, merge, publish, *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions: *\/\n\/* *\/\n\/* The above copyright notice and this permission notice shall be *\/\n\/* included in all copies or substantial portions of the Software. *\/\n\/* *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\/\n\/*************************************************************************\/\n\n#include \"image_loader_bmp.h\"\n\nError ImageLoaderBMP::convert_to_image(Ref p_image,\n\t\tconst uint8_t *p_buffer,\n\t\tconst uint8_t *p_color_buffer,\n\t\tconst uint32_t color_table_size,\n\t\tconst bmp_header_s &p_header) {\n\n\tError err = OK;\n\n\tif (p_buffer == NULL)\n\t\terr = FAILED;\n\n\tif (err == OK) {\n\t\tsize_t index = 0;\n\t\tsize_t width = (size_t)p_header.bmp_info_header.bmp_width;\n\t\tsize_t height = (size_t)p_header.bmp_info_header.bmp_height;\n\t\tsize_t bits_per_pixel = (size_t)p_header.bmp_info_header.bmp_bit_count;\n\n\t\tif (p_header.bmp_info_header.bmp_compression != BI_RGB) {\n\t\t\terr = FAILED;\n\t\t}\n\t\t\/\/ Check whether we can load it\n\n\t\tif (bits_per_pixel == 1) {\n\t\t\t\/\/ Requires bit unpacking...\n\t\t\tERR_FAIL_COND_V(width % 8 != 0, ERR_UNAVAILABLE);\n\t\t\tERR_FAIL_COND_V(height % 8 != 0, ERR_UNAVAILABLE);\n\n\t\t} else if (bits_per_pixel == 4) {\n\t\t\t\/\/ Requires bit unpacking...\n\t\t\tERR_FAIL_COND_V(width % 2 != 0, ERR_UNAVAILABLE);\n\t\t\tERR_FAIL_COND_V(height % 2 != 0, ERR_UNAVAILABLE);\n\n\t\t} else if (bits_per_pixel == 16) {\n\n\t\t\tERR_FAIL_V(ERR_UNAVAILABLE);\n\t\t}\n\t\tif (err == OK) {\n\n\t\t\t\/\/ Image data (might be indexed)\n\t\t\tPoolVector data;\n\t\t\tint data_len = 0;\n\n\t\t\tif (bits_per_pixel <= 8) { \/\/ indexed\n\t\t\t\tdata_len = width * height;\n\t\t\t} else { \/\/ color\n\t\t\t\tdata_len = width * height * 4;\n\t\t\t}\n\t\t\tERR_FAIL_COND_V(data_len == 0, ERR_BUG);\n\t\t\terr = data.resize(data_len);\n\n\t\t\tPoolVector::Write data_w = data.write();\n\t\t\tuint8_t *write_buffer = data_w.ptr();\n\n\t\t\tconst uint32_t width_bytes = width * bits_per_pixel \/ 8;\n\t\t\tconst uint32_t line_width = (width_bytes + 3) & ~3;\n\n\t\t\t\/\/ The actual data traversal is determined by\n\t\t\t\/\/ the data width in case of 8\/4\/1 bit images\n\t\t\tconst uint32_t w = bits_per_pixel >= 24 ? width : width_bytes;\n\t\t\tconst uint8_t *line = p_buffer + (line_width * (height - 1));\n\n\t\t\tfor (unsigned int i = 0; i < height; i++) {\n\t\t\t\tconst uint8_t *line_ptr = line;\n\n\t\t\t\tfor (unsigned int j = 0; j < w; j++) {\n\t\t\t\t\tswitch (bits_per_pixel) {\n\t\t\t\t\t\tcase 1: {\n\t\t\t\t\t\t\tuint8_t color_index = *line_ptr;\n\n\t\t\t\t\t\t\twrite_buffer[index + 0] = (color_index >> 7) & 1;\n\t\t\t\t\t\t\twrite_buffer[index + 1] = (color_index >> 6) & 1;\n\t\t\t\t\t\t\twrite_buffer[index + 2] = (color_index >> 5) & 1;\n\t\t\t\t\t\t\twrite_buffer[index + 3] = (color_index >> 4) & 1;\n\t\t\t\t\t\t\twrite_buffer[index + 4] = (color_index >> 3) & 1;\n\t\t\t\t\t\t\twrite_buffer[index + 5] = (color_index >> 2) & 1;\n\t\t\t\t\t\t\twrite_buffer[index + 6] = (color_index >> 1) & 1;\n\t\t\t\t\t\t\twrite_buffer[index + 7] = (color_index >> 0) & 1;\n\n\t\t\t\t\t\t\tindex += 8;\n\t\t\t\t\t\t\tline_ptr += 1;\n\t\t\t\t\t\t} break;\n\t\t\t\t\t\tcase 4: {\n\t\t\t\t\t\t\tuint8_t color_index = *line_ptr;\n\n\t\t\t\t\t\t\twrite_buffer[index + 0] = (color_index >> 4) & 0x0f;\n\t\t\t\t\t\t\twrite_buffer[index + 1] = color_index & 0x0f;\n\n\t\t\t\t\t\t\tindex += 2;\n\t\t\t\t\t\t\tline_ptr += 1;\n\t\t\t\t\t\t} break;\n\t\t\t\t\t\tcase 8: {\n\t\t\t\t\t\t\tuint8_t color_index = *line_ptr;\n\n\t\t\t\t\t\t\twrite_buffer[index] = color_index;\n\n\t\t\t\t\t\t\tindex += 1;\n\t\t\t\t\t\t\tline_ptr += 1;\n\t\t\t\t\t\t} break;\n\t\t\t\t\t\tcase 24: {\n\t\t\t\t\t\t\tuint32_t color = *((uint32_t *)line_ptr);\n\n\t\t\t\t\t\t\twrite_buffer[index + 2] = color & 0xff;\n\t\t\t\t\t\t\twrite_buffer[index + 1] = (color >> 8) & 0xff;\n\t\t\t\t\t\t\twrite_buffer[index + 0] = (color >> 16) & 0xff;\n\t\t\t\t\t\t\twrite_buffer[index + 3] = 0xff;\n\n\t\t\t\t\t\t\tindex += 4;\n\t\t\t\t\t\t\tline_ptr += 3;\n\t\t\t\t\t\t} break;\n\t\t\t\t\t\tcase 32: {\n\t\t\t\t\t\t\tuint32_t color = *((uint32_t *)line_ptr);\n\n\t\t\t\t\t\t\twrite_buffer[index + 2] = color & 0xff;\n\t\t\t\t\t\t\twrite_buffer[index + 1] = (color >> 8) & 0xff;\n\t\t\t\t\t\t\twrite_buffer[index + 0] = (color >> 16) & 0xff;\n\t\t\t\t\t\t\twrite_buffer[index + 3] = color >> 24;\n\n\t\t\t\t\t\t\tindex += 4;\n\t\t\t\t\t\t\tline_ptr += 4;\n\t\t\t\t\t\t} break;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tline -= line_width;\n\t\t\t}\n\n\t\t\tif (p_color_buffer == NULL || color_table_size == 0) { \/\/ regular pixels\n\n\t\t\t\tp_image->create(width, height, 0, Image::FORMAT_RGBA8, data);\n\n\t\t\t} else { \/\/ data is in indexed format, extend it\n\n\t\t\t\t\/\/ Palette data\n\t\t\t\tPoolVector palette_data;\n\t\t\t\tpalette_data.resize(color_table_size * 4);\n\n\t\t\t\tPoolVector::Write palette_data_w = palette_data.write();\n\t\t\t\tuint8_t *pal = palette_data_w.ptr();\n\n\t\t\t\tconst uint8_t *cb = p_color_buffer;\n\n\t\t\t\tfor (unsigned int i = 0; i < color_table_size; ++i) {\n\t\t\t\t\tuint32_t color = *((uint32_t *)cb);\n\n\t\t\t\t\tpal[i * 4 + 0] = (color >> 16) & 0xff;\n\t\t\t\t\tpal[i * 4 + 1] = (color >> 8) & 0xff;\n\t\t\t\t\tpal[i * 4 + 2] = (color)&0xff;\n\t\t\t\t\tpal[i * 4 + 3] = 0xff;\n\n\t\t\t\t\tcb += 4;\n\t\t\t\t}\n\t\t\t\t\/\/ Extend palette to image\n\t\t\t\tPoolVector extended_data;\n\t\t\t\textended_data.resize(data.size() * 4);\n\n\t\t\t\tPoolVector::Write ex_w = extended_data.write();\n\t\t\t\tuint8_t *dest = ex_w.ptr();\n\n\t\t\t\tconst int num_pixels = width * height;\n\n\t\t\t\tfor (int i = 0; i < num_pixels; i++) {\n\t\t\t\t\tdest[0] = pal[write_buffer[i] * 4 + 0];\n\t\t\t\t\tdest[1] = pal[write_buffer[i] * 4 + 1];\n\t\t\t\t\tdest[2] = pal[write_buffer[i] * 4 + 2];\n\t\t\t\t\tdest[3] = pal[write_buffer[i] * 4 + 3];\n\n\t\t\t\t\tdest += 4;\n\t\t\t\t}\n\t\t\t\tp_image->create(width, height, 0, Image::FORMAT_RGBA8, extended_data);\n\t\t\t}\n\t\t}\n\t}\n\treturn err;\n}\n\nError ImageLoaderBMP::load_image(Ref p_image, FileAccess *f,\n\t\tbool p_force_linear, float p_scale) {\n\n\tbmp_header_s bmp_header;\n\tError err = ERR_INVALID_DATA;\n\n\t\/\/ A valid bmp file should always at least have a\n\t\/\/ file header and a minimal info header\n\tif (f->get_len() > BITMAP_FILE_HEADER_SIZE + BITMAP_INFO_HEADER_MIN_SIZE) {\n\t\t\/\/ File Header\n\t\tbmp_header.bmp_file_header.bmp_signature = f->get_16();\n\t\tif (bmp_header.bmp_file_header.bmp_signature == BITMAP_SIGNATURE) {\n\t\t\tbmp_header.bmp_file_header.bmp_file_size = f->get_32();\n\t\t\tbmp_header.bmp_file_header.bmp_file_padding = f->get_32();\n\t\t\tbmp_header.bmp_file_header.bmp_file_offset = f->get_32();\n\n\t\t\t\/\/ Info Header\n\t\t\tbmp_header.bmp_info_header.bmp_header_size = f->get_32();\n\t\t\tERR_FAIL_COND_V(bmp_header.bmp_info_header.bmp_header_size < BITMAP_INFO_HEADER_MIN_SIZE, ERR_FILE_CORRUPT);\n\n\t\t\tbmp_header.bmp_info_header.bmp_width = f->get_32();\n\t\t\tbmp_header.bmp_info_header.bmp_height = f->get_32();\n\n\t\t\tbmp_header.bmp_info_header.bmp_planes = f->get_16();\n\t\t\tERR_FAIL_COND_V(bmp_header.bmp_info_header.bmp_planes != 1, ERR_FILE_CORRUPT);\n\n\t\t\tbmp_header.bmp_info_header.bmp_bit_count = f->get_16();\n\t\t\tbmp_header.bmp_info_header.bmp_compression = f->get_32();\n\t\t\tbmp_header.bmp_info_header.bmp_size_image = f->get_32();\n\t\t\tbmp_header.bmp_info_header.bmp_pixels_per_meter_x = f->get_32();\n\t\t\tbmp_header.bmp_info_header.bmp_pixels_per_meter_y = f->get_32();\n\t\t\tbmp_header.bmp_info_header.bmp_colors_used = f->get_32();\n\t\t\tbmp_header.bmp_info_header.bmp_important_colors = f->get_32();\n\n\t\t\t\/\/ Compressed bitmaps not supported, stop parsing\n\t\t\tif (bmp_header.bmp_info_header.bmp_compression != BI_RGB) {\n\t\t\t\tERR_EXPLAIN(\"Unsupported bmp file: \" + f->get_path());\n\t\t\t\tf->close();\n\t\t\t\tERR_FAIL_V(ERR_UNAVAILABLE);\n\t\t\t}\n\t\t\t\/\/ Don't rely on sizeof(bmp_file_header) as structure padding\n\t\t\t\/\/ adds 2 bytes offset leading to misaligned color table reading\n\t\t\tuint32_t ct_offset = BITMAP_FILE_HEADER_SIZE +\n\t\t\t\t\t\t\t\t bmp_header.bmp_info_header.bmp_header_size;\n\t\t\tf->seek(ct_offset);\n\n\t\t\tuint32_t color_table_size = 0;\n\n\t\t\t\/\/ bmp_colors_used may report 0 despite having a color table\n\t\t\t\/\/ for 4 and 1 bit images, so don't rely on this information\n\t\t\tif (bmp_header.bmp_info_header.bmp_bit_count <= 8) {\n\t\t\t\t\/\/ Support 256 colors max\n\t\t\t\tcolor_table_size = 1 << bmp_header.bmp_info_header.bmp_bit_count;\n\t\t\t\tERR_FAIL_COND_V(color_table_size == 0, ERR_BUG);\n\t\t\t}\n\n\t\t\tPoolVector bmp_color_table;\n\t\t\t\/\/ Color table is usually 4 bytes per color -> [B][G][R][0]\n\t\t\tbmp_color_table.resize(color_table_size * 4);\n\t\t\tPoolVector::Write bmp_color_table_w = bmp_color_table.write();\n\t\t\tf->get_buffer(bmp_color_table_w.ptr(), color_table_size * 4);\n\n\t\t\tf->seek(bmp_header.bmp_file_header.bmp_file_offset);\n\n\t\t\tuint32_t bmp_buffer_size = (bmp_header.bmp_file_header.bmp_file_size -\n\t\t\t\t\t\t\t\t\t\tbmp_header.bmp_file_header.bmp_file_offset);\n\n\t\t\tPoolVector bmp_buffer;\n\t\t\terr = bmp_buffer.resize(bmp_buffer_size);\n\t\t\tif (err == OK) {\n\t\t\t\tPoolVector::Write bmp_buffer_w = bmp_buffer.write();\n\t\t\t\tf->get_buffer(bmp_buffer_w.ptr(), bmp_buffer_size);\n\n\t\t\t\tPoolVector::Read bmp_buffer_r = bmp_buffer.read();\n\t\t\t\tPoolVector::Read bmp_color_table_r = bmp_color_table.read();\n\t\t\t\terr = convert_to_image(p_image, bmp_buffer_r.ptr(),\n\t\t\t\t\t\tbmp_color_table_r.ptr(), color_table_size, bmp_header);\n\t\t\t}\n\t\t\tf->close();\n\t\t}\n\t}\n\treturn err;\n}\n\nvoid ImageLoaderBMP::get_recognized_extensions(\n\t\tList *p_extensions) const {\n\n\tp_extensions->push_back(\"bmp\");\n}\n\nImageLoaderBMP::ImageLoaderBMP() {}\n<|endoftext|>"} {"text":"#include \"sample.hpp\"\n\n#include \n#include \n#include \n\n#include \n\n#include \n\n#include \n\n#include \n#include \n#include \n\n#include \"shader.hpp\"\n\nclass FBOSample : public Sample\n{\npublic:\n\tvirtual bool initContents()\n\t{\n\t\tglClearColor(0.0f, 0.0f, 0.3f, 0.0f);\n\n\t\tglGenVertexArrays(1, &_contentVAO);\n\t\tassert(_contentVAO != -1);\n\n\t\tglBindVertexArray(_contentVAO);\n\t\t{\n\t\t\t_contentProgram = LoadShaders(\"content.vert\", \"content.frag\");\n\t\t\tassert(_contentProgram != -1);\n\n\t\t\tstatic const GLfloat g_vertex_buffer_data[] = {\n\t\t\t\t-1.0f, -1.0f, 0.0f,\n\t\t\t\t 1.0f, -1.0f, 0.0f,\n\t\t\t\t 0.0f, 1.0f, 0.0f,\n\t\t\t};\n\n\t\t\tglGenBuffers(1, &_contentVBO);\n\t\t\tassert(_contentVBO != -1);\n\n\t\t\tglBindBuffer(GL_ARRAY_BUFFER, _contentVBO);\n\t\t\tglBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW);\n\n\t\t\tglVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);\n\n\t\t\tGLfloat* transform_buffer_data = new float[16 * 4];\n\t\t\t{\n\t\t\t\tfor (int i = 0; i < 4; ++i) {\n\t\t\t\t\tauto T = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, (float)i, 0.0f));\n\t\t\t\t\tauto R = glm::rotate(glm::mat4(1.0f), _globalTimer, glm::vec3(0.0f, 1.0f, 0.0f));\n\t\t\t\t\tauto S = glm::scale(glm::mat4(1.0f), glm::vec3(1.0f, 1.0f, 1.0f));\n\n\t\t\t\t\tauto M = T * R * S;\n\n\t\t\t\t\tmemcpy(transform_buffer_data + 16 * i, glm::value_ptr(M), sizeof(float) * 16);\n\t\t\t\t}\n\n\t\t\t\tglGenBuffers(1, &_contentTransformBO);\n\t\t\t\tglBindBuffer(GL_TEXTURE_BUFFER, _contentTransformBO);\n\t\t\t\tglBufferData(GL_TEXTURE_BUFFER, sizeof(float) * 16 * 4,\n\t\t\t\t\t\ttransform_buffer_data, GL_STATIC_DRAW);\n\n\t\t\t\tglGenTextures(1, &_contentTransformTBO);\n\t\t\t\tglBindTexture(GL_TEXTURE_BUFFER, _contentTransformTBO);\n\t\t\t\tglTexBuffer(GL_TEXTURE_BUFFER, GL_RGBA32F, _contentTransformBO);\n\t\t\t}\n\t\t\tif (transform_buffer_data) {\n\t\t\t\tdelete[] transform_buffer_data;\n\t\t\t\ttransform_buffer_data = nullptr;\n\t\t\t}\n\t\t}\n\t\tglBindVertexArray(0);\n\n\t\t_contentVPID = glGetUniformLocation(_contentProgram, \"VP\");\n\t\t_contentMsID = glGetUniformLocation(_contentProgram, \"Ms\");\n\n\t\t_globalTimer = 0.0f;\n\n\t\treturn true;\n\t}\n\n\tvirtual void destroyContents()\n\t{\n\t\tglDeleteVertexArrays(1, &_contentVAO);\n\t\tglDeleteBuffers(1, &_contentVBO);\n\t\tglDeleteBuffers(1, &_contentTransformBO);\n\n\t\tglDeleteTextures(1, &_contentTransformTBO);\n\n\t\tglDeleteProgram(_contentProgram);\n\t}\n\n\tvirtual void update(float dt)\n\t{\n\t\tglBindVertexArray(_contentVAO);\n\t\tglBindBuffer(GL_TEXTURE_BUFFER, _contentTransformBO);\n\n\t\tfloat* pointer = (float*)glMapBufferRange(GL_TEXTURE_BUFFER, 0, sizeof(float) * 16 * 4, GL_MAP_WRITE_BIT);\n\t\tassert(pointer);\n\n\t\tfor (int i = 0; i < 4; ++i) {\n\t\t\tauto T = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, (float)i, 0.0f));\n\t\t\tauto R = glm::rotate(glm::mat4(1.0f), _globalTimer, glm::vec3(0.0f, 1.0f, 0.0f));\n\t\t\tauto S = glm::scale(glm::mat4(1.0f), glm::vec3(1.0f, 1.0f, 1.0f));\n\n\t\t\tauto M = T * R * S;\n\n\t\t\tmemcpy(pointer + 16 * i, glm::value_ptr(M), sizeof(float) * 16);\n\t\t}\n\n\t\tglUnmapBuffer(GL_TEXTURE_BUFFER);\n\n\t\tauto V = glm::lookAt(\n\t\t\t\tglm::vec3(3,4,10),\n\t\t\t\tglm::vec3(0,0,0),\n\t\t\t\tglm::vec3(0,1,0)\n\t\t\t\t);\n\n\t\tauto P = glm::perspective(45.0f, (float)windowWidth() \/ windowHeight(),\n\t\t\t\t0.1f, 100.0f);\n\n\t\tauto VP = P * V;\n\n\t\tglUseProgram(_contentProgram);\n\t\tglUniform1i(_contentMsID, 0);\n\t\tglUniformMatrix4fv(_contentVPID, 1, false, glm::value_ptr(VP));\n\t\tglUseProgram(0);\n\n\t\t_globalTimer += dt;\n\t}\n\n\tvirtual void render()\n\t{\n\t\tglViewport(0, 0, windowWidth(), windowHeight());\n\t\tglClear(GL_COLOR_BUFFER_BIT);\n\n\t\tglUseProgram(_contentProgram);\n\n\t\tglBindVertexArray(_contentVAO);\n\t\t{\n\t\t\tglEnableVertexAttribArray(0);\n\n\t\t\tglActiveTexture(GL_TEXTURE0);\n\t\t\tglBindTexture(GL_TEXTURE_BUFFER, _contentTransformTBO);\n\t\t\tglDrawArraysInstanced(GL_TRIANGLES, 0, 3, 4);\n\n\t\t\tglDisableVertexAttribArray(0);\n\t\t}\n\n\t\tglUseProgram(0);\n\t}\n\nprivate:\n\tGLuint _contentVAO, _contentVBO;\n\tGLuint _contentTransformBO;\n\tGLuint _contentTransformTBO;\n\n\tGLuint _contentProgram;\n\tGLuint _contentVPID;\n\tGLuint _contentMsID;\n\n\tfloat _globalTimer;\n};\n\nSample* sample = nullptr;\n\nvoid interruptHandler(int signal)\n{\n\tif (sample == nullptr)\n\t\treturn;\n\n\tsample->destroy();\n\n\tif (sample) {\n\t\tdelete sample;\n\t\tsample = nullptr;\n\t}\n\n\tprintf(\"interrupted!\\n\");\n\n\texit(EXIT_SUCCESS);\n}\n\nint main(int argc, char** argv)\n{\n\tif (signal(SIGINT, interruptHandler) == SIG_ERR) {\n\t\tfprintf(stderr, \"cannot catch signal\\n\");\n\t}\n\n\tsample = new FBOSample();\n\tsample->init();\n\n\tsample->run();\n\n\tsample->destroy();\n\n\tif (sample) {\n\t\tdelete sample;\n\t\tsample = nullptr;\n\t}\n\n\treturn 0;\n}\nSeparate prototype and implementation#include \"sample.hpp\"\n\n#include \n#include \n#include \n\n#include \n\n#include \n\n#include \n\n#include \n#include \n#include \n\n#include \"shader.hpp\"\n\nclass FBOSample : public Sample\n{\npublic:\n\tvirtual bool initContents();\n\tvirtual void destroyContents();\n\tvirtual void update(float dt);\n\tvirtual void render();\n\nprivate:\n\tGLuint _contentVAO, _contentVBO;\n\tGLuint _contentTransformBO;\n\tGLuint _contentTransformTBO;\n\n\tGLuint _contentProgram;\n\tGLuint _contentVPID;\n\tGLuint _contentMsID;\n\n\tfloat _globalTimer;\n\n\tGLuint _fboVAO, _fboVBO;\n\n\tGLuint _fboProgram;\n};\n\nSample* sample = nullptr;\n\nvoid interruptHandler(int signal)\n{\n\tif (sample == nullptr)\n\t\treturn;\n\n\tsample->destroy();\n\n\tif (sample) {\n\t\tdelete sample;\n\t\tsample = nullptr;\n\t}\n\n\tprintf(\"interrupted!\\n\");\n\n\texit(EXIT_SUCCESS);\n}\n\nint main(int argc, char** argv)\n{\n\tif (signal(SIGINT, interruptHandler) == SIG_ERR) {\n\t\tfprintf(stderr, \"cannot catch signal\\n\");\n\t}\n\n\tsample = new FBOSample();\n\tsample->init();\n\n\tsample->run();\n\n\tsample->destroy();\n\n\tif (sample) {\n\t\tdelete sample;\n\t\tsample = nullptr;\n\t}\n\n\treturn 0;\n}\n\nbool FBOSample::initContents()\n{\n\tglClearColor(0.0f, 0.0f, 0.3f, 0.0f);\n\n\t\/\/ Init Content\n\tglGenVertexArrays(1, &_contentVAO);\n\tassert(_contentVAO != -1);\n\n\tglBindVertexArray(_contentVAO);\n\t{\n\t\t_contentProgram = LoadShaders(\"content.vert\", \"content.frag\");\n\t\tassert(_contentProgram != -1);\n\n\t\tstatic const GLfloat g_vertex_buffer_data[] = {\n\t\t\t-1.0f, -1.0f, 0.0f,\n\t\t\t 1.0f, -1.0f, 0.0f,\n\t\t\t 0.0f, 1.0f, 0.0f,\n\t\t};\n\n\t\tglGenBuffers(1, &_contentVBO);\n\t\tassert(_contentVBO != -1);\n\n\t\tglBindBuffer(GL_ARRAY_BUFFER, _contentVBO);\n\t\tglBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW);\n\n\t\tglVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);\n\n\t\tGLfloat* transform_buffer_data = new float[16 * 4];\n\t\t{\n\t\t\tfor (int i = 0; i < 4; ++i) {\n\t\t\t\tauto T = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, (float)i, 0.0f));\n\t\t\t\tauto R = glm::rotate(glm::mat4(1.0f), _globalTimer, glm::vec3(0.0f, 1.0f, 0.0f));\n\t\t\t\tauto S = glm::scale(glm::mat4(1.0f), glm::vec3(1.0f, 1.0f, 1.0f));\n\n\t\t\t\tauto M = T * R * S;\n\n\t\t\t\tmemcpy(transform_buffer_data + 16 * i, glm::value_ptr(M), sizeof(float) * 16);\n\t\t\t}\n\n\t\t\tglGenBuffers(1, &_contentTransformBO);\n\t\t\tglBindBuffer(GL_TEXTURE_BUFFER, _contentTransformBO);\n\t\t\tglBufferData(GL_TEXTURE_BUFFER, sizeof(float) * 16 * 4,\n\t\t\t\t\ttransform_buffer_data, GL_STATIC_DRAW);\n\n\t\t\tglGenTextures(1, &_contentTransformTBO);\n\t\t\tglBindTexture(GL_TEXTURE_BUFFER, _contentTransformTBO);\n\t\t\tglTexBuffer(GL_TEXTURE_BUFFER, GL_RGBA32F, _contentTransformBO);\n\t\t}\n\t\tif (transform_buffer_data) {\n\t\t\tdelete[] transform_buffer_data;\n\t\t\ttransform_buffer_data = nullptr;\n\t\t}\n\t}\n\tglBindVertexArray(0);\n\n\t_contentVPID = glGetUniformLocation(_contentProgram, \"VP\");\n\t_contentMsID = glGetUniformLocation(_contentProgram, \"Ms\");\n\n\t_globalTimer = 0.0f;\n\n\treturn true;\n}\n\nvoid FBOSample::destroyContents()\n{\n\tglDeleteVertexArrays(1, &_contentVAO);\n\tglDeleteBuffers(1, &_contentVBO);\n\tglDeleteBuffers(1, &_contentTransformBO);\n\n\tglDeleteTextures(1, &_contentTransformTBO);\n\n\tglDeleteProgram(_contentProgram);\n}\n\nvoid FBOSample::update(float dt)\n{\n\tglBindVertexArray(_contentVAO);\n\tglBindBuffer(GL_TEXTURE_BUFFER, _contentTransformBO);\n\n\tfloat* pointer = (float*)glMapBufferRange(GL_TEXTURE_BUFFER, 0, sizeof(float) * 16 * 4, GL_MAP_WRITE_BIT);\n\tassert(pointer);\n\n\tfor (int i = 0; i < 4; ++i) {\n\t\tauto T = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, (float)i, 0.0f));\n\t\tauto R = glm::rotate(glm::mat4(1.0f), _globalTimer, glm::vec3(0.0f, 1.0f, 0.0f));\n\t\tauto S = glm::scale(glm::mat4(1.0f), glm::vec3(1.0f, 1.0f, 1.0f));\n\n\t\tauto M = T * R * S;\n\n\t\tmemcpy(pointer + 16 * i, glm::value_ptr(M), sizeof(float) * 16);\n\t}\n\n\tglUnmapBuffer(GL_TEXTURE_BUFFER);\n\n\tauto V = glm::lookAt(\n\t\t\tglm::vec3(3,4,10),\n\t\t\tglm::vec3(0,0,0),\n\t\t\tglm::vec3(0,1,0)\n\t\t\t);\n\n\tauto P = glm::perspective(45.0f, (float)windowWidth() \/ windowHeight(),\n\t\t\t0.1f, 100.0f);\n\n\tauto VP = P * V;\n\n\tglUseProgram(_contentProgram);\n\tglUniform1i(_contentMsID, 0);\n\tglUniformMatrix4fv(_contentVPID, 1, false, glm::value_ptr(VP));\n\tglUseProgram(0);\n\n\t_globalTimer += dt;\n}\n\nvoid FBOSample::render()\n{\n\tglViewport(0, 0, windowWidth(), windowHeight());\n\tglClear(GL_COLOR_BUFFER_BIT);\n\n\tglUseProgram(_contentProgram);\n\n\tglBindVertexArray(_contentVAO);\n\t{\n\t\tglEnableVertexAttribArray(0);\n\n\t\tglActiveTexture(GL_TEXTURE0);\n\t\tglBindTexture(GL_TEXTURE_BUFFER, _contentTransformTBO);\n\t\tglDrawArraysInstanced(GL_TRIANGLES, 0, 3, 4);\n\n\t\tglDisableVertexAttribArray(0);\n\t}\n\n\tglUseProgram(0);\n}\n\n\n<|endoftext|>"} {"text":"#include \"Method_GNEB.h\"\n\n#include \"Manifoldmath.h\"\n#include \"Cubic_Hermite_Spline.h\"\n#include \"IO.h\"\n#include \"Timing.h\"\n\n#include \"Optimizer_Heun.h\"\n#include \"Optimizer_SIB.h\"\n#include \"Vectormath.h\"\n\n#include\"Logging.h\"\n\n#include \n#include \n\nusing namespace Utility;\n\nnamespace Engine\n{\n Method_GNEB::Method_GNEB(std::shared_ptr chain, int idx_chain) :\n\t\tMethod(chain->gneb_parameters, -1, idx_chain), chain(chain)\n\t{\n\t\tthis->systems = chain->images;\n\t\tthis->SenderName = Utility::Log_Sender::GNEB;\n\n\t\tint noi = chain->noi;\n\t\tint nos = chain->images[0]->nos;\n\n\t\tthis->energies = std::vector(noi, 0.0);\n\t\tthis->Rx = std::vector(noi, 0.0);\n\n\t\t\/\/ We assume that the chain is not converged before the first iteration\n\t\tthis->force_maxAbsComponent = this->chain->gneb_parameters->force_convergence + 1.0;\n\n\t\t\/\/ Tangents\n\t\tthis->tangents = std::vector>(noi, std::vector(3 * nos));\t\/\/ [noi][3nos]\n\t\t\/\/ Forces\n\t\tthis->F_total = std::vector>(noi, std::vector(3 * nos));\t\/\/ [noi][3nos]\n\t\tthis->F_gradient = std::vector>(noi, std::vector(3 * nos));\t\/\/ [noi][3nos]\n\t\tthis->F_spring = std::vector>(noi, std::vector(3 * nos));\t\/\/ [noi][3nos]\n\t}\n\n\tvoid Method_GNEB::Calculate_Force(std::vector>> configurations, std::vector> & forces)\n\t{\n\t\tint nos = configurations[0]->size()\/3;\n\n\t\t\/\/ We assume here that we receive a vector of configurations that corresponds to the vector of systems we gave the optimizer.\n\t\t\/\/\t\tThe Optimizer shuld respect this, but there is no way to enforce it.\n\t\t\/\/ Get Energy and Effective Field of configurations\n\t\tfor (int i = 0; i < chain->noi; ++i)\n\t\t{\n\t\t\t\/\/ Calculate the Energy of the image\n\t\t\tenergies[i] = this->chain->images[i]->hamiltonian->Energy(*configurations[i]);\n\t\t\tif (i>0) Rx[i] = Rx[i - 1] + Utility::Manifoldmath::Dist_Geodesic(*configurations[i], *configurations[i - 1]);\n\t\t}\n\n\t\t\/\/ Calculate relevant tangent to magnetisation sphere, considering also the energies of images\n\t\tUtility::Manifoldmath::Tangents(configurations, energies, tangents);\n\n\t\t\/\/ Get the total force on the image chain\n\t\t\/\/ Loop over images to calculate the total Effective Field on each Image\n\t\tfor (int img = 1; img < chain->noi - 1; ++img)\n\t\t{\n\t\t\tauto& image = *configurations[img];\n\t\t\t\/\/ The gradient force (unprojected) is simply the effective field\n\t\t\tthis->chain->images[img]->hamiltonian->Effective_Field(image, F_gradient[img]);\n\n\t\t\t\/\/ Calculate Force\n\t\t\tif (chain->climbing_image[img])\n\t\t\t{\n\t\t\t\t\/\/ We reverse the component in tangent direction\n\t\t\t\tUtility::Manifoldmath::Project_Reverse(F_gradient[img], tangents[img]);\n\t\t\t\t\/\/ And Spring Force is zero\n\t\t\t\tF_total[img] = F_gradient[img];\n\t\t\t}\n\t\t\telse if (chain->falling_image[img])\n\t\t\t{\n\t\t\t\t\/\/ We project the gradient force orthogonal to the tangent\n\t\t\t\t\/\/ If anything, project orthogonal to the spins... idiot! But Heun already does that.\n\t\t\t\t\/\/Utility::Manifoldmath::Project_Orthogonal(F_gradient[img], this->c->tangents[img]);\n\t\t\t\t\/\/ Spring Force is zero\n\t\t\t\tF_total[img] = F_gradient[img];\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\n\t\t\t\t\/\/ We project the gradient force orthogonal to the SPIN\n\t\t\t\t\/\/Utility::Manifoldmath::Project_Orthogonal(F_gradient[img], this->c->tangents[img]);\n\t\t\t\t\/\/ Get the scalar product of the vectors\n\t\t\t\tdouble v1v2 = 0.0;\n\t\t\t\tint dim;\n\t\t\t\t\/\/ Take out component in direction of v2\n\t\t\t\tfor (int i = 0; i < nos; ++i)\n\t\t\t\t{\n\t\t\t\t\tv1v2 = 0.0;\n\t\t\t\t\tfor (dim = 0; dim < 3; ++dim)\n\t\t\t\t\t{\n\t\t\t\t\t\tv1v2 += F_gradient[img][i+dim*nos] * image[i+dim*nos];\n\t\t\t\t\t}\n\t\t\t\t\tfor (dim = 0; dim < 3; ++dim)\n\t\t\t\t\t{\n\t\t\t\t\t\tF_gradient[img][i + dim*nos] = F_gradient[img][i + dim*nos] - v1v2 * image[i + dim*nos];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\n\n\t\t\t\t\/\/ We project the gradient force orthogonal to the TANGENT\n\t\t\t\t\/\/Utility::Manifoldmath::Project_Orthogonal(F_gradient[img], this->c->tangents[img]);\n\t\t\t\t\/\/ Get the scalar product of the vectors\n\t\t\t\tv1v2 = 0.0;\n\t\t\t\tfor (int i = 0; i < 3*nos; ++i)\n\t\t\t\t{\n\t\t\t\t\tv1v2 += F_gradient[img][i] * tangents[img][i];\n\t\t\t\t}\n\t\t\t\t\/\/ Take out component in direction of v2\n\t\t\t\tfor (int i = 0; i < 3 * nos; ++i)\n\t\t\t\t{\n\t\t\t\t\tF_gradient[img][i] = F_gradient[img][i] - v1v2 * tangents[img][i];\n\t\t\t\t}\n\n\n\t\t\t\t\/\/ Calculate the spring force\n\t\t\t\t\/\/spring_forces(:, : ) = spring_constant *(dist_geodesic(NOS, IMAGES_LAST(idx_img + 1, :, : ), IMAGES(idx_img, :, : )) - dist_geodesic(NOS, IMAGES(idx_img, :, : ), IMAGES_LAST(idx_img - 1, :, : )))* tangents(:, : );\n\t\t\t\tdouble d = this->chain->gneb_parameters->spring_constant * (Rx[img+1] - Rx[img-1]);\n\t\t\t\tfor (unsigned int i = 0; i < F_spring[0].size(); ++i)\n\t\t\t\t{\n\t\t\t\t\tF_spring[img][i] = d * tangents[img][i];\n\t\t\t\t}\n\n\t\t\t\t\/\/ Calculate the total force\n\t\t\t\tfor (int j = 0; j < 3 * nos; ++j)\n\t\t\t\t{\n\t\t\t\t\tF_total[img][j] = F_gradient[img][j] + F_spring[img][j];\n\t\t\t\t}\n\n\t\t\t\t\/\/ Copy out\n\t\t\t\tforces[img] = F_total[img];\n\t\t\t}\/\/ end if climbing\n\t\t}\/\/ end for img=1..noi-1\n\t}\/\/ end Calculate\n\n\tbool Method_GNEB::Force_Converged()\n\t{\n\t\t\/\/ return this->isConverged;\n\t\tif (this->force_maxAbsComponent < this->chain->gneb_parameters->force_convergence) return true;\n\t\treturn false;\n\t}\n\n\tbool Method_GNEB::Iterations_Allowed()\n\t{\n\t\treturn this->chain->iteration_allowed;\n\t}\n\n\tvoid Method_GNEB::Hook_Pre_Iteration()\n\t{\n\n\t}\n\n\tvoid Method_GNEB::Hook_Post_Iteration()\n\t{\n\t\t\/\/ --- Convergence Parameter Update\n\t\tthis->force_maxAbsComponent = 0;\n\t\tfor (int img = 1; img < chain->noi - 1; ++img)\n\t\t{\n\t\t\tdouble fmax = this->Force_on_Image_MaxAbsComponent(*(systems[img]->spins), F_total[img]);\n\t\t\t\/\/ TODO: how to handle convergence??\n\t\t\t\/\/ if (fmax > this->parameters->force_convergence) this->isConverged = false;\n\t\t\tif (fmax > this->force_maxAbsComponent) this->force_maxAbsComponent = fmax;\n\t\t}\n\n\t\t\/\/ --- Chain Data Update\n\t\t\/\/ Calculate the inclinations at the data points\n\t\tstd::vector dE_dRx(chain->noi, 0);\n\t\tfor (int i = 0; i < chain->noi; ++i)\n\t\t{\n\t\t\t\/\/ dy\/dx\n\t\t\tfor (int j = 0; j < 3 * chain->images[i]->nos; ++j)\n\t\t\t{\n\t\t\t\tdE_dRx[i] += this->F_gradient[i][j] * this->tangents[i][j];\n\t\t\t}\n\t\t}\n\t\t\/\/ Interpolate data points\n\t\tauto interp = Utility::Cubic_Hermite_Spline::Interpolate(this->Rx, this->energies, dE_dRx, chain->gneb_parameters->n_E_interpolations);\n\t\t\/\/ Update the chain\n\t\t\/\/\t\tRx\n\t\tchain->Rx = this->Rx;\n\t\t\/\/\t\tE\n\t\tfor (int img = 1; img < chain->noi; ++img) chain->images[img]->E = this->energies[img];\n\t\t\/\/\t\tRx interpolated\n\t\tchain->Rx_interpolated = interp[0];\n\t\t\/\/\t\tE interpolated\n\t\tchain->E_interpolated = interp[1];\n\t}\n\n\tvoid Method_GNEB::Finalize()\n {\n this->chain->iteration_allowed=false;\n }\n\n\n\tvoid Method_GNEB::Save_Current(std::string starttime, int iteration, bool initial, bool final)\n\t{\n\n\t\t\/\/ Get the file suffix\n\t\tstd::string suffix = \"\";\n\t\tif (final) suffix = \"_final\";\n\t\telse suffix = \"\";\n\n\t\t\/\/ always formatting to 6 digits may be problematic!\n\t\tauto s_iter = IO::int_to_formatted_string(iteration, 6);\n\n\t\t\/\/ Save current Image Chain\n\t\tauto imagesFile = this->chain->gneb_parameters->output_folder + \"\/\" + starttime + \"_Images_\" + s_iter + suffix + \".txt\";\n\t\tUtility::IO::Save_SpinChain_Configuration(this->chain, imagesFile);\n\n\t\t\/\/ Save current Energies with reaction coordinates\n\t\tauto energiesFile = this->chain->gneb_parameters->output_folder + \"\/\" + starttime + \"_E_Images_\" + s_iter + suffix + \".txt\";\n\t\t\/\/\t\tCheck if Energy File exists and write Header if it doesn't\n\t\tstd::ifstream f(energiesFile);\n\t\tif (!f.good()) Utility::IO::Write_Energy_Header(energiesFile);\n\t\t\/\/\t\tSave\n\t\tUtility::IO::Save_Energies(*this->chain, iteration, energiesFile);\n\n\t\t\/\/ Save interpolated Energies\n\t\tauto energiesInterpFile = this->chain->gneb_parameters->output_folder + \"\/\" + starttime + \"_E_interp_Images_\" + s_iter + suffix + \".txt\";\n\t\tUtility::IO::Save_Energies_Interpolated(*this->chain, energiesInterpFile);\n\n\t\t\/\/ Save Log\n\t\tLog.Append_to_File();\n\t}\n\n\t\/\/ Optimizer name as string\n std::string Method_GNEB::Name() { return \"GNEB\"; }\n}BUGFIX: GNEB method - calculation of spring force The spring force was incorrectly calculated, leading to idiotic results. The orthogonalisation of the gradient forces w.r.t. the spins has been removed from GNEB, as it is already automatically done by the Optimizers.#include \"Method_GNEB.h\"\n\n#include \"Manifoldmath.h\"\n#include \"Cubic_Hermite_Spline.h\"\n#include \"IO.h\"\n#include \"Timing.h\"\n\n#include \"Optimizer_Heun.h\"\n#include \"Optimizer_SIB.h\"\n#include \"Vectormath.h\"\n\n#include\"Logging.h\"\n\n#include \n#include \n\nusing namespace Utility;\n\nnamespace Engine\n{\n Method_GNEB::Method_GNEB(std::shared_ptr chain, int idx_chain) :\n\t\tMethod(chain->gneb_parameters, -1, idx_chain), chain(chain)\n\t{\n\t\tthis->systems = chain->images;\n\t\tthis->SenderName = Utility::Log_Sender::GNEB;\n\n\t\tint noi = chain->noi;\n\t\tint nos = chain->images[0]->nos;\n\n\t\tthis->energies = std::vector(noi, 0.0);\n\t\tthis->Rx = std::vector(noi, 0.0);\n\n\t\t\/\/ We assume that the chain is not converged before the first iteration\n\t\tthis->force_maxAbsComponent = this->chain->gneb_parameters->force_convergence + 1.0;\n\n\t\t\/\/ Tangents\n\t\tthis->tangents = std::vector>(noi, std::vector(3 * nos));\t\/\/ [noi][3nos]\n\t\t\/\/ Forces\n\t\tthis->F_total = std::vector>(noi, std::vector(3 * nos));\t\/\/ [noi][3nos]\n\t\tthis->F_gradient = std::vector>(noi, std::vector(3 * nos));\t\/\/ [noi][3nos]\n\t\tthis->F_spring = std::vector>(noi, std::vector(3 * nos));\t\/\/ [noi][3nos]\n\t}\n\n\tvoid Method_GNEB::Calculate_Force(std::vector>> configurations, std::vector> & forces)\n\t{\n\t\tint nos = configurations[0]->size()\/3;\n\n\t\t\/\/ We assume here that we receive a vector of configurations that corresponds to the vector of systems we gave the optimizer.\n\t\t\/\/\t\tThe Optimizer shuld respect this, but there is no way to enforce it.\n\t\t\/\/ Get Energy and Effective Field of configurations\n\t\tfor (int i = 0; i < chain->noi; ++i)\n\t\t{\n\t\t\t\/\/ Calculate the Energy of the image\n\t\t\tenergies[i] = this->chain->images[i]->hamiltonian->Energy(*configurations[i]);\n\t\t\tif (i>0) Rx[i] = Rx[i - 1] + Utility::Manifoldmath::Dist_Geodesic(*configurations[i], *configurations[i - 1]);\n\t\t}\n\n\t\t\/\/ Calculate relevant tangent to magnetisation sphere, considering also the energies of images\n\t\tUtility::Manifoldmath::Tangents(configurations, energies, tangents);\n\n\t\t\/\/ Get the total force on the image chain\n\t\t\/\/ Loop over images to calculate the total Effective Field on each Image\n\t\tfor (int img = 1; img < chain->noi - 1; ++img)\n\t\t{\n\t\t\tauto& image = *configurations[img];\n\t\t\t\/\/ The gradient force (unprojected) is simply the effective field\n\t\t\tthis->chain->images[img]->hamiltonian->Effective_Field(image, F_gradient[img]);\n\n\t\t\t\/\/ Calculate Force\n\t\t\tif (chain->climbing_image[img])\n\t\t\t{\n\t\t\t\t\/\/ We reverse the component in tangent direction\n\t\t\t\tUtility::Manifoldmath::Project_Reverse(F_gradient[img], tangents[img]);\n\t\t\t\t\/\/ And Spring Force is zero\n\t\t\t\tF_total[img] = F_gradient[img];\n\t\t\t}\n\t\t\telse if (chain->falling_image[img])\n\t\t\t{\n\t\t\t\t\/\/ We project the gradient force orthogonal to the tangent\n\t\t\t\t\/\/ If anything, project orthogonal to the spins... idiot! But Heun already does that.\n\t\t\t\t\/\/Utility::Manifoldmath::Project_Orthogonal(F_gradient[img], this->c->tangents[img]);\n\t\t\t\t\/\/ Spring Force is zero\n\t\t\t\tF_total[img] = F_gradient[img];\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/ We project the gradient force orthogonal to the SPIN\n\t\t\t\t\/\/Utility::Manifoldmath::Project_Orthogonal(F_gradient[img], this->c->tangents[img]);\n\t\t\t\t\/\/ Get the scalar product of the vectors\n\t\t\t\t\/\/ double v1v2 = 0.0;\n\t\t\t\t\/\/ int dim;\n\t\t\t\t\/\/ \/\/ Take out component in direction of v2\n\t\t\t\t\/\/ for (int i = 0; i < nos; ++i)\n\t\t\t\t\/\/ {\n\t\t\t\t\/\/ \tv1v2 = 0.0;\n\t\t\t\t\/\/ \tfor (dim = 0; dim < 3; ++dim)\n\t\t\t\t\/\/ \t{\n\t\t\t\t\/\/ \t\tv1v2 += F_gradient[img][i+dim*nos] * image[i+dim*nos];\n\t\t\t\t\/\/ \t}\n\t\t\t\t\/\/ \tfor (dim = 0; dim < 3; ++dim)\n\t\t\t\t\/\/ \t{\n\t\t\t\t\/\/ \t\tF_gradient[img][i + dim*nos] = F_gradient[img][i + dim*nos] - v1v2 * image[i + dim*nos];\n\t\t\t\t\/\/ \t}\n\t\t\t\t\/\/ }\n\t\t\t\n\n\t\t\t\t\/\/ We project the gradient force orthogonal to the TANGENT\n\t\t\t\t\/\/Utility::Manifoldmath::Project_Orthogonal(F_gradient[img], this->c->tangents[img]);\n\t\t\t\t\/\/ Get the scalar product of the vectors\n\t\t\t\tdouble v1v2 = 0.0;\n\t\t\t\tfor (int i = 0; i < 3*nos; ++i)\n\t\t\t\t{\n\t\t\t\t\tv1v2 += F_gradient[img][i] * tangents[img][i];\n\t\t\t\t}\n\t\t\t\t\/\/ Take out component in direction of v2\n\t\t\t\tfor (int i = 0; i < 3 * nos; ++i)\n\t\t\t\t{\n\t\t\t\t\tF_gradient[img][i] = F_gradient[img][i] - v1v2 * tangents[img][i];\n\t\t\t\t}\n\n\n\t\t\t\t\/\/ Calculate the spring force\n\t\t\t\t\/\/spring_forces(:, : ) = spring_constant *(dist_geodesic(NOS, IMAGES_LAST(idx_img + 1, :, : ), IMAGES(idx_img, :, : )) - dist_geodesic(NOS, IMAGES(idx_img, :, : ), IMAGES_LAST(idx_img - 1, :, : )))* tangents(:, : );\n\t\t\t\tdouble d = this->chain->gneb_parameters->spring_constant * (Rx[img+1] - 2*Rx[img] + Rx[img-1]);\n\t\t\t\tfor (unsigned int i = 0; i < F_spring[0].size(); ++i)\n\t\t\t\t{\n\t\t\t\t\tF_spring[img][i] = d * tangents[img][i];\n\t\t\t\t}\n\n\t\t\t\t\/\/ Calculate the total force\n\t\t\t\tfor (int j = 0; j < 3 * nos; ++j)\n\t\t\t\t{\n\t\t\t\t\tF_total[img][j] = F_gradient[img][j] + F_spring[img][j];\n\t\t\t\t}\n\n\t\t\t\t\/\/ Copy out\n\t\t\t\tforces[img] = F_total[img];\n\t\t\t}\/\/ end if climbing\n\t\t}\/\/ end for img=1..noi-1\n\t}\/\/ end Calculate\n\n\tbool Method_GNEB::Force_Converged()\n\t{\n\t\t\/\/ return this->isConverged;\n\t\tif (this->force_maxAbsComponent < this->chain->gneb_parameters->force_convergence) return true;\n\t\treturn false;\n\t}\n\n\tbool Method_GNEB::Iterations_Allowed()\n\t{\n\t\treturn this->chain->iteration_allowed;\n\t}\n\n\tvoid Method_GNEB::Hook_Pre_Iteration()\n\t{\n\n\t}\n\n\tvoid Method_GNEB::Hook_Post_Iteration()\n\t{\n\t\t\/\/ --- Convergence Parameter Update\n\t\tthis->force_maxAbsComponent = 0;\n\t\tfor (int img = 1; img < chain->noi - 1; ++img)\n\t\t{\n\t\t\tdouble fmax = this->Force_on_Image_MaxAbsComponent(*(systems[img]->spins), F_total[img]);\n\t\t\t\/\/ TODO: how to handle convergence??\n\t\t\t\/\/ if (fmax > this->parameters->force_convergence) this->isConverged = false;\n\t\t\tif (fmax > this->force_maxAbsComponent) this->force_maxAbsComponent = fmax;\n\t\t}\n\n\t\t\/\/ --- Chain Data Update\n\t\t\/\/ Calculate the inclinations at the data points\n\t\tstd::vector dE_dRx(chain->noi, 0);\n\t\tfor (int i = 0; i < chain->noi; ++i)\n\t\t{\n\t\t\t\/\/ dy\/dx\n\t\t\tfor (int j = 0; j < 3 * chain->images[i]->nos; ++j)\n\t\t\t{\n\t\t\t\tdE_dRx[i] += this->F_gradient[i][j] * this->tangents[i][j];\n\t\t\t}\n\t\t}\n\t\t\/\/ Interpolate data points\n\t\tauto interp = Utility::Cubic_Hermite_Spline::Interpolate(this->Rx, this->energies, dE_dRx, chain->gneb_parameters->n_E_interpolations);\n\t\t\/\/ Update the chain\n\t\t\/\/\t\tRx\n\t\tchain->Rx = this->Rx;\n\t\t\/\/\t\tE\n\t\tfor (int img = 1; img < chain->noi; ++img) chain->images[img]->E = this->energies[img];\n\t\t\/\/\t\tRx interpolated\n\t\tchain->Rx_interpolated = interp[0];\n\t\t\/\/\t\tE interpolated\n\t\tchain->E_interpolated = interp[1];\n\t}\n\n\tvoid Method_GNEB::Finalize()\n {\n this->chain->iteration_allowed=false;\n }\n\n\n\tvoid Method_GNEB::Save_Current(std::string starttime, int iteration, bool initial, bool final)\n\t{\n\n\t\t\/\/ Get the file suffix\n\t\tstd::string suffix = \"\";\n\t\tif (final) suffix = \"_final\";\n\t\telse suffix = \"\";\n\n\t\t\/\/ always formatting to 6 digits may be problematic!\n\t\tauto s_iter = IO::int_to_formatted_string(iteration, 6);\n\n\t\t\/\/ Save current Image Chain\n\t\tauto imagesFile = this->chain->gneb_parameters->output_folder + \"\/\" + starttime + \"_Images_\" + s_iter + suffix + \".txt\";\n\t\tUtility::IO::Save_SpinChain_Configuration(this->chain, imagesFile);\n\n\t\t\/\/ Save current Energies with reaction coordinates\n\t\tauto energiesFile = this->chain->gneb_parameters->output_folder + \"\/\" + starttime + \"_E_Images_\" + s_iter + suffix + \".txt\";\n\t\t\/\/\t\tCheck if Energy File exists and write Header if it doesn't\n\t\tstd::ifstream f(energiesFile);\n\t\tif (!f.good()) Utility::IO::Write_Energy_Header(energiesFile);\n\t\t\/\/\t\tSave\n\t\tUtility::IO::Save_Energies(*this->chain, iteration, energiesFile);\n\n\t\t\/\/ Save interpolated Energies\n\t\tauto energiesInterpFile = this->chain->gneb_parameters->output_folder + \"\/\" + starttime + \"_E_interp_Images_\" + s_iter + suffix + \".txt\";\n\t\tUtility::IO::Save_Energies_Interpolated(*this->chain, energiesInterpFile);\n\n\t\t\/\/ Save Log\n\t\tLog.Append_to_File();\n\t}\n\n\t\/\/ Optimizer name as string\n std::string Method_GNEB::Name() { return \"GNEB\"; }\n}<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2012 BMW Car IT GmbH\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n#include \n\nnamespace capu\n{\n TEST(ConfigTest, Types)\n {\n EXPECT_EQ(1u, sizeof(int8_t));\n EXPECT_EQ(1u, sizeof(int8_t));\n EXPECT_EQ(1u, sizeof(uint8_t));\n EXPECT_EQ(2u, sizeof(int16_t));\n EXPECT_EQ(2u, sizeof(uint16_t));\n EXPECT_EQ(4u, sizeof(int32_t));\n EXPECT_EQ(8u, sizeof(int64_t));\n EXPECT_EQ(4u, sizeof(uint32_t));\n EXPECT_EQ(8u, sizeof(uint64_t));\n EXPECT_EQ(4u, sizeof(float_t));\n EXPECT_EQ(8u, sizeof(double_t));\n EXPECT_EQ(1u, sizeof(bool_t));\n EXPECT_EQ(1u, sizeof(char_t));\n EXPECT_EQ(1u, sizeof(uchar_t));\n#if defined (OS_MacOSX)\n EXPECT_EQ(4u, sizeof(time_t));\n#elif defined (OS_WINDOWS)\n EXPECT_EQ(8u, sizeof(time_t));\n#elif defined (ARCH_X86_32)\n EXPECT_EQ(4u, sizeof(time_t));\n#elif defined (ARCH_X86_64)\n EXPECT_EQ(8u, sizeof(time_t));\n#elif defined (ARCH_ARMV7L)\n EXPECT_EQ(4u, sizeof(time_t));\n#endif\n\n#if defined (ARCH_X86_32)\n EXPECT_EQ(4u, sizeof(int_t));\n EXPECT_EQ(4u, sizeof(uint_t));\n#elif defined (ARCH_X86_64)\n EXPECT_EQ(8u, sizeof(int_t));\n EXPECT_EQ(8u, sizeof(uint_t));\n#elif defined (ARCH_ARMV7L)\n EXPECT_EQ(4u, sizeof(int_t));\n EXPECT_EQ(4u, sizeof(uint_t));\n#endif\n }\n}\nRemoving special treatment of MacOSX in ConfigTest\/*\n * Copyright (C) 2012 BMW Car IT GmbH\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n#include \n\nnamespace capu\n{\n TEST(ConfigTest, Types)\n {\n EXPECT_EQ(1u, sizeof(int8_t));\n EXPECT_EQ(1u, sizeof(int8_t));\n EXPECT_EQ(1u, sizeof(uint8_t));\n EXPECT_EQ(2u, sizeof(int16_t));\n EXPECT_EQ(2u, sizeof(uint16_t));\n EXPECT_EQ(4u, sizeof(int32_t));\n EXPECT_EQ(8u, sizeof(int64_t));\n EXPECT_EQ(4u, sizeof(uint32_t));\n EXPECT_EQ(8u, sizeof(uint64_t));\n EXPECT_EQ(4u, sizeof(float_t));\n EXPECT_EQ(8u, sizeof(double_t));\n EXPECT_EQ(1u, sizeof(bool_t));\n EXPECT_EQ(1u, sizeof(char_t));\n EXPECT_EQ(1u, sizeof(uchar_t));\n\n#if defined (OS_WINDOWS)\n EXPECT_EQ(8u, sizeof(time_t));\n#elif defined (ARCH_X86_32)\n EXPECT_EQ(4u, sizeof(time_t));\n#elif defined (ARCH_X86_64)\n EXPECT_EQ(8u, sizeof(time_t));\n#elif defined (ARCH_ARMV7L)\n EXPECT_EQ(4u, sizeof(time_t));\n#endif\n\n#if defined (ARCH_X86_32)\n EXPECT_EQ(4u, sizeof(int_t));\n EXPECT_EQ(4u, sizeof(uint_t));\n#elif defined (ARCH_X86_64)\n EXPECT_EQ(8u, sizeof(int_t));\n EXPECT_EQ(8u, sizeof(uint_t));\n#elif defined (ARCH_ARMV7L)\n EXPECT_EQ(4u, sizeof(int_t));\n EXPECT_EQ(4u, sizeof(uint_t));\n#endif\n }\n}\n<|endoftext|>"} {"text":"\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2020 Inviwo Foundation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *********************************************************************************\/\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#ifdef WIN32\n#include \n#endif\n\nnamespace inviwo {\n\n#ifdef WIN32\n\nclass WatcherThread {\npublic:\n enum class Action { Added, Removed, Modified };\n\n WatcherThread(\n std::function changeCallback)\n : changeCallback_{std::move(changeCallback)} {\n\n util::setThreadDescription(thread_, \"Inviwo File Watcher Thread\");\n }\n\n ~WatcherThread() {\n stop_ = true;\n thread_.join();\n }\n\n bool addObservation(const std::string& path) {\n std::scoped_lock lock{mutex_};\n if (active_ + toAdd_.size() - toRemove_.size() + 1 < MAXIMUM_WAIT_OBJECTS) {\n toAdd_.push_back(path);\n return true;\n } else {\n return false;\n }\n }\n void removeObservation(const std::string& path) {\n std::scoped_lock lock{mutex_};\n toRemove_.push_back(path);\n }\n\nprivate:\n void remove(const std::vector& toRemove) {\n auto range = util::zip(handles_, observed_);\n auto it = std::remove_if(range.begin(), range.end(), [&](auto&& elem) {\n return std::find(toRemove.begin(), toRemove.end(), elem.second().first) !=\n toRemove.end();\n });\n for (auto&& [handle, observed] : util::as_range(it, range.end())) {\n FindCloseChangeNotification(handle);\n observed.first.clear();\n observed.second.clear();\n --active_;\n }\n }\n\n void add(const std::vector& toAdd) {\n for (auto& path : toAdd) {\n auto wpath = util::toWstring(path);\n const auto handle = FindFirstChangeNotification(wpath.c_str(), TRUE, filter);\n\n if (handle == INVALID_HANDLE_VALUE || handle == nullptr) {\n LogError(\"FindFirstChangeNotification function failed.\");\n continue;\n }\n\n handles_[active_] = handle;\n observed_[active_].first = path;\n for (auto& elem : filesystem::getDirectoryContentsRecursively(\n path, filesystem::ListMode::FilesAndDirectories)) {\n observed_[active_].second[elem] = filesystem::fileModificationTime(elem);\n }\n\n ++active_;\n }\n }\n\n void watch() {\n while (!stop_) {\n {\n std::scoped_lock lock{mutex_};\n if (!toRemove_.empty()) {\n remove(toRemove_);\n toRemove_.clear();\n }\n if (!toAdd_.empty()) {\n add(toAdd_);\n toAdd_.clear();\n }\n }\n if (active_ == 0) {\n std::this_thread::sleep_for(timeout_);\n } else {\n const auto status =\n WaitForMultipleObjects(static_cast(active_), handles_.data(), FALSE,\n static_cast(timeout_.count()));\n if (status >= WAIT_OBJECT_0 && status < WAIT_OBJECT_0 + MAXIMUM_WAIT_OBJECTS) {\n\n const auto& path = observed_[status - WAIT_OBJECT_0].first;\n auto& files = observed_[status - WAIT_OBJECT_0].second;\n\n const auto changedFiles = getChangedAndUpdateFiles(path, files);\n for (auto&& [changedFile, action] : changedFiles) {\n changeCallback_(path, changedFile, action);\n }\n\n const auto handle = handles_[status - WAIT_OBJECT_0];\n FindNextChangeNotification(handle);\n }\n }\n }\n for (auto handle : util::as_range(handles_.begin(), handles_.begin() + active_)) {\n FindCloseChangeNotification(handle);\n }\n }\n\n std::vector> getChangedAndUpdateFiles(\n const std::string& path, std::unordered_map& files) {\n\n std::vector> changed;\n\n util::map_erase_remove_if(files, [&](auto& item) {\n if (!filesystem::fileExists(item.first)) {\n changed.emplace_back(item.first, Action::Removed);\n return true;\n } else {\n return false;\n }\n });\n\n for (auto& elem : filesystem::getDirectoryContentsRecursively(\n path, filesystem::ListMode::FilesAndDirectories)) {\n\n auto it = files.find(elem);\n if (it == files.end()) {\n changed.emplace_back(elem, Action::Removed);\n files[elem] = filesystem::fileModificationTime(elem);\n } else {\n auto newTime = filesystem::fileModificationTime(elem);\n if (newTime > it->second) {\n changed.emplace_back(elem, Action::Modified);\n it->second = newTime;\n }\n }\n }\n\n return changed;\n }\n\n static constexpr DWORD filter =\n FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE;\n\n std::array handles_{};\n std::array>,\n MAXIMUM_WAIT_OBJECTS>\n observed_{};\n std::atomic active_ = 0;\n\n std::function changeCallback_;\n std::mutex mutex_;\n std::vector toAdd_;\n std::vector toRemove_;\n std::atomic stop_{false};\n std::chrono::milliseconds timeout_{1000};\n std::thread thread_{[this]() { watch(); }};\n};\n\nFileWatcher::FileWatcher(InviwoApplication* app)\n : app_{app}\n , watcher_{std::make_unique(\n [this](const std::string& dir, const std::string& path, WatcherThread::Action) {\n auto notifyAboutChanges = [this, dir, path]() {\n if (filesystem::fileExists(path)) {\n \/\/ don't use iterators here, they might be invalidated.\n const auto orgSize = fileObservers_.size();\n for (size_t i = 0; i < orgSize && i < fileObservers_.size(); ++i) {\n if (fileObservers_[i]->isObserved(path)) {\n fileObservers_[i]->fileChanged(path);\n }\n }\n }\n if (filesystem::directoryExists(dir)) {\n \/\/ don't use iterators here, they might be invalidated.\n const auto orgSize = fileObservers_.size();\n for (size_t i = 0; i < orgSize && i < fileObservers_.size(); ++i) {\n if (fileObservers_[i]->isObserved(dir)) {\n fileObservers_[i]->fileChanged(dir);\n }\n }\n }\n };\n\n if (app_) {\n app_->dispatchFront(notifyAboutChanges);\n } else {\n notifyAboutChanges();\n }\n })} {}\n\nFileWatcher::~FileWatcher() = default;\n\nvoid FileWatcher::registerFileObserver(FileObserver* fileObserver) {\n IVW_ASSERT(std::find(fileObservers_.cbegin(), fileObservers_.cend(), fileObserver) ==\n fileObservers_.cend(),\n \"File observer already registered.\");\n fileObservers_.push_back(fileObserver);\n}\n\nvoid FileWatcher::unRegisterFileObserver(FileObserver* fileObserver) {\n const auto it = std::find(fileObservers_.begin(), fileObservers_.end(), fileObserver);\n if (it != fileObservers_.end()) {\n fileObservers_.erase(it);\n }\n}\n\nvoid FileWatcher::startFileObservation(const std::string& fileName) {\n const bool isDirectory = filesystem::directoryExists(fileName);\n const auto dir = isDirectory ? fileName : filesystem::getFileDirectory(fileName);\n\n const auto it = observed_.find(dir);\n if (it == observed_.end()) {\n observed_[dir].insert(fileName);\n if (!watcher_->addObservation(dir)) {\n LogError(\"Can't watch more files\");\n }\n } else {\n it->second.insert(fileName);\n }\n}\n\nvoid FileWatcher::stopFileObservation(const std::string& fileName) {\n auto observerit =\n std::find_if(std::begin(fileObservers_), std::end(fileObservers_),\n [fileName](const auto observer) { return observer->isObserved(fileName); });\n \/\/ Make sure that no observer is observing the file\n if (observerit == std::end(fileObservers_)) {\n const bool isDirectory = filesystem::directoryExists(fileName);\n const auto dir = isDirectory ? fileName : filesystem::getFileDirectory(fileName);\n\n const auto it = observed_.find(dir);\n if (it != observed_.end()) {\n it->second.erase(fileName);\n if (it->second.empty()) {\n watcher_->removeObservation(dir);\n observed_.erase(it);\n }\n }\n }\n}\n\n#else\n\nclass WatcherThread {\npublic:\n WatcherThread() = default;\n};\n\nFileWatcher::FileWatcher(InviwoApplication* app) : app_{app} {\n (void) app_;\n LogWarn(\"FileObserver are currently not supported using GLFW on this platform\");\n}\n\nFileWatcher::~FileWatcher() = default;\n\nvoid FileWatcher::registerFileObserver(FileObserver* fileObserver) {\n IVW_ASSERT(std::find(fileObservers_.cbegin(), fileObservers_.cend(), fileObserver) ==\n fileObservers_.cend(),\n \"File observer already registered.\");\n fileObservers_.push_back(fileObserver);\n}\n\nvoid FileWatcher::unRegisterFileObserver(FileObserver* fileObserver) {\n util::erase_remove(fileObservers_, fileObserver);\n}\n\nvoid FileWatcher::stopFileObservation(const std::string& fileName) {}\nvoid FileWatcher::startFileObservation(const std::string& fileName) {}\n\n#endif\n\n} \/\/ namespace inviwo\nJenkins: Format fixes\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2020 Inviwo Foundation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *********************************************************************************\/\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#ifdef WIN32\n#include \n#endif\n\nnamespace inviwo {\n\n#ifdef WIN32\n\nclass WatcherThread {\npublic:\n enum class Action { Added, Removed, Modified };\n\n WatcherThread(\n std::function changeCallback)\n : changeCallback_{std::move(changeCallback)} {\n\n util::setThreadDescription(thread_, \"Inviwo File Watcher Thread\");\n }\n\n ~WatcherThread() {\n stop_ = true;\n thread_.join();\n }\n\n bool addObservation(const std::string& path) {\n std::scoped_lock lock{mutex_};\n if (active_ + toAdd_.size() - toRemove_.size() + 1 < MAXIMUM_WAIT_OBJECTS) {\n toAdd_.push_back(path);\n return true;\n } else {\n return false;\n }\n }\n void removeObservation(const std::string& path) {\n std::scoped_lock lock{mutex_};\n toRemove_.push_back(path);\n }\n\nprivate:\n void remove(const std::vector& toRemove) {\n auto range = util::zip(handles_, observed_);\n auto it = std::remove_if(range.begin(), range.end(), [&](auto&& elem) {\n return std::find(toRemove.begin(), toRemove.end(), elem.second().first) !=\n toRemove.end();\n });\n for (auto&& [handle, observed] : util::as_range(it, range.end())) {\n FindCloseChangeNotification(handle);\n observed.first.clear();\n observed.second.clear();\n --active_;\n }\n }\n\n void add(const std::vector& toAdd) {\n for (auto& path : toAdd) {\n auto wpath = util::toWstring(path);\n const auto handle = FindFirstChangeNotification(wpath.c_str(), TRUE, filter);\n\n if (handle == INVALID_HANDLE_VALUE || handle == nullptr) {\n LogError(\"FindFirstChangeNotification function failed.\");\n continue;\n }\n\n handles_[active_] = handle;\n observed_[active_].first = path;\n for (auto& elem : filesystem::getDirectoryContentsRecursively(\n path, filesystem::ListMode::FilesAndDirectories)) {\n observed_[active_].second[elem] = filesystem::fileModificationTime(elem);\n }\n\n ++active_;\n }\n }\n\n void watch() {\n while (!stop_) {\n {\n std::scoped_lock lock{mutex_};\n if (!toRemove_.empty()) {\n remove(toRemove_);\n toRemove_.clear();\n }\n if (!toAdd_.empty()) {\n add(toAdd_);\n toAdd_.clear();\n }\n }\n if (active_ == 0) {\n std::this_thread::sleep_for(timeout_);\n } else {\n const auto status =\n WaitForMultipleObjects(static_cast(active_), handles_.data(), FALSE,\n static_cast(timeout_.count()));\n if (status >= WAIT_OBJECT_0 && status < WAIT_OBJECT_0 + MAXIMUM_WAIT_OBJECTS) {\n\n const auto& path = observed_[status - WAIT_OBJECT_0].first;\n auto& files = observed_[status - WAIT_OBJECT_0].second;\n\n const auto changedFiles = getChangedAndUpdateFiles(path, files);\n for (auto&& [changedFile, action] : changedFiles) {\n changeCallback_(path, changedFile, action);\n }\n\n const auto handle = handles_[status - WAIT_OBJECT_0];\n FindNextChangeNotification(handle);\n }\n }\n }\n for (auto handle : util::as_range(handles_.begin(), handles_.begin() + active_)) {\n FindCloseChangeNotification(handle);\n }\n }\n\n std::vector> getChangedAndUpdateFiles(\n const std::string& path, std::unordered_map& files) {\n\n std::vector> changed;\n\n util::map_erase_remove_if(files, [&](auto& item) {\n if (!filesystem::fileExists(item.first)) {\n changed.emplace_back(item.first, Action::Removed);\n return true;\n } else {\n return false;\n }\n });\n\n for (auto& elem : filesystem::getDirectoryContentsRecursively(\n path, filesystem::ListMode::FilesAndDirectories)) {\n\n auto it = files.find(elem);\n if (it == files.end()) {\n changed.emplace_back(elem, Action::Removed);\n files[elem] = filesystem::fileModificationTime(elem);\n } else {\n auto newTime = filesystem::fileModificationTime(elem);\n if (newTime > it->second) {\n changed.emplace_back(elem, Action::Modified);\n it->second = newTime;\n }\n }\n }\n\n return changed;\n }\n\n static constexpr DWORD filter =\n FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE;\n\n std::array handles_{};\n std::array>,\n MAXIMUM_WAIT_OBJECTS>\n observed_{};\n std::atomic active_ = 0;\n\n std::function changeCallback_;\n std::mutex mutex_;\n std::vector toAdd_;\n std::vector toRemove_;\n std::atomic stop_{false};\n std::chrono::milliseconds timeout_{1000};\n std::thread thread_{[this]() { watch(); }};\n};\n\nFileWatcher::FileWatcher(InviwoApplication* app)\n : app_{app}\n , watcher_{std::make_unique(\n [this](const std::string& dir, const std::string& path, WatcherThread::Action) {\n auto notifyAboutChanges = [this, dir, path]() {\n if (filesystem::fileExists(path)) {\n \/\/ don't use iterators here, they might be invalidated.\n const auto orgSize = fileObservers_.size();\n for (size_t i = 0; i < orgSize && i < fileObservers_.size(); ++i) {\n if (fileObservers_[i]->isObserved(path)) {\n fileObservers_[i]->fileChanged(path);\n }\n }\n }\n if (filesystem::directoryExists(dir)) {\n \/\/ don't use iterators here, they might be invalidated.\n const auto orgSize = fileObservers_.size();\n for (size_t i = 0; i < orgSize && i < fileObservers_.size(); ++i) {\n if (fileObservers_[i]->isObserved(dir)) {\n fileObservers_[i]->fileChanged(dir);\n }\n }\n }\n };\n\n if (app_) {\n app_->dispatchFront(notifyAboutChanges);\n } else {\n notifyAboutChanges();\n }\n })} {}\n\nFileWatcher::~FileWatcher() = default;\n\nvoid FileWatcher::registerFileObserver(FileObserver* fileObserver) {\n IVW_ASSERT(std::find(fileObservers_.cbegin(), fileObservers_.cend(), fileObserver) ==\n fileObservers_.cend(),\n \"File observer already registered.\");\n fileObservers_.push_back(fileObserver);\n}\n\nvoid FileWatcher::unRegisterFileObserver(FileObserver* fileObserver) {\n const auto it = std::find(fileObservers_.begin(), fileObservers_.end(), fileObserver);\n if (it != fileObservers_.end()) {\n fileObservers_.erase(it);\n }\n}\n\nvoid FileWatcher::startFileObservation(const std::string& fileName) {\n const bool isDirectory = filesystem::directoryExists(fileName);\n const auto dir = isDirectory ? fileName : filesystem::getFileDirectory(fileName);\n\n const auto it = observed_.find(dir);\n if (it == observed_.end()) {\n observed_[dir].insert(fileName);\n if (!watcher_->addObservation(dir)) {\n LogError(\"Can't watch more files\");\n }\n } else {\n it->second.insert(fileName);\n }\n}\n\nvoid FileWatcher::stopFileObservation(const std::string& fileName) {\n auto observerit =\n std::find_if(std::begin(fileObservers_), std::end(fileObservers_),\n [fileName](const auto observer) { return observer->isObserved(fileName); });\n \/\/ Make sure that no observer is observing the file\n if (observerit == std::end(fileObservers_)) {\n const bool isDirectory = filesystem::directoryExists(fileName);\n const auto dir = isDirectory ? fileName : filesystem::getFileDirectory(fileName);\n\n const auto it = observed_.find(dir);\n if (it != observed_.end()) {\n it->second.erase(fileName);\n if (it->second.empty()) {\n watcher_->removeObservation(dir);\n observed_.erase(it);\n }\n }\n }\n}\n\n#else\n\nclass WatcherThread {\npublic:\n WatcherThread() = default;\n};\n\nFileWatcher::FileWatcher(InviwoApplication* app) : app_{app} {\n (void)app_;\n LogWarn(\"FileObserver are currently not supported using GLFW on this platform\");\n}\n\nFileWatcher::~FileWatcher() = default;\n\nvoid FileWatcher::registerFileObserver(FileObserver* fileObserver) {\n IVW_ASSERT(std::find(fileObservers_.cbegin(), fileObservers_.cend(), fileObserver) ==\n fileObservers_.cend(),\n \"File observer already registered.\");\n fileObservers_.push_back(fileObserver);\n}\n\nvoid FileWatcher::unRegisterFileObserver(FileObserver* fileObserver) {\n util::erase_remove(fileObservers_, fileObserver);\n}\n\nvoid FileWatcher::stopFileObservation(const std::string& fileName) {}\nvoid FileWatcher::startFileObservation(const std::string& fileName) {}\n\n#endif\n\n} \/\/ namespace inviwo\n<|endoftext|>"} {"text":"#ifndef LISP_PTR_I_HH\n#define LISP_PTR_I_HH\n\n#ifndef LISP_PTR_HH\n#error \"Please include via parent file\"\n#endif\n\n#include \n#include \n\n\/\/ Lisp_ptr constructors\ninline constexpr\nLisp_ptr::Lisp_ptr()\n : tag_(Ptr_tag::undefined), u_(0){}\n\ninline constexpr\nLisp_ptr::Lisp_ptr(bool b)\n : tag_(to_tag()), u_(b){}\n\ninline constexpr\nLisp_ptr::Lisp_ptr(char c)\n : tag_(to_tag()), u_(c){}\n\ninline constexpr\nLisp_ptr::Lisp_ptr(int i)\n : tag_(to_tag()), u_(i){}\n\ntemplate\ninline constexpr\nLisp_ptr::Lisp_ptr(T p)\n : tag_(to_tag()), u_(p){\n static_assert(!std::is_fundamental::value,\n \"Lisp_ptr cannot accept the specified type.\");\n}\n\ntemplate<>\ninline constexpr\nLisp_ptr::Lisp_ptr(Notation n)\n : tag_(to_tag()), u_(static_cast(n)){}\n\n\/\/ Lisp_ptr getters\ntemplate<>\ninline\nVMArgcount Lisp_ptr::get() const {\n assert(tag() == to_tag());\n return static_cast(u_.i_);\n}\n\ntemplate<>\ninline\nNotation Lisp_ptr::get() const {\n assert(tag() == to_tag());\n return static_cast(u_.i_);\n}\n\ntemplate<>\ninline constexpr\nintptr_t Lisp_ptr::get() const{\n return u_.i_;\n}\n\ntemplate<>\ninline constexpr\nvoid* Lisp_ptr::get() const{\n return u_.ptr_;\n}\n\ntemplate<>\ninline constexpr\nconst void* Lisp_ptr::get() const{\n return u_.ptr_;\n}\n\ntemplate<>\ninline constexpr\nvoid (*Lisp_ptr::get())(void) const{\n return u_.f_;\n}\n\nnamespace lisp_ptr_detail {\n\ntemplate\ninline constexpr\nT lisp_ptr_cast(const Lisp_ptr& p,\n typename std::enable_if::value>::type* = nullptr){\n return static_cast(p.get());\n}\n\ntemplate\ninline constexpr\nT lisp_ptr_cast(const Lisp_ptr& p,\n typename std::enable_if::value>::type* = nullptr,\n typename std::enable_if<\n std::is_function::type>::value\n >::type* = nullptr){\n static_assert(std::is_same::value,\n \"inacceptable function-pointer type\");\n return static_cast(p.get());\n}\n\ntemplate\ninline constexpr\nT lisp_ptr_cast(const Lisp_ptr& p,\n typename std::enable_if::value>::type* = nullptr,\n typename std::enable_if<\n !std::is_function::type>::value\n >::type* = nullptr,\n typename std::enable_if<\n !std::is_const::type>::value\n >::type* = nullptr){\n return static_cast(p.get());\n}\n\ntemplate\ninline constexpr\nT lisp_ptr_cast(const Lisp_ptr& p,\n typename std::enable_if::value>::type* = nullptr,\n typename std::enable_if<\n !std::is_function::type>::value\n >::type* = nullptr,\n typename std::enable_if<\n std::is_const::type>::value\n >::type* = nullptr){\n return static_cast(p.get());\n}\n\n}\n\ntemplate\ninline\nT Lisp_ptr::get() const {\n static_assert(to_tag() != Ptr_tag::undefined, \"inacceptable type\");\n assert(tag() == to_tag());\n return lisp_ptr_detail::lisp_ptr_cast(*this);\n}\n\n#endif \/\/ LISP_PTR_I_HH\nlisp_ptr can handle enum#ifndef LISP_PTR_I_HH\n#define LISP_PTR_I_HH\n\n#ifndef LISP_PTR_HH\n#error \"Please include via parent file\"\n#endif\n\n#include \n#include \n\n\/\/ Lisp_ptr constructors\ninline constexpr\nLisp_ptr::Lisp_ptr()\n : tag_(Ptr_tag::undefined), u_(0){}\n\ninline constexpr\nLisp_ptr::Lisp_ptr(bool b)\n : tag_(to_tag()), u_(b){}\n\ninline constexpr\nLisp_ptr::Lisp_ptr(char c)\n : tag_(to_tag()), u_(c){}\n\ninline constexpr\nLisp_ptr::Lisp_ptr(int i)\n : tag_(to_tag()), u_(i){}\n\ntemplate\ninline constexpr\nLisp_ptr::Lisp_ptr(T p)\n : tag_(to_tag()), u_(p){\n static_assert(!std::is_fundamental::value,\n \"Lisp_ptr cannot accept the specified type.\");\n}\n\ntemplate<>\ninline constexpr\nLisp_ptr::Lisp_ptr(Notation n)\n : tag_(to_tag()), u_(static_cast(n)){}\n\n\/\/ Lisp_ptr getters\ntemplate<>\ninline\nVMArgcount Lisp_ptr::get() const {\n assert(tag() == to_tag());\n return static_cast(u_.i_);\n}\n\ntemplate<>\ninline constexpr\nintptr_t Lisp_ptr::get() const{\n return u_.i_;\n}\n\ntemplate<>\ninline constexpr\nvoid* Lisp_ptr::get() const{\n return u_.ptr_;\n}\n\ntemplate<>\ninline constexpr\nconst void* Lisp_ptr::get() const{\n return u_.cptr_;\n}\n\ntemplate<>\ninline constexpr\nvoid (*Lisp_ptr::get())(void) const{\n return u_.f_;\n}\n\nnamespace lisp_ptr_detail {\n\ntemplate\ninline constexpr\nT lisp_ptr_cast(const Lisp_ptr& p,\n typename std::enable_if::value>::type* = nullptr){\n return static_cast(p.get());\n}\n\ntemplate\ninline constexpr\nT lisp_ptr_cast(const Lisp_ptr& p,\n typename std::enable_if::value>::type* = nullptr){\n \/\/ GCC 4.6 cannot accept below..\n \/\/ static_assert(std::is_convertible::type,\n \/\/ intptr_t>::value,\n \/\/ \"inacceptable enum type\");\n return static_cast(p.get());\n}\n\ntemplate\ninline constexpr\nT lisp_ptr_cast(const Lisp_ptr& p,\n typename std::enable_if::value>::type* = nullptr,\n typename std::enable_if<\n std::is_function::type>::value\n >::type* = nullptr){\n static_assert(std::is_same::value,\n \"inacceptable function-pointer type\");\n return static_cast(p.get());\n}\n\ntemplate\ninline constexpr\nT lisp_ptr_cast(const Lisp_ptr& p,\n typename std::enable_if::value>::type* = nullptr,\n typename std::enable_if<\n !std::is_function::type>::value\n >::type* = nullptr,\n typename std::enable_if<\n !std::is_const::type>::value\n >::type* = nullptr){\n return static_cast(p.get());\n}\n\ntemplate\ninline constexpr\nT lisp_ptr_cast(const Lisp_ptr& p,\n typename std::enable_if::value>::type* = nullptr,\n typename std::enable_if<\n !std::is_function::type>::value\n >::type* = nullptr,\n typename std::enable_if<\n std::is_const::type>::value\n >::type* = nullptr){\n return static_cast(p.get());\n}\n\n}\n\ntemplate\ninline\nT Lisp_ptr::get() const {\n static_assert(to_tag() != Ptr_tag::undefined, \"inacceptable type\");\n assert(tag() == to_tag());\n return lisp_ptr_detail::lisp_ptr_cast(*this);\n}\n\n#endif \/\/ LISP_PTR_I_HH\n<|endoftext|>"} {"text":"#include \/\/ max()\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"test_comm.h\"\n#include \"libmesh_cppunit.h\"\n\n#include \n\n\nusing namespace libMesh;\n\nclass MeshTriangulationTest : public CppUnit::TestCase\n{\n \/**\n * The goal of this test is to verify proper operation of the\n * interfaces to triangulation libraries\n *\/\npublic:\n CPPUNIT_TEST_SUITE( MeshTriangulationTest );\n\n CPPUNIT_TEST( testTriangleHoleArea );\n\n#ifdef LIBMESH_HAVE_POLY2TRI\n CPPUNIT_TEST( testPoly2Tri );\n CPPUNIT_TEST( testPoly2TriHoles );\n CPPUNIT_TEST( testPoly2TriSegments );\n CPPUNIT_TEST( testPoly2TriRefined );\n#endif\n\n#ifdef LIBMESH_HAVE_TRIANGLE\n CPPUNIT_TEST( testTriangle );\n CPPUNIT_TEST( testTriangleHoles );\n CPPUNIT_TEST( testTriangleSegments );\n#endif\n\n CPPUNIT_TEST_SUITE_END();\n\npublic:\n void setUp() {}\n\n void tearDown() {}\n\n void testTriangleHoleArea()\n {\n \/\/ Using center=(1,0), radius=2 for the heck of it\n Point center{1};\n Real radius = 2;\n std::vector polyholes;\n\n \/\/ Line\n polyholes.emplace_back(center, radius, 2);\n \/\/ Triangle\n polyholes.emplace_back(center, radius, 3);\n \/\/ Square\n polyholes.emplace_back(center, radius, 4);\n \/\/ Pentagon\n polyholes.emplace_back(center, radius, 5);\n \/\/ Hexagon\n polyholes.emplace_back(center, radius, 6);\n\n for (int i=0; i != 5; ++i)\n {\n const int n_sides = i+2;\n const TriangulatorInterface::Hole & hole = polyholes[i];\n\n \/\/ Really? This isn't until C++20?\n constexpr double my_pi = 3.141592653589793238462643383279;\n\n const Real computed_area = hole.area();\n const Real theta = my_pi\/n_sides;\n const Real half_side_length = radius*std::cos(theta);\n const Real apothem = radius*std::sin(theta);\n const Real area = n_sides * apothem * half_side_length;\n\n LIBMESH_ASSERT_FP_EQUAL(computed_area, area, TOLERANCE*TOLERANCE);\n }\n\n TriangulatorInterface::ArbitraryHole arbhole {center, {{0,-1},{2,-1},{2,1},{0,2}}};\n LIBMESH_ASSERT_FP_EQUAL(arbhole.area(), Real(5), TOLERANCE*TOLERANCE);\n\n#ifdef LIBMESH_HAVE_TRIANGLE\n \/\/ Make sure we're compatible with the old naming structure too\n TriangleInterface::PolygonHole square(center, radius, 4);\n LIBMESH_ASSERT_FP_EQUAL(square.area(), 2*radius*radius, TOLERANCE*TOLERANCE);\n#endif\n }\n\n void testTriangulatorBase(MeshBase & mesh,\n TriangulatorInterface & triangulator)\n {\n \/\/ Use the point order to define the boundary, because our\n \/\/ Poly2Tri implementation doesn't do convex hulls yet, even when\n \/\/ that would give the same answer.\n triangulator.triangulation_type() = TriangulatorInterface::PSLG;\n\n \/\/ Don't try to insert points yet\n triangulator.desired_area() = 1000;\n triangulator.minimum_angle() = 0;\n triangulator.smooth_after_generating() = false;\n\n triangulator.triangulate();\n\n CPPUNIT_ASSERT_EQUAL(mesh.n_elem(), dof_id_type(2));\n for (const auto & elem : mesh.element_ptr_range())\n {\n CPPUNIT_ASSERT_EQUAL(elem->type(), TRI3);\n\n \/\/ Make sure we're not getting any inverted elements\n auto cross_prod =\n (elem->point(1) - elem->point(0)).cross\n (elem->point(2) - elem->point(0));\n\n CPPUNIT_ASSERT_GREATER(Real(0), cross_prod(2));\n\n bool found_triangle = false;\n for (const auto & node : elem->node_ref_range())\n {\n const Point & point = node;\n if (point == Point(0,0))\n {\n found_triangle = true;\n CPPUNIT_ASSERT((elem->point(0) == Point(0,0) &&\n elem->point(1) == Point(1,0) &&\n elem->point(2) == Point(0,1)) ||\n (elem->point(1) == Point(0,0) &&\n elem->point(2) == Point(1,0) &&\n elem->point(0) == Point(0,1)) ||\n (elem->point(2) == Point(0,0) &&\n elem->point(0) == Point(1,0) &&\n elem->point(1) == Point(0,1)));\n }\n if (point == Point(1,2))\n {\n found_triangle = true;\n CPPUNIT_ASSERT((elem->point(0) == Point(0,1) &&\n elem->point(1) == Point(1,0) &&\n elem->point(2) == Point(1,2)) ||\n (elem->point(1) == Point(0,1) &&\n elem->point(2) == Point(1,0) &&\n elem->point(0) == Point(1,2)) ||\n (elem->point(2) == Point(0,1) &&\n elem->point(0) == Point(1,0) &&\n elem->point(1) == Point(1,2)));\n }\n }\n CPPUNIT_ASSERT(found_triangle);\n }\n }\n\n\n void testTriangulator(MeshBase & mesh,\n TriangulatorInterface & triangulator)\n {\n \/\/ A non-square quad, so we don't have ambiguity about which\n \/\/ diagonal a Delaunay algorithm will pick.\n mesh.add_point(Point(0,0));\n mesh.add_point(Point(1,0));\n mesh.add_point(Point(1,2));\n mesh.add_point(Point(0,1));\n\n this->testTriangulatorBase(mesh, triangulator);\n }\n\n\n\n void testTriangulatorHoles(MeshBase & mesh,\n TriangulatorInterface & triangulator)\n {\n \/\/ A square quad; we'll put a diamond hole in the middle to make\n \/\/ the Delaunay selection unambiguous.\n mesh.add_point(Point(-1,-1));\n mesh.add_point(Point(1,-1));\n mesh.add_point(Point(1,1));\n mesh.add_point(Point(-1,1));\n\n \/\/ Use the point order to define the boundary, because our\n \/\/ Poly2Tri implementation doesn't do convex hulls yet, even when\n \/\/ that would give the same answer.\n triangulator.triangulation_type() = TriangulatorInterface::PSLG;\n\n \/\/ Add a diamond hole in the center\n TriangulatorInterface::PolygonHole diamond(Point(0), std::sqrt(2)\/2, 4);\n const std::vector holes { &diamond };\n triangulator.attach_hole_list(&holes);\n\n \/\/ Don't try to insert points yet\n triangulator.desired_area() = 1000;\n triangulator.minimum_angle() = 0;\n triangulator.smooth_after_generating() = false;\n\n triangulator.triangulate();\n\n CPPUNIT_ASSERT_EQUAL(mesh.n_elem(), dof_id_type(8));\n\n \/\/ Center coordinates for all the elements we expect\n Real r2p2o6 = (std::sqrt(Real(2))+2)\/6;\n Real r2p4o6 = (std::sqrt(Real(2))+4)\/6;\n\n std::vector expected_centers\n { {r2p2o6,r2p2o6}, {r2p2o6,-r2p2o6},\n {-r2p2o6,r2p2o6}, {-r2p2o6,-r2p2o6},\n {0,r2p4o6}, {r2p4o6, 0},\n {0,-r2p4o6}, {-r2p4o6, 0}\n };\n\n std::vector found_centers(expected_centers.size(), false);\n\n for (const auto & elem : mesh.element_ptr_range())\n {\n CPPUNIT_ASSERT_EQUAL(elem->type(), TRI3);\n\n \/\/ Make sure we're not getting any inverted elements\n auto cross_prod =\n (elem->point(1) - elem->point(0)).cross\n (elem->point(2) - elem->point(0));\n\n CPPUNIT_ASSERT_GREATER(Real(0), cross_prod(2));\n\n \/\/ Make sure we're finding all the elements we expect\n Point center = elem->vertex_average();\n\n bool found_mine = false;\n for (auto i : index_range(expected_centers))\n {\n Point possible = expected_centers[i];\n\n if (possible.absolute_fuzzy_equals(center, TOLERANCE*TOLERANCE))\n {\n found_mine = true;\n found_centers[i] = true;\n }\n }\n CPPUNIT_ASSERT(found_mine);\n }\n\n mesh.comm().max(found_centers);\n\n for (auto found_it : found_centers)\n CPPUNIT_ASSERT(found_it);\n }\n\n\n void testTriangulatorSegments(MeshBase & mesh,\n TriangulatorInterface & triangulator)\n {\n \/\/ The same quad as testTriangulator, but out of order\n mesh.add_point(Point(0,0));\n mesh.add_point(Point(1,2));\n mesh.add_point(Point(1,0));\n mesh.add_point(Point(0,1));\n\n \/\/ Segments to put them in order\n triangulator.segments = {{0,2},{2,1},{1,3},{3,0}};\n\n this->testTriangulatorBase(mesh, triangulator);\n }\n\n\n#ifdef LIBMESH_HAVE_TRIANGLE\n void testTriangle()\n {\n Mesh mesh(*TestCommWorld);\n TriangleInterface triangle(mesh);\n testTriangulator(mesh, triangle);\n }\n\n\n void testTriangleHoles()\n {\n Mesh mesh(*TestCommWorld);\n TriangleInterface triangle(mesh);\n testTriangulatorHoles(mesh, triangle);\n }\n\n\n void testTriangleSegments()\n {\n Mesh mesh(*TestCommWorld);\n TriangleInterface triangle(mesh);\n testTriangulatorSegments(mesh, triangle);\n }\n#endif \/\/ LIBMESH_HAVE_TRIANGLE\n\n\n#ifdef LIBMESH_HAVE_POLY2TRI\n void testPoly2Tri()\n {\n Mesh mesh(*TestCommWorld);\n Poly2TriTriangulator p2t_tri(mesh);\n testTriangulator(mesh, p2t_tri);\n }\n\n\n void testPoly2TriHoles()\n {\n Mesh mesh(*TestCommWorld);\n Poly2TriTriangulator p2t_tri(mesh);\n testTriangulatorHoles(mesh, p2t_tri);\n }\n\n\n void testPoly2TriSegments()\n {\n Mesh mesh(*TestCommWorld);\n Poly2TriTriangulator p2t_tri(mesh);\n testTriangulatorSegments(mesh, p2t_tri);\n }\n\n\n void testPoly2TriRefined()\n {\n Mesh mesh(*TestCommWorld);\n mesh.add_point(Point(0,0));\n mesh.add_point(Point(1,0));\n mesh.add_point(Point(1,2));\n mesh.add_point(Point(0,1));\n\n Poly2TriTriangulator triangulator(mesh);\n\n \/\/ Use the point order to define the boundary, because our\n \/\/ Poly2Tri implementation doesn't do convex hulls yet, even when\n \/\/ that would give the same answer.\n triangulator.triangulation_type() = TriangulatorInterface::PSLG;\n\n \/\/ Try to insert points!\n triangulator.desired_area() = 0.1;\n triangulator.minimum_angle() = 0;\n triangulator.smooth_after_generating() = false;\n\n triangulator.triangulate();\n\n CPPUNIT_ASSERT(mesh.n_elem() > 2);\n\n Real area = 0;\n for (const auto & elem : mesh.element_ptr_range())\n {\n CPPUNIT_ASSERT_EQUAL(elem->type(), TRI3);\n\n area += elem->volume();\n }\n\n LIBMESH_ASSERT_FP_EQUAL(area, 1.5, TOLERANCE*TOLERANCE);\n }\n#endif \/\/ LIBMESH_HAVE_POLY2TRI\n\n};\n\n\nCPPUNIT_TEST_SUITE_REGISTRATION( MeshTriangulationTest );\nExplicit numbering in triangulation tests#include \/\/ max()\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"test_comm.h\"\n#include \"libmesh_cppunit.h\"\n\n#include \n\n\nusing namespace libMesh;\n\nclass MeshTriangulationTest : public CppUnit::TestCase\n{\n \/**\n * The goal of this test is to verify proper operation of the\n * interfaces to triangulation libraries\n *\/\npublic:\n CPPUNIT_TEST_SUITE( MeshTriangulationTest );\n\n CPPUNIT_TEST( testTriangleHoleArea );\n\n#ifdef LIBMESH_HAVE_POLY2TRI\n CPPUNIT_TEST( testPoly2Tri );\n CPPUNIT_TEST( testPoly2TriHoles );\n CPPUNIT_TEST( testPoly2TriSegments );\n CPPUNIT_TEST( testPoly2TriRefined );\n#endif\n\n#ifdef LIBMESH_HAVE_TRIANGLE\n CPPUNIT_TEST( testTriangle );\n CPPUNIT_TEST( testTriangleHoles );\n CPPUNIT_TEST( testTriangleSegments );\n#endif\n\n CPPUNIT_TEST_SUITE_END();\n\npublic:\n void setUp() {}\n\n void tearDown() {}\n\n void testTriangleHoleArea()\n {\n \/\/ Using center=(1,0), radius=2 for the heck of it\n Point center{1};\n Real radius = 2;\n std::vector polyholes;\n\n \/\/ Line\n polyholes.emplace_back(center, radius, 2);\n \/\/ Triangle\n polyholes.emplace_back(center, radius, 3);\n \/\/ Square\n polyholes.emplace_back(center, radius, 4);\n \/\/ Pentagon\n polyholes.emplace_back(center, radius, 5);\n \/\/ Hexagon\n polyholes.emplace_back(center, radius, 6);\n\n for (int i=0; i != 5; ++i)\n {\n const int n_sides = i+2;\n const TriangulatorInterface::Hole & hole = polyholes[i];\n\n \/\/ Really? This isn't until C++20?\n constexpr double my_pi = 3.141592653589793238462643383279;\n\n const Real computed_area = hole.area();\n const Real theta = my_pi\/n_sides;\n const Real half_side_length = radius*std::cos(theta);\n const Real apothem = radius*std::sin(theta);\n const Real area = n_sides * apothem * half_side_length;\n\n LIBMESH_ASSERT_FP_EQUAL(computed_area, area, TOLERANCE*TOLERANCE);\n }\n\n TriangulatorInterface::ArbitraryHole arbhole {center, {{0,-1},{2,-1},{2,1},{0,2}}};\n LIBMESH_ASSERT_FP_EQUAL(arbhole.area(), Real(5), TOLERANCE*TOLERANCE);\n\n#ifdef LIBMESH_HAVE_TRIANGLE\n \/\/ Make sure we're compatible with the old naming structure too\n TriangleInterface::PolygonHole square(center, radius, 4);\n LIBMESH_ASSERT_FP_EQUAL(square.area(), 2*radius*radius, TOLERANCE*TOLERANCE);\n#endif\n }\n\n void testTriangulatorBase(MeshBase & mesh,\n TriangulatorInterface & triangulator)\n {\n \/\/ Use the point order to define the boundary, because our\n \/\/ Poly2Tri implementation doesn't do convex hulls yet, even when\n \/\/ that would give the same answer.\n triangulator.triangulation_type() = TriangulatorInterface::PSLG;\n\n \/\/ Don't try to insert points yet\n triangulator.desired_area() = 1000;\n triangulator.minimum_angle() = 0;\n triangulator.smooth_after_generating() = false;\n\n triangulator.triangulate();\n\n CPPUNIT_ASSERT_EQUAL(mesh.n_elem(), dof_id_type(2));\n for (const auto & elem : mesh.element_ptr_range())\n {\n CPPUNIT_ASSERT_EQUAL(elem->type(), TRI3);\n\n \/\/ Make sure we're not getting any inverted elements\n auto cross_prod =\n (elem->point(1) - elem->point(0)).cross\n (elem->point(2) - elem->point(0));\n\n CPPUNIT_ASSERT_GREATER(Real(0), cross_prod(2));\n\n bool found_triangle = false;\n for (const auto & node : elem->node_ref_range())\n {\n const Point & point = node;\n if (point == Point(0,0))\n {\n found_triangle = true;\n CPPUNIT_ASSERT((elem->point(0) == Point(0,0) &&\n elem->point(1) == Point(1,0) &&\n elem->point(2) == Point(0,1)) ||\n (elem->point(1) == Point(0,0) &&\n elem->point(2) == Point(1,0) &&\n elem->point(0) == Point(0,1)) ||\n (elem->point(2) == Point(0,0) &&\n elem->point(0) == Point(1,0) &&\n elem->point(1) == Point(0,1)));\n }\n if (point == Point(1,2))\n {\n found_triangle = true;\n CPPUNIT_ASSERT((elem->point(0) == Point(0,1) &&\n elem->point(1) == Point(1,0) &&\n elem->point(2) == Point(1,2)) ||\n (elem->point(1) == Point(0,1) &&\n elem->point(2) == Point(1,0) &&\n elem->point(0) == Point(1,2)) ||\n (elem->point(2) == Point(0,1) &&\n elem->point(0) == Point(1,0) &&\n elem->point(1) == Point(1,2)));\n }\n }\n CPPUNIT_ASSERT(found_triangle);\n }\n }\n\n\n void testTriangulator(MeshBase & mesh,\n TriangulatorInterface & triangulator)\n {\n \/\/ A non-square quad, so we don't have ambiguity about which\n \/\/ diagonal a Delaunay algorithm will pick.\n \/\/ Manually-numbered points, so we can use the point numbering as\n \/\/ a segment ordering even on DistributedMesh.\n mesh.add_point(Point(0,0), 0);\n mesh.add_point(Point(1,0), 1);\n mesh.add_point(Point(1,2), 2);\n mesh.add_point(Point(0,1), 3);\n\n this->testTriangulatorBase(mesh, triangulator);\n }\n\n\n\n void testTriangulatorHoles(MeshBase & mesh,\n TriangulatorInterface & triangulator)\n {\n \/\/ A square quad; we'll put a diamond hole in the middle to make\n \/\/ the Delaunay selection unambiguous.\n mesh.add_point(Point(-1,-1), 0);\n mesh.add_point(Point(1,-1), 1);\n mesh.add_point(Point(1,1), 2);\n mesh.add_point(Point(-1,1), 3);\n\n \/\/ Use the point order to define the boundary, because our\n \/\/ Poly2Tri implementation doesn't do convex hulls yet, even when\n \/\/ that would give the same answer.\n triangulator.triangulation_type() = TriangulatorInterface::PSLG;\n\n \/\/ Add a diamond hole in the center\n TriangulatorInterface::PolygonHole diamond(Point(0), std::sqrt(2)\/2, 4);\n const std::vector holes { &diamond };\n triangulator.attach_hole_list(&holes);\n\n \/\/ Don't try to insert points yet\n triangulator.desired_area() = 1000;\n triangulator.minimum_angle() = 0;\n triangulator.smooth_after_generating() = false;\n\n triangulator.triangulate();\n\n CPPUNIT_ASSERT_EQUAL(mesh.n_elem(), dof_id_type(8));\n\n \/\/ Center coordinates for all the elements we expect\n Real r2p2o6 = (std::sqrt(Real(2))+2)\/6;\n Real r2p4o6 = (std::sqrt(Real(2))+4)\/6;\n\n std::vector expected_centers\n { {r2p2o6,r2p2o6}, {r2p2o6,-r2p2o6},\n {-r2p2o6,r2p2o6}, {-r2p2o6,-r2p2o6},\n {0,r2p4o6}, {r2p4o6, 0},\n {0,-r2p4o6}, {-r2p4o6, 0}\n };\n\n std::vector found_centers(expected_centers.size(), false);\n\n for (const auto & elem : mesh.element_ptr_range())\n {\n CPPUNIT_ASSERT_EQUAL(elem->type(), TRI3);\n\n \/\/ Make sure we're not getting any inverted elements\n auto cross_prod =\n (elem->point(1) - elem->point(0)).cross\n (elem->point(2) - elem->point(0));\n\n CPPUNIT_ASSERT_GREATER(Real(0), cross_prod(2));\n\n \/\/ Make sure we're finding all the elements we expect\n Point center = elem->vertex_average();\n\n bool found_mine = false;\n for (auto i : index_range(expected_centers))\n {\n Point possible = expected_centers[i];\n\n if (possible.absolute_fuzzy_equals(center, TOLERANCE*TOLERANCE))\n {\n found_mine = true;\n found_centers[i] = true;\n }\n }\n CPPUNIT_ASSERT(found_mine);\n }\n\n mesh.comm().max(found_centers);\n\n for (auto found_it : found_centers)\n CPPUNIT_ASSERT(found_it);\n }\n\n\n void testTriangulatorSegments(MeshBase & mesh,\n TriangulatorInterface & triangulator)\n {\n \/\/ The same quad as testTriangulator, but out of order\n mesh.add_point(Point(0,0), 0);\n mesh.add_point(Point(1,2), 1);\n mesh.add_point(Point(1,0), 2);\n mesh.add_point(Point(0,1), 3);\n\n \/\/ Segments to put them in order\n triangulator.segments = {{0,2},{2,1},{1,3},{3,0}};\n\n this->testTriangulatorBase(mesh, triangulator);\n }\n\n\n#ifdef LIBMESH_HAVE_TRIANGLE\n void testTriangle()\n {\n Mesh mesh(*TestCommWorld);\n TriangleInterface triangle(mesh);\n testTriangulator(mesh, triangle);\n }\n\n\n void testTriangleHoles()\n {\n Mesh mesh(*TestCommWorld);\n TriangleInterface triangle(mesh);\n testTriangulatorHoles(mesh, triangle);\n }\n\n\n void testTriangleSegments()\n {\n Mesh mesh(*TestCommWorld);\n TriangleInterface triangle(mesh);\n testTriangulatorSegments(mesh, triangle);\n }\n#endif \/\/ LIBMESH_HAVE_TRIANGLE\n\n\n#ifdef LIBMESH_HAVE_POLY2TRI\n void testPoly2Tri()\n {\n Mesh mesh(*TestCommWorld);\n Poly2TriTriangulator p2t_tri(mesh);\n testTriangulator(mesh, p2t_tri);\n }\n\n\n void testPoly2TriHoles()\n {\n Mesh mesh(*TestCommWorld);\n Poly2TriTriangulator p2t_tri(mesh);\n testTriangulatorHoles(mesh, p2t_tri);\n }\n\n\n void testPoly2TriSegments()\n {\n Mesh mesh(*TestCommWorld);\n Poly2TriTriangulator p2t_tri(mesh);\n testTriangulatorSegments(mesh, p2t_tri);\n }\n\n\n void testPoly2TriRefined()\n {\n Mesh mesh(*TestCommWorld);\n mesh.add_point(Point(0,0), 0);\n mesh.add_point(Point(1,0), 1);\n mesh.add_point(Point(1,2), 2);\n mesh.add_point(Point(0,1), 3);\n\n Poly2TriTriangulator triangulator(mesh);\n\n \/\/ Use the point order to define the boundary, because our\n \/\/ Poly2Tri implementation doesn't do convex hulls yet, even when\n \/\/ that would give the same answer.\n triangulator.triangulation_type() = TriangulatorInterface::PSLG;\n\n \/\/ Try to insert points!\n triangulator.desired_area() = 0.1;\n triangulator.minimum_angle() = 0;\n triangulator.smooth_after_generating() = false;\n\n triangulator.triangulate();\n\n CPPUNIT_ASSERT(mesh.n_elem() > 2);\n\n Real area = 0;\n for (const auto & elem : mesh.element_ptr_range())\n {\n CPPUNIT_ASSERT_EQUAL(elem->type(), TRI3);\n\n area += elem->volume();\n }\n\n LIBMESH_ASSERT_FP_EQUAL(area, 1.5, TOLERANCE*TOLERANCE);\n }\n#endif \/\/ LIBMESH_HAVE_POLY2TRI\n\n};\n\n\nCPPUNIT_TEST_SUITE_REGISTRATION( MeshTriangulationTest );\n<|endoftext|>"} {"text":"\/\/ Important copyright notice: \n\/\/ Some parts of this file were copied from Mikael Patel's Cosa library, which copyright appears below.\n\/\/ Some parts of this file directly derive from https:\/\/tty1.net\/blog\/2008\/avr-gcc-optimisations_en.html\n\/\/ Other parts are under Copyright (c) 2016, Jean-Francois Poilpret\n\n\/**\n * @file Cosa\/Types.h\n * @version 1.0\n *\n * @section License\n * Copyright (C) 2012-2015, Mikael Patel\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * @section Description\n * Common literals, data types and syntax abstractions.\n *\n * This file is part of the Arduino Che Cosa project.\n *\/\n#ifndef UTILITIES_HH\n#define\tUTILITIES_HH\n\n#include \n#include \n\n#ifndef UNUSED\n#define UNUSED __attribute__((unused))\n#endif\n\n#ifndef INLINE\n#define INLINE __attribute__((always_inline))\n#endif\n\ninline uint8_t _lock() INLINE;\ninline uint8_t _lock()\n{\n\tuint8_t key = SREG;\n\tasm volatile(\"cli\" ::: \"memory\");\n\treturn key;\n}\n\ninline void _unlock(uint8_t* key) INLINE;\ninline void _unlock(uint8_t* key)\n{\n SREG = *key;\n asm volatile(\"\" ::: \"memory\");\n}\n\n#define synchronized \\\n_Pragma (\"GCC diagnostic ignored \\\"-Wreturn-type\\\"\") \\\nfor (uint8_t __key __attribute__((__cleanup__(_unlock))) = _lock(), i = 1; i != 0; i--)\n\n\/\/ Macro found on https:\/\/tty1.net\/blog\/2008\/avr-gcc-optimisations_en.html\n\/\/ This allows processing pointers to SRAM data be performed directly from Y, Z registers\n\/\/ this may optimize code size on some circumstances\n#define FIX_BASE_POINTER(_ptr) __asm__ __volatile__(\"\" : \"=b\" (_ptr) : \"0\" (_ptr))\n\nclass REGISTER\n{\npublic:\n\tconstexpr REGISTER():ADDR(0) {}\n\tconstexpr REGISTER(const REGISTER& rhs):ADDR(rhs.ADDR) {}\n\tconstexpr REGISTER(uint8_t ADDR):ADDR(ADDR) {}\n\tuint8_t io_addr() const\n\t{\n\t\treturn ADDR - __SFR_OFFSET;\n\t}\n\tuint8_t mem_addr() const\n\t{\n\t\treturn ADDR;\n\t}\n\toperator volatile uint8_t& () const\n\t{\n\t\treturn *((volatile uint8_t*) (uint16_t) ADDR);\n\t}\n\toperator volatile uint16_t& () const\n\t{\n\t\treturn *((volatile uint16_t*) (uint16_t) ADDR);\n\t}\n\t\/\/TODO small enhancement: use operators () instead\n\tvoid set(uint8_t value) const\n\t{\n\t\t*((volatile uint8_t*) (uint16_t) ADDR) = value;\n\t}\n\tuint8_t get() const\n\t{\n\t\treturn *((volatile uint8_t*) (uint16_t) ADDR);\n\t}\n\nprivate:\t\n\tuint8_t ADDR;\n};\n\nconstexpr uint16_t as_uint16_t(uint8_t high, uint8_t low)\n{\n\treturn (high << 8) | low;\n}\n\n\/\/TODO Add optimized versions for IOREG registers: set_ioreg_mask, clear_ioreg_mask\ninline void set_mask(REGISTER REG, uint8_t MASK) INLINE;\ninline void set_mask(REGISTER REG, uint8_t MASK)\n{\n\t((volatile uint8_t&) REG) |= MASK;\n}\n\ninline void clear_mask(REGISTER REG, uint8_t MASK) INLINE;\ninline void clear_mask(REGISTER REG, uint8_t MASK)\n{\n\t((volatile uint8_t&) REG) &= ~MASK;\n}\n\ninline void set_bit_field(REGISTER REG, uint8_t MASK, uint8_t VALUE) INLINE;\ninline void set_bit_field(REGISTER REG, uint8_t MASK, uint8_t VALUE)\n{\n\tvolatile uint8_t& ref = (volatile uint8_t&) REG;\n\tref = (ref & ~MASK) | (VALUE & MASK);\n}\n\ninline void set_ioreg_bit(REGISTER IOREG, uint8_t BIT) INLINE;\ninline void set_ioreg_bit(REGISTER IOREG, uint8_t BIT)\n{\n\tasm volatile(\"SBI %[IOREG], %[BIT] \\n\\t\"::[IOREG] \"I\" (IOREG.io_addr()), [BIT] \"I\" (BIT));\n}\n\ninline void clear_ioreg_bit(REGISTER IOREG, uint8_t BIT) INLINE;\ninline void clear_ioreg_bit(REGISTER IOREG, uint8_t BIT)\n{\n\tasm volatile(\"CBI %[IOREG], %[BIT] \\n\\t\"::[IOREG] \"I\" (IOREG.io_addr()), [BIT] \"I\" (BIT));\n}\n\ninline bool ioreg_bit_value(REGISTER IOREG, uint8_t BIT) INLINE;\ninline bool ioreg_bit_value(REGISTER IOREG, uint8_t BIT)\n{\n\t\/\/TODO check if optimization is possible in actual usage of this function\n\t\/\/ E.g. in code below, extra mov r15,r30 is not absolutely necessary (r30 could be directly used)\n\t\/\/ 2ae: e0 e0 ldi r30, 0x00 ; 0\n\t\/\/ 2b0: 4f 99 sbic 0x09, 7 ; 9\n\t\/\/ 2b2: e1 e0 ldi r30, 0x01 ; 1\n\t\/\/ 2b4: fe 2e mov r15, r30\n\tbool result;\n\tasm volatile(\n\t\t\"LDI %[RESULT], 0\\n\\t\"\t\t\t\/\/ Clear result value by default\n\t\t\"SBIC %[IOREG], %[BIT] \\n\\t\"\n\t\t\"LDI %[RESULT], 1\\n\\t\"\t\t\t\/\/ Bit is set, set result value accordingly\n\t\t:[RESULT] \"=&d\" (result)\n\t\t:[IOREG] \"I\" (IOREG.io_addr()), [BIT] \"I\" (BIT)\n\t);\n\treturn result;\n}\n\ninline void set_ioreg_byte(REGISTER IOREG, uint8_t value) INLINE;\ninline void set_ioreg_byte(REGISTER IOREG, uint8_t value)\n{\n\tasm volatile(\"OUT %[IOREG], %[VALUE]\\n\\t\"::[IOREG] \"I\" (IOREG.io_addr()), [VALUE] \"r\" (value));\n}\n\ninline uint8_t get_ioreg_byte(REGISTER IOREG) INLINE;\ninline uint8_t get_ioreg_byte(REGISTER IOREG)\n{\n\tuint8_t value = 0;\n\tasm volatile(\"IN %[VALUE], %[IOREG]\\n\\t\":[VALUE] \"+r\" (value):[IOREG] \"I\" (IOREG.io_addr()));\n\treturn value;\n}\n\n\/\/ Utilities to handle ISR callbacks\n#define HANDLER_HOLDER_(HANDLER) HandlerHolder< HANDLER >\n\n#define CALLBACK_HANDLER_HOLDER_(HANDLER, CALLBACK,...)\t\\\nHandlerHolder< HANDLER >::ArgsHodler< __VA_ARGS__ >::CallbackHolder< CALLBACK >\n\n#define CALL_HANDLER_(HANDLER, CALLBACK,...)\t\\\nCALLBACK_HANDLER_HOLDER_(HANDLER, CALLBACK, ##__VA_ARGS__)::handle\n\n#define REGISTER_ISR_METHOD_(VECTOR, HANDLER, CALLBACK)\t\\\nISR(VECTOR)\t\t\t\t\t\t\t\t\t\t\t\t\\\n{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\tCALL_HANDLER_(HANDLER , CALLBACK)();\t\t\t\t\\\n}\n\n#define REGISTER_ISR_FUNCTION_(VECTOR, CALLBACK)\t\\\nISR(VECTOR)\t\t\t\t\t\t\t\t\t\t\t\\\n{\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\tCALLBACK ();\t\t\t\t\t\t\t\t\t\\\n}\n\ntemplate void register_handler(Handler&);\ntemplate\nclass HandlerHolder\n{\npublic:\n\tstatic Handler* handler()\n\t{\n\t\treturn _handler;\n\t}\n\t\n\tusing Holder = HandlerHolder;\n\t\n\ttemplate\n\tstruct ArgsHodler\n\t{\n\t\ttemplate\n\t\tstruct CallbackHolder\n\t\t{\n\t\t\tstatic void handle(Args... args)\n\t\t\t{\n\t\t\t\tHandler* handler_instance = Holder::handler();\n\t\t\t\tFIX_BASE_POINTER(handler_instance);\n\t\t\t\t(handler_instance->*Callback)(args...);\n\t\t\t}\n\t\t};\n\t};\n\t\nprivate:\n\tstatic Handler* _handler;\n\tfriend void register_handler(Handler&);\n};\n\ntemplate\nHandler* HandlerHolder::_handler = 0;\n\ntemplate\nvoid register_handler(Handler& handler)\n{\n\tHandlerHolder::_handler = &handler;\n}\n\n\/\/ Useful macro to iterate\n\/\/ NOTE: these macros have been inspired by several readings:\n\/\/ http:\/\/stackoverflow.com\/questions\/11761703\/overloading-macro-on-number-of-arguments\n\/\/ http:\/\/stackoverflow.com\/questions\/1872220\/is-it-possible-to-iterate-over-arguments-in-variadic-macros\n\/\/ https:\/\/github.com\/pfultz2\/Cloak\/wiki\/C-Preprocessor-tricks,-tips,-and-idioms\n\n#define EMPTY(...)\n#define CAT(X, Y) X ## Y\n#define CAT3(X, Y, Z) X ## Y ## Z\n#define COMMA() ,\n#define STRINGIFY(X, ...) #X\n#define ID(X, ...) X\n\n#define FE_0_(M, DATA, FIRST, SEP, LAST) \n#define FE_1_(M, DATA, FIRST, SEP, LAST, X1) FIRST() M(X1, DATA) LAST()\n#define FE_2_(M, DATA, FIRST, SEP, LAST, X1, X2) FIRST() M(X1, DATA) SEP() M(X2, DATA) LAST()\n#define FE_3_(M, DATA, FIRST, SEP, LAST, X1, X2, X3) FIRST() M(X1, DATA) SEP() M(X2, DATA) SEP() M(X3, DATA) LAST()\n#define FE_4_(M, DATA, FIRST, SEP, LAST, X1, X2, X3, X4) FIRST() M(X1, DATA) SEP() M(X2, DATA) SEP() M(X3, DATA) SEP() M(X4, DATA) LAST()\n#define FE_5_(M, DATA, FIRST, SEP, LAST, X1, X2, X3, X4, X5) FIRST() M(X1, DATA) SEP() M(X2, DATA) SEP() M(X3, DATA) SEP() M(X4, DATA) SEP() M(X5, DATA) LAST()\n#define FE_6_(M, DATA, FIRST, SEP, LAST, X1, X2, X3, X4, X5, X6) FIRST() M(X1, DATA) SEP() M(X2, DATA) SEP() M(X3, DATA) SEP() M(X4, DATA) SEP() M(X5, DATA) SEP() M(X6, DATA) LAST()\n#define FE_7_(M, DATA, FIRST, SEP, LAST, X1, X2, X3, X4, X5, X6, X7) FIRST() M(X1, DATA) SEP() M(X2, DATA) SEP() M(X3, DATA) SEP() M(X4, DATA) SEP() M(X5, DATA) SEP() M(X6, DATA) SEP() M(X7, DATA) LAST()\n#define FE_8_(M, DATA, FIRST, SEP, LAST, X1, X2, X3, X4, X5, X6, X7, X8) FIRST() M(X1, DATA) SEP() M(X2, DATA) SEP() M(X3, DATA) SEP() M(X4, DATA) SEP() M(X5, DATA) SEP() M(X6, DATA) SEP() M(X7, DATA) SEP() M(X8, DATA) LAST()\n#define FE_9_(M, DATA, FIRST, SEP, LAST, X1, X2, X3, X4, X5, X6, X7, X8, X9) FIRST() M(X1, DATA) SEP() M(X2, DATA) SEP() M(X3, DATA) SEP() M(X4, DATA) SEP() M(X5, DATA) SEP() M(X6, DATA) SEP() M(X7, DATA) SEP() M(X8, DATA) SEP() M(X9, DATA) LAST()\n\n#define GET_MACRO_9_(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, NAME,...) NAME \n\n\/\/ FOR_EACH executes M macro for each argument passed to it, returns empty if passed an empty list.\n\/\/ Number of arguments in variadic list must be between 0 and 9\n#define FOR_EACH(M, DATA, ...) GET_MACRO_9_(unused, ##__VA_ARGS__, FE_9_, FE_8_, FE_7_, FE_6_, FE_5_, FE_4_, FE_3_, FE_2_, FE_1_, FE_0_)(M, DATA, EMPTY, EMPTY, EMPTY, ## __VA_ARGS__)\n\/\/ FOR_EACH_SEP executes M macro for each argument passed to it, separates each transformed value with SEP(),\n\/\/ prepends FIRST() and appends LAST() if result list is not empty; returns empty if passed an empty list\n\/\/ Number of arguments in variadic list must be between 0 and 9\n#define FOR_EACH_SEP(M, DATA, FIRST, SEP, LAST, ...) GET_MACRO_9_(unused, ##__VA_ARGS__, FE_9_, FE_8_, FE_7_, FE_6_, FE_5_, FE_4_, FE_3_, FE_2_, FE_1_, FE_0_)(M, DATA, FIRST, SEP, LAST, ##__VA_ARGS__)\n\n#endif\t\/* UTILITIES_HH *\/\nReplace Cosa's synchronized implementation with direct use of AVR atomic macros.\/\/ Important copyright notice: \n\/\/ Some parts of this file directly derive from https:\/\/tty1.net\/blog\/2008\/avr-gcc-optimisations_en.html\n\/\/ Other parts are under Copyright (c) 2016, Jean-Francois Poilpret\n\n#ifndef UTILITIES_HH\n#define\tUTILITIES_HH\n\n#include \n#include \n#include \n\n#ifndef UNUSED\n#define UNUSED __attribute__((unused))\n#endif\n\n#ifndef INLINE\n#define INLINE __attribute__((always_inline))\n#endif\n\n#define synchronized \\\n_Pragma (\"GCC diagnostic ignored \\\"-Wreturn-type\\\"\") \\\nATOMIC_BLOCK(ATOMIC_RESTORESTATE)\n\n\/\/ Macro found on https:\/\/tty1.net\/blog\/2008\/avr-gcc-optimisations_en.html\n\/\/ This allows processing pointers to SRAM data be performed directly from Y, Z registers\n\/\/ this may optimize code size on some circumstances\n#define FIX_BASE_POINTER(_ptr) __asm__ __volatile__(\"\" : \"=b\" (_ptr) : \"0\" (_ptr))\n\nclass REGISTER\n{\npublic:\n\tconstexpr REGISTER():ADDR(0) {}\n\tconstexpr REGISTER(const REGISTER& rhs):ADDR(rhs.ADDR) {}\n\tconstexpr REGISTER(uint8_t ADDR):ADDR(ADDR) {}\n\tuint8_t io_addr() const\n\t{\n\t\treturn ADDR - __SFR_OFFSET;\n\t}\n\tuint8_t mem_addr() const\n\t{\n\t\treturn ADDR;\n\t}\n\toperator volatile uint8_t& () const\n\t{\n\t\treturn *((volatile uint8_t*) (uint16_t) ADDR);\n\t}\n\toperator volatile uint16_t& () const\n\t{\n\t\treturn *((volatile uint16_t*) (uint16_t) ADDR);\n\t}\n\t\/\/TODO small enhancement: use operators () instead\n\tvoid set(uint8_t value) const\n\t{\n\t\t*((volatile uint8_t*) (uint16_t) ADDR) = value;\n\t}\n\tuint8_t get() const\n\t{\n\t\treturn *((volatile uint8_t*) (uint16_t) ADDR);\n\t}\n\nprivate:\t\n\tuint8_t ADDR;\n};\n\nconstexpr uint16_t as_uint16_t(uint8_t high, uint8_t low)\n{\n\treturn (high << 8) | low;\n}\n\n\/\/TODO Add optimized versions for IOREG registers: set_ioreg_mask, clear_ioreg_mask\ninline void set_mask(REGISTER REG, uint8_t MASK) INLINE;\ninline void set_mask(REGISTER REG, uint8_t MASK)\n{\n\t((volatile uint8_t&) REG) |= MASK;\n}\n\ninline void clear_mask(REGISTER REG, uint8_t MASK) INLINE;\ninline void clear_mask(REGISTER REG, uint8_t MASK)\n{\n\t((volatile uint8_t&) REG) &= ~MASK;\n}\n\ninline void set_bit_field(REGISTER REG, uint8_t MASK, uint8_t VALUE) INLINE;\ninline void set_bit_field(REGISTER REG, uint8_t MASK, uint8_t VALUE)\n{\n\tvolatile uint8_t& ref = (volatile uint8_t&) REG;\n\tref = (ref & ~MASK) | (VALUE & MASK);\n}\n\ninline void set_ioreg_bit(REGISTER IOREG, uint8_t BIT) INLINE;\ninline void set_ioreg_bit(REGISTER IOREG, uint8_t BIT)\n{\n\tasm volatile(\"SBI %[IOREG], %[BIT] \\n\\t\"::[IOREG] \"I\" (IOREG.io_addr()), [BIT] \"I\" (BIT));\n}\n\ninline void clear_ioreg_bit(REGISTER IOREG, uint8_t BIT) INLINE;\ninline void clear_ioreg_bit(REGISTER IOREG, uint8_t BIT)\n{\n\tasm volatile(\"CBI %[IOREG], %[BIT] \\n\\t\"::[IOREG] \"I\" (IOREG.io_addr()), [BIT] \"I\" (BIT));\n}\n\ninline bool ioreg_bit_value(REGISTER IOREG, uint8_t BIT) INLINE;\ninline bool ioreg_bit_value(REGISTER IOREG, uint8_t BIT)\n{\n\t\/\/TODO check if optimization is possible in actual usage of this function\n\t\/\/ E.g. in code below, extra mov r15,r30 is not absolutely necessary (r30 could be directly used)\n\t\/\/ 2ae: e0 e0 ldi r30, 0x00 ; 0\n\t\/\/ 2b0: 4f 99 sbic 0x09, 7 ; 9\n\t\/\/ 2b2: e1 e0 ldi r30, 0x01 ; 1\n\t\/\/ 2b4: fe 2e mov r15, r30\n\tbool result;\n\tasm volatile(\n\t\t\"LDI %[RESULT], 0\\n\\t\"\t\t\t\/\/ Clear result value by default\n\t\t\"SBIC %[IOREG], %[BIT] \\n\\t\"\n\t\t\"LDI %[RESULT], 1\\n\\t\"\t\t\t\/\/ Bit is set, set result value accordingly\n\t\t:[RESULT] \"=&d\" (result)\n\t\t:[IOREG] \"I\" (IOREG.io_addr()), [BIT] \"I\" (BIT)\n\t);\n\treturn result;\n}\n\ninline void set_ioreg_byte(REGISTER IOREG, uint8_t value) INLINE;\ninline void set_ioreg_byte(REGISTER IOREG, uint8_t value)\n{\n\tasm volatile(\"OUT %[IOREG], %[VALUE]\\n\\t\"::[IOREG] \"I\" (IOREG.io_addr()), [VALUE] \"r\" (value));\n}\n\ninline uint8_t get_ioreg_byte(REGISTER IOREG) INLINE;\ninline uint8_t get_ioreg_byte(REGISTER IOREG)\n{\n\tuint8_t value = 0;\n\tasm volatile(\"IN %[VALUE], %[IOREG]\\n\\t\":[VALUE] \"+r\" (value):[IOREG] \"I\" (IOREG.io_addr()));\n\treturn value;\n}\n\n\/\/ Utilities to handle ISR callbacks\n#define HANDLER_HOLDER_(HANDLER) HandlerHolder< HANDLER >\n\n#define CALLBACK_HANDLER_HOLDER_(HANDLER, CALLBACK,...)\t\\\nHandlerHolder< HANDLER >::ArgsHodler< __VA_ARGS__ >::CallbackHolder< CALLBACK >\n\n#define CALL_HANDLER_(HANDLER, CALLBACK,...)\t\\\nCALLBACK_HANDLER_HOLDER_(HANDLER, CALLBACK, ##__VA_ARGS__)::handle\n\n#define REGISTER_ISR_METHOD_(VECTOR, HANDLER, CALLBACK)\t\\\nISR(VECTOR)\t\t\t\t\t\t\t\t\t\t\t\t\\\n{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\tCALL_HANDLER_(HANDLER , CALLBACK)();\t\t\t\t\\\n}\n\n#define REGISTER_ISR_FUNCTION_(VECTOR, CALLBACK)\t\\\nISR(VECTOR)\t\t\t\t\t\t\t\t\t\t\t\\\n{\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\tCALLBACK ();\t\t\t\t\t\t\t\t\t\\\n}\n\ntemplate void register_handler(Handler&);\ntemplate\nclass HandlerHolder\n{\npublic:\n\tstatic Handler* handler()\n\t{\n\t\treturn _handler;\n\t}\n\t\n\tusing Holder = HandlerHolder;\n\t\n\ttemplate\n\tstruct ArgsHodler\n\t{\n\t\ttemplate\n\t\tstruct CallbackHolder\n\t\t{\n\t\t\tstatic void handle(Args... args)\n\t\t\t{\n\t\t\t\tHandler* handler_instance = Holder::handler();\n\t\t\t\tFIX_BASE_POINTER(handler_instance);\n\t\t\t\t(handler_instance->*Callback)(args...);\n\t\t\t}\n\t\t};\n\t};\n\t\nprivate:\n\tstatic Handler* _handler;\n\tfriend void register_handler(Handler&);\n};\n\ntemplate\nHandler* HandlerHolder::_handler = 0;\n\ntemplate\nvoid register_handler(Handler& handler)\n{\n\tHandlerHolder::_handler = &handler;\n}\n\n\/\/ Useful macro to iterate\n\/\/ NOTE: these macros have been inspired by several readings:\n\/\/ http:\/\/stackoverflow.com\/questions\/11761703\/overloading-macro-on-number-of-arguments\n\/\/ http:\/\/stackoverflow.com\/questions\/1872220\/is-it-possible-to-iterate-over-arguments-in-variadic-macros\n\/\/ https:\/\/github.com\/pfultz2\/Cloak\/wiki\/C-Preprocessor-tricks,-tips,-and-idioms\n\n#define EMPTY(...)\n#define CAT(X, Y) X ## Y\n#define CAT3(X, Y, Z) X ## Y ## Z\n#define COMMA() ,\n#define STRINGIFY(X, ...) #X\n#define ID(X, ...) X\n\n#define FE_0_(M, DATA, FIRST, SEP, LAST) \n#define FE_1_(M, DATA, FIRST, SEP, LAST, X1) FIRST() M(X1, DATA) LAST()\n#define FE_2_(M, DATA, FIRST, SEP, LAST, X1, X2) FIRST() M(X1, DATA) SEP() M(X2, DATA) LAST()\n#define FE_3_(M, DATA, FIRST, SEP, LAST, X1, X2, X3) FIRST() M(X1, DATA) SEP() M(X2, DATA) SEP() M(X3, DATA) LAST()\n#define FE_4_(M, DATA, FIRST, SEP, LAST, X1, X2, X3, X4) FIRST() M(X1, DATA) SEP() M(X2, DATA) SEP() M(X3, DATA) SEP() M(X4, DATA) LAST()\n#define FE_5_(M, DATA, FIRST, SEP, LAST, X1, X2, X3, X4, X5) FIRST() M(X1, DATA) SEP() M(X2, DATA) SEP() M(X3, DATA) SEP() M(X4, DATA) SEP() M(X5, DATA) LAST()\n#define FE_6_(M, DATA, FIRST, SEP, LAST, X1, X2, X3, X4, X5, X6) FIRST() M(X1, DATA) SEP() M(X2, DATA) SEP() M(X3, DATA) SEP() M(X4, DATA) SEP() M(X5, DATA) SEP() M(X6, DATA) LAST()\n#define FE_7_(M, DATA, FIRST, SEP, LAST, X1, X2, X3, X4, X5, X6, X7) FIRST() M(X1, DATA) SEP() M(X2, DATA) SEP() M(X3, DATA) SEP() M(X4, DATA) SEP() M(X5, DATA) SEP() M(X6, DATA) SEP() M(X7, DATA) LAST()\n#define FE_8_(M, DATA, FIRST, SEP, LAST, X1, X2, X3, X4, X5, X6, X7, X8) FIRST() M(X1, DATA) SEP() M(X2, DATA) SEP() M(X3, DATA) SEP() M(X4, DATA) SEP() M(X5, DATA) SEP() M(X6, DATA) SEP() M(X7, DATA) SEP() M(X8, DATA) LAST()\n#define FE_9_(M, DATA, FIRST, SEP, LAST, X1, X2, X3, X4, X5, X6, X7, X8, X9) FIRST() M(X1, DATA) SEP() M(X2, DATA) SEP() M(X3, DATA) SEP() M(X4, DATA) SEP() M(X5, DATA) SEP() M(X6, DATA) SEP() M(X7, DATA) SEP() M(X8, DATA) SEP() M(X9, DATA) LAST()\n\n#define GET_MACRO_9_(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, NAME,...) NAME \n\n\/\/ FOR_EACH executes M macro for each argument passed to it, returns empty if passed an empty list.\n\/\/ Number of arguments in variadic list must be between 0 and 9\n#define FOR_EACH(M, DATA, ...) GET_MACRO_9_(unused, ##__VA_ARGS__, FE_9_, FE_8_, FE_7_, FE_6_, FE_5_, FE_4_, FE_3_, FE_2_, FE_1_, FE_0_)(M, DATA, EMPTY, EMPTY, EMPTY, ## __VA_ARGS__)\n\/\/ FOR_EACH_SEP executes M macro for each argument passed to it, separates each transformed value with SEP(),\n\/\/ prepends FIRST() and appends LAST() if result list is not empty; returns empty if passed an empty list\n\/\/ Number of arguments in variadic list must be between 0 and 9\n#define FOR_EACH_SEP(M, DATA, FIRST, SEP, LAST, ...) GET_MACRO_9_(unused, ##__VA_ARGS__, FE_9_, FE_8_, FE_7_, FE_6_, FE_5_, FE_4_, FE_3_, FE_2_, FE_1_, FE_0_)(M, DATA, FIRST, SEP, LAST, ##__VA_ARGS__)\n\n#endif\t\/* UTILITIES_HH *\/\n<|endoftext|>"} {"text":"\/\/! Copyright (c) 2013 ASMlover. All rights reserved.\n\/\/!\n\/\/! Redistribution and use in source and binary forms, with or without\n\/\/! modification, are permitted provided that the following conditions\n\/\/! are met:\n\/\/!\n\/\/! * Redistributions of source code must retain the above copyright\n\/\/! notice, this list ofconditions and the following disclaimer.\n\/\/!\n\/\/! * Redistributions in binary form must reproduce the above copyright\n\/\/! notice, this list of conditions and the following disclaimer in\n\/\/! the documentation and\/or other materialsprovided with the\n\/\/! distribution.\n\/\/!\n\/\/! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/! \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/! LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/! FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/! COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/! INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/! BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/! LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/! CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/! ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/! POSSIBILITY OF SUCH DAMAGE.\n#if defined(_WINDOWS_) || defined(_MSC_VER)\n# include \n# include \n# include \n#elif defined(__linux__)\n# include \n# include \n# include \n# include \n\n# define MAX_PATH PATH_MAX\n#endif\n#include \n#include \n#include \"el_time.h\"\n#include \"el_logging.h\"\n\n\n#define ROOT_DIR (\"logging\")\n\nnamespace el {\n\nstatic inline int \nlogging_mkdir(const char* path)\n{\n int ret = -1;\n#if defined(_WINDOWS_) || defined(_MSC_VER)\n ret = mkdir(path);\n#elif defined(_MSC_VER)\n ret = mkdir(path, S_IRWXU);\n#endif \n\n return ret;\n}\n\nstatic inline bool \nKeyEqual(LogFile* lf, Time* t)\n{\n return (lf->year == t->year \n && lf->mon == t->mon \n && lf->day == t->day);\n}\n\nstatic inline void \nCreateLogDirectory(const char* directory)\n{\n if (0 != access(ROOT_DIR, 0))\n logging_mkdir(ROOT_DIR);\n\n char path[MAX_PATH];\n sprintf(path, \"%s\/%s\", ROOT_DIR, directory);\n if (0 != access(path, 0))\n logging_mkdir(path);\n}\n\n\n\nLogging::Logging(void)\n{\n memset(file_list_, 0, sizeof(file_list_));\n}\n\nLogging::~Logging(void)\n{\n for (int i = 0; i < ST_COUNT; ++i) {\n if (NULL != file_list_[i].stream)\n fclose(file_list_[i].stream);\n }\n}\n\nLogging& \nLogging::Singleton(void)\n{\n static Logging _s_logging;\n return _s_logging;\n}\n\nconst char* \nLogging::GetSeverityName(int severity)\n{\n switch (severity) {\n case ST_DEBUG:\n return \"debug\";\n case ST_MESSGAE:\n return \"message\";\n case ST_WARNING:\n return \"warn\";\n case ST_ERROR:\n return \"error\";\n case ST_FAIL:\n return \"fail\";\n }\n\n return \"???\";\n}\n\nFILE* \nLogging::GetFileStream(int severity, Time* time)\n{\n if ((severity < 0 || severity >= ST_COUNT) || NULL == time)\n return NULL;\n\n FILE* stream;\n const char* directory = GetSeverityName(severity);\n if (NULL == file_list_[severity].stream) {\n CreateLogDirectory(directory);\n\n char fname[MAX_PATH];\n sprintf(fname, \"%s\/%s\/%04d%02d%02d.log\", \n ROOT_DIR, directory, time->year, time->mon, time->day);\n stream = fopen(fname, \"a+\");\n setvbuf(stream, NULL, _IOFBF, DEF_BUFSIZE);\n\n file_list_[severity].year = time->year;\n file_list_[severity].mon = time->mon;\n file_list_[severity].day = time->day;\n file_list_[severity].stream = stream;\n }\n else {\n if (KeyEqual(&file_list_[severity], time)) {\n stream = file_list_[severity].stream;\n }\n else {\n fclose(file_list_[severity].stream);\n\n char fname[MAX_PATH];\n sprintf(fname, \"%s\/%s\/%04d%02d%02d.log\", \n ROOT_DIR, directory, time->year, time->mon, time->day);\n stream = fopen(fname, \"a+\");\n setvbuf(stream, NULL, _IOFBF, DEF_BUFSIZE);\n\n file_list_[severity].year = time->year;\n file_list_[severity].mon = time->mon;\n file_list_[severity].day = time->day;\n file_list_[severity].stream = stream;\n }\n }\n\n return stream;\n}\n\n\nvoid \nLogging::Write(int severity, const char* format, ...)\n{\n Time time;\n Localtime(&time);\n\n FILE* stream = GetFileStream(severity, &time);\n if (NULL == stream)\n return;\n\n va_list ap;\n va_start(ap, format);\n vfprintf(stream, format, ap);\n va_end(ap);\n}\n\nvoid \nLogging::WriteX(int severity, \n const char* file, int line, const char* format, ...)\n{\n Time time;\n Localtime(&time);\n\n FILE* stream = GetFileStream(severity, &time);\n if (NULL == stream)\n return;\n\n va_list ap;\n va_start(ap, format);\n\n char buf[1024];\n vsprintf(buf, format, ap);\n fprintf(stream, \"[%02d:%02d:%02d:%03d] [%s](%d) : %s\", \n time.hour, time.min, time.sec, time.millitm, file, line, buf);\n\n va_end(ap);\n}\n\n\n}\nfixed bug of el::Logging module in linux platform about mkdir\/\/! Copyright (c) 2013 ASMlover. All rights reserved.\n\/\/!\n\/\/! Redistribution and use in source and binary forms, with or without\n\/\/! modification, are permitted provided that the following conditions\n\/\/! are met:\n\/\/!\n\/\/! * Redistributions of source code must retain the above copyright\n\/\/! notice, this list ofconditions and the following disclaimer.\n\/\/!\n\/\/! * Redistributions in binary form must reproduce the above copyright\n\/\/! notice, this list of conditions and the following disclaimer in\n\/\/! the documentation and\/or other materialsprovided with the\n\/\/! distribution.\n\/\/!\n\/\/! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/! \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/! LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/! FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/! COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/! INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/! BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/! LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/! CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/! ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/! POSSIBILITY OF SUCH DAMAGE.\n#if defined(_WINDOWS_) || defined(_MSC_VER)\n# include \n# include \n# include \n#elif defined(__linux__)\n# include \n# include \n# include \n# include \n\n# define MAX_PATH PATH_MAX\n#endif\n#include \n#include \n#include \"el_time.h\"\n#include \"el_logging.h\"\n\n\n#define ROOT_DIR (\"logging\")\n\nnamespace el {\n\nstatic inline int \nlogging_mkdir(const char* path)\n{\n int ret = -1;\n#if defined(_WINDOWS_) || defined(_MSC_VER)\n ret = mkdir(path);\n#elif defined(__linux__)\n ret = mkdir(path, S_IRWXU);\n#endif \n\n return ret;\n}\n\nstatic inline bool \nKeyEqual(LogFile* lf, Time* t)\n{\n return (lf->year == t->year \n && lf->mon == t->mon \n && lf->day == t->day);\n}\n\nstatic inline void \nCreateLogDirectory(const char* directory)\n{\n if (0 != access(ROOT_DIR, 0))\n logging_mkdir(ROOT_DIR);\n\n char path[MAX_PATH];\n sprintf(path, \"%s\/%s\", ROOT_DIR, directory);\n if (0 != access(path, 0))\n logging_mkdir(path);\n}\n\n\n\nLogging::Logging(void)\n{\n memset(file_list_, 0, sizeof(file_list_));\n}\n\nLogging::~Logging(void)\n{\n for (int i = 0; i < ST_COUNT; ++i) {\n if (NULL != file_list_[i].stream)\n fclose(file_list_[i].stream);\n }\n}\n\nLogging& \nLogging::Singleton(void)\n{\n static Logging _s_logging;\n return _s_logging;\n}\n\nconst char* \nLogging::GetSeverityName(int severity)\n{\n switch (severity) {\n case ST_DEBUG:\n return \"debug\";\n case ST_MESSGAE:\n return \"message\";\n case ST_WARNING:\n return \"warn\";\n case ST_ERROR:\n return \"error\";\n case ST_FAIL:\n return \"fail\";\n }\n\n return \"???\";\n}\n\nFILE* \nLogging::GetFileStream(int severity, Time* time)\n{\n if ((severity < 0 || severity >= ST_COUNT) || NULL == time)\n return NULL;\n\n FILE* stream;\n const char* directory = GetSeverityName(severity);\n if (NULL == file_list_[severity].stream) {\n CreateLogDirectory(directory);\n\n char fname[MAX_PATH];\n sprintf(fname, \".\/%s\/%s\/%04d%02d%02d.log\", \n ROOT_DIR, directory, time->year, time->mon, time->day);\n stream = fopen(fname, \"a+\");\n setvbuf(stream, NULL, _IOFBF, DEF_BUFSIZE);\n\n file_list_[severity].year = time->year;\n file_list_[severity].mon = time->mon;\n file_list_[severity].day = time->day;\n file_list_[severity].stream = stream;\n }\n else {\n if (KeyEqual(&file_list_[severity], time)) {\n stream = file_list_[severity].stream;\n }\n else {\n fclose(file_list_[severity].stream);\n\n char fname[MAX_PATH];\n sprintf(fname, \"%s\/%s\/%04d%02d%02d.log\", \n ROOT_DIR, directory, time->year, time->mon, time->day);\n stream = fopen(fname, \"a+\");\n setvbuf(stream, NULL, _IOFBF, DEF_BUFSIZE);\n\n file_list_[severity].year = time->year;\n file_list_[severity].mon = time->mon;\n file_list_[severity].day = time->day;\n file_list_[severity].stream = stream;\n }\n }\n\n return stream;\n}\n\n\nvoid \nLogging::Write(int severity, const char* format, ...)\n{\n Time time;\n Localtime(&time);\n\n FILE* stream = GetFileStream(severity, &time);\n if (NULL == stream)\n return;\n\n va_list ap;\n va_start(ap, format);\n vfprintf(stream, format, ap);\n va_end(ap);\n}\n\nvoid \nLogging::WriteX(int severity, \n const char* file, int line, const char* format, ...)\n{\n Time time;\n Localtime(&time);\n\n FILE* stream = GetFileStream(severity, &time);\n if (NULL == stream)\n return;\n\n va_list ap;\n va_start(ap, format);\n\n char buf[1024];\n vsprintf(buf, format, ap);\n fprintf(stream, \"[%02d:%02d:%02d:%03d] [%s](%d) : %s\", \n time.hour, time.min, time.sec, time.millitm, file, line, buf);\n\n va_end(ap);\n}\n\n\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\nint main(int argc, char* argv[])\n{\n using namespace std;\n \n vector cmdlineargs(argv+1, argv+argc);\n \n auto rbiterv = cmdlineargs.rbegin();\n \n while( rbiterv != cmdlineargs.rend() ) {\n auto& arg = *rbiterv++;\n auto rbiterarg = arg.rbegin();\n \n while( rbiterarg != arg.rend() ) {\n cout << *rbiterarg++;\n }\n cout << endl;\n }\n \n return EXIT_SUCCESS;\n} \nLocalized scope of variables to the loop#include \n#include \n#include \n#include \n\nint main(int argc, char* argv[])\n{\n using namespace std;\n \n vector cmdlineargs(argv+1, argv+argc);\n \n for(auto rbiterv=cmdlineargs.rbegin(); rbiterv != cmdlineargs.rend(); ++rbiterv) {\n auto& arg = *rbiterv;\n \n for(auto rbiterarg = arg.rbegin(); rbiterarg != arg.rend(); ++rbiterarg) {\n cout << *rbiterarg; \n }\n \n cout << endl;\n }\n \n return EXIT_SUCCESS;\n}\n\n<|endoftext|>"} {"text":"\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/run_loop.h\"\n#include \"chrome\/browser\/extensions\/api\/gcm\/gcm_api.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/services\/gcm\/fake_gcm_profile_service.h\"\n#include \"chrome\/browser\/services\/gcm\/gcm_profile_service_factory.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n\nnamespace {\n\nconst char kFunctionsTestExtension[] = \"gcm\/functions\";\nconst char kEventsExtension[] = \"gcm\/events\";\n\n} \/\/ namespace\n\nnamespace extensions {\n\nclass GcmApiTest : public ExtensionApiTest {\n public:\n GcmApiTest() : fake_gcm_profile_service_(NULL) {}\n\n protected:\n void SetUpFakeService(bool collect);\n\n const Extension* LoadTestExtension(const std::string& extension_path,\n const std::string& page_name);\n\n void WaitUntilIdle();\n\n gcm::FakeGCMProfileService* service() const;\n\n gcm::FakeGCMProfileService* fake_gcm_profile_service_;\n};\n\nvoid GcmApiTest::SetUpFakeService(bool collect) {\n gcm::GCMProfileServiceFactory::GetInstance()->SetTestingFactory(\n profile(), &gcm::FakeGCMProfileService::Build);\n\n fake_gcm_profile_service_ = static_cast(\n gcm::GCMProfileServiceFactory::GetInstance()->GetForProfile(profile()));\n fake_gcm_profile_service_->set_collect(collect);\n gcm::FakeGCMProfileService::EnableGCMForTesting();\n}\n\nvoid GcmApiTest::WaitUntilIdle() {\n base::RunLoop run_loop;\n run_loop.RunUntilIdle();\n}\n\ngcm::FakeGCMProfileService* GcmApiTest::service() const {\n return fake_gcm_profile_service_;\n}\n\nconst Extension* GcmApiTest::LoadTestExtension(\n const std::string& extension_path,\n const std::string& page_name) {\n const Extension* extension =\n LoadExtension(test_data_dir_.AppendASCII(extension_path));\n if (extension) {\n ui_test_utils::NavigateToURL(\n browser(), extension->GetResourceURL(page_name));\n }\n return extension;\n}\n\n\/\/ http:\/\/crbug.com\/177163 and http:\/\/crbug.com\/324982\n#if defined(OS_WIN) && !defined(NDEBUG)\n#define MAYBE_RegisterValidation DISABLED_RegisterValidation\n#else\n#define MAYBE_RegisterValidation RegisterValidation\n#endif\nIN_PROC_BROWSER_TEST_F(GcmApiTest, MAYBE_RegisterValidation) {\n SetUpFakeService(false);\n EXPECT_TRUE(RunExtensionSubtest(kFunctionsTestExtension,\n \"register_validation.html\"));\n}\n\n\/\/ http:\/\/crbug.com\/177163 and http:\/\/crbug.com\/324982\n#if defined(OS_WIN) && !defined(NDEBUG)\n#define MAYBE_Register DISABLED_Register\n#else\n#define MAYBE_Register Register\n#endif\nIN_PROC_BROWSER_TEST_F(GcmApiTest, MAYBE_Register) {\n SetUpFakeService(true);\n const extensions::Extension* extension =\n LoadTestExtension(kFunctionsTestExtension, \"register.html\");\n ASSERT_TRUE(extension);\n\n WaitUntilIdle();\n\n EXPECT_EQ(extension->id(), service()->last_registered_app_id());\n \/\/ SHA1 of the public key provided in manifest.json.\n EXPECT_EQ(\"26469186F238EE08FA71C38311C6990F61D40DCA\",\n service()->last_registered_cert());\n const std::vector& sender_ids =\n service()->last_registered_sender_ids();\n EXPECT_TRUE(std::find(sender_ids.begin(), sender_ids.end(), \"Sender1\") !=\n sender_ids.end());\n EXPECT_TRUE(std::find(sender_ids.begin(), sender_ids.end(), \"Sender2\") !=\n sender_ids.end());\n}\n\n\/\/ http:\/\/crbug.com\/177163 and http:\/\/crbug.com\/324982\n#if defined(OS_WIN) && !defined(NDEBUG)\n#define MAYBE_SendValidation DISABLED_SendValidation\n#else\n#define MAYBE_SendValidation SendValidation\n#endif\nIN_PROC_BROWSER_TEST_F(GcmApiTest, MAYBE_SendValidation) {\n SetUpFakeService(false);\n EXPECT_TRUE(RunExtensionSubtest(kFunctionsTestExtension, \"send.html\"));\n}\n\n\/\/ http:\/\/crbug.com\/177163 and http:\/\/crbug.com\/324982\n#if defined(OS_WIN) && !defined(NDEBUG)\n#define MAYBE_SendMessageData DISABLED_SendMessageData\n#else\n#define MAYBE_SendMessageData SendMessageData\n#endif\nIN_PROC_BROWSER_TEST_F(GcmApiTest, MAYBE_SendMessageData) {\n SetUpFakeService(true);\n const extensions::Extension* extension =\n LoadTestExtension(kFunctionsTestExtension, \"send_message_data.html\");\n ASSERT_TRUE(extension);\n\n WaitUntilIdle();\n\n EXPECT_EQ(\"destination-id\", service()->last_receiver_id());\n const gcm::GCMClient::OutgoingMessage& message =\n service()->last_sent_message();\n gcm::GCMClient::MessageData::const_iterator iter;\n\n EXPECT_TRUE((iter = message.data.find(\"key1\")) != message.data.end());\n EXPECT_EQ(\"value1\", iter->second);\n\n EXPECT_TRUE((iter = message.data.find(\"key2\")) != message.data.end());\n EXPECT_EQ(\"value2\", iter->second);\n}\n\n\/\/ http:\/\/crbug.com\/177163 and http:\/\/crbug\/324982\n#if defined(OS_WIN) && !defined(NDEBUG)\n#define MAYBE_OnMessagesDeleted DISABLED_OnMessagesDeleted\n#else\n#define MAYBE_OnMessagesDeleted OnMessagesDeleted\n#endif\nIN_PROC_BROWSER_TEST_F(GcmApiTest, MAYBE_OnMessagesDeleted) {\n ResultCatcher catcher;\n catcher.RestrictToProfile(profile());\n\n const extensions::Extension* extension =\n LoadTestExtension(kEventsExtension, \"on_messages_deleted.html\");\n ASSERT_TRUE(extension);\n\n GcmJsEventRouter router(profile());\n router.OnMessagesDeleted(extension->id());\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\n\/\/ http:\/\/crbug.com\/177163 and http:\/\/crbug\/324982\n#if defined(OS_WIN) && !defined(NDEBUG)\n#define MAYBE_OnMessage DISABLED_OnMessage\n#else\n#define MAYBE_OnMessage OnMessage\n#endif\nIN_PROC_BROWSER_TEST_F(GcmApiTest, MAYBE_OnMessage) {\n ResultCatcher catcher;\n catcher.RestrictToProfile(profile());\n\n const extensions::Extension* extension =\n LoadTestExtension(kEventsExtension, \"on_message.html\");\n ASSERT_TRUE(extension);\n\n GcmJsEventRouter router(profile());\n\n gcm::GCMClient::IncomingMessage message;\n message.data[\"property1\"] = \"value1\";\n message.data[\"property2\"] = \"value2\";\n router.OnMessage(extension->id(), message);\n\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\n\/\/ http:\/\/crbug.com\/177163 and http:\/\/crbug\/324982\n#if defined(OS_WIN) && !defined(NDEBUG)\n#define MAYBE_OnSendError DISABLED_OnSendError\n#else\n#define MAYBE_OnSendError OnSendError\n#endif\nIN_PROC_BROWSER_TEST_F(GcmApiTest, MAYBE_OnSendError) {\n ResultCatcher catcher;\n catcher.RestrictToProfile(profile());\n\n const extensions::Extension* extension =\n LoadTestExtension(kEventsExtension, \"on_send_error.html\");\n ASSERT_TRUE(extension);\n\n GcmJsEventRouter router(profile());\n router.OnSendError(extension->id(), \"error_message_1\",\n gcm::GCMClient::ASYNC_OPERATION_PENDING);\n router.OnSendError(extension->id(), \"error_message_2\",\n gcm::GCMClient::SERVER_ERROR);\n router.OnSendError(extension->id(), \"error_message_3\",\n gcm::GCMClient::NETWORK_ERROR);\n router.OnSendError(extension->id(), \"error_message_4\",\n gcm::GCMClient::UNKNOWN_ERROR);\n router.OnSendError(extension->id(), \"error_message_5\",\n gcm::GCMClient::TTL_EXCEEDED);\n\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\n} \/\/ namespace extensions\nAnother attempt at disabling the GCM API test from running on windows.\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/run_loop.h\"\n#include \"chrome\/browser\/extensions\/api\/gcm\/gcm_api.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/services\/gcm\/fake_gcm_profile_service.h\"\n#include \"chrome\/browser\/services\/gcm\/gcm_profile_service_factory.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n\nnamespace {\n\nconst char kFunctionsTestExtension[] = \"gcm\/functions\";\nconst char kEventsExtension[] = \"gcm\/events\";\n\n} \/\/ namespace\n\nnamespace extensions {\n\nclass GcmApiTest : public ExtensionApiTest {\n public:\n GcmApiTest() : fake_gcm_profile_service_(NULL) {}\n\n protected:\n void SetUpFakeService(bool collect);\n\n const Extension* LoadTestExtension(const std::string& extension_path,\n const std::string& page_name);\n\n void WaitUntilIdle();\n\n gcm::FakeGCMProfileService* service() const;\n\n gcm::FakeGCMProfileService* fake_gcm_profile_service_;\n};\n\nvoid GcmApiTest::SetUpFakeService(bool collect) {\n gcm::GCMProfileServiceFactory::GetInstance()->SetTestingFactory(\n profile(), &gcm::FakeGCMProfileService::Build);\n\n fake_gcm_profile_service_ = static_cast(\n gcm::GCMProfileServiceFactory::GetInstance()->GetForProfile(profile()));\n fake_gcm_profile_service_->set_collect(collect);\n gcm::FakeGCMProfileService::EnableGCMForTesting();\n}\n\nvoid GcmApiTest::WaitUntilIdle() {\n base::RunLoop run_loop;\n run_loop.RunUntilIdle();\n}\n\ngcm::FakeGCMProfileService* GcmApiTest::service() const {\n return fake_gcm_profile_service_;\n}\n\nconst Extension* GcmApiTest::LoadTestExtension(\n const std::string& extension_path,\n const std::string& page_name) {\n const Extension* extension =\n LoadExtension(test_data_dir_.AppendASCII(extension_path));\n if (extension) {\n ui_test_utils::NavigateToURL(\n browser(), extension->GetResourceURL(page_name));\n }\n return extension;\n}\n\n\/\/ http:\/\/crbug.com\/177163 and http:\/\/crbug.com\/324982\n#if defined(OS_WIN)\n#define MAYBE_RegisterValidation DISABLED_RegisterValidation\n#else\n#define MAYBE_RegisterValidation RegisterValidation\n#endif\nIN_PROC_BROWSER_TEST_F(GcmApiTest, MAYBE_RegisterValidation) {\n SetUpFakeService(false);\n EXPECT_TRUE(RunExtensionSubtest(kFunctionsTestExtension,\n \"register_validation.html\"));\n}\n\n\/\/ http:\/\/crbug.com\/177163 and http:\/\/crbug.com\/324982\n#if defined(OS_WIN)\n#define MAYBE_Register DISABLED_Register\n#else\n#define MAYBE_Register Register\n#endif\nIN_PROC_BROWSER_TEST_F(GcmApiTest, MAYBE_Register) {\n SetUpFakeService(true);\n const extensions::Extension* extension =\n LoadTestExtension(kFunctionsTestExtension, \"register.html\");\n ASSERT_TRUE(extension);\n\n WaitUntilIdle();\n\n EXPECT_EQ(extension->id(), service()->last_registered_app_id());\n \/\/ SHA1 of the public key provided in manifest.json.\n EXPECT_EQ(\"26469186F238EE08FA71C38311C6990F61D40DCA\",\n service()->last_registered_cert());\n const std::vector& sender_ids =\n service()->last_registered_sender_ids();\n EXPECT_TRUE(std::find(sender_ids.begin(), sender_ids.end(), \"Sender1\") !=\n sender_ids.end());\n EXPECT_TRUE(std::find(sender_ids.begin(), sender_ids.end(), \"Sender2\") !=\n sender_ids.end());\n}\n\n\/\/ http:\/\/crbug.com\/177163 and http:\/\/crbug.com\/324982\n#if defined(OS_WIN)\n#define MAYBE_SendValidation DISABLED_SendValidation\n#else\n#define MAYBE_SendValidation SendValidation\n#endif\nIN_PROC_BROWSER_TEST_F(GcmApiTest, MAYBE_SendValidation) {\n SetUpFakeService(false);\n EXPECT_TRUE(RunExtensionSubtest(kFunctionsTestExtension, \"send.html\"));\n}\n\n\/\/ http:\/\/crbug.com\/177163 and http:\/\/crbug.com\/324982\n#if defined(OS_WIN)\n#define MAYBE_SendMessageData DISABLED_SendMessageData\n#else\n#define MAYBE_SendMessageData SendMessageData\n#endif\nIN_PROC_BROWSER_TEST_F(GcmApiTest, MAYBE_SendMessageData) {\n SetUpFakeService(true);\n const extensions::Extension* extension =\n LoadTestExtension(kFunctionsTestExtension, \"send_message_data.html\");\n ASSERT_TRUE(extension);\n\n WaitUntilIdle();\n\n EXPECT_EQ(\"destination-id\", service()->last_receiver_id());\n const gcm::GCMClient::OutgoingMessage& message =\n service()->last_sent_message();\n gcm::GCMClient::MessageData::const_iterator iter;\n\n EXPECT_TRUE((iter = message.data.find(\"key1\")) != message.data.end());\n EXPECT_EQ(\"value1\", iter->second);\n\n EXPECT_TRUE((iter = message.data.find(\"key2\")) != message.data.end());\n EXPECT_EQ(\"value2\", iter->second);\n}\n\n\/\/ http:\/\/crbug.com\/177163 and http:\/\/crbug\/324982\n#if defined(OS_WIN) && !defined(NDEBUG)\n#define MAYBE_OnMessagesDeleted DISABLED_OnMessagesDeleted\n#else\n#define MAYBE_OnMessagesDeleted OnMessagesDeleted\n#endif\nIN_PROC_BROWSER_TEST_F(GcmApiTest, MAYBE_OnMessagesDeleted) {\n ResultCatcher catcher;\n catcher.RestrictToProfile(profile());\n\n const extensions::Extension* extension =\n LoadTestExtension(kEventsExtension, \"on_messages_deleted.html\");\n ASSERT_TRUE(extension);\n\n GcmJsEventRouter router(profile());\n router.OnMessagesDeleted(extension->id());\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\n\/\/ http:\/\/crbug.com\/177163 and http:\/\/crbug\/324982\n#if defined(OS_WIN) && !defined(NDEBUG)\n#define MAYBE_OnMessage DISABLED_OnMessage\n#else\n#define MAYBE_OnMessage OnMessage\n#endif\nIN_PROC_BROWSER_TEST_F(GcmApiTest, MAYBE_OnMessage) {\n ResultCatcher catcher;\n catcher.RestrictToProfile(profile());\n\n const extensions::Extension* extension =\n LoadTestExtension(kEventsExtension, \"on_message.html\");\n ASSERT_TRUE(extension);\n\n GcmJsEventRouter router(profile());\n\n gcm::GCMClient::IncomingMessage message;\n message.data[\"property1\"] = \"value1\";\n message.data[\"property2\"] = \"value2\";\n router.OnMessage(extension->id(), message);\n\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\n\/\/ http:\/\/crbug.com\/177163 and http:\/\/crbug\/324982\n#if defined(OS_WIN) && !defined(NDEBUG)\n#define MAYBE_OnSendError DISABLED_OnSendError\n#else\n#define MAYBE_OnSendError OnSendError\n#endif\nIN_PROC_BROWSER_TEST_F(GcmApiTest, MAYBE_OnSendError) {\n ResultCatcher catcher;\n catcher.RestrictToProfile(profile());\n\n const extensions::Extension* extension =\n LoadTestExtension(kEventsExtension, \"on_send_error.html\");\n ASSERT_TRUE(extension);\n\n GcmJsEventRouter router(profile());\n router.OnSendError(extension->id(), \"error_message_1\",\n gcm::GCMClient::ASYNC_OPERATION_PENDING);\n router.OnSendError(extension->id(), \"error_message_2\",\n gcm::GCMClient::SERVER_ERROR);\n router.OnSendError(extension->id(), \"error_message_3\",\n gcm::GCMClient::NETWORK_ERROR);\n router.OnSendError(extension->id(), \"error_message_4\",\n gcm::GCMClient::UNKNOWN_ERROR);\n router.OnSendError(extension->id(), \"error_message_5\",\n gcm::GCMClient::TTL_EXCEEDED);\n\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\n} \/\/ namespace extensions\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/prerender\/prerender_tab_helper.h\"\n\n#include \"base\/metrics\/histogram.h\"\n#include \"base\/strings\/string_number_conversions.h\"\n#include \"base\/time.h\"\n#include \"chrome\/browser\/prerender\/prerender_histograms.h\"\n#include \"chrome\/browser\/prerender\/prerender_manager.h\"\n#include \"chrome\/browser\/prerender\/prerender_manager_factory.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"content\/public\/browser\/render_view_host.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"content\/public\/browser\/web_contents_view.h\"\n#include \"skia\/ext\/platform_canvas.h\"\n#include \"third_party\/skia\/include\/core\/SkBitmap.h\"\n#include \"ui\/gfx\/rect.h\"\n\nusing content::WebContents;\n\nDEFINE_WEB_CONTENTS_USER_DATA_KEY(prerender::PrerenderTabHelper);\n\nnamespace prerender {\n\n\/\/ Helper class to compute pixel-based stats on the paint progress\n\/\/ between when a prerendered page is swapped in and when the onload event\n\/\/ fires.\nclass PrerenderTabHelper::PixelStats {\n public:\n explicit PixelStats(PrerenderTabHelper* tab_helper) :\n weak_factory_(this),\n tab_helper_(tab_helper) {\n }\n\n \/\/ Reasons why we need to fetch bitmaps: either a prerender was swapped in,\n \/\/ or a prerendered page has finished loading.\n enum BitmapType {\n BITMAP_SWAP_IN,\n BITMAP_ON_LOAD\n };\n\n void GetBitmap(BitmapType bitmap_type, WebContents* web_contents) {\n if (bitmap_type == BITMAP_SWAP_IN) {\n bitmap_.reset();\n bitmap_web_contents_ = web_contents;\n }\n\n if (bitmap_type == BITMAP_ON_LOAD && bitmap_web_contents_ != web_contents)\n return;\n\n if (!web_contents || !web_contents->GetView() ||\n !web_contents->GetRenderViewHost()) {\n return;\n }\n\n web_contents->GetRenderViewHost()->CopyFromBackingStore(\n gfx::Rect(),\n gfx::Size(),\n base::Bind(&PrerenderTabHelper::PixelStats::HandleBitmapResult,\n weak_factory_.GetWeakPtr(),\n bitmap_type,\n web_contents));\n }\n\n private:\n void HandleBitmapResult(BitmapType bitmap_type,\n WebContents* web_contents,\n bool succeeded,\n const SkBitmap& canvas_bitmap) {\n scoped_ptr bitmap;\n if (succeeded) {\n \/\/ TODO(nick): This copy may now be unnecessary.\n bitmap.reset(new SkBitmap());\n canvas_bitmap.copyTo(bitmap.get(), SkBitmap::kARGB_8888_Config);\n }\n\n if (bitmap_web_contents_ != web_contents)\n return;\n\n if (bitmap_type == BITMAP_SWAP_IN)\n bitmap_.swap(bitmap);\n\n if (bitmap_type == BITMAP_ON_LOAD) {\n PrerenderManager* prerender_manager =\n tab_helper_->MaybeGetPrerenderManager();\n if (prerender_manager) {\n prerender_manager->RecordFractionPixelsFinalAtSwapin(\n web_contents, CompareBitmaps(bitmap_.get(), bitmap.get()));\n }\n bitmap_.reset();\n bitmap_web_contents_ = NULL;\n }\n }\n\n \/\/ Helper comparing two bitmaps of identical size.\n \/\/ Returns a value < 0.0 if there is an error, and otherwise, a double in\n \/\/ [0, 1] indicating the fraction of pixels that are the same.\n double CompareBitmaps(SkBitmap* bitmap1, SkBitmap* bitmap2) {\n if (!bitmap1 || !bitmap2) {\n return -2.0;\n }\n if (bitmap1->width() != bitmap2->width() ||\n bitmap1->height() != bitmap2->height()) {\n return -1.0;\n }\n int pixels = bitmap1->width() * bitmap1->height();\n int same_pixels = 0;\n for (int y = 0; y < bitmap1->height(); ++y) {\n for (int x = 0; x < bitmap1->width(); ++x) {\n if (bitmap1->getColor(x, y) == bitmap2->getColor(x, y))\n same_pixels++;\n }\n }\n return static_cast(same_pixels) \/ static_cast(pixels);\n }\n\n \/\/ Bitmap of what the last swapped in prerendered tab looked like at swapin,\n \/\/ and the WebContents that it was swapped into.\n scoped_ptr bitmap_;\n WebContents* bitmap_web_contents_;\n\n base::WeakPtrFactory weak_factory_;\n\n PrerenderTabHelper* tab_helper_;\n};\n\nPrerenderTabHelper::PrerenderTabHelper(content::WebContents* web_contents)\n : content::WebContentsObserver(web_contents) {\n}\n\nPrerenderTabHelper::~PrerenderTabHelper() {\n}\n\nvoid PrerenderTabHelper::ProvisionalChangeToMainFrameUrl(\n const GURL& url,\n content::RenderViewHost* render_view_host) {\n url_ = url;\n PrerenderManager* prerender_manager = MaybeGetPrerenderManager();\n if (!prerender_manager)\n return;\n if (prerender_manager->IsWebContentsPrerendering(web_contents(), NULL))\n return;\n prerender_manager->MarkWebContentsAsNotPrerendered(web_contents());\n}\n\nvoid PrerenderTabHelper::DidCommitProvisionalLoadForFrame(\n int64 frame_id,\n bool is_main_frame,\n const GURL& validated_url,\n content::PageTransition transition_type,\n content::RenderViewHost* render_view_host) {\n if (!is_main_frame)\n return;\n url_ = validated_url;\n PrerenderManager* prerender_manager = MaybeGetPrerenderManager();\n if (!prerender_manager)\n return;\n if (prerender_manager->IsWebContentsPrerendering(web_contents(), NULL))\n return;\n prerender_manager->RecordNavigation(validated_url);\n}\n\nvoid PrerenderTabHelper::DidStopLoading(\n content::RenderViewHost* render_view_host) {\n \/\/ Compute the PPLT metric and report it in a histogram, if needed.\n \/\/ We include pages that are still prerendering and have just finished\n \/\/ loading -- PrerenderManager will sort this out and handle it correctly\n \/\/ (putting those times into a separate histogram).\n if (!pplt_load_start_.is_null()) {\n double fraction_elapsed_at_swapin = -1.0;\n base::TimeTicks now = base::TimeTicks::Now();\n if (!actual_load_start_.is_null()) {\n double plt = (now - actual_load_start_).InMillisecondsF();\n if (plt > 0.0) {\n fraction_elapsed_at_swapin = 1.0 -\n (now - pplt_load_start_).InMillisecondsF() \/ plt;\n } else {\n fraction_elapsed_at_swapin = 1.0;\n }\n DCHECK_GE(fraction_elapsed_at_swapin, 0.0);\n DCHECK_LE(fraction_elapsed_at_swapin, 1.0);\n }\n PrerenderManager::RecordPerceivedPageLoadTime(\n now - pplt_load_start_, fraction_elapsed_at_swapin, web_contents(),\n url_);\n if (IsPrerendered() && pixel_stats_.get())\n pixel_stats_->GetBitmap(PixelStats::BITMAP_ON_LOAD, web_contents());\n }\n\n \/\/ Reset the PPLT metric.\n pplt_load_start_ = base::TimeTicks();\n actual_load_start_ = base::TimeTicks();\n}\n\nvoid PrerenderTabHelper::DidStartProvisionalLoadForFrame(\n int64 frame_id,\n int64 parent_frame_id,\n bool is_main_frame,\n const GURL& validated_url,\n bool is_error_page,\n bool is_iframe_srcdoc,\n content::RenderViewHost* render_view_host) {\n if (is_main_frame) {\n \/\/ Record the beginning of a new PPLT navigation.\n pplt_load_start_ = base::TimeTicks::Now();\n actual_load_start_ = base::TimeTicks();\n }\n}\n\nPrerenderManager* PrerenderTabHelper::MaybeGetPrerenderManager() const {\n return PrerenderManagerFactory::GetForProfile(\n Profile::FromBrowserContext(web_contents()->GetBrowserContext()));\n}\n\nbool PrerenderTabHelper::IsPrerendering() {\n PrerenderManager* prerender_manager = MaybeGetPrerenderManager();\n if (!prerender_manager)\n return false;\n return prerender_manager->IsWebContentsPrerendering(web_contents(), NULL);\n}\n\nbool PrerenderTabHelper::IsPrerendered() {\n PrerenderManager* prerender_manager = MaybeGetPrerenderManager();\n if (!prerender_manager)\n return false;\n return prerender_manager->IsWebContentsPrerendered(web_contents(), NULL);\n}\n\nvoid PrerenderTabHelper::PrerenderSwappedIn() {\n \/\/ Ensure we are not prerendering any more.\n DCHECK(!IsPrerendering());\n if (pplt_load_start_.is_null()) {\n \/\/ If we have already finished loading, report a 0 PPLT.\n PrerenderManager::RecordPerceivedPageLoadTime(base::TimeDelta(), 1.0,\n web_contents(), url_);\n PrerenderManager* prerender_manager = MaybeGetPrerenderManager();\n if (prerender_manager)\n prerender_manager->RecordFractionPixelsFinalAtSwapin(web_contents(), 1.0);\n } else {\n \/\/ If we have not finished loading yet, record the actual load start, and\n \/\/ rebase the start time to now.\n actual_load_start_ = pplt_load_start_;\n pplt_load_start_ = base::TimeTicks::Now();\n if (pixel_stats_.get())\n pixel_stats_->GetBitmap(PixelStats::BITMAP_SWAP_IN, web_contents());\n }\n}\n\n} \/\/ namespace prerender\n[Coverity] Fix uninitalized member variable in PrerenderTabHelper.\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/prerender\/prerender_tab_helper.h\"\n\n#include \"base\/metrics\/histogram.h\"\n#include \"base\/strings\/string_number_conversions.h\"\n#include \"base\/time.h\"\n#include \"chrome\/browser\/prerender\/prerender_histograms.h\"\n#include \"chrome\/browser\/prerender\/prerender_manager.h\"\n#include \"chrome\/browser\/prerender\/prerender_manager_factory.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"content\/public\/browser\/render_view_host.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"content\/public\/browser\/web_contents_view.h\"\n#include \"skia\/ext\/platform_canvas.h\"\n#include \"third_party\/skia\/include\/core\/SkBitmap.h\"\n#include \"ui\/gfx\/rect.h\"\n\nusing content::WebContents;\n\nDEFINE_WEB_CONTENTS_USER_DATA_KEY(prerender::PrerenderTabHelper);\n\nnamespace prerender {\n\n\/\/ Helper class to compute pixel-based stats on the paint progress\n\/\/ between when a prerendered page is swapped in and when the onload event\n\/\/ fires.\nclass PrerenderTabHelper::PixelStats {\n public:\n explicit PixelStats(PrerenderTabHelper* tab_helper) :\n bitmap_web_contents_(NULL),\n weak_factory_(this),\n tab_helper_(tab_helper) {\n }\n\n \/\/ Reasons why we need to fetch bitmaps: either a prerender was swapped in,\n \/\/ or a prerendered page has finished loading.\n enum BitmapType {\n BITMAP_SWAP_IN,\n BITMAP_ON_LOAD\n };\n\n void GetBitmap(BitmapType bitmap_type, WebContents* web_contents) {\n if (bitmap_type == BITMAP_SWAP_IN) {\n bitmap_.reset();\n bitmap_web_contents_ = web_contents;\n }\n\n if (bitmap_type == BITMAP_ON_LOAD && bitmap_web_contents_ != web_contents)\n return;\n\n if (!web_contents || !web_contents->GetView() ||\n !web_contents->GetRenderViewHost()) {\n return;\n }\n\n web_contents->GetRenderViewHost()->CopyFromBackingStore(\n gfx::Rect(),\n gfx::Size(),\n base::Bind(&PrerenderTabHelper::PixelStats::HandleBitmapResult,\n weak_factory_.GetWeakPtr(),\n bitmap_type,\n web_contents));\n }\n\n private:\n void HandleBitmapResult(BitmapType bitmap_type,\n WebContents* web_contents,\n bool succeeded,\n const SkBitmap& canvas_bitmap) {\n scoped_ptr bitmap;\n if (succeeded) {\n \/\/ TODO(nick): This copy may now be unnecessary.\n bitmap.reset(new SkBitmap());\n canvas_bitmap.copyTo(bitmap.get(), SkBitmap::kARGB_8888_Config);\n }\n\n if (bitmap_web_contents_ != web_contents)\n return;\n\n if (bitmap_type == BITMAP_SWAP_IN)\n bitmap_.swap(bitmap);\n\n if (bitmap_type == BITMAP_ON_LOAD) {\n PrerenderManager* prerender_manager =\n tab_helper_->MaybeGetPrerenderManager();\n if (prerender_manager) {\n prerender_manager->RecordFractionPixelsFinalAtSwapin(\n web_contents, CompareBitmaps(bitmap_.get(), bitmap.get()));\n }\n bitmap_.reset();\n bitmap_web_contents_ = NULL;\n }\n }\n\n \/\/ Helper comparing two bitmaps of identical size.\n \/\/ Returns a value < 0.0 if there is an error, and otherwise, a double in\n \/\/ [0, 1] indicating the fraction of pixels that are the same.\n double CompareBitmaps(SkBitmap* bitmap1, SkBitmap* bitmap2) {\n if (!bitmap1 || !bitmap2) {\n return -2.0;\n }\n if (bitmap1->width() != bitmap2->width() ||\n bitmap1->height() != bitmap2->height()) {\n return -1.0;\n }\n int pixels = bitmap1->width() * bitmap1->height();\n int same_pixels = 0;\n for (int y = 0; y < bitmap1->height(); ++y) {\n for (int x = 0; x < bitmap1->width(); ++x) {\n if (bitmap1->getColor(x, y) == bitmap2->getColor(x, y))\n same_pixels++;\n }\n }\n return static_cast(same_pixels) \/ static_cast(pixels);\n }\n\n \/\/ Bitmap of what the last swapped in prerendered tab looked like at swapin,\n \/\/ and the WebContents that it was swapped into.\n scoped_ptr bitmap_;\n WebContents* bitmap_web_contents_;\n\n base::WeakPtrFactory weak_factory_;\n\n PrerenderTabHelper* tab_helper_;\n};\n\nPrerenderTabHelper::PrerenderTabHelper(content::WebContents* web_contents)\n : content::WebContentsObserver(web_contents) {\n}\n\nPrerenderTabHelper::~PrerenderTabHelper() {\n}\n\nvoid PrerenderTabHelper::ProvisionalChangeToMainFrameUrl(\n const GURL& url,\n content::RenderViewHost* render_view_host) {\n url_ = url;\n PrerenderManager* prerender_manager = MaybeGetPrerenderManager();\n if (!prerender_manager)\n return;\n if (prerender_manager->IsWebContentsPrerendering(web_contents(), NULL))\n return;\n prerender_manager->MarkWebContentsAsNotPrerendered(web_contents());\n}\n\nvoid PrerenderTabHelper::DidCommitProvisionalLoadForFrame(\n int64 frame_id,\n bool is_main_frame,\n const GURL& validated_url,\n content::PageTransition transition_type,\n content::RenderViewHost* render_view_host) {\n if (!is_main_frame)\n return;\n url_ = validated_url;\n PrerenderManager* prerender_manager = MaybeGetPrerenderManager();\n if (!prerender_manager)\n return;\n if (prerender_manager->IsWebContentsPrerendering(web_contents(), NULL))\n return;\n prerender_manager->RecordNavigation(validated_url);\n}\n\nvoid PrerenderTabHelper::DidStopLoading(\n content::RenderViewHost* render_view_host) {\n \/\/ Compute the PPLT metric and report it in a histogram, if needed.\n \/\/ We include pages that are still prerendering and have just finished\n \/\/ loading -- PrerenderManager will sort this out and handle it correctly\n \/\/ (putting those times into a separate histogram).\n if (!pplt_load_start_.is_null()) {\n double fraction_elapsed_at_swapin = -1.0;\n base::TimeTicks now = base::TimeTicks::Now();\n if (!actual_load_start_.is_null()) {\n double plt = (now - actual_load_start_).InMillisecondsF();\n if (plt > 0.0) {\n fraction_elapsed_at_swapin = 1.0 -\n (now - pplt_load_start_).InMillisecondsF() \/ plt;\n } else {\n fraction_elapsed_at_swapin = 1.0;\n }\n DCHECK_GE(fraction_elapsed_at_swapin, 0.0);\n DCHECK_LE(fraction_elapsed_at_swapin, 1.0);\n }\n PrerenderManager::RecordPerceivedPageLoadTime(\n now - pplt_load_start_, fraction_elapsed_at_swapin, web_contents(),\n url_);\n if (IsPrerendered() && pixel_stats_.get())\n pixel_stats_->GetBitmap(PixelStats::BITMAP_ON_LOAD, web_contents());\n }\n\n \/\/ Reset the PPLT metric.\n pplt_load_start_ = base::TimeTicks();\n actual_load_start_ = base::TimeTicks();\n}\n\nvoid PrerenderTabHelper::DidStartProvisionalLoadForFrame(\n int64 frame_id,\n int64 parent_frame_id,\n bool is_main_frame,\n const GURL& validated_url,\n bool is_error_page,\n bool is_iframe_srcdoc,\n content::RenderViewHost* render_view_host) {\n if (is_main_frame) {\n \/\/ Record the beginning of a new PPLT navigation.\n pplt_load_start_ = base::TimeTicks::Now();\n actual_load_start_ = base::TimeTicks();\n }\n}\n\nPrerenderManager* PrerenderTabHelper::MaybeGetPrerenderManager() const {\n return PrerenderManagerFactory::GetForProfile(\n Profile::FromBrowserContext(web_contents()->GetBrowserContext()));\n}\n\nbool PrerenderTabHelper::IsPrerendering() {\n PrerenderManager* prerender_manager = MaybeGetPrerenderManager();\n if (!prerender_manager)\n return false;\n return prerender_manager->IsWebContentsPrerendering(web_contents(), NULL);\n}\n\nbool PrerenderTabHelper::IsPrerendered() {\n PrerenderManager* prerender_manager = MaybeGetPrerenderManager();\n if (!prerender_manager)\n return false;\n return prerender_manager->IsWebContentsPrerendered(web_contents(), NULL);\n}\n\nvoid PrerenderTabHelper::PrerenderSwappedIn() {\n \/\/ Ensure we are not prerendering any more.\n DCHECK(!IsPrerendering());\n if (pplt_load_start_.is_null()) {\n \/\/ If we have already finished loading, report a 0 PPLT.\n PrerenderManager::RecordPerceivedPageLoadTime(base::TimeDelta(), 1.0,\n web_contents(), url_);\n PrerenderManager* prerender_manager = MaybeGetPrerenderManager();\n if (prerender_manager)\n prerender_manager->RecordFractionPixelsFinalAtSwapin(web_contents(), 1.0);\n } else {\n \/\/ If we have not finished loading yet, record the actual load start, and\n \/\/ rebase the start time to now.\n actual_load_start_ = pplt_load_start_;\n pplt_load_start_ = base::TimeTicks::Now();\n if (pixel_stats_.get())\n pixel_stats_->GetBitmap(PixelStats::BITMAP_SWAP_IN, web_contents());\n }\n}\n\n} \/\/ namespace prerender\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/common\/render_messages.h\"\n#include \"chrome\/test\/render_view_test.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebDocument.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebString.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebURLError.h\"\n#include \"webkit\/glue\/form_data.h\"\n\nusing webkit_glue::FormData;\nusing WebKit::WebCompositionCommand;\nusing WebKit::WebFrame;\nusing WebKit::WebString;\nusing WebKit::WebTextDirection;\nusing WebKit::WebURLError;\n\ntypedef RenderViewTest FormAutocompleteTest;\n\n\/\/ Tests that submitting a form generates a FormSubmitted message\n\/\/ with the form fields.\nTEST_F(FormAutocompleteTest, NormalFormSubmit) {\n \/\/ Load a form.\n LoadHTML(\"
\"\n \"<\/form><\/html>\");\n\n \/\/ Submit the form.\n ExecuteJavaScript(\"document.getElementById('myForm').submit();\");\n ProcessPendingMessages();\n\n const IPC::Message* message = render_thread_.sink().GetFirstMessageMatching(\n ViewHostMsg_FormSubmitted::ID);\n ASSERT_TRUE(message != NULL);\n\n Tuple1 forms;\n ViewHostMsg_FormSubmitted::Read(message, &forms);\n ASSERT_EQ(2U, forms.a.fields.size());\n\n webkit_glue::FormField& form_field = forms.a.fields[0];\n EXPECT_EQ(WebString(\"fname\"), form_field.name());\n EXPECT_EQ(WebString(\"Rick\"), form_field.value());\n\n form_field = forms.a.fields[1];\n EXPECT_EQ(WebString(\"lname\"), form_field.name());\n EXPECT_EQ(WebString(\"Deckard\"), form_field.value());\n}\n\n\/\/ Tests that submitting a form that has autocomplete=\"off\" does not generate a\n\/\/ FormSubmitted message.\nTEST_F(FormAutocompleteTest, AutoCompleteOffFormSubmit) {\n \/\/ Load a form.\n LoadHTML(\"\"\n \"\"\n \"\"\n \"<\/form><\/html>\");\n\n \/\/ Submit the form.\n ExecuteJavaScript(\"document.getElementById('myForm').submit();\");\n ProcessPendingMessages();\n\n \/\/ No FormSubmitted message should have been sent.\n EXPECT_FALSE(render_thread_.sink().GetFirstMessageMatching(\n ViewHostMsg_FormSubmitted::ID));\n}\n\n\/\/ Tests that fields with autocomplete off are not submitted.\nTEST_F(FormAutocompleteTest, AutoCompleteOffInputSubmit) {\n \/\/ Load a form.\n LoadHTML(\"\"\n \"\"\n \"\"\n \"<\/form><\/html>\");\n\n \/\/ Submit the form.\n ExecuteJavaScript(\"document.getElementById('myForm').submit();\");\n ProcessPendingMessages();\n\n \/\/ No FormSubmitted message should have been sent.\n const IPC::Message* message = render_thread_.sink().GetFirstMessageMatching(\n ViewHostMsg_FormSubmitted::ID);\n ASSERT_TRUE(message != NULL);\n\n Tuple1 forms;\n ViewHostMsg_FormSubmitted::Read(message, &forms);\n ASSERT_EQ(1U, forms.a.fields.size());\n\n webkit_glue::FormField& form_field = forms.a.fields[0];\n EXPECT_EQ(WebString(\"fname\"), form_field.name());\n EXPECT_EQ(WebString(\"Rick\"), form_field.value());\n}\n\n\/\/ Tests that submitting a form that has been dynamically set as autocomplete\n\/\/ off does not generate a FormSubmitted message.\n\/\/ http:\/\/crbug.com\/36520\n\/\/ TODO(jcampan): reenable when WebKit bug 35823 is fixed.\nTEST_F(FormAutocompleteTest, DISABLED_DynamicAutoCompleteOffFormSubmit) {\n LoadHTML(\"\"\n \"<\/form><\/html>\");\n\n WebKit::WebElement element =\n GetMainFrame()->document().getElementById(WebKit::WebString(\"myForm\"));\n ASSERT_FALSE(element.isNull());\n WebKit::WebFormElement form = element.to();\n EXPECT_TRUE(form.autoComplete());\n\n \/\/ Dynamically mark the form as autocomplete off.\n ExecuteJavaScript(\"document.getElementById('myForm').autocomplete='off';\");\n ProcessPendingMessages();\n EXPECT_FALSE(form.autoComplete());\n\n \/\/ Submit the form.\n ExecuteJavaScript(\"document.getElementById('myForm').submit();\");\n ProcessPendingMessages();\n\n \/\/ No FormSubmitted message should have been sent.\n EXPECT_FALSE(render_thread_.sink().GetFirstMessageMatching(\n ViewHostMsg_FormSubmitted::ID));\n}\nTTF: Re-enable FormAutocompleteTest.AutoCompleteOffInputSubmit by marking it as failing.\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/common\/render_messages.h\"\n#include \"chrome\/test\/render_view_test.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebDocument.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebString.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebURLError.h\"\n#include \"webkit\/glue\/form_data.h\"\n\nusing webkit_glue::FormData;\nusing WebKit::WebCompositionCommand;\nusing WebKit::WebFrame;\nusing WebKit::WebString;\nusing WebKit::WebTextDirection;\nusing WebKit::WebURLError;\n\ntypedef RenderViewTest FormAutocompleteTest;\n\n\/\/ Tests that submitting a form generates a FormSubmitted message\n\/\/ with the form fields.\nTEST_F(FormAutocompleteTest, NormalFormSubmit) {\n \/\/ Load a form.\n LoadHTML(\"\"\n \"<\/form><\/html>\");\n\n \/\/ Submit the form.\n ExecuteJavaScript(\"document.getElementById('myForm').submit();\");\n ProcessPendingMessages();\n\n const IPC::Message* message = render_thread_.sink().GetFirstMessageMatching(\n ViewHostMsg_FormSubmitted::ID);\n ASSERT_TRUE(message != NULL);\n\n Tuple1 forms;\n ViewHostMsg_FormSubmitted::Read(message, &forms);\n ASSERT_EQ(2U, forms.a.fields.size());\n\n webkit_glue::FormField& form_field = forms.a.fields[0];\n EXPECT_EQ(WebString(\"fname\"), form_field.name());\n EXPECT_EQ(WebString(\"Rick\"), form_field.value());\n\n form_field = forms.a.fields[1];\n EXPECT_EQ(WebString(\"lname\"), form_field.name());\n EXPECT_EQ(WebString(\"Deckard\"), form_field.value());\n}\n\n\/\/ Tests that submitting a form that has autocomplete=\"off\" does not generate a\n\/\/ FormSubmitted message.\nTEST_F(FormAutocompleteTest, AutoCompleteOffFormSubmit) {\n \/\/ Load a form.\n LoadHTML(\"\"\n \"\"\n \"\"\n \"<\/form><\/html>\");\n\n \/\/ Submit the form.\n ExecuteJavaScript(\"document.getElementById('myForm').submit();\");\n ProcessPendingMessages();\n\n \/\/ No FormSubmitted message should have been sent.\n EXPECT_FALSE(render_thread_.sink().GetFirstMessageMatching(\n ViewHostMsg_FormSubmitted::ID));\n}\n\n\/\/ Tests that fields with autocomplete off are not submitted.\nTEST_F(FormAutocompleteTest, AutoCompleteOffInputSubmit) {\n \/\/ Load a form.\n LoadHTML(\"\"\n \"\"\n \"\"\n \"<\/form><\/html>\");\n\n \/\/ Submit the form.\n ExecuteJavaScript(\"document.getElementById('myForm').submit();\");\n ProcessPendingMessages();\n\n \/\/ No FormSubmitted message should have been sent.\n const IPC::Message* message = render_thread_.sink().GetFirstMessageMatching(\n ViewHostMsg_FormSubmitted::ID);\n ASSERT_TRUE(message != NULL);\n\n Tuple1 forms;\n ViewHostMsg_FormSubmitted::Read(message, &forms);\n ASSERT_EQ(1U, forms.a.fields.size());\n\n webkit_glue::FormField& form_field = forms.a.fields[0];\n EXPECT_EQ(WebString(\"fname\"), form_field.name());\n EXPECT_EQ(WebString(\"Rick\"), form_field.value());\n}\n\n\/\/ Tests that submitting a form that has been dynamically set as autocomplete\n\/\/ off does not generate a FormSubmitted message.\n\/\/ http:\/\/crbug.com\/36520\n\/\/ TODO(jcampan): Waiting on WebKit bug 35823.\nTEST_F(FormAutocompleteTest, FAILS_DynamicAutoCompleteOffFormSubmit) {\n LoadHTML(\"\"\n \"<\/form><\/html>\");\n\n WebKit::WebElement element =\n GetMainFrame()->document().getElementById(WebKit::WebString(\"myForm\"));\n ASSERT_FALSE(element.isNull());\n WebKit::WebFormElement form = element.to();\n EXPECT_TRUE(form.autoComplete());\n\n \/\/ Dynamically mark the form as autocomplete off.\n ExecuteJavaScript(\"document.getElementById('myForm').autocomplete='off';\");\n ProcessPendingMessages();\n EXPECT_FALSE(form.autoComplete());\n\n \/\/ Submit the form.\n ExecuteJavaScript(\"document.getElementById('myForm').submit();\");\n ProcessPendingMessages();\n\n \/\/ No FormSubmitted message should have been sent.\n EXPECT_FALSE(render_thread_.sink().GetFirstMessageMatching(\n ViewHostMsg_FormSubmitted::ID));\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n\/\/ Constant defines used in the cloud print proxy code\n\n#include \"chrome\/service\/cloud_print\/cloud_print_consts.h\"\n\nconst char kProxyIdValue[] = \"proxy\";\nconst char kPrinterNameValue[] = \"printer\";\nconst char kPrinterDescValue[] = \"description\";\nconst char kPrinterCapsValue[] = \"capabilities\";\nconst char kPrinterDefaultsValue[] = \"defaults\";\nconst char kPrinterStatusValue[] = \"status\";\nconst char kPrinterTagValue[] = \"tag\";\n\n\/\/ Values in the respone JSON from the cloud print server\nconst wchar_t kPrinterListValue[] = L\"printers\";\nconst wchar_t kSuccessValue[] = L\"success\";\nconst wchar_t kNameValue[] = L\"name\";\nconst wchar_t kIdValue[] = L\"id\";\nconst wchar_t kTicketUrlValue[] = L\"ticketUrl\";\nconst wchar_t kFileUrlValue[] = L\"fileUrl\";\nconst wchar_t kJobListValue[] = L\"jobs\";\nconst wchar_t kTitleValue[] = L\"title\";\nconst wchar_t kPrinterCapsHashValue[] = L\"capsHash\";\n\nconst char kDefaultCloudPrintServerUrl[] = \"https:\/\/www.google.com\/cloudprint\";\n\/\/ TODO(sanjeevr): Change this to a real one.\nconst char kCloudPrintTalkServiceUrl[] = \"http:\/\/www.google.com\/printing\";\nconst char kGaiaUrl[] = \"https:\/\/www.google.com\/accounts\/ClientLogin\";\n\/\/ TODO(sanjeevr): Change this to a real one once we get a GAIA service id.\nconst char kCloudPrintGaiaServiceId[] = \"print\";\nconst char kSyncGaiaServiceId[] = \"chromiumsync\";\n\nChanged values of Cloud Print GAIA service id and Talk service URL to production values. BUG=None. TEST=Test with production cloudprint service. Review URL: http:\/\/codereview.chromium.org\/2254003\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n\/\/ Constant defines used in the cloud print proxy code\n\n#include \"chrome\/service\/cloud_print\/cloud_print_consts.h\"\n\nconst char kProxyIdValue[] = \"proxy\";\nconst char kPrinterNameValue[] = \"printer\";\nconst char kPrinterDescValue[] = \"description\";\nconst char kPrinterCapsValue[] = \"capabilities\";\nconst char kPrinterDefaultsValue[] = \"defaults\";\nconst char kPrinterStatusValue[] = \"status\";\nconst char kPrinterTagValue[] = \"tag\";\n\n\/\/ Values in the respone JSON from the cloud print server\nconst wchar_t kPrinterListValue[] = L\"printers\";\nconst wchar_t kSuccessValue[] = L\"success\";\nconst wchar_t kNameValue[] = L\"name\";\nconst wchar_t kIdValue[] = L\"id\";\nconst wchar_t kTicketUrlValue[] = L\"ticketUrl\";\nconst wchar_t kFileUrlValue[] = L\"fileUrl\";\nconst wchar_t kJobListValue[] = L\"jobs\";\nconst wchar_t kTitleValue[] = L\"title\";\nconst wchar_t kPrinterCapsHashValue[] = L\"capsHash\";\n\nconst char kDefaultCloudPrintServerUrl[] = \"https:\/\/www.google.com\/cloudprint\";\nconst char kCloudPrintTalkServiceUrl[] = \"http:\/\/www.google.com\/cloudprint\";\nconst char kGaiaUrl[] = \"https:\/\/www.google.com\/accounts\/ClientLogin\";\nconst char kCloudPrintGaiaServiceId[] = \"cloudprint\";\nconst char kSyncGaiaServiceId[] = \"chromiumsync\";\n\n<|endoftext|>"} {"text":"#include \n\n#include \"BFER.hpp\"\n\nusing namespace aff3ct;\nusing namespace aff3ct::factory;\n\nconst std::string aff3ct::factory::BFER::name = \"Simulation BFER\";\nconst std::string aff3ct::factory::BFER::prefix = \"sim\";\n\nBFER::parameters\n::parameters(const std::string name, const std::string prefix)\n: Simulation::parameters(name, prefix)\n{\n}\n\nBFER::parameters\n::~parameters()\n{\n\tif (src != nullptr) { delete src; src = nullptr; }\n\tif (crc != nullptr) { delete crc; crc = nullptr; }\n\tif (cdc != nullptr) { delete cdc; cdc = nullptr; }\n\tif (mdm != nullptr) { delete mdm; mdm = nullptr; }\n\tif (chn != nullptr) { delete chn; chn = nullptr; }\n\tif (qnt != nullptr) { delete qnt; qnt = nullptr; }\n\tif (mnt != nullptr) { delete mnt; mnt = nullptr; }\n\tif (ter != nullptr) { delete ter; ter = nullptr; }\n}\n\nBFER::parameters* BFER::parameters\n::clone() const\n{\n\tauto clone = new BFER::parameters(*this);\n\n\tif (src != nullptr) { clone->src = src->clone(); }\n\tif (crc != nullptr) { clone->crc = crc->clone(); }\n\tif (cdc != nullptr) { clone->cdc = cdc->clone(); }\n\tif (mdm != nullptr) { clone->mdm = mdm->clone(); }\n\tif (chn != nullptr) { clone->chn = chn->clone(); }\n\tif (qnt != nullptr) { clone->qnt = qnt->clone(); }\n\tif (mnt != nullptr) { clone->mnt = mnt->clone(); }\n\tif (ter != nullptr) { clone->ter = ter->clone(); }\n\n\treturn clone;\n}\n\nstd::vector BFER::parameters\n::get_names() const\n{\n\tauto n = Simulation::parameters::get_names();\n\tif (src != nullptr) { auto nn = src->get_names(); for (auto &x : nn) n.push_back(x); }\n\tif (crc != nullptr) { auto nn = crc->get_names(); for (auto &x : nn) n.push_back(x); }\n\tif (cdc != nullptr) { auto nn = cdc->get_names(); for (auto &x : nn) n.push_back(x); }\n\tif (mdm != nullptr) { auto nn = mdm->get_names(); for (auto &x : nn) n.push_back(x); }\n\tif (chn != nullptr) { auto nn = chn->get_names(); for (auto &x : nn) n.push_back(x); }\n\tif (qnt != nullptr) { auto nn = qnt->get_names(); for (auto &x : nn) n.push_back(x); }\n\tif (mnt != nullptr) { auto nn = mnt->get_names(); for (auto &x : nn) n.push_back(x); }\n\tif (ter != nullptr) { auto nn = ter->get_names(); for (auto &x : nn) n.push_back(x); }\n\treturn n;\n}\n\nstd::vector BFER::parameters\n::get_short_names() const\n{\n\tauto sn = Factory::parameters::get_short_names();\n\tif (src != nullptr) { auto nn = src->get_short_names(); for (auto &x : nn) sn.push_back(x); }\n\tif (crc != nullptr) { auto nn = crc->get_short_names(); for (auto &x : nn) sn.push_back(x); }\n\tif (cdc != nullptr) { auto nn = cdc->get_short_names(); for (auto &x : nn) sn.push_back(x); }\n\tif (mdm != nullptr) { auto nn = mdm->get_short_names(); for (auto &x : nn) sn.push_back(x); }\n\tif (chn != nullptr) { auto nn = chn->get_short_names(); for (auto &x : nn) sn.push_back(x); }\n\tif (qnt != nullptr) { auto nn = qnt->get_short_names(); for (auto &x : nn) sn.push_back(x); }\n\tif (mnt != nullptr) { auto nn = mnt->get_short_names(); for (auto &x : nn) sn.push_back(x); }\n\tif (ter != nullptr) { auto nn = ter->get_short_names(); for (auto &x : nn) sn.push_back(x); }\n\treturn sn;\n}\n\nstd::vector BFER::parameters\n::get_prefixes() const\n{\n\tauto p = Factory::parameters::get_prefixes();\n\tif (src != nullptr) { auto nn = src->get_prefixes(); for (auto &x : nn) p.push_back(x); }\n\tif (crc != nullptr) { auto nn = crc->get_prefixes(); for (auto &x : nn) p.push_back(x); }\n\tif (cdc != nullptr) { auto nn = cdc->get_prefixes(); for (auto &x : nn) p.push_back(x); }\n\tif (mdm != nullptr) { auto nn = mdm->get_prefixes(); for (auto &x : nn) p.push_back(x); }\n\tif (chn != nullptr) { auto nn = chn->get_prefixes(); for (auto &x : nn) p.push_back(x); }\n\tif (qnt != nullptr) { auto nn = qnt->get_prefixes(); for (auto &x : nn) p.push_back(x); }\n\tif (mnt != nullptr) { auto nn = mnt->get_prefixes(); for (auto &x : nn) p.push_back(x); }\n\tif (ter != nullptr) { auto nn = ter->get_prefixes(); for (auto &x : nn) p.push_back(x); }\n\treturn p;\n}\n\nvoid BFER::parameters\n::get_description(arg_map &req_args, arg_map &opt_args) const\n{\n\tSimulation::parameters::get_description(req_args, opt_args);\n\n\tauto p = this->get_prefix();\n\n\topt_args[{p+\"-snr-type\", \"E\"}] =\n\t\t{\"string\",\n\t\t \"select the type of SNR: symbol energy or information bit energy.\",\n\t\t \"ES, EB\"};\n\n\topt_args[{p+\"-coset\", \"c\"}] =\n\t\t{\"\",\n\t\t \"enable the coset approach.\"};\n\n\topt_args[{p+\"-err-trk\"}] =\n\t\t{\"\",\n\t\t \"enable the tracking of the bad frames (by default the frames are stored in the current folder).\"};\n\n\topt_args[{p+\"-err-trk-rev\"}] =\n\t\t{\"\",\n\t\t \"automatically replay the saved frames.\"};\n\n\topt_args[{p+\"-err-trk-path\"}] =\n\t\t{\"string\",\n\t\t \"base path for the files where the bad frames will be stored or read.\"};\n\n\topt_args[{p+\"-err-trk-thold\"}] =\n\t\t{\"positive_int\",\n\t\t \"dump only frames with a bit error count above or equal to this threshold.\"};\n\n\topt_args[{p+\"-coded\"}] =\n\t\t{\"\",\n\t\t \"enable the coded monitoring (extends the monitored bits to the entire codeword).\"};\n}\n\nvoid BFER::parameters\n::store(const arg_val_map &vals)\n{\n#if !defined(SYSTEMC)\n\tthis->n_threads = std::thread::hardware_concurrency() ? std::thread::hardware_concurrency() : 1;\n#endif\n\n\tSimulation::parameters::store(vals);\n\n\tauto p = this->get_prefix();\n\n\tif(exist(vals, {p+\"-snr-type\", \"E\"})) this->snr_type = vals.at({p+\"-snr-type\", \"E\"});\n\tif(exist(vals, {p+\"-err-trk-path\" })) this->err_track_path = vals.at({p+\"-err-trk-path\" });\n\tif(exist(vals, {p+\"-err-trk-thold\" })) this->err_track_threshold = std::stoi(vals.at({p+\"-err-trk-thold\"}));\n\tif(exist(vals, {p+\"-err-trk-rev\" })) this->err_track_revert = true;\n\tif(exist(vals, {p+\"-err-trk\" })) this->err_track_enable = true;\n\tif(exist(vals, {p+\"-coset\", \"c\"})) this->coset = true;\n\tif(exist(vals, {p+\"-coded\", })) this->coded_monitoring = true;\n\n\tif (this->err_track_revert)\n\t{\n\t\tthis->err_track_enable = false;\n\t\tthis->n_threads = 1;\n\t}\n}\n\nvoid BFER::parameters\n::get_headers(std::map& headers, const bool full) const\n{\n\tSimulation::parameters::get_headers(headers, full);\n\n\tauto p = this->get_prefix();\n\n\theaders[p].push_back(std::make_pair(\"SNR type\", this->snr_type));\n\theaders[p].push_back(std::make_pair(\"Coset approach (c)\", this->coset ? \"yes\" : \"no\"));\n\theaders[p].push_back(std::make_pair(\"Coded monitoring\", this->coded_monitoring ? \"yes\" : \"no\"));\n\n\tstd::string enable_track = (this->err_track_enable) ? \"on\" : \"off\";\n\theaders[p].push_back(std::make_pair(\"Bad frames tracking\", enable_track));\n\n\tstd::string enable_rev_track = (this->err_track_revert) ? \"on\" : \"off\";\n\theaders[p].push_back(std::make_pair(\"Bad frames replay\", enable_rev_track));\n\n\theaders[p].push_back(std::make_pair(\"Bad frames threshold\", std::to_string(this->err_track_threshold)));\n\n\tif (this->err_track_enable || this->err_track_revert)\n\t{\n\t\tstd::string path = this->err_track_path + std::string(\"_$snr.[src,enc,chn]\");\n\t\theaders[p].push_back(std::make_pair(\"Bad frames base path\", path));\n\t}\n\n\tif (this->src != nullptr && this->cdc != nullptr)\n\t{\n\t\tconst auto bit_rate = (float)this->src->K \/ (float)this->cdc->N;\n\t\theaders[p].push_back(std::make_pair(\"Bit rate\", std::to_string(bit_rate)));\n\t}\n\n\tif (this->src != nullptr)\n\t\theaders[p].push_back(std::make_pair(\"Inter frame level\", std::to_string(this->src->n_frames)));\n\n\tif (this->src != nullptr) { this->src->get_headers(headers, full); }\n\tif (this->crc != nullptr) { this->crc->get_headers(headers, full); }\n\tif (this->cdc != nullptr) { this->cdc->get_headers(headers, full); }\n\tif (this->mdm != nullptr) { this->mdm->get_headers(headers, full); }\n\tif (this->chn != nullptr) { this->chn->get_headers(headers, full); }\n\tif (this->qnt != nullptr) { this->qnt->get_headers(headers, full); }\n\tif (this->mnt != nullptr) { this->mnt->get_headers(headers, full); }\n\tif (this->ter != nullptr) { this->ter->get_headers(headers, full); }\n}\nDo not show the 'Bad frames threshold' parameter when its value is 0.#include \n\n#include \"BFER.hpp\"\n\nusing namespace aff3ct;\nusing namespace aff3ct::factory;\n\nconst std::string aff3ct::factory::BFER::name = \"Simulation BFER\";\nconst std::string aff3ct::factory::BFER::prefix = \"sim\";\n\nBFER::parameters\n::parameters(const std::string name, const std::string prefix)\n: Simulation::parameters(name, prefix)\n{\n}\n\nBFER::parameters\n::~parameters()\n{\n\tif (src != nullptr) { delete src; src = nullptr; }\n\tif (crc != nullptr) { delete crc; crc = nullptr; }\n\tif (cdc != nullptr) { delete cdc; cdc = nullptr; }\n\tif (mdm != nullptr) { delete mdm; mdm = nullptr; }\n\tif (chn != nullptr) { delete chn; chn = nullptr; }\n\tif (qnt != nullptr) { delete qnt; qnt = nullptr; }\n\tif (mnt != nullptr) { delete mnt; mnt = nullptr; }\n\tif (ter != nullptr) { delete ter; ter = nullptr; }\n}\n\nBFER::parameters* BFER::parameters\n::clone() const\n{\n\tauto clone = new BFER::parameters(*this);\n\n\tif (src != nullptr) { clone->src = src->clone(); }\n\tif (crc != nullptr) { clone->crc = crc->clone(); }\n\tif (cdc != nullptr) { clone->cdc = cdc->clone(); }\n\tif (mdm != nullptr) { clone->mdm = mdm->clone(); }\n\tif (chn != nullptr) { clone->chn = chn->clone(); }\n\tif (qnt != nullptr) { clone->qnt = qnt->clone(); }\n\tif (mnt != nullptr) { clone->mnt = mnt->clone(); }\n\tif (ter != nullptr) { clone->ter = ter->clone(); }\n\n\treturn clone;\n}\n\nstd::vector BFER::parameters\n::get_names() const\n{\n\tauto n = Simulation::parameters::get_names();\n\tif (src != nullptr) { auto nn = src->get_names(); for (auto &x : nn) n.push_back(x); }\n\tif (crc != nullptr) { auto nn = crc->get_names(); for (auto &x : nn) n.push_back(x); }\n\tif (cdc != nullptr) { auto nn = cdc->get_names(); for (auto &x : nn) n.push_back(x); }\n\tif (mdm != nullptr) { auto nn = mdm->get_names(); for (auto &x : nn) n.push_back(x); }\n\tif (chn != nullptr) { auto nn = chn->get_names(); for (auto &x : nn) n.push_back(x); }\n\tif (qnt != nullptr) { auto nn = qnt->get_names(); for (auto &x : nn) n.push_back(x); }\n\tif (mnt != nullptr) { auto nn = mnt->get_names(); for (auto &x : nn) n.push_back(x); }\n\tif (ter != nullptr) { auto nn = ter->get_names(); for (auto &x : nn) n.push_back(x); }\n\treturn n;\n}\n\nstd::vector BFER::parameters\n::get_short_names() const\n{\n\tauto sn = Factory::parameters::get_short_names();\n\tif (src != nullptr) { auto nn = src->get_short_names(); for (auto &x : nn) sn.push_back(x); }\n\tif (crc != nullptr) { auto nn = crc->get_short_names(); for (auto &x : nn) sn.push_back(x); }\n\tif (cdc != nullptr) { auto nn = cdc->get_short_names(); for (auto &x : nn) sn.push_back(x); }\n\tif (mdm != nullptr) { auto nn = mdm->get_short_names(); for (auto &x : nn) sn.push_back(x); }\n\tif (chn != nullptr) { auto nn = chn->get_short_names(); for (auto &x : nn) sn.push_back(x); }\n\tif (qnt != nullptr) { auto nn = qnt->get_short_names(); for (auto &x : nn) sn.push_back(x); }\n\tif (mnt != nullptr) { auto nn = mnt->get_short_names(); for (auto &x : nn) sn.push_back(x); }\n\tif (ter != nullptr) { auto nn = ter->get_short_names(); for (auto &x : nn) sn.push_back(x); }\n\treturn sn;\n}\n\nstd::vector BFER::parameters\n::get_prefixes() const\n{\n\tauto p = Factory::parameters::get_prefixes();\n\tif (src != nullptr) { auto nn = src->get_prefixes(); for (auto &x : nn) p.push_back(x); }\n\tif (crc != nullptr) { auto nn = crc->get_prefixes(); for (auto &x : nn) p.push_back(x); }\n\tif (cdc != nullptr) { auto nn = cdc->get_prefixes(); for (auto &x : nn) p.push_back(x); }\n\tif (mdm != nullptr) { auto nn = mdm->get_prefixes(); for (auto &x : nn) p.push_back(x); }\n\tif (chn != nullptr) { auto nn = chn->get_prefixes(); for (auto &x : nn) p.push_back(x); }\n\tif (qnt != nullptr) { auto nn = qnt->get_prefixes(); for (auto &x : nn) p.push_back(x); }\n\tif (mnt != nullptr) { auto nn = mnt->get_prefixes(); for (auto &x : nn) p.push_back(x); }\n\tif (ter != nullptr) { auto nn = ter->get_prefixes(); for (auto &x : nn) p.push_back(x); }\n\treturn p;\n}\n\nvoid BFER::parameters\n::get_description(arg_map &req_args, arg_map &opt_args) const\n{\n\tSimulation::parameters::get_description(req_args, opt_args);\n\n\tauto p = this->get_prefix();\n\n\topt_args[{p+\"-snr-type\", \"E\"}] =\n\t\t{\"string\",\n\t\t \"select the type of SNR: symbol energy or information bit energy.\",\n\t\t \"ES, EB\"};\n\n\topt_args[{p+\"-coset\", \"c\"}] =\n\t\t{\"\",\n\t\t \"enable the coset approach.\"};\n\n\topt_args[{p+\"-err-trk\"}] =\n\t\t{\"\",\n\t\t \"enable the tracking of the bad frames (by default the frames are stored in the current folder).\"};\n\n\topt_args[{p+\"-err-trk-rev\"}] =\n\t\t{\"\",\n\t\t \"automatically replay the saved frames.\"};\n\n\topt_args[{p+\"-err-trk-path\"}] =\n\t\t{\"string\",\n\t\t \"base path for the files where the bad frames will be stored or read.\"};\n\n\topt_args[{p+\"-err-trk-thold\"}] =\n\t\t{\"positive_int\",\n\t\t \"dump only frames with a bit error count above or equal to this threshold.\"};\n\n\topt_args[{p+\"-coded\"}] =\n\t\t{\"\",\n\t\t \"enable the coded monitoring (extends the monitored bits to the entire codeword).\"};\n}\n\nvoid BFER::parameters\n::store(const arg_val_map &vals)\n{\n#if !defined(SYSTEMC)\n\tthis->n_threads = std::thread::hardware_concurrency() ? std::thread::hardware_concurrency() : 1;\n#endif\n\n\tSimulation::parameters::store(vals);\n\n\tauto p = this->get_prefix();\n\n\tif(exist(vals, {p+\"-snr-type\", \"E\"})) this->snr_type = vals.at({p+\"-snr-type\", \"E\"});\n\tif(exist(vals, {p+\"-err-trk-path\" })) this->err_track_path = vals.at({p+\"-err-trk-path\" });\n\tif(exist(vals, {p+\"-err-trk-thold\" })) this->err_track_threshold = std::stoi(vals.at({p+\"-err-trk-thold\"}));\n\tif(exist(vals, {p+\"-err-trk-rev\" })) this->err_track_revert = true;\n\tif(exist(vals, {p+\"-err-trk\" })) this->err_track_enable = true;\n\tif(exist(vals, {p+\"-coset\", \"c\"})) this->coset = true;\n\tif(exist(vals, {p+\"-coded\", })) this->coded_monitoring = true;\n\n\tif (this->err_track_revert)\n\t{\n\t\tthis->err_track_enable = false;\n\t\tthis->n_threads = 1;\n\t}\n}\n\nvoid BFER::parameters\n::get_headers(std::map& headers, const bool full) const\n{\n\tSimulation::parameters::get_headers(headers, full);\n\n\tauto p = this->get_prefix();\n\n\theaders[p].push_back(std::make_pair(\"SNR type\", this->snr_type));\n\theaders[p].push_back(std::make_pair(\"Coset approach (c)\", this->coset ? \"yes\" : \"no\"));\n\theaders[p].push_back(std::make_pair(\"Coded monitoring\", this->coded_monitoring ? \"yes\" : \"no\"));\n\n\tstd::string enable_track = (this->err_track_enable) ? \"on\" : \"off\";\n\theaders[p].push_back(std::make_pair(\"Bad frames tracking\", enable_track));\n\n\tstd::string enable_rev_track = (this->err_track_revert) ? \"on\" : \"off\";\n\theaders[p].push_back(std::make_pair(\"Bad frames replay\", enable_rev_track));\n\n\tif (this->err_track_threshold)\n\t\theaders[p].push_back(std::make_pair(\"Bad frames threshold\", std::to_string(this->err_track_threshold)));\n\n\tif (this->err_track_enable || this->err_track_revert)\n\t{\n\t\tstd::string path = this->err_track_path + std::string(\"_$snr.[src,enc,chn]\");\n\t\theaders[p].push_back(std::make_pair(\"Bad frames base path\", path));\n\t}\n\n\tif (this->src != nullptr && this->cdc != nullptr)\n\t{\n\t\tconst auto bit_rate = (float)this->src->K \/ (float)this->cdc->N;\n\t\theaders[p].push_back(std::make_pair(\"Bit rate\", std::to_string(bit_rate)));\n\t}\n\n\tif (this->src != nullptr)\n\t\theaders[p].push_back(std::make_pair(\"Inter frame level\", std::to_string(this->src->n_frames)));\n\n\tif (this->src != nullptr) { this->src->get_headers(headers, full); }\n\tif (this->crc != nullptr) { this->crc->get_headers(headers, full); }\n\tif (this->cdc != nullptr) { this->cdc->get_headers(headers, full); }\n\tif (this->mdm != nullptr) { this->mdm->get_headers(headers, full); }\n\tif (this->chn != nullptr) { this->chn->get_headers(headers, full); }\n\tif (this->qnt != nullptr) { this->qnt->get_headers(headers, full); }\n\tif (this->mnt != nullptr) { this->mnt->get_headers(headers, full); }\n\tif (this->ter != nullptr) { this->ter->get_headers(headers, full); }\n}\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2012, John Haddon. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer in the documentation and\/or other materials provided with\n\/\/ the distribution.\n\/\/\n\/\/ * Neither the name of John Haddon nor the names of\n\/\/ any other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"boost\/python.hpp\"\n#include \"boost\/python\/suite\/indexing\/container_utils.hpp\"\n\n#include \"IECorePython\/ScopedGILRelease.h\"\n\n#include \"Gaffer\/Plug.h\"\n#include \"Gaffer\/Context.h\"\n\n#include \"GafferBindings\/NodeBinding.h\"\n\n#include \"GafferUI\/View.h\"\n#include \"GafferUIBindings\/ViewBinding.h\"\n\nusing namespace boost::python;\nusing namespace Gaffer;\nusing namespace GafferUI;\nusing namespace GafferUIBindings;\n\nnamespace\n{\n\nclass ViewWrapper : public GafferBindings::NodeWrapper\n{\n\n\tpublic :\n\n\t\tViewWrapper( PyObject *self, const std::string &name, PlugPtr input )\n\t\t\t:\tGafferBindings::NodeWrapper( self, name, input )\n\t\t{\n\t\t}\n\n};\n\nstruct ViewCreator\n{\n\tViewCreator( object fn )\n\t\t:\tm_fn( fn )\n\t{\n\t}\n\n\tViewPtr operator()( Gaffer::PlugPtr plug )\n\t{\n\t\tIECorePython::ScopedGILLock gilLock;\n\t\tViewPtr result = extract( m_fn( plug ) );\n\t\treturn result;\n\t}\n\n\tprivate :\n\n\t\tobject m_fn;\n\n};\n\nvoid registerView1( IECore::TypeId plugType, object creator )\n{\n\tView::registerView( plugType, ViewCreator( creator ) );\n}\n\nvoid registerView2( IECore::TypeId nodeType, const std::string &plugPath, object creator )\n{\n\tView::registerView( nodeType, plugPath, ViewCreator( creator ) );\n}\n\n} \/\/ namespace\n\nGaffer::NodePtr GafferUIBindings::getPreprocessor( View &v )\n{\n\treturn v.getPreprocessor();\n}\n\nvoid GafferUIBindings::bindView()\n{\n\tGafferBindings::NodeClass( NULL, no_init )\n\t\t.def( init() )\n\t\t.def( \"getContext\", (Context *(View::*)())&View::getContext, return_value_policy() )\n\t\t.def( \"setContext\", &View::setContext )\n\t\t.def( \"contextChangedSignal\", &View::contextChangedSignal, return_internal_reference<1>() )\n\t\t.def( \"viewportGadget\", (ViewportGadget *(View::*)())&View::viewportGadget, return_value_policy() )\n\t\t.def( \"_setPreprocessor\", &View::setPreprocessor )\n\t\t.def( \"_getPreprocessor\", &getPreprocessor )\n\t\t.def( \"create\", &View::create )\n\t\t.staticmethod( \"create\" )\n\t\t.def( \"registerView\", ®isterView1 )\n\t\t.def( \"registerView\", ®isterView2 )\n\t\t.staticmethod( \"registerView\" )\n\t;\n}\nViewBinding : Release GIL in View::create().\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2012, John Haddon. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer in the documentation and\/or other materials provided with\n\/\/ the distribution.\n\/\/\n\/\/ * Neither the name of John Haddon nor the names of\n\/\/ any other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"boost\/python.hpp\"\n#include \"boost\/python\/suite\/indexing\/container_utils.hpp\"\n\n#include \"IECorePython\/ScopedGILRelease.h\"\n\n#include \"Gaffer\/Plug.h\"\n#include \"Gaffer\/Context.h\"\n\n#include \"GafferBindings\/NodeBinding.h\"\n\n#include \"GafferUI\/View.h\"\n#include \"GafferUIBindings\/ViewBinding.h\"\n\nusing namespace boost::python;\nusing namespace Gaffer;\nusing namespace GafferUI;\nusing namespace GafferUIBindings;\n\nnamespace\n{\n\nclass ViewWrapper : public GafferBindings::NodeWrapper\n{\n\n\tpublic :\n\n\t\tViewWrapper( PyObject *self, const std::string &name, PlugPtr input )\n\t\t\t:\tGafferBindings::NodeWrapper( self, name, input )\n\t\t{\n\t\t}\n\n};\n\nstruct ViewCreator\n{\n\tViewCreator( object fn )\n\t\t:\tm_fn( fn )\n\t{\n\t}\n\n\tViewPtr operator()( Gaffer::PlugPtr plug )\n\t{\n\t\tIECorePython::ScopedGILLock gilLock;\n\t\tViewPtr result = extract( m_fn( plug ) );\n\t\treturn result;\n\t}\n\n\tprivate :\n\n\t\tobject m_fn;\n\n};\n\nvoid registerView1( IECore::TypeId plugType, object creator )\n{\n\tView::registerView( plugType, ViewCreator( creator ) );\n}\n\nvoid registerView2( IECore::TypeId nodeType, const std::string &plugPath, object creator )\n{\n\tView::registerView( nodeType, plugPath, ViewCreator( creator ) );\n}\n\nViewPtr create( Gaffer::PlugPtr input )\n{\n\tIECorePython::ScopedGILRelease gilRelease;\n\treturn View::create( input );\n}\n\n} \/\/ namespace\n\nGaffer::NodePtr GafferUIBindings::getPreprocessor( View &v )\n{\n\treturn v.getPreprocessor();\n}\n\nvoid GafferUIBindings::bindView()\n{\n\tGafferBindings::NodeClass( NULL, no_init )\n\t\t.def( init() )\n\t\t.def( \"getContext\", (Context *(View::*)())&View::getContext, return_value_policy() )\n\t\t.def( \"setContext\", &View::setContext )\n\t\t.def( \"contextChangedSignal\", &View::contextChangedSignal, return_internal_reference<1>() )\n\t\t.def( \"viewportGadget\", (ViewportGadget *(View::*)())&View::viewportGadget, return_value_policy() )\n\t\t.def( \"_setPreprocessor\", &View::setPreprocessor )\n\t\t.def( \"_getPreprocessor\", &getPreprocessor )\n\t\t.def( \"create\", &create )\n\t\t.staticmethod( \"create\" )\n\t\t.def( \"registerView\", ®isterView1 )\n\t\t.def( \"registerView\", ®isterView2 )\n\t\t.staticmethod( \"registerView\" )\n\t;\n}\n<|endoftext|>"} {"text":"\/*\n Copyright (C) 2018 Alexander Akulich \n\n This file is a part of TelegramQt library.\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n *\/\n\n#include \"PhotosOperationFactory.hpp\"\n\n#include \"RpcOperationFactory_p.hpp\"\n\/\/ TODO: Instead of this include, add a generated cpp with all needed template instances\n#include \"ServerRpcOperation_p.hpp\"\n\n#include \"ServerApi.hpp\"\n#include \"ServerRpcLayer.hpp\"\n#include \"ServerUtils.hpp\"\n#include \"Storage.hpp\"\n#include \"TelegramServerUser.hpp\"\n\n#include \"Debug_p.hpp\"\n#include \"RpcError.hpp\"\n#include \"RpcProcessingContext.hpp\"\n\n#include \"CTelegramStreamExtraOperators.hpp\"\n#include \"FunctionStreamOperators.hpp\"\n\n#include \n\nnamespace Telegram {\n\nnamespace Server {\n\n\/\/ Generated process methods\nbool PhotosRpcOperation::processDeletePhotos(RpcProcessingContext &context)\n{\n setRunMethod(&PhotosRpcOperation::runDeletePhotos);\n context.inputStream() >> m_deletePhotos;\n return !context.inputStream().error();\n}\n\nbool PhotosRpcOperation::processGetUserPhotos(RpcProcessingContext &context)\n{\n setRunMethod(&PhotosRpcOperation::runGetUserPhotos);\n context.inputStream() >> m_getUserPhotos;\n return !context.inputStream().error();\n}\n\nbool PhotosRpcOperation::processUpdateProfilePhoto(RpcProcessingContext &context)\n{\n setRunMethod(&PhotosRpcOperation::runUpdateProfilePhoto);\n context.inputStream() >> m_updateProfilePhoto;\n return !context.inputStream().error();\n}\n\nbool PhotosRpcOperation::processUploadProfilePhoto(RpcProcessingContext &context)\n{\n setRunMethod(&PhotosRpcOperation::runUploadProfilePhoto);\n context.inputStream() >> m_uploadProfilePhoto;\n return !context.inputStream().error();\n}\n\/\/ End of generated process methods\n\n\/\/ Generated run methods\nvoid PhotosRpcOperation::runDeletePhotos()\n{\n \/\/ TLFunctions::TLPhotosDeletePhotos &arguments = m_deletePhotos;\n if (processNotImplementedMethod(TLValue::PhotosDeletePhotos)) {\n return;\n }\n TLVector result;\n sendRpcReply(result);\n}\n\nvoid PhotosRpcOperation::runGetUserPhotos()\n{\n \/\/ TLFunctions::TLPhotosGetUserPhotos &arguments = m_getUserPhotos;\n if (processNotImplementedMethod(TLValue::PhotosGetUserPhotos)) {\n return;\n }\n TLPhotosPhotos result;\n sendRpcReply(result);\n}\n\nvoid PhotosRpcOperation::runUpdateProfilePhoto()\n{\n \/\/ TLFunctions::TLPhotosUpdateProfilePhoto &arguments = m_updateProfilePhoto;\n if (processNotImplementedMethod(TLValue::PhotosUpdateProfilePhoto)) {\n return;\n }\n TLUserProfilePhoto result;\n sendRpcReply(result);\n}\n\nvoid PhotosRpcOperation::runUploadProfilePhoto()\n{\n TLFunctions::TLPhotosUploadProfilePhoto &arguments = m_uploadProfilePhoto;\n const FileDescriptor desc = api()->storage()->getFileDescriptor(arguments.file.id, arguments.file.parts);\n\n if (!desc.isValid()) {\n sendRpcError(RpcError());\n }\n\n const ImageDescriptor image = api()->storage()->processImageFile(desc, arguments.file.name);\n\n LocalUser *self = layer()->getUser();\n\n self->updateImage(image);\n\n TLPhotosPhoto result;\n Utils::setupTLPhoto(&result.photo, image);\n result.users.resize(1);\n Utils::setupTLUser(&result.users[0], self, self);\n\n sendRpcReply(result);\n}\n\/\/ End of generated run methods\n\nvoid PhotosRpcOperation::setRunMethod(PhotosRpcOperation::RunMethod method)\n{\n m_runMethod = method;\n}\n\nPhotosRpcOperation::ProcessingMethod PhotosRpcOperation::getMethodForRpcFunction(TLValue function)\n{\n switch (function) {\n \/\/ Generated methodForRpcFunction cases\n case TLValue::PhotosDeletePhotos:\n return &PhotosRpcOperation::processDeletePhotos;\n case TLValue::PhotosGetUserPhotos:\n return &PhotosRpcOperation::processGetUserPhotos;\n case TLValue::PhotosUpdateProfilePhoto:\n return &PhotosRpcOperation::processUpdateProfilePhoto;\n case TLValue::PhotosUploadProfilePhoto:\n return &PhotosRpcOperation::processUploadProfilePhoto;\n \/\/ End of generated methodForRpcFunction cases\n default:\n return nullptr;\n }\n}\n\nRpcOperation *PhotosOperationFactory::processRpcCall(RpcLayer *layer, RpcProcessingContext &context)\n{\n return processRpcCallImpl(layer, context);\n}\n\n} \/\/ Server namespace\n\n} \/\/ Telegram namespace\nServer: Implement PhotosGetUserPhotos\/*\n Copyright (C) 2018 Alexander Akulich \n\n This file is a part of TelegramQt library.\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n *\/\n\n#include \"PhotosOperationFactory.hpp\"\n\n#include \"RpcOperationFactory_p.hpp\"\n\/\/ TODO: Instead of this include, add a generated cpp with all needed template instances\n#include \"ServerRpcOperation_p.hpp\"\n\n#include \"ServerApi.hpp\"\n#include \"ServerRpcLayer.hpp\"\n#include \"ServerUtils.hpp\"\n#include \"Storage.hpp\"\n#include \"TelegramServerUser.hpp\"\n\n#include \"Debug_p.hpp\"\n#include \"RpcError.hpp\"\n#include \"RpcProcessingContext.hpp\"\n\n#include \"CTelegramStreamExtraOperators.hpp\"\n#include \"FunctionStreamOperators.hpp\"\n\n#include \n\nnamespace Telegram {\n\nnamespace Server {\n\n\/\/ Generated process methods\nbool PhotosRpcOperation::processDeletePhotos(RpcProcessingContext &context)\n{\n setRunMethod(&PhotosRpcOperation::runDeletePhotos);\n context.inputStream() >> m_deletePhotos;\n return !context.inputStream().error();\n}\n\nbool PhotosRpcOperation::processGetUserPhotos(RpcProcessingContext &context)\n{\n setRunMethod(&PhotosRpcOperation::runGetUserPhotos);\n context.inputStream() >> m_getUserPhotos;\n return !context.inputStream().error();\n}\n\nbool PhotosRpcOperation::processUpdateProfilePhoto(RpcProcessingContext &context)\n{\n setRunMethod(&PhotosRpcOperation::runUpdateProfilePhoto);\n context.inputStream() >> m_updateProfilePhoto;\n return !context.inputStream().error();\n}\n\nbool PhotosRpcOperation::processUploadProfilePhoto(RpcProcessingContext &context)\n{\n setRunMethod(&PhotosRpcOperation::runUploadProfilePhoto);\n context.inputStream() >> m_uploadProfilePhoto;\n return !context.inputStream().error();\n}\n\/\/ End of generated process methods\n\n\/\/ Generated run methods\nvoid PhotosRpcOperation::runDeletePhotos()\n{\n \/\/ TLFunctions::TLPhotosDeletePhotos &arguments = m_deletePhotos;\n if (processNotImplementedMethod(TLValue::PhotosDeletePhotos)) {\n return;\n }\n TLVector result;\n sendRpcReply(result);\n}\n\nvoid PhotosRpcOperation::runGetUserPhotos()\n{\n TLFunctions::TLPhotosGetUserPhotos &arguments = m_getUserPhotos;\n if (processNotImplementedMethod(TLValue::PhotosGetUserPhotos)) {\n return;\n }\n\n LocalUser *self = layer()->getUser();\n AbstractUser *targetUser = api()->getUser(arguments.userId, self);\n\n QVector images = targetUser->getImages();\n TLPhotosPhotos result;\n result.count = images.count();\n result.users.resize(1);\n Utils::setupTLUser(&result.users[0], targetUser, self);\n\n quint32 toIndex = arguments.offset + arguments.limit;\n if (toIndex > result.count) {\n toIndex = result.count;\n }\n if (toIndex <= arguments.offset) {\n \/\/ Nothing to send.\n sendRpcReply(result);\n return;\n }\n result.photos.resize(toIndex - arguments.offset);\n for (quint32 i = arguments.offset; i < toIndex; ++i) {\n if (images.at(i).id == arguments.maxId) {\n break;\n }\n Utils::setupTLPhoto(&result.photos[i - arguments.offset], images.at(i));\n }\n\n sendRpcReply(result);\n}\n\nvoid PhotosRpcOperation::runUpdateProfilePhoto()\n{\n \/\/ TLFunctions::TLPhotosUpdateProfilePhoto &arguments = m_updateProfilePhoto;\n if (processNotImplementedMethod(TLValue::PhotosUpdateProfilePhoto)) {\n return;\n }\n TLUserProfilePhoto result;\n sendRpcReply(result);\n}\n\nvoid PhotosRpcOperation::runUploadProfilePhoto()\n{\n TLFunctions::TLPhotosUploadProfilePhoto &arguments = m_uploadProfilePhoto;\n const FileDescriptor desc = api()->storage()->getFileDescriptor(arguments.file.id, arguments.file.parts);\n\n if (!desc.isValid()) {\n sendRpcError(RpcError());\n }\n\n const ImageDescriptor image = api()->storage()->processImageFile(desc, arguments.file.name);\n\n LocalUser *self = layer()->getUser();\n\n self->updateImage(image);\n\n TLPhotosPhoto result;\n Utils::setupTLPhoto(&result.photo, image);\n result.users.resize(1);\n Utils::setupTLUser(&result.users[0], self, self);\n\n sendRpcReply(result);\n}\n\/\/ End of generated run methods\n\nvoid PhotosRpcOperation::setRunMethod(PhotosRpcOperation::RunMethod method)\n{\n m_runMethod = method;\n}\n\nPhotosRpcOperation::ProcessingMethod PhotosRpcOperation::getMethodForRpcFunction(TLValue function)\n{\n switch (function) {\n \/\/ Generated methodForRpcFunction cases\n case TLValue::PhotosDeletePhotos:\n return &PhotosRpcOperation::processDeletePhotos;\n case TLValue::PhotosGetUserPhotos:\n return &PhotosRpcOperation::processGetUserPhotos;\n case TLValue::PhotosUpdateProfilePhoto:\n return &PhotosRpcOperation::processUpdateProfilePhoto;\n case TLValue::PhotosUploadProfilePhoto:\n return &PhotosRpcOperation::processUploadProfilePhoto;\n \/\/ End of generated methodForRpcFunction cases\n default:\n return nullptr;\n }\n}\n\nRpcOperation *PhotosOperationFactory::processRpcCall(RpcLayer *layer, RpcProcessingContext &context)\n{\n return processRpcCallImpl(layer, context);\n}\n\n} \/\/ Server namespace\n\n} \/\/ Telegram namespace\n<|endoftext|>"} {"text":"\n\/* tests\/test-param-fuzzy.C\n * Copyright (C) 2002 David Saunders\n * shamelessly mutated from one of the other field tests.\n *\n *\n * ========LICENCE========\n * This file is part of the library LinBox.\n *\n * LinBox is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n * ========LICENCE========\n *.\n *\/\n\n\n\/*! @file tests\/test-param-fuzzy.C\n * @ingroup tests\n * @brief no doc\n * @test no doc\n *\/\n\n\n\n#include \"linbox\/linbox-config.h\"\n\n#include \n#include \n\n\n#include \"linbox\/field\/param-fuzzy.h\"\n\n#include \"test-common.h\"\n#include \"test-generic.h\"\n\nusing namespace LinBox;\n\nint main (int argc, char **argv)\n{\n\t\/\/static integer q = 65521U;\n\tstatic size_t n = 10000;\n\tstatic unsigned int iterations = 10;\n\n\tstatic Argument args[] = {\n\t\t{ 'n', \"-n N\", \"Set dimension of test vectors to NxN.\", TYPE_INT, &n },\n\t\t{ 'i', \"-i I\", \"Perform each test for I iterations.\", TYPE_INT, &iterations },\n\t\tEND_OF_ARGUMENTS\n\t};\n\n\tparseArguments (argc, argv, args);\n\n\tbool pass = true;\n\n\tParamFuzzy F(.0000001);\n\n\t\/\/ Make sure some more detailed messages get printed\n\tcommentator().getMessageClass (INTERNAL_DESCRIPTION).setMaxDepth (4);\n\tcommentator().getMessageClass (INTERNAL_DESCRIPTION).setMaxDetailLevel (Commentator::LEVEL_UNIMPORTANT);\n\n\tostream &report = commentator().report (Commentator::LEVEL_IMPORTANT, INTERNAL_DESCRIPTION);\n report << endl << \"ParamFuzzy field approximation test suite\" << endl;\n\n\t\/* I am distressed that this field passes the testField()\n\t We need a test that distinguishes exact fields from\n\t approximate ones. -bds *\/\n\n\tif (!runFieldTests (F, \"ParamFuzzy\", iterations, n, false)) pass = false;\n\n#if 0\n\tFieldArchetype K(new ParamFuzzy(.000001));\n\n\tif (!testField (K, \"Testing archetype with envelope of UnField field\"))\n\t\tpass = false;\n#endif\n\n\tif (!testField (F, \"Testing DoubleRealApproximation field\"))\n\t\tpass = false;\n\n\treturn pass ? 0 : -1;\n\n}\n\n\/\/ vim:sts=8:sw=8:ts=8:noet:sr:cino=>s,f0,{0,g0,(0,:0,t0,+0,=s\n\/\/ Local Variables:\n\/\/ mode: C++\n\/\/ tab-width: 8\n\/\/ indent-tabs-mode: nil\n\/\/ c-basic-offset: 8\n\/\/ End:\n\n test-param-fuzzy: sufficient that it compiles, can't possibly meet field spec.\n\/* tests\/test-param-fuzzy.C\n * Copyright (C) 2002 David Saunders\n * shamelessly mutated from one of the other field tests.\n *\n *\n * ========LICENCE========\n * This file is part of the library LinBox.\n *\n * LinBox is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n * ========LICENCE========\n *.\n *\/\n\n\n\/*! @file tests\/test-param-fuzzy.C\n * @ingroup tests\n * @brief no doc\n * @test no doc\n *\/\n\n\n\n#include \"linbox\/linbox-config.h\"\n\n#include \n#include \n\n\n#include \"linbox\/field\/param-fuzzy.h\"\n\n#include \"test-common.h\"\n#include \"test-generic.h\"\n\nusing namespace LinBox;\n\nint main (int argc, char **argv)\n{\n\t\/\/static integer q = 65521U;\n\tstatic size_t n = 10000;\n\tstatic unsigned int iterations = 10;\n\n\tstatic Argument args[] = {\n\t\t{ 'n', \"-n N\", \"Set dimension of test vectors to NxN.\", TYPE_INT, &n },\n\t\t{ 'i', \"-i I\", \"Perform each test for I iterations.\", TYPE_INT, &iterations },\n\t\tEND_OF_ARGUMENTS\n\t};\n\n\tparseArguments (argc, argv, args);\n\n\tbool pass = true;\n\n\tParamFuzzy F(.0000001);\n\n\t\/\/ Make sure some more detailed messages get printed\n\tcommentator().getMessageClass (INTERNAL_DESCRIPTION).setMaxDepth (4);\n\tcommentator().getMessageClass (INTERNAL_DESCRIPTION).setMaxDetailLevel (Commentator::LEVEL_UNIMPORTANT);\n\n\tostream &report = commentator().report (Commentator::LEVEL_IMPORTANT, INTERNAL_DESCRIPTION);\n report << endl << \"ParamFuzzy field approximation test suite\" << endl;\n\n\t\/* I am distressed that this field passes the testField()\n\t We need a test that distinguishes exact fields from\n\t approximate ones. -bds *\/\n\n\tif (!runFieldTests (F, \"ParamFuzzy\", iterations, n, false)) pass = false;\n\n#if 0\n\tFieldArchetype K(new ParamFuzzy(.000001));\n\n\tif (!testField (K, \"Testing archetype with envelope of UnField field\"))\n\t\tpass = false;\n#endif\n\n\tif (!testField (F, \"Testing DoubleRealApproximation field\"))\n\t\tpass = false;\n\n\t\/\/ Can't meet field spec (e.g. init\/convert from\/to integer),\n\t\/\/ so we accept if field test compiles.\n\treturn pass ? 0 : 0; \/\/-1;\n\n}\n\n\/\/ vim:sts=8:sw=8:ts=8:noet:sr:cino=>s,f0,{0,g0,(0,:0,t0,+0,=s\n\/\/ Local Variables:\n\/\/ mode: C++\n\/\/ tab-width: 8\n\/\/ indent-tabs-mode: nil\n\/\/ c-basic-offset: 8\n\/\/ End:\n\n<|endoftext|>"} {"text":"#include \"mainpatch.h\"\n\n#include \"console\/windows_wrap.h\"\n#include \n\n#include \"patchmanager.h\"\n#include \"memory.h\"\n#include \"offsets.h\"\n#include \"commands.h\"\n#include \"unit.h\"\n#include \"text.h\"\n#include \"selection.h\"\n#include \"order.h\"\n#include \"limits.h\"\n#include \"targeting.h\"\n#include \"draw.h\"\n#include \"scthread.h\"\n#include \"log.h\"\n#include \"unitlist.h\"\n#include \"bullet.h\"\n#include \"ai.h\"\n#include \"triggers.h\"\n#include \"scconsole.h\"\n#include \"bullet.h\"\n#include \"sprite.h\"\n#include \"building.h\"\n#include \"replay.h\"\n#include \"yms.h\"\n#include \"unit_cache.h\"\n#include \"perfclock.h\"\n#include \"common\/log_freeze.h\"\n\nnamespace bw\n{\n namespace storm\n {\n intptr_t base_diff;\n }\n}\n\nvoid WindowCreatedPatch()\n{\n #ifdef CONSOLE\n Common::console->HookWndProc(*bw::main_window_hwnd);\n #endif\n}\n\nvoid WinMainPatch()\n{\n Common::PatchContext patch = patch_mgr->BeginPatch(0, bw::base::starcraft);\n PatchDraw(&patch);\n #ifdef CONSOLE\n PatchConsole();\n Common::console->HookTranslateAccelerator(&patch, bw::base::starcraft);\n #endif\n}\n\nuint32_t GetRngSeed()\n{\n uint32_t seed;\n if (StaticSeed)\n seed = StaticSeed;\n else if (SyncTest)\n seed = 0;\n else\n seed = time(0);\n\n debug_log->Log(\"Rng seed %08x\\n\", seed);\n return seed;\n}\n\nuint32_t __stdcall VersionCheckGuard(uint8_t *a, void *b, void *c, void *d, void *e)\n{\n patch_mgr->Unpatch();\n uint32_t ret = SNetInitializeProvider(a, b, c, d, e);\n patch_mgr->Repatch();\n return ret;\n}\n\nstatic void SavePanickedReplay()\n{\n if (!IsInGame())\n return;\n \/\/ Add some frames (1 should be enough) to make crash surely reproductable\n bw::replay_header[0].replay_end_frame = *bw::frame_count + 50;\n SaveReplay(\"crash\", 1);\n}\n\nstatic LPTOP_LEVEL_EXCEPTION_FILTER previous_exception_filter = nullptr;\nstatic LONG WINAPI ExceptionFilter(EXCEPTION_POINTERS *info)\n{\n LONG result = EXCEPTION_CONTINUE_SEARCH;\n if (previous_exception_filter)\n result = previous_exception_filter(info);\n\n SavePanickedReplay();\n \/\/ Terminate on debug because why not - release crashes properly so people won't get confused\n if (Debug && result != EXCEPTION_CONTINUE_EXECUTION)\n TerminateProcess(GetCurrentProcess(), info->ExceptionRecord->ExceptionCode);\n\n return result;\n}\n\nstruct DetectFreeze\n{\n DetectFreeze() : last_value(draw_counter.load(std::memory_order_acquire)) {}\n bool operator()()\n {\n if (!IsInGame())\n return false;\n uintptr_t new_value = draw_counter.load(std::memory_order_acquire);\n bool frozen = new_value == last_value;\n last_value = new_value;\n return frozen;\n }\n uintptr_t last_value;\n};\n\nstatic void InitFreezeLogging()\n{\n HANDLE thread_handle;\n auto success = DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(),\n &thread_handle, 0, FALSE, DUPLICATE_SAME_ACCESS);\n if (success == 0)\n {\n char buf[64];\n auto error = GetLastError();\n snprintf(buf, sizeof buf, \"DuplicateHandle: %x (%d)\", error, error);\n \/\/ Show a noisy error instead of easily missed log line\n MessageBoxA(0, buf, \"InitFreezeLogging failed\", 0);\n }\n else\n {\n new FreezeLogger(thread_handle, \"Errors\/freeze.log\", DetectFreeze(), [](const std::string &msg) {\n MessageBoxA(0, \"InitFreezeLogging failed\", msg.c_str(), 0);\n });\n }\n}\n\nvoid InitialPatch()\n{\n InitLogs();\n InitSystemInfo();\n InitPerfClockFrequency();\n InitFreezeLogging();\n\n threads = new ThreadPool;\n threads->Init(sysinfo.dwNumberOfProcessors * 2);\n int thread_count = threads->GetThreadCount();\n perf_log->Log(\"Thread amount: %d\\n\", thread_count);\n\n patch_mgr = new Common::PatchManager;\n Common::PatchContext patch = patch_mgr->BeginPatch(nullptr, bw::base::starcraft);\n\n patch.Patch(bw::WinMain, (void *)&WinMainPatch, 0, PATCH_HOOKBEFORE | PATCH_CALLHOOK);\n patch.Patch(bw::WindowCreated, (void *)&WindowCreatedPatch, 0, PATCH_HOOKBEFORE | PATCH_SAFECALLHOOK);\n\n PatchProcessCommands(&patch);\n PatchSelection(&patch);\n PatchTargeting(&patch);\n RemoveLimits(&patch);\n patch.Patch(bw::RngSeedPatch, 0, 9, PATCH_NOP);\n patch.Patch(bw::RngSeedPatch, (void *)&GetRngSeed, 0, PATCH_CALLHOOK);\n patch.JumpHook(bw::UpdateBuildingPlacementState, UpdateBuildingPlacementState);\n\n Common::PatchContext storm_patch = patch_mgr->BeginPatch(\"storm\", bw::base::storm);\n bw::storm::base_diff = storm_patch.GetDiff();\n \/\/ #117 is SNetInitializeProvider\n storm_patch.Patch((void *)GetProcAddress(GetModuleHandle(\"storm\"), (char *)117), (void *)&VersionCheckGuard, 0, PATCH_JMPHOOK);\n\n if (UseConsole)\n patch.JumpHook(bw::GenerateFog, GenerateFog);\n\n bullet_system = new BulletSystem;\n lone_sprites = new LoneSpriteSystem;\n enemy_unit_cache = new EnemyUnitCache;\n\n previous_exception_filter = SetUnhandledExceptionFilter(&ExceptionFilter);\n}\nCreate unique win32 event that can be used to tell if the hack is applied#include \"mainpatch.h\"\n\n#include \"console\/windows_wrap.h\"\n#include \n\n#include \"patchmanager.h\"\n#include \"memory.h\"\n#include \"offsets.h\"\n#include \"commands.h\"\n#include \"unit.h\"\n#include \"text.h\"\n#include \"selection.h\"\n#include \"order.h\"\n#include \"limits.h\"\n#include \"targeting.h\"\n#include \"draw.h\"\n#include \"scthread.h\"\n#include \"log.h\"\n#include \"unitlist.h\"\n#include \"bullet.h\"\n#include \"ai.h\"\n#include \"triggers.h\"\n#include \"scconsole.h\"\n#include \"bullet.h\"\n#include \"sprite.h\"\n#include \"building.h\"\n#include \"replay.h\"\n#include \"yms.h\"\n#include \"unit_cache.h\"\n#include \"perfclock.h\"\n#include \"common\/log_freeze.h\"\n\nnamespace bw\n{\n namespace storm\n {\n intptr_t base_diff;\n }\n}\n\nvoid WindowCreatedPatch()\n{\n #ifdef CONSOLE\n Common::console->HookWndProc(*bw::main_window_hwnd);\n #endif\n}\n\nvoid WinMainPatch()\n{\n Common::PatchContext patch = patch_mgr->BeginPatch(0, bw::base::starcraft);\n PatchDraw(&patch);\n #ifdef CONSOLE\n PatchConsole();\n Common::console->HookTranslateAccelerator(&patch, bw::base::starcraft);\n #endif\n}\n\nuint32_t GetRngSeed()\n{\n uint32_t seed;\n if (StaticSeed)\n seed = StaticSeed;\n else if (SyncTest)\n seed = 0;\n else\n seed = time(0);\n\n debug_log->Log(\"Rng seed %08x\\n\", seed);\n return seed;\n}\n\nuint32_t __stdcall VersionCheckGuard(uint8_t *a, void *b, void *c, void *d, void *e)\n{\n patch_mgr->Unpatch();\n uint32_t ret = SNetInitializeProvider(a, b, c, d, e);\n patch_mgr->Repatch();\n return ret;\n}\n\nstatic void SavePanickedReplay()\n{\n if (!IsInGame())\n return;\n \/\/ Add some frames (1 should be enough) to make crash surely reproductable\n bw::replay_header[0].replay_end_frame = *bw::frame_count + 50;\n SaveReplay(\"crash\", 1);\n}\n\nstatic LPTOP_LEVEL_EXCEPTION_FILTER previous_exception_filter = nullptr;\nstatic LONG WINAPI ExceptionFilter(EXCEPTION_POINTERS *info)\n{\n LONG result = EXCEPTION_CONTINUE_SEARCH;\n if (previous_exception_filter)\n result = previous_exception_filter(info);\n\n SavePanickedReplay();\n \/\/ Terminate on debug because why not - release crashes properly so people won't get confused\n if (Debug && result != EXCEPTION_CONTINUE_EXECUTION)\n TerminateProcess(GetCurrentProcess(), info->ExceptionRecord->ExceptionCode);\n\n return result;\n}\n\nstruct DetectFreeze\n{\n DetectFreeze() : last_value(draw_counter.load(std::memory_order_acquire)) {}\n bool operator()()\n {\n if (!IsInGame())\n return false;\n uintptr_t new_value = draw_counter.load(std::memory_order_acquire);\n bool frozen = new_value == last_value;\n last_value = new_value;\n return frozen;\n }\n uintptr_t last_value;\n};\n\nstatic void InitFreezeLogging()\n{\n HANDLE thread_handle;\n auto success = DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(),\n &thread_handle, 0, FALSE, DUPLICATE_SAME_ACCESS);\n if (success == 0)\n {\n char buf[64];\n auto error = GetLastError();\n snprintf(buf, sizeof buf, \"DuplicateHandle: %x (%d)\", error, error);\n \/\/ Show a noisy error instead of easily missed log line\n MessageBoxA(0, buf, \"InitFreezeLogging failed\", 0);\n }\n else\n {\n new FreezeLogger(thread_handle, \"Errors\/freeze.log\", DetectFreeze(), [](const std::string &msg) {\n MessageBoxA(0, \"InitFreezeLogging failed\", msg.c_str(), 0);\n });\n }\n}\n\nstatic void CreateIdentifyingEvent()\n{\n char buf[32];\n auto pid = GetCurrentProcessId();\n snprintf(buf, sizeof buf, \"Teippi #%d\", pid);\n CreateEventA(NULL, FALSE, FALSE, buf);\n if (GetLastError() == ERROR_ALREADY_EXISTS)\n {\n \/\/ Maybe should silently abort patching?\n MessageBoxA(0, \"Second copy of Teippi has been loaded to same process.\\n\\\nCrashing is very likely.\", \"Very important warning\", 0);\n }\n}\n\nvoid InitialPatch()\n{\n CreateIdentifyingEvent();\n InitLogs();\n InitSystemInfo();\n InitPerfClockFrequency();\n InitFreezeLogging();\n\n threads = new ThreadPool;\n threads->Init(sysinfo.dwNumberOfProcessors * 2);\n int thread_count = threads->GetThreadCount();\n perf_log->Log(\"Thread amount: %d\\n\", thread_count);\n\n patch_mgr = new Common::PatchManager;\n Common::PatchContext patch = patch_mgr->BeginPatch(nullptr, bw::base::starcraft);\n\n patch.Patch(bw::WinMain, (void *)&WinMainPatch, 0, PATCH_HOOKBEFORE | PATCH_CALLHOOK);\n patch.Patch(bw::WindowCreated, (void *)&WindowCreatedPatch, 0, PATCH_HOOKBEFORE | PATCH_SAFECALLHOOK);\n\n PatchProcessCommands(&patch);\n PatchSelection(&patch);\n PatchTargeting(&patch);\n RemoveLimits(&patch);\n patch.Patch(bw::RngSeedPatch, 0, 9, PATCH_NOP);\n patch.Patch(bw::RngSeedPatch, (void *)&GetRngSeed, 0, PATCH_CALLHOOK);\n patch.JumpHook(bw::UpdateBuildingPlacementState, UpdateBuildingPlacementState);\n\n Common::PatchContext storm_patch = patch_mgr->BeginPatch(\"storm\", bw::base::storm);\n bw::storm::base_diff = storm_patch.GetDiff();\n \/\/ #117 is SNetInitializeProvider\n storm_patch.Patch((void *)GetProcAddress(GetModuleHandle(\"storm\"), (char *)117), (void *)&VersionCheckGuard, 0, PATCH_JMPHOOK);\n\n if (UseConsole)\n patch.JumpHook(bw::GenerateFog, GenerateFog);\n\n bullet_system = new BulletSystem;\n lone_sprites = new LoneSpriteSystem;\n enemy_unit_cache = new EnemyUnitCache;\n\n previous_exception_filter = SetUnhandledExceptionFilter(&ExceptionFilter);\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"..\/algorithm.h\"\n#include \"..\/parallel.h\"\n#include \"..\/sequence.h\"\n#include \"..\/async.h\"\n#include \"..\/task.h\"\n\nclass Parallel2Test : testing::Test { };\n\nTEST(Parallel2Test, Test1)\n{\n\tstd::future f1 = asyncply::_async([](int data){return data;}, 10);\n\tASSERT_EQ(f1.get(), 10);\n}\n\nTEST(Parallel2Test, Test2)\n{\n\tauto f1 = asyncply::async([](){return 15;});\n\tauto f2 = f1->then([](int data) {\n\t\tstd::cout << \"post, received: \" << data << std::endl;\n\t\treturn data + 6;\n\t});\n\tASSERT_EQ(f2->get(), 15 + 6);\n}\n\nTEST(Parallel2Test, Test3)\n{\n\tstd::vector a;\n\tfor(int i=0; i<100; ++i)\n\t{\n\t\ta.push_back(1);\n\t\ta.push_back(4);\n\t\ta.push_back(12);\n\t\ta.push_back(-3);\n\t\ta.push_back(22);\n\t}\n\tstd::atomic total;\n\ttotal = 0;\n\tasyncply::for_each_sync(a.begin(), a.end(), [&total](int i) {\n\t\ttotal += i;\n\t});\n\tASSERT_EQ(total, 3600);\n}\n\nTEST(Parallel2Test, Test3_async)\n{\n\tstd::vector a;\n\tfor(int i=0; i<100; ++i)\n\t{\n\t\ta.push_back(1);\n\t\ta.push_back(4);\n\t\ta.push_back(12);\n\t\ta.push_back(-3);\n\t\ta.push_back(22);\n\t}\n\tstd::atomic total;\n\ttotal = 0;\n\tauto task = asyncply::for_each(a.begin(), a.end(), [&total](int i) {\n\t\ttotal += i;\n\t});\n\ttask->get();\n\tASSERT_EQ(total, 3600);\n}\n\nTEST(Parallel2Test, Test4)\n{\n\tdouble total_ps = asyncply::parallel_sync(\n\t\t[]()\n\t\t{\n\t\t\treturn asyncply::sequence(1.0,\n\t\t\t\t[](double data)\n\t\t\t\t{\n\t\t\t\t\treturn data + 1.0;\n\t\t\t\t},\n\t\t\t\t[](double data)\n\t\t\t\t{\n\t\t\t\t\treturn data + 1.0;\n\t\t\t\t});\n\t\t},\n\t\t[]()\n\t\t{\n\t\t\treturn asyncply::sequence(1.0,\n\t\t\t\t[](double data)\n\t\t\t\t{\n\t\t\t\t\treturn data + 1.0;\n\t\t\t\t},\n\t\t\t\t[](double data)\n\t\t\t\t{\n\t\t\t\t\treturn data + 1.0;\n\t\t\t\t});\n\t\t}\n\t);\n\tASSERT_EQ(total_ps, 6);\n}\n\nTEST(Parallel2Test, Test5)\n{\n\tstd::atomic total;\n\ttotal = 0;\n\tauto process = asyncply::parallel(\n\t\t\t\t[&total]()\n\t\t\t\t{\n\t\t\t\t\tstd::cout << \"hi\" << std::endl;\n\t\t\t\t\ttotal += 1;\n\t\t\t\t},\n\t\t\t\t[&total]()\n\t\t\t\t{\n\t\t\t\t\tstd::cout << \"bye\" << std::endl;\n\t\t\t\t\ttotal += 1;\n\t\t\t\t}\n\t\t\t);\n\tauto process2 = process->then([&total]()\n\t\t\t{\n\t\t\t\tstd::cout << \"no accum\" << std::endl;\n\t\t\t\ttotal += 1;\n\t\t\t});\n\tprocess2->get();\n\tASSERT_EQ(total, 3);\n}\n\nTEST(Parallel2Test, Test6)\n{\n\tstd::atomic total;\n\ttotal = 0;\n\t{\n\t\tauto process = asyncply::parallel(\n\t\t\t\t\t[&total]()\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::cout << \"hi\" << std::endl;\n\t\t\t\t\t\ttotal += 1;\n\t\t\t\t\t},\n\t\t\t\t\t[&total]()\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::cout << \"bye\" << std::endl;\n\t\t\t\t\t\ttotal += 1;\n\t\t\t\t\t}\n\t\t\t\t);\n\t\tauto process_then = process->then([&total]()\n\t\t\t\t{\n\t\t\t\t\tstd::cout << \"no accum\" << std::endl;\n\t\t\t\t\ttotal += 1;\n\t\t\t\t});\n\t\tprocess_then->get();\n\t}\n\tASSERT_EQ(total, 3);\n}\nUpdate test_parallel2.cpp#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"..\/algorithm.h\"\n#include \"..\/parallel.h\"\n#include \"..\/sequence.h\"\n#include \"..\/async.h\"\n#include \"..\/task.h\"\n\nclass Parallel2Test : testing::Test { };\n\nTEST(Parallel2Test, Test1)\n{\n\tstd::future f1 = asyncply::_async([](int data){return data;}, 10);\n\tASSERT_EQ(f1.get(), 10);\n}\n\nTEST(Parallel2Test, Test2)\n{\n\tauto f1 = asyncply::async([](){return 15;});\n\tauto f2 = f1->then([](int data) {\n\t\tstd::cout << \"post, received: \" << data << std::endl;\n\t\treturn data + 6;\n\t});\n\tASSERT_EQ(f2->get(), 15 + 6);\n}\n\nTEST(Parallel2Test, Test3)\n{\n\tstd::vector a;\n\tfor(int i=0; i<100; ++i)\n\t{\n\t\ta.push_back(1);\n\t\ta.push_back(4);\n\t\ta.push_back(12);\n\t\ta.push_back(-3);\n\t\ta.push_back(22);\n\t}\n\tstd::atomic total;\n\ttotal = 0;\n\tasyncply::for_each_sync(a.begin(), a.end(), [&total](int i) {\n\t\ttotal += i;\n\t});\n\tASSERT_EQ(total, 3600);\n}\n\nTEST(Parallel2Test, Test3_async)\n{\n\tstd::vector a;\n\tfor(int i=0; i<100; ++i)\n\t{\n\t\ta.push_back(1);\n\t\ta.push_back(4);\n\t\ta.push_back(12);\n\t\ta.push_back(-3);\n\t\ta.push_back(22);\n\t}\n\tstd::atomic total;\n\ttotal = 0;\n\tauto task = asyncply::for_each(a.begin(), a.end(), [&total](int i) {\n\t\ttotal += i;\n\t});\n\ttask->get();\n\tASSERT_EQ(total, 3600);\n}\n\nTEST(Parallel2Test, collapse_double)\n{\n\tdouble total_ps = asyncply::parallel_sync(\n\t\t[]()\n\t\t{\n\t\t\treturn asyncply::sequence(1.0,\n\t\t\t\t[](double data)\n\t\t\t\t{\n\t\t\t\t\treturn data + 1.0;\n\t\t\t\t},\n\t\t\t\t[](double data)\n\t\t\t\t{\n\t\t\t\t\treturn data + 1.0;\n\t\t\t\t});\n\t\t},\n\t\t[]()\n\t\t{\n\t\t\treturn asyncply::sequence(1.0,\n\t\t\t\t[](double data)\n\t\t\t\t{\n\t\t\t\t\treturn data + 1.0;\n\t\t\t\t},\n\t\t\t\t[](double data)\n\t\t\t\t{\n\t\t\t\t\treturn data + 1.0;\n\t\t\t\t});\n\t\t}\n\t);\n\tASSERT_EQ(total_ps, 6);\n}\n\nTEST(Parallel2Test, collapse_bool)\n{\n\tbool result = asyncply::parallel_sync(\n\t\t[]()\n\t\t{\n\t\t\treturn asyncply::sequence(true,\n\t\t\t\t[](bool data)\n\t\t\t\t{\n\t\t\t\t\treturn data;\n\t\t\t\t},\n\t\t\t\t[](bool data)\n\t\t\t\t{\n\t\t\t\t\treturn data;\n\t\t\t\t});\n\t\t},\n\t\t[]()\n\t\t{\n\t\t\treturn asyncply::sequence(false,\n\t\t\t\t[](bool data)\n\t\t\t\t{\n\t\t\t\t\treturn data;\n\t\t\t\t},\n\t\t\t\t[](bool data)\n\t\t\t\t{\n\t\t\t\t\treturn data;\n\t\t\t\t});\n\t\t}\n\t);\n\tASSERT_EQ(result, false);\n}\n\nTEST(Parallel2Test, Test5)\n{\n\tstd::atomic total;\n\ttotal = 0;\n\tauto process = asyncply::parallel(\n\t\t\t\t[&total]()\n\t\t\t\t{\n\t\t\t\t\tstd::cout << \"hi\" << std::endl;\n\t\t\t\t\ttotal += 1;\n\t\t\t\t},\n\t\t\t\t[&total]()\n\t\t\t\t{\n\t\t\t\t\tstd::cout << \"bye\" << std::endl;\n\t\t\t\t\ttotal += 1;\n\t\t\t\t}\n\t\t\t);\n\tauto process2 = process->then([&total]()\n\t\t\t{\n\t\t\t\tstd::cout << \"no accum\" << std::endl;\n\t\t\t\ttotal += 1;\n\t\t\t});\n\tprocess2->get();\n\tASSERT_EQ(total, 3);\n}\n\nTEST(Parallel2Test, Test6)\n{\n\tstd::atomic total;\n\ttotal = 0;\n\t{\n\t\tauto process = asyncply::parallel(\n\t\t\t\t\t[&total]()\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::cout << \"hi\" << std::endl;\n\t\t\t\t\t\ttotal += 1;\n\t\t\t\t\t},\n\t\t\t\t\t[&total]()\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::cout << \"bye\" << std::endl;\n\t\t\t\t\t\ttotal += 1;\n\t\t\t\t\t}\n\t\t\t\t);\n\t\tauto process_then = process->then([&total]()\n\t\t\t\t{\n\t\t\t\t\tstd::cout << \"no accum\" << std::endl;\n\t\t\t\t\ttotal += 1;\n\t\t\t\t});\n\t\tprocess_then->get();\n\t}\n\tASSERT_EQ(total, 3);\n}\n<|endoftext|>"} {"text":"#include \n\nint main(){\n char o;\n int i, j, c;\n float s = 0.0, n;\n scanf(\"%d\", &c);\n scanf(\"%s\", &o);\n for (i = 0; i <= 11; i++){\n for (j = 0; j <= 11; j++){\n scanf(\"%f\", &n);\n if (j == c){\n s += n;\n }\n }\n }\n if (o == 'S')\n printf(\"%.1f\\n\", s);\n else\n printf(\"%.1f\\n\", s \/ 12);\n return 0;\n}\nCorrige e reformata.#include \n\nint main() {\n char o;\n int i, j, c;\n float s = 0.0, n;\n\n scanf(\"%d \", &c);\n scanf(\"%c\", &o);\n\n for (i = 0; i <= 11; i++) {\n for (j = 0; j <= 11; j++) {\n scanf(\"%f\", &n);\n if (j == c) s += n;\n }\n }\n\n if (o == 'S') printf(\"%.1f\\n\", s);\n else printf(\"%.1f\\n\", s \/ 12);\n\n return 0;\n}\n<|endoftext|>"} {"text":"\n#include \"LightApp_ShowHideOp.h\"\n#include \"LightApp_Application.h\"\n#include \"LightApp_DataOwner.h\"\n#include \"LightApp_Module.h\"\n#include \"LightApp_Study.h\"\n#include \"LightApp_Displayer.h\"\n#include \"CAM_Study.h\"\n\n#include \"LightApp_SelectionMgr.h\"\n#include \"LightApp_Selection.h\"\n\n#include \n#include \n\nLightApp_ShowHideOp::LightApp_ShowHideOp( ActionType type )\n: LightApp_Operation(),\n myActionType( type )\n{\n}\n\nLightApp_ShowHideOp::~LightApp_ShowHideOp()\n{\n}\n\nLightApp_Displayer* LightApp_ShowHideOp::displayer( const QString& mod_name ) const\n{\n LightApp_Application* app = dynamic_cast( application() );\n LightApp_Module* m = dynamic_cast( app ? app->module( mod_name ) : 0 );\n if( !m )\n {\n m = dynamic_cast( app->loadModule( mod_name ) );\n if( m )\n app->addModule( m );\n }\n\n if( m )\n {\n m->connectToStudy( dynamic_cast( app->activeStudy() ) );\n m->setMenuShown( false );\n m->setToolShown( false );\n }\n return m ? m->displayer() : 0;\n}\n\nvoid LightApp_ShowHideOp::startOperation()\n{\n LightApp_Application* app = dynamic_cast( application() );\n LightApp_Study* study = app ? dynamic_cast( app->activeStudy() ) : 0;\n if( !app || !study )\n {\n abort();\n return;\n }\n\n LightApp_SelectionMgr* mgr = app->selectionMgr();\n LightApp_Selection sel; sel.init( \"\", mgr );\n if( sel.count()==0 && myActionType!=ERASE_ALL )\n {\n abort();\n return;\n }\n QString aStr = sel.param( 0, \"component\" ).toString();\n QString mod_name = app->moduleTitle( aStr );\/\/sel.param( 0, \"component\" ).toString() );\n LightApp_Displayer* d = displayer( mod_name );\n if( !d )\n {\n abort();\n return;\n }\n\n if( myActionType==DISPLAY_ONLY || myActionType==ERASE_ALL )\n {\n \/\/ERASE ALL\n QStringList comps;\n study->components( comps );\n QStringList::const_iterator anIt = comps.begin(), aLast = comps.end();\n for( ; anIt!=aLast; anIt++ )\n {\n LightApp_Displayer* disp = displayer( app->moduleTitle( *anIt ) );\n if( disp )\n\tdisp->EraseAll( false, false, 0 );\n }\n if( myActionType==ERASE_ALL )\n {\n d->UpdateViewer();\n commit();\n return;\n }\n }\n\n SALOME_ListIO selObjs;\n mgr->selectedObjects( selObjs );\n\n QStringList entries;\n SALOME_ListIteratorOfListIO anIt( selObjs );\n for( ; anIt.More(); anIt.Next() )\n {\n if( anIt.Value().IsNull() )\n continue;\n\n if( study->isComponent( anIt.Value()->getEntry() ) )\n study->children( anIt.Value()->getEntry(), entries );\n else\n entries.append( anIt.Value()->getEntry() );\n }\n\n for( QStringList::const_iterator it = entries.begin(), last = entries.end(); it!=last; it++ )\n {\n QString e = study->referencedToEntry( *it );\n if( myActionType==DISPLAY || myActionType==DISPLAY_ONLY )\n d->Display( e, false, 0 );\n else if( myActionType==ERASE )\n d->Erase( e, false, false, 0 );\n }\n d->UpdateViewer();\n commit();\n}\nPAL10533 - main menu is changed after DisplayOnly operation for object from other module\n#include \"LightApp_ShowHideOp.h\"\n#include \"LightApp_Application.h\"\n#include \"LightApp_DataOwner.h\"\n#include \"LightApp_Module.h\"\n#include \"LightApp_Study.h\"\n#include \"LightApp_Displayer.h\"\n#include \"CAM_Study.h\"\n\n#include \"LightApp_SelectionMgr.h\"\n#include \"LightApp_Selection.h\"\n\n#include \n#include \n\nLightApp_ShowHideOp::LightApp_ShowHideOp( ActionType type )\n: LightApp_Operation(),\n myActionType( type )\n{\n}\n\nLightApp_ShowHideOp::~LightApp_ShowHideOp()\n{\n}\n\nLightApp_Displayer* LightApp_ShowHideOp::displayer( const QString& mod_name ) const\n{\n LightApp_Application* app = dynamic_cast( application() );\n LightApp_Module* m = dynamic_cast( app ? app->module( mod_name ) : 0 );\n if( !m )\n {\n m = dynamic_cast( app->loadModule( mod_name ) );\n if( m )\n app->addModule( m );\n }\n\n if( m )\n {\n m->connectToStudy( dynamic_cast( app->activeStudy() ) );\n if( m!=app->activeModule() )\n {\n m->setMenuShown( false );\n m->setToolShown( false );\n }\n }\n return m ? m->displayer() : 0;\n}\n\nvoid LightApp_ShowHideOp::startOperation()\n{\n LightApp_Application* app = dynamic_cast( application() );\n LightApp_Study* study = app ? dynamic_cast( app->activeStudy() ) : 0;\n if( !app || !study )\n {\n abort();\n return;\n }\n\n LightApp_SelectionMgr* mgr = app->selectionMgr();\n LightApp_Selection sel; sel.init( \"\", mgr );\n if( sel.count()==0 && myActionType!=ERASE_ALL )\n {\n abort();\n return;\n }\n QString aStr = sel.param( 0, \"component\" ).toString();\n QString mod_name = app->moduleTitle( aStr );\/\/sel.param( 0, \"component\" ).toString() );\n LightApp_Displayer* d = displayer( mod_name );\n if( !d )\n {\n abort();\n return;\n }\n\n if( myActionType==DISPLAY_ONLY || myActionType==ERASE_ALL )\n {\n \/\/ERASE ALL\n QStringList comps;\n study->components( comps );\n QStringList::const_iterator anIt = comps.begin(), aLast = comps.end();\n for( ; anIt!=aLast; anIt++ )\n {\n LightApp_Displayer* disp = displayer( app->moduleTitle( *anIt ) );\n if( disp )\n\tdisp->EraseAll( false, false, 0 );\n }\n if( myActionType==ERASE_ALL )\n {\n d->UpdateViewer();\n commit();\n return;\n }\n }\n\n SALOME_ListIO selObjs;\n mgr->selectedObjects( selObjs );\n\n QStringList entries;\n SALOME_ListIteratorOfListIO anIt( selObjs );\n for( ; anIt.More(); anIt.Next() )\n {\n if( anIt.Value().IsNull() )\n continue;\n\n if( study->isComponent( anIt.Value()->getEntry() ) )\n study->children( anIt.Value()->getEntry(), entries );\n else\n entries.append( anIt.Value()->getEntry() );\n }\n\n for( QStringList::const_iterator it = entries.begin(), last = entries.end(); it!=last; it++ )\n {\n QString e = study->referencedToEntry( *it );\n if( myActionType==DISPLAY || myActionType==DISPLAY_ONLY )\n d->Display( e, false, 0 );\n else if( myActionType==ERASE )\n d->Erase( e, false, false, 0 );\n }\n d->UpdateViewer();\n commit();\n}\n<|endoftext|>"} {"text":"\/******************************************************************\n*\n* Round for C++\n*\n* Copyright (C) Satoshi Konno 2015\n*\n* This is licensed under BSD-style license, see file COPYING.\n*\n******************************************************************\/\n\n#include \n#include \n\nBOOST_AUTO_TEST_CASE(MutexTest) {\n RoundMutex *mutex;\n \n mutex = round_mutex_new();\n BOOST_CHECK(mutex);\n BOOST_CHECK(round_mutex_lock(mutex));\n BOOST_CHECK(round_mutex_unlock(mutex));\n BOOST_CHECK(round_mutex_delete(mutex));\n}\n* Added tests for mutex functions.\/******************************************************************\n*\n* Round for C++\n*\n* Copyright (C) Satoshi Konno 2015\n*\n* This is licensed under BSD-style license, see file COPYING.\n*\n******************************************************************\/\n\n#include \n#include \n\nBOOST_AUTO_TEST_CASE(MutexTest)\n{\n RoundMutex *mutex;\n \n mutex = round_mutex_new();\n BOOST_CHECK(mutex);\n BOOST_CHECK(round_mutex_lock(mutex));\n BOOST_CHECK(round_mutex_unlock(mutex));\n BOOST_CHECK(round_mutex_delete(mutex));\n}\n<|endoftext|>"} {"text":"#include \"llvm\/ADT\/APInt.h\"\n#include \"llvm\/IR\/ConstantRange.h\"\n#include \"llvm\/IR\/IRBuilder.h\"\n#include \"llvm\/IR\/LLVMContext.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/IR\/NoFolder.h\"\n#include \"llvm\/IR\/Type.h\"\n#include \"llvm\/IR\/Verifier.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \n#include \n#include \n\nusing namespace llvm;\nusing namespace std;\n\nstatic LLVMContext C;\nstatic IRBuilder Builder(C);\nstatic std::unique_ptr M = llvm::make_unique(\"calc\", C);\nstatic ifstream gInFile;\nchar gCurValue = -1;\nint gArgsLen = 6;\nint gLineNo = 1;\nenum oper {ADD = 0, SUB, MUL, DIV, MOD};\nbool debug = true;\n\nvoid parseExpression();\nvoid skipSpaces();\n\nvoid usage(void) {\n printf(\"executable \\r\\n\");\n return;\n}\n\nbool openFile(int argc, char **argv) {\n if (argc < 2) {\n usage();\n return false;\n }\n gInFile.open (argv[1], ifstream::in);\n return true;\n}\n\nchar getChar() {\n return gCurValue;\n}\n\nvoid nextChar(void) {\n if (!gInFile.eof()) {\n gCurValue = gInFile.get();\n } else {\n gCurValue = EOF;\n }\n} \n\nchar getnextChar() {\n nextChar();\n return gCurValue;\n}\n\nbool accept(char c) {\n if (getChar() == c) {\n nextChar();\n return true;\n }\n return false;\n}\n\nbool check(char c) {\n if (getChar() == c) {\n return true;\n }\n return false;\n}\n\nstring getContext() {\n string context;\n getline(gInFile, context);\n return context;\n}\n\nvoid printError() {\n printf (\"Invalid statement at LineNo:%d:%d - %s\",\n gLineNo, (int)gInFile.tellg(), getContext().c_str());\n exit(0);\n}\n\nvoid printError(const char *c) {\n printf(\"Unable to compile due to error %s at Line: %d FilePosition:%d \\r\\n\",\n c, gLineNo, (int)gInFile.tellg());\n printf(\"Remaining Code: %s\", getContext().c_str());\n exit(0);\n}\n\nvoid parseComment() {\n if (debug) {\n printf(\"Enter %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n while (getnextChar() != '\\n');\n if (debug) {\n printf(\"Exit %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n}\n\nvoid parseArgs() {\n char errmsg[50];\n if (debug) {\n printf(\"Enter %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n int i;\n \/\/Move the pointer next to a\n getnextChar();\n for (i = 0; i < gArgsLen; i++) {\n if (accept('0' + (i - 0))) { \/\/Change from int to char\n break;\n } \n }\n if (i == gArgsLen) {\n sprintf(errmsg, \"Invalid argument (a%c) used in the program\", \n getChar());\n printError(errmsg);\n }\n getnextChar();\n if (debug) {\n printf(\"Exit %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n}\n\n\/\/Guess this should return an LLVM object\nvoid parseArithmeticOperation() {\n if (debug) {\n printf(\"Enter %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n char oper = getChar();\n parseExpression();\n parseExpression();\n \/\/Get Oper1\n \/\/Oper1 = parseExpression();\n \/\/Oper2 = parseExpression();\n if (debug) {\n printf(\"Exit %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n}\n\nvoid parseNumber() {\n if (debug) {\n printf(\"Enter %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n int num = 0, count = 0;\n char ch = getChar();\n while ((ch >= 0) && (ch <= 9)) {\n num = (num * 10 * count++) + (0 + (ch - '0'));\n }\n \/\/changed the int to number;\n if (debug) {\n printf(\"Exit %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n}\n\nvoid parseRelationalOperation() {\n if (debug) {\n printf(\"Enter %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n\n if (accept('>')) {\n \/\/This is greater than\n if (accept('=')) {\n \/\/This is greater than equals \n }\n } else if (accept('<')) {\n \/\/This is less than\n if (accept('=')) {\n \/\/This is less than equals \n }\n } else if (accept('!') && accept('=')) {\n \/\/This is not equal to\n } else if (accept('=') && accept('=')) {\n \/\/This is double equals \n }\n parseExpression();\n parseExpression();\n if (debug) {\n printf(\"Exit %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n}\n\nvoid parseBoolExpression() {\n if (debug) {\n printf(\"Enter %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n\n skipSpaces();\n\n char ch = getnextChar();\n\n if (accept('t') && accept('r') && accept('u') && accept('e')) {\n \/\/Its a true condition\n } else if (accept('f') && accept('a') && accept('l') \n && accept('s') && accept('e')) {\n \/\/Its a false condition\n } else if ((ch == '>') || (ch == '<') || (ch == '=') || \n (ch == '!')) {\n parseRelationalOperation(); \n } else if (ch == ('(')) {\n parseBoolExpression();\n if (accept(')') == false) {\n printError(\"Missing ) Paranthesis in boolean exp\");\n }\n }\n\n if (debug) {\n printf(\"Exit %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n}\n\nvoid parseIf() {\n if (debug) {\n printf(\"Enter %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n if (accept('i') && accept('f')) {\n \/\/Move till you find the ( of the bool expression\n parseBoolExpression();\n parseExpression();\n parseExpression();\n } else {\n printError();\n }\n if (debug) {\n printf(\"Exit %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n}\n\nvoid skipSpaces() {\n if (debug) {\n printf(\"Enter %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n\n while (true) {\n if (accept(' ')) {\n continue;\n } else if (accept('\\n')) {\n gLineNo++;\n continue;\n }\n break;\n }\n\n if (debug) {\n printf(\"Exit %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n}\n\n\/* This function is called with the current pointer\n * at ( *\/\nvoid parseExpression() {\n char errmsg[75];\n if (debug) {\n printf(\"Enter %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n\n skipSpaces();\n\n char ch = getChar();\n\n while (ch != EOF) {\n if (ch == '#') {\n parseComment();\n getnextChar();\n } else if (ch == 'a') {\n parseArgs();\n break;\n } else if (ch == '\\n') {\n \/\/Increment the line number, so that we can give a \n \/\/meaningful error message\n gLineNo++;\n } else if (ch == ' ') {\n \/\/Ignore White space\n } else if ((ch == '+') || (ch == '-') || (ch == '*') || \n (ch == '\/') || (ch == '%')) {\n parseArithmeticOperation(); \n break;\n } else if ((ch >= 0) && (ch <= 9)) {\n return parseNumber();\n } else if (ch == '(') {\n getnextChar();\n return parseExpression();\n if (check(')') == false) {\n printError(\"Missing Matching paranthesis\");\n }\n } else if (ch == 'i') {\n parseIf();\n break;\n } else if (ch == ')') {\n getnextChar();\n break;\n } else {\n printError();\n }\n ch = getnextChar();\n }\n if (debug) {\n printf(\"Exit %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n}\n\nvoid parser() {\n if (debug) {\n printf(\"Enter %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n char ch = getnextChar();\n while(ch != EOF) {\n if (ch == '#') {\n parseComment();\n } else {\n parseExpression();\n skipSpaces();\n if (getChar() == EOF) {\n break;\n } else {\n printError();\n }\n }\n ch = getnextChar();\n }\n printf(\"Parsed successfully\\r\\n\");\n if (debug) {\n printf(\"Exit %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n}\n\nstatic int compile() {\n M->setTargetTriple(llvm::sys::getProcessTriple());\n std::vector SixInts(6, Type::getInt64Ty(C));\n FunctionType *FT = FunctionType::get(Type::getInt64Ty(C), SixInts, false);\n Function *F = Function::Create(FT, Function::ExternalLinkage, \"f\", &*M);\n BasicBlock *BB = BasicBlock::Create(C, \"entry\", F);\n Builder.SetInsertPoint(BB);\n\n \/\/ TODO: parse the source program\n \/\/ TODO: generate correct LLVM instead of just an empty function\n\n Value *RetVal = ConstantInt::get(C, APInt(64, 0));\n Builder.CreateRet(RetVal);\n assert(verifyModule(*M));\n M->dump();\n return 0;\n}\n\nint main(int argc, char **argv) { \n if (openFile(argc, argv) == true) {\n parser();\n \/\/return compile(); \n } \n return -1;\n}\nparser mostly working#include \"llvm\/ADT\/APInt.h\"\n#include \"llvm\/IR\/ConstantRange.h\"\n#include \"llvm\/IR\/IRBuilder.h\"\n#include \"llvm\/IR\/LLVMContext.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/IR\/NoFolder.h\"\n#include \"llvm\/IR\/Type.h\"\n#include \"llvm\/IR\/Verifier.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \n#include \n#include \n\nusing namespace llvm;\nusing namespace std;\n\nstatic LLVMContext C;\nstatic IRBuilder Builder(C);\nstatic std::unique_ptr M = llvm::make_unique(\"calc\", C);\nstatic ifstream gInFile;\nchar gCurValue = -1;\nint gArgsLen = 6;\nint gLineNo = 1;\nenum oper {ADD = 0, SUB, MUL, DIV, MOD};\nbool debug = true;\n\nvoid parseExpression();\nvoid skipSpaces();\n\nvoid usage(void) {\n printf(\"executable \\r\\n\");\n return;\n}\n\nbool openFile(int argc, char **argv) {\n if (argc < 2) {\n usage();\n return false;\n }\n gInFile.open (argv[1], ifstream::in);\n return true;\n}\n\nchar getChar() {\n return gCurValue;\n}\n\nvoid nextChar(void) {\n if (!gInFile.eof()) {\n gCurValue = gInFile.get();\n } else {\n gCurValue = EOF;\n }\n} \n\nchar getnextChar() {\n nextChar();\n return gCurValue;\n}\n\nbool accept(char c) {\n if (getChar() == c) {\n nextChar();\n return true;\n }\n return false;\n}\n\nbool check(char c) {\n if (getChar() == c) {\n return true;\n }\n return false;\n}\n\nstring getContext() {\n string context;\n getline(gInFile, context);\n return context;\n}\n\nvoid printError(int lineno) {\n printf (\"%d:Invalid statement at LineNo:%d:%d - %c%s\",\n lineno,\n gLineNo, (int)gInFile.tellg(), getChar(), getContext().c_str());\n exit(0);\n}\n\nvoid printError(int lineno, const char *c) {\n printf(\"%d:Unable to compile due to error %s at Line: %d FilePosition:%d \\r\\n\",\n lineno,\n c, gLineNo, (int)gInFile.tellg());\n printf(\"Remaining Code: %c%s\", getChar(), getContext().c_str());\n exit(0);\n}\n\nvoid parseComment() {\n if (debug) {\n printf(\"Enter %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n while (getnextChar() != '\\n');\n \/\/Skip \\n\n getnextChar();\n gLineNo++;\n if (debug) {\n printf(\"Exit %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n}\n\nvoid parseArgs() {\n char errmsg[50];\n if (debug) {\n printf(\"Enter %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n int i;\n \/\/Move the pointer next to a\n getnextChar();\n for (i = 0; i < gArgsLen; i++) {\n if (accept('0' + (i - 0))) { \/\/Change from int to char\n break;\n } \n }\n if (i == gArgsLen) {\n sprintf(errmsg, \"Invalid argument (a%c) used in the program\", \n getChar());\n printError(__LINE__, errmsg);\n }\n if (debug) {\n printf(\"Exit %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n}\n\n\/\/Guess this should return an LLVM object\nvoid parseArithmeticOperation(char oper) {\n if (debug) {\n printf(\"Enter %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n parseExpression();\n parseExpression();\n \/\/Get Oper1\n \/\/Oper1 = parseExpression();\n \/\/Oper2 = parseExpression();\n if (debug) {\n printf(\"Exit %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n}\n\nvoid parseNumber() {\n if (debug) {\n printf(\"Enter %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n int num = 0, count = 0;\n char ch = getChar();\n while ((ch >= '0') && (ch <= '9')) {\n num = (num * 10 * count++) + (0 + (ch - '0'));\n ch = getnextChar();\n }\n \/\/changed the int to number;\n if (debug) {\n printf(\"Exit %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n}\n\nvoid parseRelationalOperation() {\n if (debug) {\n printf(\"Enter %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n\n if (accept('>')) {\n \/\/This is greater than\n if (accept('=')) {\n \/\/This is greater than equals \n }\n } else if (accept('<')) {\n \/\/This is less than\n if (accept('=')) {\n \/\/This is less than equals \n }\n } else if (accept('!') && accept('=')) {\n \/\/This is not equal to\n } else if (accept('=') && accept('=')) {\n \/\/This is double equals \n }\n parseExpression();\n parseExpression();\n if (debug) {\n printf(\"Exit %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n}\n\nvoid parseBoolExpression() {\n if (debug) {\n printf(\"Enter %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n\n skipSpaces();\n\n char ch = getChar();\n\n if (accept('t') && accept('r') && accept('u') && accept('e')) {\n \/\/Its a true condition\n } else if (accept('f') && accept('a') && accept('l') \n && accept('s') && accept('e')) {\n \/\/Its a false condition\n } else if ((ch == '>') || (ch == '<') || (ch == '=') || \n (ch == '!')) {\n parseRelationalOperation(); \n } else if (ch == ('(')) {\n getnextChar();\n parseBoolExpression();\n if (accept(')') == false) {\n printError(__LINE__, \"Missing ) Paranthesis in boolean exp\");\n }\n } else {\n printError(__LINE__, \"Boolean expression Missing\");\n }\n\n if (debug) {\n printf(\"Exit %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n}\n\nvoid parseIf() {\n if (debug) {\n printf(\"Enter %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n if (accept('i') && accept('f')) {\n \/\/Move till you find the ( of the bool expression\n parseBoolExpression();\n parseExpression();\n parseExpression();\n } else {\n printError(__LINE__);\n }\n if (debug) {\n printf(\"Exit %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n}\n\nvoid skipSpaces() {\n if (debug) {\n printf(\"Enter %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n\n while (getChar() != EOF) {\n if (accept(' ')) {\n continue;\n } else if (accept('\\n')) {\n gLineNo++;\n continue;\n }\n break;\n }\n\n if (debug) {\n printf(\"Exit %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n}\n\n\/* This function is called with the current pointer\n * at ( *\/\nvoid parseExpression() {\n char errmsg[75];\n if (debug) {\n printf(\"Enter %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n\n skipSpaces();\n\n char ch = getChar();\n\n do{\n if (ch == '#') {\n parseComment();\n } else if (ch == 'a') {\n parseArgs();\n break;\n } else if (ch == '\\n') {\n \/\/Increment the line number, so that we can give a \n \/\/meaningful error message\n gLineNo++;\n } else if (ch == ' ') {\n \/\/Ignore White space\n } else if ((ch == '+') || (ch == '-') || (ch == '*') || \n (ch == '\/') || (ch == '%')) {\n getnextChar();\n parseArithmeticOperation(ch); \n break;\n } else if ((ch >= '0') && (ch <= '9')) {\n parseNumber();\n break;\n } else if (ch == '(') {\n getnextChar();\n parseExpression();\n if (accept(')') == false) {\n printError(__LINE__, \"Missing Matching paranthesis\");\n }\n break;\n } else if (ch == 'i') {\n parseIf();\n break;\n } else if (ch == ')') {\n getnextChar();\n break;\n } else {\n printError(__LINE__);\n }\n ch = getChar();\n }while (ch != EOF);\n if (debug) {\n printf(\"Exit %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n}\n\nvoid parser() {\n if (debug) {\n printf(\"Enter %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n char ch = getnextChar();\n while(ch != EOF) {\n if (ch == '#') {\n parseComment();\n } else {\n parseExpression();\n skipSpaces();\n if (getChar() == EOF) {\n break;\n } else {\n printError(__LINE__);\n }\n }\n ch = getChar();\n }\n printf(\"Parsed successfully\\r\\n\");\n if (debug) {\n printf(\"Exit %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n}\n\nstatic int compile() {\n M->setTargetTriple(llvm::sys::getProcessTriple());\n std::vector SixInts(6, Type::getInt64Ty(C));\n FunctionType *FT = FunctionType::get(Type::getInt64Ty(C), SixInts, false);\n Function *F = Function::Create(FT, Function::ExternalLinkage, \"f\", &*M);\n BasicBlock *BB = BasicBlock::Create(C, \"entry\", F);\n Builder.SetInsertPoint(BB);\n\n \/\/ TODO: parse the source program\n \/\/ TODO: generate correct LLVM instead of just an empty function\n\n Value *RetVal = ConstantInt::get(C, APInt(64, 0));\n Builder.CreateRet(RetVal);\n assert(verifyModule(*M));\n M->dump();\n return 0;\n}\n\nint main(int argc, char **argv) { \n if (openFile(argc, argv) == true) {\n parser();\n \/\/return compile(); \n } \n return -1;\n}\n<|endoftext|>"} {"text":"\/*\n\nCopyright (c) 2006, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/entry.hpp\"\n#include \"libtorrent\/bencode.hpp\"\n#include \"libtorrent\/torrent_info.hpp\"\n#include \"libtorrent\/file.hpp\"\n#include \"libtorrent\/storage.hpp\"\n#include \"libtorrent\/hasher.hpp\"\n#include \"libtorrent\/create_torrent.hpp\"\n#include \"libtorrent\/file.hpp\"\n\n#include \n\nusing namespace libtorrent;\n\n\/\/ do not include files and folders whose\n\/\/ name starts with a .\nbool file_filter(std::string const& f)\n{\n\tif (filename(f)[0] == '.') return false;\n\tfprintf(stderr, \"%s\\n\", f.c_str());\n\treturn true;\n}\n\nvoid print_progress(int i, int num)\n{\n\tfprintf(stderr, \"\\r%d\/%d\", i+1, num);\n}\n\nvoid print_usage()\n{\n\tfputs(\"usage: make_torrent FILE [OPTIONS]\\n\"\n\t\t\"\\n\"\n\t\t\"Generates a torrent file from the specified file\\n\"\n\t\t\"or directory and writes it to standard out\\n\\n\"\n\t\t\"OPTIONS:\\n\"\n\t\t\"-m generate a merkle hash tree torrent.\\n\"\n\t\t\" merkle torrents require client support\\n\"\n\t\t\"-w url adds a web seed to the torrent with\\n\"\n\t\t\" the specified url\\n\"\n\t\t\"-t url adds the specified tracker to the\\n\"\n\t\t\" torrent\\n\"\n\t\t\"-p bytes enables padding files. Files larger\\n\"\n\t\t\" than bytes will be piece-aligned\\n\"\n\t\t\"-s bytes specifies a piece size for the torrent\\n\"\n\t\t\" This has to be a multiple of 16 kiB\\n\"\n\t\t, stderr);\n}\n\nint main(int argc, char* argv[])\n{\n\tusing namespace libtorrent;\n\n\tchar const* creator_str = \"libtorrent\";\n\n\tif (argc < 2)\n\t{\n\t\tprint_usage();\n\t\treturn 1;\n\t}\n\n#ifndef BOOST_NO_EXCEPTIONS\n\ttry\n\t{\n#endif\n\t\tstd::vector web_seeds;\n\t\tstd::vector trackers;\n\t\tint pad_file_limit = -1;\n\t\tint piece_size = 0;\n\t\tint flags = 0;\n\n\t\tfor (int i = 2; i < argc; ++i)\n\t\t{\n\t\t\tif (argv[i][0] != '-')\n\t\t\t{\n\t\t\t\tprint_usage();\n\t\t\t\treturn 1;\n\t\t\t}\n\n\t\t\tswitch (argv[i][1])\n\t\t\t{\n\t\t\t\tcase 'w':\n\t\t\t\t\t++i;\n\t\t\t\t\tweb_seeds.push_back(argv[i]);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 't':\n\t\t\t\t\t++i;\n\t\t\t\t\ttrackers.push_back(argv[i]);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'p':\n\t\t\t\t\t++i;\n\t\t\t\t\tpad_file_limit = atoi(argv[i]);\n\t\t\t\t\tflags |= create_torrent::optimize;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 's':\n\t\t\t\t\t++i;\n\t\t\t\t\tpiece_size = atoi(argv[i]);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'm':\n\t\t\t\t\tflags |= create_torrent::merkle;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tprint_usage();\n\t\t\t\t\treturn 1;\n\t\t\t}\n\t\t}\n\n\t\tfile_storage fs;\n\t\tfile_pool fp;\n\t\tstd::string full_path = libtorrent::complete(argv[1]);\n\n\t\tadd_files(fs, full_path, file_filter);\n\n\t\tcreate_torrent t(fs, piece_size, pad_file_limit, flags);\n\t\tfor (std::vector::iterator i = trackers.begin()\n\t\t\t, end(trackers.end()); i != end; ++i)\n\t\t\tt.add_tracker(*i);\n\n\t\tfor (std::vector::iterator i = web_seeds.begin()\n\t\t\t, end(web_seeds.end()); i != end; ++i)\n\t\t\tt.add_url_seed(*i);\n\n\t\terror_code ec;\n\t\tset_piece_hashes(t, parent_path(full_path)\n\t\t\t, boost::bind(&print_progress, _1, t.num_pieces()), ec);\n\t\tif (ec)\n\t\t{\n\t\t\tfprintf(stderr, \"%s\\n\", ec.message().c_str());\n\t\t\treturn 1;\n\t\t}\n\n\t\tfprintf(stderr, \"\\n\");\n\t\tt.set_creator(creator_str);\n\n\t\t\/\/ create the torrent and print it to stdout\n\t\tstd::vector torrent;\n\t\tbencode(back_inserter(torrent), t.generate());\n\t\tfwrite(&torrent[0], 1, torrent.size(), stdout);\n\n#ifndef BOOST_NO_EXCEPTIONS\n\t}\n\tcatch (std::exception& e)\n\t{\n\t\tfprintf(stderr, \"%s\\n\", e.what());\n\t}\n#endif\n\n\treturn 0;\n}\n\nerror handling in make_torrent\/*\n\nCopyright (c) 2006, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/entry.hpp\"\n#include \"libtorrent\/bencode.hpp\"\n#include \"libtorrent\/torrent_info.hpp\"\n#include \"libtorrent\/file.hpp\"\n#include \"libtorrent\/storage.hpp\"\n#include \"libtorrent\/hasher.hpp\"\n#include \"libtorrent\/create_torrent.hpp\"\n#include \"libtorrent\/file.hpp\"\n\n#include \n\nusing namespace libtorrent;\n\n\/\/ do not include files and folders whose\n\/\/ name starts with a .\nbool file_filter(std::string const& f)\n{\n\tif (filename(f)[0] == '.') return false;\n\tfprintf(stderr, \"%s\\n\", f.c_str());\n\treturn true;\n}\n\nvoid print_progress(int i, int num)\n{\n\tfprintf(stderr, \"\\r%d\/%d\", i+1, num);\n}\n\nvoid print_usage()\n{\n\tfputs(\"usage: make_torrent FILE [OPTIONS]\\n\"\n\t\t\"\\n\"\n\t\t\"Generates a torrent file from the specified file\\n\"\n\t\t\"or directory and writes it to standard out\\n\\n\"\n\t\t\"OPTIONS:\\n\"\n\t\t\"-m generate a merkle hash tree torrent.\\n\"\n\t\t\" merkle torrents require client support\\n\"\n\t\t\"-w url adds a web seed to the torrent with\\n\"\n\t\t\" the specified url\\n\"\n\t\t\"-t url adds the specified tracker to the\\n\"\n\t\t\" torrent\\n\"\n\t\t\"-p bytes enables padding files. Files larger\\n\"\n\t\t\" than bytes will be piece-aligned\\n\"\n\t\t\"-s bytes specifies a piece size for the torrent\\n\"\n\t\t\" This has to be a multiple of 16 kiB\\n\"\n\t\t, stderr);\n}\n\nint main(int argc, char* argv[])\n{\n\tusing namespace libtorrent;\n\n\tchar const* creator_str = \"libtorrent\";\n\n\tif (argc < 2)\n\t{\n\t\tprint_usage();\n\t\treturn 1;\n\t}\n\n#ifndef BOOST_NO_EXCEPTIONS\n\ttry\n\t{\n#endif\n\t\tstd::vector web_seeds;\n\t\tstd::vector trackers;\n\t\tint pad_file_limit = -1;\n\t\tint piece_size = 0;\n\t\tint flags = 0;\n\n\t\tfor (int i = 2; i < argc; ++i)\n\t\t{\n\t\t\tif (argv[i][0] != '-')\n\t\t\t{\n\t\t\t\tprint_usage();\n\t\t\t\treturn 1;\n\t\t\t}\n\n\t\t\tswitch (argv[i][1])\n\t\t\t{\n\t\t\t\tcase 'w':\n\t\t\t\t\t++i;\n\t\t\t\t\tweb_seeds.push_back(argv[i]);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 't':\n\t\t\t\t\t++i;\n\t\t\t\t\ttrackers.push_back(argv[i]);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'p':\n\t\t\t\t\t++i;\n\t\t\t\t\tpad_file_limit = atoi(argv[i]);\n\t\t\t\t\tflags |= create_torrent::optimize;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 's':\n\t\t\t\t\t++i;\n\t\t\t\t\tpiece_size = atoi(argv[i]);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'm':\n\t\t\t\t\tflags |= create_torrent::merkle;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tprint_usage();\n\t\t\t\t\treturn 1;\n\t\t\t}\n\t\t}\n\n\t\tfile_storage fs;\n\t\tfile_pool fp;\n\t\tstd::string full_path = libtorrent::complete(argv[1]);\n\n\t\tadd_files(fs, full_path, file_filter);\n\t\tif (fs.num_files() == 0)\n\t\t{\n\t\t\tfputs(\"no files specified.\\n\", stderr);\n\t\t\treturn 1;\n\t\t}\n\n\t\tcreate_torrent t(fs, piece_size, pad_file_limit, flags);\n\t\tfor (std::vector::iterator i = trackers.begin()\n\t\t\t, end(trackers.end()); i != end; ++i)\n\t\t\tt.add_tracker(*i);\n\n\t\tfor (std::vector::iterator i = web_seeds.begin()\n\t\t\t, end(web_seeds.end()); i != end; ++i)\n\t\t\tt.add_url_seed(*i);\n\n\t\terror_code ec;\n\t\tset_piece_hashes(t, parent_path(full_path)\n\t\t\t, boost::bind(&print_progress, _1, t.num_pieces()), ec);\n\t\tif (ec)\n\t\t{\n\t\t\tfprintf(stderr, \"%s\\n\", ec.message().c_str());\n\t\t\treturn 1;\n\t\t}\n\n\t\tfprintf(stderr, \"\\n\");\n\t\tt.set_creator(creator_str);\n\n\t\t\/\/ create the torrent and print it to stdout\n\t\tstd::vector torrent;\n\t\tbencode(back_inserter(torrent), t.generate());\n\t\tfwrite(&torrent[0], 1, torrent.size(), stdout);\n\n#ifndef BOOST_NO_EXCEPTIONS\n\t}\n\tcatch (std::exception& e)\n\t{\n\t\tfprintf(stderr, \"%s\\n\", e.what());\n\t}\n#endif\n\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"\/\/ Author: Daisuke Kanaizumi\n\/\/ Affiliation: Department of Applied Mathematics, Waseda University\n\/\/ Email: daisuke15@asagi.waseda.jp\n\n\/\/ Verification program for modified q-Bessel functions \n\/\/ by using double exponential formula with verified error bounds.\n\/\/ References\n\n\/\/ Zhang, R. (2008). Plancherel–Rotach Asymptotics for Certain Basic Hypergeometric Series. Advances in Mathematics, 217(4), 1588-1613.\n\/\/ Okayama, T. (2013). Error estimates with explicit constants for Sinc quadrature and Sinc indefinite integration over infinite intervals. arXiv preprint arXiv:1302.1314.\n\/\/ Ismail, M. E. (1981). The basic Bessel functions and polynomials. SIAM Journal on Mathematical Analysis, 12(3), 454-468.\n#ifndef MQB_DE_HPP\n#define MQB_DE_HPP\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nnamespace kv{\n\n template struct mqBreal {\n TT z, q, nu;\n int n; \/\/ Setting parameters\n mqBreal(TT z, TT q, TT nu,int n) : z(z),q(q),nu(nu),n(n) {}\n \n template T operator() (const T& t) {\n complex pro;\n T proreal;\n complex i;\n pro=1.;\n i=complex::i();\n for(int k=0;k<=n-1;k++){\n\tpro=pro\/(1-z*0.5*pow(T(q),k)*exp(i*t))\/(1-z*0.5*pow(T(q),k)*exp(-i*t));\n }\n pro=pro*cos(T(nu)*t);\n proreal=pro.real();\n return proreal;\n }\n };\n \n template struct mqBimag {\n TT z, q, nu;\n int n; \/\/ Setting parameters\n mqBimag(TT z, TT q, TT nu,int n) : z(z),q(q),nu(nu),n(n) {}\n \n template T operator() (const T& t) {\n complex pro;\n T proimag;\n complex i;\n pro=1.;\n i=complex::i();\n for(int k=0;k<=n-1;k++){\n\tpro=pro\/(1-z*0.5*pow(T(q),k)*exp(i*t))\/(1-z*0.5*pow(T(q),k)*exp(-i*t));\n }\n pro=pro*cos(T(nu)*t);\n proimag=pro.imag();\n return proimag;\n \n }\n };\n\n template complex >modified_qBesselI2_DE(const interval & z,const interval & nu,const interval& q){\n \/\/verification program for 2nd modified q-Bessel function I2\n if(abs(q)>=1){\n throw std::domain_error(\"absolute value of q must be under 1\");\n }\n if(nu<=0){\n throw std::domain_error(\"value of nu must be more than 0\");\n }\n interval pi,realint,imagint,second,e,d,h,K,C3,sum,intrad;\n complex >res,first;\n pi=constants >::pi();\n e=constants >::e();\n int m,n,M,N;\n m=100;\n while(abs(z*pow(q,m))*0.5\/(1-q)>=0.5){\n m=m+10;\n }\n d=1.;\n \n n=150;\n M=n;\n h=log(4*d*n)\/T(n);\n N=n-std::floor(mid(log(nu)\/h));\n \n while(n<=nu*e*0.25*d){\n n=n+10;\n }\n intrad=pow(1+2*abs(z)*pow(q,m)\/(1-q)*interval(-1.,1.),2);\n realint=defint(mqBreal >(z,q,nu,m),interval(0.),interval(pi),10,10);\n imagint=defint(mqBimag >(z,q,nu,m),interval(0.),interval(pi),10,10);\n first=intrad*complex >(realint,imagint)\/pi;\n \n K=(1+2*z*pow(q,m)\/(1-q))\/infinite_qPochhammer(interval(abs(z)*0.5),interval(q))\n \/qPochhammer(interval(z*0.5),interval(q),int(m));\n\n C3=2*K*(2\/(1-exp(-pi*e*0.5))\/cos(d)\/pow(cos(pi*0.5*sin(d)),nu+1)+exp(pi*nu*0.5));\n\n sum=0.;\n for(int k=-M;k<=N;k++){\n sum=sum+exp(-(nu)*log(1+exp(pi*sinh(k*h))))\n\t\/infinite_qPochhammer(interval (-z*0.5*(1.+exp(pi*sinh(k*h)))),interval(q))\n\t\/infinite_qPochhammer(interval (-0.5*z\/(1.+exp(pi*sinh(k*h)))),interval(q))\n\t*pi*exp(pi*sinh(k*h))*cosh(k*h)\/(1.+exp(pi*sinh(k*h)));\n }\n\n second=(h*sum+C3*exp(-2*pi*d\/h)*interval(-1.,1.))*sin(pi*nu)\/pi;\n res=(first-second)*infinite_qPochhammer(interval (z*z*0.25),interval(q));\n return res;\n \/\/ to be repaired\n }\n}\n#endif\nUpdate mqB_DE.hpp\/\/ Author: Daisuke Kanaizumi\n\/\/ Affiliation: Department of Applied Mathematics, Waseda University\n\n\/\/ Verification program for modified q-Bessel functions \n\/\/ by using double exponential formula with verified error bounds.\n\/\/ References\n\n\/\/ Zhang, R. (2008). Plancherel–Rotach Asymptotics for Certain Basic Hypergeometric Series. Advances in Mathematics, 217(4), 1588-1613.\n\/\/ Okayama, T. (2013). Error estimates with explicit constants for Sinc quadrature and Sinc indefinite integration over infinite intervals. arXiv preprint arXiv:1302.1314.\n\/\/ Ismail, M. E. (1981). The basic Bessel functions and polynomials. SIAM Journal on Mathematical Analysis, 12(3), 454-468.\n#ifndef MQB_DE_HPP\n#define MQB_DE_HPP\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nnamespace kv{\n\n template struct mqBreal {\n TT z, q, nu;\n int n; \/\/ Setting parameters\n mqBreal(TT z, TT q, TT nu,int n) : z(z),q(q),nu(nu),n(n) {}\n \n template T operator() (const T& t) {\n complex pro;\n T proreal;\n complex i;\n pro=1.;\n i=complex::i();\n for(int k=0;k<=n-1;k++){\n\tpro=pro\/(1-z*0.5*pow(T(q),k)*exp(i*t))\/(1-z*0.5*pow(T(q),k)*exp(-i*t));\n }\n pro=pro*cos(T(nu)*t);\n proreal=pro.real();\n return proreal;\n }\n };\n \n template struct mqBimag {\n TT z, q, nu;\n int n; \/\/ Setting parameters\n mqBimag(TT z, TT q, TT nu,int n) : z(z),q(q),nu(nu),n(n) {}\n \n template T operator() (const T& t) {\n complex pro;\n T proimag;\n complex i;\n pro=1.;\n i=complex::i();\n for(int k=0;k<=n-1;k++){\n\tpro=pro\/(1-z*0.5*pow(T(q),k)*exp(i*t))\/(1-z*0.5*pow(T(q),k)*exp(-i*t));\n }\n pro=pro*cos(T(nu)*t);\n proimag=pro.imag();\n return proimag;\n \n }\n };\n\n template complex >modified_qBesselI2_DE(const interval & z,const interval & nu,const interval& q){\n \/\/verification program for 2nd modified q-Bessel function I2\n if(abs(q)>=1){\n throw std::domain_error(\"absolute value of q must be under 1\");\n }\n if(nu<=0){\n throw std::domain_error(\"value of nu must be more than 0\");\n }\n interval pi,realint,imagint,second,e,d,h,K,C3,sum,intrad;\n complex >res,first;\n pi=constants >::pi();\n e=constants >::e();\n int m,n,M,N;\n m=100;\n while(abs(z*pow(q,m))*0.5\/(1-q)>=0.5){\n m=m+10;\n }\n d=1.;\n \n n=150;\n M=n;\n h=log(4*d*n)\/T(n);\n N=n-std::floor(mid(log(nu)\/h));\n \n while(n<=nu*e*0.25*d){\n n=n+10;\n }\n intrad=pow(1+2*abs(z)*pow(q,m)\/(1-q)*interval(-1.,1.),2);\n realint=defint(mqBreal >(z,q,nu,m),interval(0.),interval(pi),10,10);\n imagint=defint(mqBimag >(z,q,nu,m),interval(0.),interval(pi),10,10);\n first=intrad*complex >(realint,imagint)\/pi;\n \n K=(1+2*z*pow(q,m)\/(1-q))\/infinite_qPochhammer(interval(abs(z)*0.5),interval(q))\n \/qPochhammer(interval(z*0.5),interval(q),int(m));\n\n C3=2*K*(2\/(1-exp(-pi*e*0.5))\/cos(d)\/pow(cos(pi*0.5*sin(d)),nu+1)+exp(pi*nu*0.5));\n\n sum=0.;\n for(int k=-M;k<=N;k++){\n sum=sum+exp(-(nu)*log(1+exp(pi*sinh(k*h))))\n\t\/infinite_qPochhammer(interval (-z*0.5*(1.+exp(pi*sinh(k*h)))),interval(q))\n\t\/infinite_qPochhammer(interval (-0.5*z\/(1.+exp(pi*sinh(k*h)))),interval(q))\n\t*pi*exp(pi*sinh(k*h))*cosh(k*h)\/(1.+exp(pi*sinh(k*h)));\n }\n\n second=(h*sum+C3*exp(-2*pi*d\/h)*interval(-1.,1.))*sin(pi*nu)\/pi;\n res=(first-second)*infinite_qPochhammer(interval (z*z*0.25),interval(q));\n return res;\n \/\/ to be repaired\n }\n}\n#endif\n<|endoftext|>"} {"text":"#include \n#include \"Stuff.h\"\n#include \"ESpectrumBase.h\"\n\n#include \n\n\/** @class\tStuffTest\n * @brief\tTests EMPA processor stuff functionality\n * \n *\/\nextern bool UNIT_TESTING;\t\t\/\/ Switched off by default\n\/\/ A new test class of these is created for each test\nclass EvalTest : public testing::Test\n{\npublic:\npublic:\n\n};\n \n\/**\n * Tests some routines of the stuff\n *\/\nTEST_F(EvalTest, Tools)\n{\n ESpectrumBase SP;\n EXPECT_EQ(-1, SP.XEnergy_Get()); \/\/ After creating, the X energy is invalid\n EXPECT_FALSE(SP.XEnergy_Valid());\n SP.XEnergy_Set(1486.295);\n EXPECT_EQ(1486.295, SP.XEnergy_Get()); \/\/ After setting, the X energy is valid\n EXPECT_TRUE(SP.XEnergy_Valid());\n}\nNew structure tested#include \n#include \"Stuff.h\"\n#include \"ESpectrumBase.h\"\n\n#include \n\n\/** @class\tStuffTest\n * @brief\tTests EMPA processor stuff functionality\n * \n *\/\nextern bool UNIT_TESTING;\t\t\/\/ Switched off by default\n\/\/ A new test class of these is created for each test\nclass EvalTest : public testing::Test\n{\npublic:\npublic:\n\n};\n \n\/**\n * Tests some routines of the stuff\n *\/\nTEST_F(EvalTest, Tools)\n{\n double myints[]={10.,20.,30.,40.,50.,60.,70.};\n std::vector myvector (7);\n std::copy ( myints, myints+7, myvector.begin() );\n ESpectrumBase SP(&myvector);\n EXPECT_EQ(-1, SP.XEnergy_Get()); \/\/ After creating, the X energy is invalid\n EXPECT_FALSE(SP.XEnergy_Valid());\n EXPECT_EQ(20,SP.Y_Get(1));\n EXPECT_EQ(1,SP.X_Get(1));\n EXPECT_EQ(1,SP.X_Get_Kinetic(1));\n SP.XEnergy_Set(1486.295);\n EXPECT_EQ(20,SP.Y_Get(1));\n EXPECT_EQ(1,SP.X_Get(1));\n EXPECT_EQ(1,SP.X_Get_Kinetic(1));\n EXPECT_EQ(1485.295,SP.X_Get_Binding(1));\n EXPECT_EQ(1486.295, SP.XEnergy_Get()); \/\/ After setting, the X energy is valid\n EXPECT_TRUE(SP.XEnergy_Valid());\n}\n<|endoftext|>"} {"text":"\/*\n Copyright (c) 2020 ANON authors, see AUTHORS file.\n \n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n \n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n \n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE.\n*\/\n\n#include \"resin.h\"\n#include \"time_utils.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace\n{\n\nstd::string replace_all(std::string &s, const std::string &pat, const std::string &rep)\n{\n size_t pos = 0;\n auto plen = pat.size();\n auto rlen = rep.size();\n while (true)\n {\n auto fpos = s.find(pat, pos);\n if (fpos == std::string::npos)\n break;\n s = s.replace(fpos, plen, rep);\n pos = fpos + rlen;\n }\n return s;\n}\n\nstd::string get_body(const Aws::SQS::Model::Message &m)\n{\n auto body = m.GetBody();\n body = replace_all(body, \"&\", \"&\");\n body = replace_all(body, \""\", \"\\\"\");\n body = replace_all(body, \"'\", \"\\'\");\n body = replace_all(body, \"<\", \"<\");\n return replace_all(body, \">\", \">\");\n}\n\nbool should_shut_down(const ec2_info &ec2i)\n{\n if (ec2i.user_data_js.find(\"min_instance_url\") != ec2i.user_data_js.end())\n {\n Aws::Client::ClientConfiguration ddb_config;\n if (ec2i.user_data_js.find(\"min_instance_region\") != ec2i.user_data_js.end())\n ddb_config.region = ec2i.user_data_js[\"min_instance_region\"];\n else\n ddb_config.region = ec2i.default_region;\n ddb_config.executor = ec2i.executor;\n Aws::DynamoDB::DynamoDBClient ddbc(ddb_config);\n\n Aws::DynamoDB::Model::AttributeValue primary_key;\n primary_key.SetS(ec2i.user_data_js[\"min_instance_primary_key_value\"]);\n Aws::DynamoDB::Model::GetItemRequest req;\n req.WithTableName(ec2i.user_data_js[\"min_instance_table_name\"])\n .AddKey(ec2i.user_data_js[\"min_instance_primary_key_name\"], primary_key);\n auto outcome = ddbc.GetItem(req);\n if (outcome.IsSuccess())\n {\n auto map = outcome.GetResult().GetItem();\n auto it = map.find(\"min_instances\");\n if (it != map.end())\n {\n auto min_instances = std::atoi(it->second.GetN().c_str());\n std::string instance_name = ec2i.user_data_js[\"min_instance_name\"];\n\n Aws::Client::ClientConfiguration ec2_config;\n ec2_config.region = ec2i.default_region;\n ec2_config.executor = ec2i.executor;\n Aws::EC2::EC2Client ec2(ec2_config);\n\n Aws::EC2::Model::DescribeInstancesRequest request;\n Aws::EC2::Model::Filter filter1;\n filter1.SetName(\"tag:Name\");\n filter1.AddValues(instance_name);\n request.AddFilters(filter1);\n Aws::EC2::Model::Filter filter2;\n filter2.SetName(\"instance-state-name\");\n filter2.AddValues(\"running\");\n request.AddFilters(filter2);\n\n bool done = false;\n int total_instances = 0;\n while (!done)\n {\n auto outcome = ec2.DescribeInstances(request);\n if (outcome.IsSuccess())\n {\n const auto &reservations = outcome.GetResult().GetReservations();\n for (const auto &reservation : reservations)\n {\n const auto &instances = reservation.GetInstances();\n total_instances += instances.size();\n if (total_instances > min_instances)\n return true;\n }\n if (outcome.GetResult().GetNextToken().size() > 0)\n request.SetNextToken(outcome.GetResult().GetNextToken());\n else\n done = true;\n }\n else\n return true;\n }\n\n return total_instances > min_instances;\n }\n }\n }\n return true;\n}\n\n} \/\/ namespace\n\nvoid run_worker(const ec2_info &ec2i)\n{\n Aws::Client::ClientConfiguration config;\n if (ec2i.user_data_js.find(\"task_queue_region\") != ec2i.user_data_js.end())\n config.region = ec2i.user_data_js[\"task_queue_region\"];\n else\n config.region = ec2i.default_region;\n config.executor = ec2i.executor;\n\n std::string queue_url = ec2i.user_data_js[\"task_queue_url\"];\n\n Aws::SQS::SQSClient client(config);\n std::mutex keep_alive_mutex;\n std::map keep_alive_set;\n bool stop = false;\n auto timerfd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC);\n struct itimerspec t_spec = {0};\n t_spec.it_value = cur_time() + 30;\n timerfd_settime(timerfd, TFD_TIMER_ABSTIME, &t_spec, 0);\n\n std::thread keep_alive_thread([&client, &keep_alive_mutex, &keep_alive_set,\n &stop, &timerfd, &queue_url] {\n while (true)\n {\n struct pollfd pfd;\n pfd.fd = timerfd;\n pfd.events = POLLIN;\n poll(&pfd, 1, 31000);\n\n std::unique_lock l(keep_alive_mutex);\n if (stop)\n break;\n\n auto num_messages = keep_alive_set.size();\n if (num_messages > 0)\n {\n Aws::SQS::Model::ChangeMessageVisibilityBatchRequest req;\n Aws::Vector> entries_v;\n int index = 0;\n for (auto it : keep_alive_set)\n {\n Aws::SQS::Model::ChangeMessageVisibilityBatchRequestEntry ent;\n std::ostringstream str;\n if (index % 10 == 0)\n entries_v.push_back(Aws::Vector());\n str << \"message_\" << ++index;\n ent.WithReceiptHandle(it.first).WithVisibilityTimeout(60).WithId(str.str());\n entries_v.back().push_back(ent);\n }\n l.unlock();\n for (auto &entries : entries_v)\n {\n req.WithQueueUrl(queue_url).WithEntries(entries);\n auto outcome = client.ChangeMessageVisibilityBatch(req);\n if (!outcome.IsSuccess())\n anon_log(\"ChangeMessageVisibilityBatch failed: \" << outcome.GetError());\n }\n }\n\n struct itimerspec t_spec = {0};\n t_spec.it_value = cur_time() + 30;\n timerfd_settime(timerfd, TFD_TIMER_ABSTIME, &t_spec, 0);\n }\n });\n\n while (true)\n {\n Aws::SQS::Model::ReceiveMessageRequest req;\n req.WithQueueUrl(queue_url).WithMaxNumberOfMessages(1).WithWaitTimeSeconds(5);\n Aws::Vector att;\n att.push_back(Aws::SQS::Model::QueueAttributeName::All);\n req.WithAttributeNames(std::move(att));\n\n auto outcome = client.ReceiveMessage(req);\n if (!outcome.IsSuccess())\n {\n anon_log(\"ReceiveMessage failed: \" << outcome.GetError());\n break;\n }\n auto &messages = outcome.GetResult().GetMessages();\n if (messages.size() > 0)\n {\n {\n std::unique_lock l(keep_alive_mutex);\n for (auto &m : messages)\n keep_alive_set[m.GetReceiptHandle()] = m.GetMessageId();\n }\n struct itimerspec t_spec = {0};\n timerfd_settime(timerfd, TFD_TIMER_ABSTIME, &t_spec, 0);\n\n for (auto &m : messages)\n {\n auto bash_cmd = get_body(m);\n\n const auto max_retries = 2;\n\n const auto &att = m.GetAttributes();\n auto arc = att.find(Aws::SQS::Model::MessageSystemAttributeName::ApproximateReceiveCount);\n auto approx_receive_count = 1000;\n if (arc != att.end())\n approx_receive_count = std::stoull(arc->second);\n\n auto pid = fork();\n if (pid == -1)\n do_error(\"fork()\");\n if (pid != 0)\n {\n \/\/ the calling parent\n int status;\n auto w = waitpid(-1, &status, WUNTRACED | WCONTINUED);\n if (w == -1)\n do_error(\"waitpid(-1, &status, WUNTRACED | WCONTINUED)\");\n\n auto script_exited_zero = false;\n if (WIFEXITED(status))\n {\n anon_log(\"bash exited with exit code: \" << WEXITSTATUS(status));\n script_exited_zero = WEXITSTATUS(status) == 0;\n }\n else if (WIFSIGNALED(status))\n anon_log(\"bash killed by signal: \" << WTERMSIG(status));\n else if (WIFSTOPPED(status))\n anon_log(\"bash stopped by signal: \" << WSTOPSIG(status));\n\n {\n \/\/ regardless of whether the bash command succeeded or not\n \/\/ we don't want to keep calling ChangeVisibilityStatus on this message\n std::unique_lock l(keep_alive_mutex);\n keep_alive_set.erase(m.GetReceiptHandle());\n }\n\n \/\/ if the script succeeded, or if we have failed too many times,\n \/\/ delete the message from sqs\n if (script_exited_zero || approx_receive_count >= max_retries)\n {\n Aws::SQS::Model::DeleteMessageRequest req;\n req.WithQueueUrl(queue_url).WithReceiptHandle(m.GetReceiptHandle());\n auto outcome = client.DeleteMessage(req);\n if (!outcome.IsSuccess())\n anon_log(\"DeleteMessage failed: \" << outcome.GetError());\n }\n }\n else\n {\n \/\/ the child process\n auto bash_file_name = \"\/bin\/bash\";\n auto bash_fd = open(bash_file_name, O_RDONLY);\n if (bash_fd == -1)\n do_error(\"open(\\\"\" << bash_file_name << \"\\\", O_RDONLY)\");\n\n const char *dash_c = \"-c\";\n const char *script = bash_cmd.c_str();\n const char *do_retry = approx_receive_count < max_retries ? \"1\" : \"0\";\n char *args[]{\n const_cast(bash_file_name),\n const_cast(dash_c),\n const_cast(script),\n const_cast(do_retry),\n 0};\n\n fexecve(bash_fd, &args[0], environ);\n\n \/\/ if fexecve succeeded then we never get here. So getting here is a failure,\n \/\/ but we are already in the child process at this point, so we do what we can\n \/\/ to signifify the error and then exit\n fprintf(stderr, \"fexecve(%d, ...) failed with errno: %d - %s\\n\", bash_fd, errno, strerror(errno));\n exit(1);\n }\n }\n }\n else\n {\n \/\/ no messages after 10 seconds. Check for shutdown\n anon_log(\"no messages after wating period\");\n if (should_shut_down(ec2i))\n {\n\tanon_log(\"no reason to keep running, shutting down\");\n break;\n }\n }\n }\n\n {\n std::unique_lock l(keep_alive_mutex);\n stop = true;\n struct itimerspec t_spec = {0};\n t_spec.it_value = cur_time();\n timerfd_settime(timerfd, TFD_TIMER_ABSTIME, &t_spec, 0);\n }\n keep_alive_thread.join();\n}\nadding comments about libcurl timeout\/*\n Copyright (c) 2020 ANON authors, see AUTHORS file.\n \n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n \n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n \n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE.\n*\/\n\n#include \"resin.h\"\n#include \"time_utils.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace\n{\n\nstd::string replace_all(std::string &s, const std::string &pat, const std::string &rep)\n{\n size_t pos = 0;\n auto plen = pat.size();\n auto rlen = rep.size();\n while (true)\n {\n auto fpos = s.find(pat, pos);\n if (fpos == std::string::npos)\n break;\n s = s.replace(fpos, plen, rep);\n pos = fpos + rlen;\n }\n return s;\n}\n\nstd::string get_body(const Aws::SQS::Model::Message &m)\n{\n auto body = m.GetBody();\n body = replace_all(body, \"&\", \"&\");\n body = replace_all(body, \""\", \"\\\"\");\n body = replace_all(body, \"'\", \"\\'\");\n body = replace_all(body, \"<\", \"<\");\n return replace_all(body, \">\", \">\");\n}\n\nbool should_shut_down(const ec2_info &ec2i)\n{\n if (ec2i.user_data_js.find(\"min_instance_url\") != ec2i.user_data_js.end())\n {\n Aws::Client::ClientConfiguration ddb_config;\n if (ec2i.user_data_js.find(\"min_instance_region\") != ec2i.user_data_js.end())\n ddb_config.region = ec2i.user_data_js[\"min_instance_region\"];\n else\n ddb_config.region = ec2i.default_region;\n ddb_config.executor = ec2i.executor;\n Aws::DynamoDB::DynamoDBClient ddbc(ddb_config);\n\n Aws::DynamoDB::Model::AttributeValue primary_key;\n primary_key.SetS(ec2i.user_data_js[\"min_instance_primary_key_value\"]);\n Aws::DynamoDB::Model::GetItemRequest req;\n req.WithTableName(ec2i.user_data_js[\"min_instance_table_name\"])\n .AddKey(ec2i.user_data_js[\"min_instance_primary_key_name\"], primary_key);\n auto outcome = ddbc.GetItem(req);\n if (outcome.IsSuccess())\n {\n auto map = outcome.GetResult().GetItem();\n auto it = map.find(\"min_instances\");\n if (it != map.end())\n {\n auto min_instances = std::atoi(it->second.GetN().c_str());\n std::string instance_name = ec2i.user_data_js[\"min_instance_name\"];\n\n Aws::Client::ClientConfiguration ec2_config;\n ec2_config.region = ec2i.default_region;\n ec2_config.executor = ec2i.executor;\n Aws::EC2::EC2Client ec2(ec2_config);\n\n Aws::EC2::Model::DescribeInstancesRequest request;\n Aws::EC2::Model::Filter filter1;\n filter1.SetName(\"tag:Name\");\n filter1.AddValues(instance_name);\n request.AddFilters(filter1);\n Aws::EC2::Model::Filter filter2;\n filter2.SetName(\"instance-state-name\");\n filter2.AddValues(\"running\");\n request.AddFilters(filter2);\n\n bool done = false;\n int total_instances = 0;\n while (!done)\n {\n auto outcome = ec2.DescribeInstances(request);\n if (outcome.IsSuccess())\n {\n const auto &reservations = outcome.GetResult().GetReservations();\n for (const auto &reservation : reservations)\n {\n const auto &instances = reservation.GetInstances();\n total_instances += instances.size();\n if (total_instances > min_instances)\n return true;\n }\n if (outcome.GetResult().GetNextToken().size() > 0)\n request.SetNextToken(outcome.GetResult().GetNextToken());\n else\n done = true;\n }\n else\n return true;\n }\n\n return total_instances > min_instances;\n }\n }\n }\n return true;\n}\n\n} \/\/ namespace\n\nvoid run_worker(const ec2_info &ec2i)\n{\n Aws::Client::ClientConfiguration config;\n if (ec2i.user_data_js.find(\"task_queue_region\") != ec2i.user_data_js.end())\n config.region = ec2i.user_data_js[\"task_queue_region\"];\n else\n config.region = ec2i.default_region;\n config.executor = ec2i.executor;\n\n std::string queue_url = ec2i.user_data_js[\"task_queue_url\"];\n\n Aws::SQS::SQSClient client(config);\n std::mutex keep_alive_mutex;\n std::map keep_alive_set;\n bool stop = false;\n auto timerfd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC);\n struct itimerspec t_spec = {0};\n t_spec.it_value = cur_time() + 30;\n timerfd_settime(timerfd, TFD_TIMER_ABSTIME, &t_spec, 0);\n\n std::thread keep_alive_thread([&client, &keep_alive_mutex, &keep_alive_set,\n &stop, &timerfd, &queue_url] {\n while (true)\n {\n struct pollfd pfd;\n pfd.fd = timerfd;\n pfd.events = POLLIN;\n poll(&pfd, 1, 31000);\n\n std::unique_lock l(keep_alive_mutex);\n if (stop)\n break;\n\n auto num_messages = keep_alive_set.size();\n if (num_messages > 0)\n {\n Aws::SQS::Model::ChangeMessageVisibilityBatchRequest req;\n Aws::Vector> entries_v;\n int index = 0;\n for (auto it : keep_alive_set)\n {\n Aws::SQS::Model::ChangeMessageVisibilityBatchRequestEntry ent;\n std::ostringstream str;\n if (index % 10 == 0)\n entries_v.push_back(Aws::Vector());\n str << \"message_\" << ++index;\n ent.WithReceiptHandle(it.first).WithVisibilityTimeout(60).WithId(str.str());\n entries_v.back().push_back(ent);\n }\n l.unlock();\n for (auto &entries : entries_v)\n {\n req.WithQueueUrl(queue_url).WithEntries(entries);\n auto outcome = client.ChangeMessageVisibilityBatch(req);\n if (!outcome.IsSuccess())\n anon_log(\"ChangeMessageVisibilityBatch failed: \" << outcome.GetError());\n }\n }\n\n struct itimerspec t_spec = {0};\n t_spec.it_value = cur_time() + 30;\n timerfd_settime(timerfd, TFD_TIMER_ABSTIME, &t_spec, 0);\n }\n });\n\n while (true)\n {\n Aws::SQS::Model::ReceiveMessageRequest req;\n \/\/ be careful with the timeout for now.\n \/\/ we are using the default libcurl and it seems to have a timeout\n \/\/ that is less than 10 seconds. If we set this value to 10 seconds\n \/\/ the aws code internally sees a timeout error from libcurl, which it\n \/\/ then decides to retry the request. To get it to return from this\n \/\/ function we need to set the timeout less than whatever the libcurl\n \/\/ timeout is set to.\n req.WithQueueUrl(queue_url).WithMaxNumberOfMessages(1).WithWaitTimeSeconds(5);\n Aws::Vector att;\n att.push_back(Aws::SQS::Model::QueueAttributeName::All);\n req.WithAttributeNames(std::move(att));\n\n auto outcome = client.ReceiveMessage(req);\n if (!outcome.IsSuccess())\n {\n anon_log(\"ReceiveMessage failed: \" << outcome.GetError());\n break;\n }\n auto &messages = outcome.GetResult().GetMessages();\n if (messages.size() > 0)\n {\n {\n std::unique_lock l(keep_alive_mutex);\n for (auto &m : messages)\n keep_alive_set[m.GetReceiptHandle()] = m.GetMessageId();\n }\n struct itimerspec t_spec = {0};\n timerfd_settime(timerfd, TFD_TIMER_ABSTIME, &t_spec, 0);\n\n for (auto &m : messages)\n {\n auto bash_cmd = get_body(m);\n\n const auto max_retries = 2;\n\n const auto &att = m.GetAttributes();\n auto arc = att.find(Aws::SQS::Model::MessageSystemAttributeName::ApproximateReceiveCount);\n auto approx_receive_count = 1000;\n if (arc != att.end())\n approx_receive_count = std::stoull(arc->second);\n\n auto pid = fork();\n if (pid == -1)\n do_error(\"fork()\");\n if (pid != 0)\n {\n \/\/ the calling parent\n int status;\n auto w = waitpid(-1, &status, WUNTRACED | WCONTINUED);\n if (w == -1)\n do_error(\"waitpid(-1, &status, WUNTRACED | WCONTINUED)\");\n\n auto script_exited_zero = false;\n if (WIFEXITED(status))\n {\n anon_log(\"bash exited with exit code: \" << WEXITSTATUS(status));\n script_exited_zero = WEXITSTATUS(status) == 0;\n }\n else if (WIFSIGNALED(status))\n anon_log(\"bash killed by signal: \" << WTERMSIG(status));\n else if (WIFSTOPPED(status))\n anon_log(\"bash stopped by signal: \" << WSTOPSIG(status));\n\n {\n \/\/ regardless of whether the bash command succeeded or not\n \/\/ we don't want to keep calling ChangeVisibilityStatus on this message\n std::unique_lock l(keep_alive_mutex);\n keep_alive_set.erase(m.GetReceiptHandle());\n }\n\n \/\/ if the script succeeded, or if we have failed too many times,\n \/\/ delete the message from sqs\n if (script_exited_zero || approx_receive_count >= max_retries)\n {\n Aws::SQS::Model::DeleteMessageRequest req;\n req.WithQueueUrl(queue_url).WithReceiptHandle(m.GetReceiptHandle());\n auto outcome = client.DeleteMessage(req);\n if (!outcome.IsSuccess())\n anon_log(\"DeleteMessage failed: \" << outcome.GetError());\n }\n }\n else\n {\n \/\/ the child process\n auto bash_file_name = \"\/bin\/bash\";\n auto bash_fd = open(bash_file_name, O_RDONLY);\n if (bash_fd == -1)\n do_error(\"open(\\\"\" << bash_file_name << \"\\\", O_RDONLY)\");\n\n const char *dash_c = \"-c\";\n const char *script = bash_cmd.c_str();\n const char *do_retry = approx_receive_count < max_retries ? \"1\" : \"0\";\n char *args[]{\n const_cast(bash_file_name),\n const_cast(dash_c),\n const_cast(script),\n const_cast(do_retry),\n 0};\n\n fexecve(bash_fd, &args[0], environ);\n\n \/\/ if fexecve succeeded then we never get here. So getting here is a failure,\n \/\/ but we are already in the child process at this point, so we do what we can\n \/\/ to signifify the error and then exit\n fprintf(stderr, \"fexecve(%d, ...) failed with errno: %d - %s\\n\", bash_fd, errno, strerror(errno));\n exit(1);\n }\n }\n }\n else\n {\n \/\/ no messages after 10 seconds. Check for shutdown\n anon_log(\"no messages after wating period\");\n if (should_shut_down(ec2i))\n {\n\tanon_log(\"no reason to keep running, shutting down\");\n break;\n }\n }\n }\n\n {\n std::unique_lock l(keep_alive_mutex);\n stop = true;\n struct itimerspec t_spec = {0};\n t_spec.it_value = cur_time();\n timerfd_settime(timerfd, TFD_TIMER_ABSTIME, &t_spec, 0);\n }\n keep_alive_thread.join();\n}\n<|endoftext|>"} {"text":"#ifndef _vector_hpp_1337420\r\n#define _vector_hpp_1337420\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \"..\/core\/algorithm.hpp\"\r\n#include \"..\/ztl_base.hpp\"\r\n\r\n__ztl_namespace_start\r\n\ttemplate \r\n\tclass vector {\r\n\tpublic:\r\n\t\ttypedef T\t\t\t\t\t\tvalue_type;\r\n\t\ttypedef T&\t\t\t\t\t\treference;\r\n\t\ttypedef T*\t\t\t\t\t\titerator;\r\n\t\ttypedef const T*\t\t\t\t\t\tconst_iterator;\r\n\t\ttypedef __stl::random_access_iterator_tag\t\titerator_category;\r\n\t\ttypedef __stl::reverse_iterator\t\tconst_reverse_iterator;\r\n\t\ttypedef __stl::reverse_iterator\t\treverse_iterator;\r\n\t\ttypedef size_t\t\t\t\t\t\tsize_type;\r\n\t\ttypedef int\t\t\t\t\t\tdifference_type;\r\n\r\n\tprivate:\r\n\t\titerator p_begin;\r\n\t\titerator p_last;\r\n\t\titerator p_end;\r\n\r\n\t\tinline void enlarge() {\r\n\t\t\tenlarge((p_end - p_begin + 1) * 2);\r\n\t\t}\r\n\r\n\t\tinline void enlarge(int size) {\r\n\t\t\tint n = p_last - p_begin;\r\n\t\t\tp_begin = (iterator)realloc((void*)p_begin, sizeof(value_type) * size);\r\n\t\t\tp_end = p_begin + size - 1;\r\n\t\t\tp_last = p_begin + n;\r\n\t\t}\r\n\r\n\tpublic:\r\n\t\tvector() {\r\n\t\t\tp_begin = p_end = (iterator)malloc(sizeof(value_type));\r\n\t\t\tp_last = p_begin - 1;\r\n\t\t}\r\n\r\n\t\tvector(size_type starting_size) {\r\n\t\t\tp_begin = (iterator)calloc(starting_size, sizeof(value_type));\r\n\t\t\tp_end = p_begin + starting_size - 1;\r\n\t\t\tp_last = p_end - 1;\r\n\t\t}\r\n\t\t\r\n\t\tvector(size_type starting_size, T init_value) {\r\n\t\t\tp_begin = (iterator)malloc(sizeof(value_type) * starting_size);\r\n\t\t\tp_end = p_begin + starting_size - 1;\r\n\t\t\tp_last = p_begin - 1;\r\n\r\n\t\t\tif(sizeof(T) == 1) memset(p_begin, (int)init_value, starting_size);\r\n\t\t\tif(sizeof(T) == 4) memset32(p_begin, init_value, starting_size);\r\n\t\t\telse memset_custom(p_begin, init_value, starting_size);\r\n\t\t}\r\n\r\n\t\t~vector() {\r\n\t\t\tif (!__stl::is_trivially_destructible::value) {\r\n\t\t\t\t++p_last;\r\n\t\t\t\twhile (--p_last >= p_begin) {\r\n\t\t\t\t\t(p_last)->~T();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tfree(p_begin);\r\n\t\t}\r\n\r\n\t\ttemplate\r\n\t\tinline void emplace_back(Args&&... args) {\r\n\t\t\tif (p_last == p_end) enlarge();\r\n\t\t\tnew (++p_last) T(__stl::forward(args)...);\r\n\t\t}\r\n\r\n\t\tinline void push_back(const T& other) {\r\n\t\t\tif (p_last == p_end) enlarge();\r\n\t\t\tnew (++p_last) T(other);\r\n\t\t}\r\n\t\t\r\n\t\tinline void pop_back() {\r\n\t\t\tif (empty()) return;\r\n\t\t\t(p_last--)->~T();\r\n\t\t}\r\n\r\n\t\t\/* Access elements *\/\r\n\t\tinline reference at(unsigned int id) {\r\n\t\t\tif (!(id < size()))\r\n\t\t\t\tthrow __stl::out_of_range(\"Index out of range\");\r\n\t\t\treturn p_begin[id];\r\n\t\t}\r\n\r\n\t\tinline const reference at(unsigned int id) const {\r\n\t\t\tif (!(id < size()))\r\n\t\t\t\tthrow __stl::out_of_range(\"Index out of range\");\r\n\t\t\treturn p_begin[id];\r\n\t\t}\r\n\r\n\t\tinline reference operator[](unsigned int id) { return p_begin[id]; }\r\n\t\tinline const reference operator[](unsigned int id) const { return p_begin[id]; }\r\n\r\n\r\n\t\t\/* Iterators *\/\r\n\t\tinline iterator\t\t\t\tbegin() { return p_begin; }\r\n\t\tinline iterator\t\t\t\tend() { return p_last + 1; }\r\n\t\tinline const_iterator\t\t\tcbegin() const { return p_begin; }\r\n\t\tinline const_iterator\t\t\tcend() const { return p_last + 1; }\r\n\t\tinline reverse_iterator\t\t\trbegin() { return reverse_iterator(end()); }\r\n\t\tinline reverse_iterator\t\t\trend() { return reverse_iterator(p_begin); }\r\n\t\tinline const_reverse_iterator\t\tcrbegin() const { return const_reverse_iterator(cend()); }\r\n\t\tinline const_reverse_iterator\t\tcrend() const { return const_reverse_iterator(p_begin); }\r\n\r\n\t\tinline reference\t\t\tfirst() { return *p_begin; }\r\n\t\tinline const reference\t\t\tfirst() const { return *p_begin; }\r\n\t\tinline reference\t\t\tlast() { return *p_last; }\r\n\t\tinline const reference\t\t\tlast() const { return *p_last; }\r\n\r\n\t\t\/* Size \/ Allocation *\/\r\n\t\tinline bool\t\t\t\tempty() const { return size() == 0; }\r\n\t\tinline size_type\t\t\tsize() const { return p_last - p_begin + 1; }\r\n\t\tinline size_type\t\t\tmax_size() const { return size_type(-1); }\r\n\t\tinline size_type\t\t\treserved() const { return p_end - p_begin + 1; }\r\n\t\tinline void\t\t\t\treserve(size_type num) { enlarge(num); }\r\n\t\tinline void\t\t\t\tclear() { erase(p_begin, p_last); }\r\n\t\tinline void\t\t\t\terase(size_type a, size_type b) { erase(p_begin + a, p_begin + b); }\r\n\t\tinline void\t\t\t\terase(iterator pa, iterator pb) {\r\n\t\t\tif (!__stl::is_trivially_destructible::value) {\r\n\t\t\t\titerator a = pa - 1;\r\n\t\t\t\twhile (a < pb) (++a)->~T();\r\n\t\t\t}\r\n\r\n\t\t\tmemmove(pa, pb + 1, sizeof(value_type) * (p_last - pb));\r\n\t\t\tp_last = pa + (p_last - pb) - 1;\r\n\t\t}\r\n\t};\r\n\r\n__ztl_namespace_end\r\n\r\n#endif \/* _vector_hpp_1337420 *\/\r\nFixed allocation issues#ifndef _vector_hpp_1337420\r\n#define _vector_hpp_1337420\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \"..\/core\/algorithm.hpp\"\r\n#include \"..\/ztl_base.hpp\"\r\n\r\n__ztl_namespace_start\r\n\ttemplate \r\n\tclass vector {\r\n\tpublic:\r\n\t\ttypedef T\t\t\t\t\t\tvalue_type;\r\n\t\ttypedef T&\t\t\t\t\t\treference;\r\n\t\ttypedef T*\t\t\t\t\t\titerator;\r\n\t\ttypedef const T*\t\t\t\t\t\tconst_iterator;\r\n\t\ttypedef __stl::random_access_iterator_tag\t\titerator_category;\r\n\t\ttypedef __stl::reverse_iterator\t\tconst_reverse_iterator;\r\n\t\ttypedef __stl::reverse_iterator\t\treverse_iterator;\r\n\t\ttypedef size_t\t\t\t\t\t\tsize_type;\r\n\t\ttypedef int\t\t\t\t\t\tdifference_type;\r\n\r\n\tprivate:\r\n\t\titerator p_begin;\r\n\t\titerator p_last;\r\n\t\titerator p_end;\r\n\r\n\t\tinline void enlarge() {\r\n\t\t\tenlarge((p_end - p_begin + 1) * 2);\r\n\t\t}\r\n\r\n\t\tinline void enlarge(int size) {\r\n\t\t\tint n = p_last - p_begin;\r\n\t\t\tp_begin = (iterator)realloc((void*)p_begin, sizeof(value_type) * size);\r\n\t\t\tp_end = p_begin + size - 1;\r\n\t\t\tp_last = p_begin + n;\r\n\t\t}\r\n\r\n\tpublic:\r\n\t\tvector() {\r\n\t\t\tp_begin = p_end = (iterator)malloc(sizeof(value_type));\r\n\t\t\tp_last = p_begin - 1;\r\n\t\t}\r\n\r\n\t\tvector(size_type starting_size) {\r\n\t\t\tp_begin = (iterator)calloc(starting_size, sizeof(value_type));\r\n\t\t\tp_end = p_begin + starting_size ;\r\n\t\t\tp_last = p_end - 1;\r\n\t\t}\r\n\t\t\r\n\t\tvector(size_type starting_size, T init_value) {\r\n\t\t\tp_begin = (iterator)malloc(sizeof(value_type) * starting_size);\r\n\t\t\tp_end = p_begin + starting_size;\r\n\t\t\tp_last = p_begin - 1;\r\n\r\n\t\t\tif(sizeof(T) == 1) memset(p_begin, (int)init_value, starting_size);\r\n\t\t\tif(sizeof(T) == 4) memset32(p_begin, init_value, starting_size);\r\n\t\t\telse memset_custom(p_begin, init_value, starting_size);\r\n\t\t}\r\n\r\n\t\t~vector() {\r\n\t\t\tif (!__stl::is_trivially_destructible::value) {\r\n\t\t\t\t++p_last;\r\n\t\t\t\twhile (--p_last >= p_begin) {\r\n\t\t\t\t\t(p_last)->~T();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tfree(p_begin);\r\n\t\t}\r\n\r\n\t\ttemplate\r\n\t\tinline void emplace_back(Args&&... args) {\r\n\t\t\tif (p_last == p_end) enlarge();\r\n\t\t\tnew (++p_last) T(__stl::forward(args)...);\r\n\t\t}\r\n\r\n\t\tinline void push_back(const T& other) {\r\n\t\t\tif (p_last == p_end) enlarge();\r\n\t\t\tnew (++p_last) T(other);\r\n\t\t}\r\n\t\t\r\n\t\tinline void pop_back() {\r\n\t\t\tif (empty()) return;\r\n\t\t\t(p_last--)->~T();\r\n\t\t}\r\n\r\n\t\t\/* Access elements *\/\r\n\t\tinline reference at(unsigned int id) {\r\n\t\t\tif (!(id < size()))\r\n\t\t\t\tthrow __stl::out_of_range(\"Index out of range\");\r\n\t\t\treturn p_begin[id];\r\n\t\t}\r\n\r\n\t\tinline const reference at(unsigned int id) const {\r\n\t\t\tif (!(id < size()))\r\n\t\t\t\tthrow __stl::out_of_range(\"Index out of range\");\r\n\t\t\treturn p_begin[id];\r\n\t\t}\r\n\r\n\t\tinline reference operator[](unsigned int id) { return p_begin[id]; }\r\n\t\tinline const reference operator[](unsigned int id) const { return p_begin[id]; }\r\n\r\n\r\n\t\t\/* Iterators *\/\r\n\t\tinline iterator\t\t\t\tbegin() { return p_begin; }\r\n\t\tinline iterator\t\t\t\tend() { return p_last + 1; }\r\n\t\tinline const_iterator\t\t\tcbegin() const { return p_begin; }\r\n\t\tinline const_iterator\t\t\tcend() const { return p_last + 1; }\r\n\t\tinline reverse_iterator\t\t\trbegin() { return reverse_iterator(end()); }\r\n\t\tinline reverse_iterator\t\t\trend() { return reverse_iterator(p_begin); }\r\n\t\tinline const_reverse_iterator\t\tcrbegin() const { return const_reverse_iterator(cend()); }\r\n\t\tinline const_reverse_iterator\t\tcrend() const { return const_reverse_iterator(p_begin); }\r\n\r\n\t\tinline reference\t\t\tfirst() { return *p_begin; }\r\n\t\tinline const reference\t\t\tfirst() const { return *p_begin; }\r\n\t\tinline reference\t\t\tlast() { return *p_last; }\r\n\t\tinline const reference\t\t\tlast() const { return *p_last; }\r\n\r\n\t\t\/* Size \/ Allocation *\/\r\n\t\tinline bool\t\t\t\tempty() const { return size() == 0; }\r\n\t\tinline size_type\t\t\tsize() const { return p_last - p_begin + 1; }\r\n\t\tinline size_type\t\t\tmax_size() const { return size_type(-1); }\r\n\t\tinline size_type\t\t\treserved() const { return p_end - p_begin + 1; }\r\n\t\tinline void\t\t\t\treserve(size_type num) { enlarge(num); }\r\n\t\tinline void\t\t\t\tclear() { erase(p_begin, p_last); }\r\n\t\tinline void\t\t\t\terase(size_type a, size_type b) { erase(p_begin + a, p_begin + b); }\r\n\t\tinline void\t\t\t\terase(iterator pa, iterator pb) {\r\n\t\t\tif (!__stl::is_trivially_destructible::value) {\r\n\t\t\t\titerator a = pa - 1;\r\n\t\t\t\twhile (a < pb) (++a)->~T();\r\n\t\t\t}\r\n\r\n\t\t\tmemmove(pa, pb + 1, sizeof(value_type) * (p_last - pb));\r\n\t\t\tp_last = pa + (p_last - pb) - 1;\r\n\t\t}\r\n\t};\r\n\r\n__ztl_namespace_end\r\n\r\n#endif \/* _vector_hpp_1337420 *\/\r\n<|endoftext|>"} {"text":"\/\/\n\/\/ Defines main() function and command-line arguments used by ccons.\n\/\/\n\/\/ Part of ccons, the interactive console for the C programming language.\n\/\/\n\/\/ Copyright (c) 2009 Alexei Svitkine. This file is distributed under the\n\/\/ terms of MIT Open Source License. See file LICENSE for details.\n\/\/\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \"Console.h\"\n#include \"EditLineReader.h\"\n#include \"InternalCommands.h\"\n#include \"RemoteConsole.h\"\n\nusing std::string;\nusing ccons::Console;\nusing ccons::IConsole;\nusing ccons::RemoteConsole;\nusing ccons::SerializedOutputConsole;\nusing ccons::LineReader;\nusing ccons::EditLineReader;\nusing ccons::StdInLineReader;\n\nstatic llvm::cl::opt\n\tDebugMode(\"ccons-debug\",\n\t\t\tllvm::cl::desc(\"Print debugging information\"));\nstatic llvm::cl::opt\n\tUseStdIo(\"ccons-use-std-io\",\n\t\t\tllvm::cl::desc(\"Use standard IO for input and output\"));\nstatic llvm::cl::opt\n\tSerializedOutput(\"ccons-serialized-output\",\n\t\t\tllvm::cl::desc(\"Output will be serialized\"));\nstatic llvm::cl::opt\n\tMultiProcess(\"ccons-multi-process\",\n\t\t\tllvm::cl::desc(\"Run in multi-process mode\"));\n\nstatic IConsole * createConsole()\n{\n\tif (MultiProcess)\n\t\treturn new RemoteConsole(DebugMode);\n\telse if (SerializedOutput)\n\t\treturn new SerializedOutputConsole(DebugMode);\t\t\n\telse\n\t\treturn new Console(DebugMode);\n}\n\nstatic LineReader * createReader()\n{\n\tif (UseStdIo)\n\t\treturn new StdInLineReader;\n\telse\n\t\treturn new EditLineReader;\n}\n\nextern \"C\" void LLVMInitializeX86TargetMC();\n\nint main(const int argc, char **argv)\n{\n\tllvm::cl::SetVersionPrinter(ccons::PrintVersionInformation);\n\tllvm::cl::ParseCommandLineOptions(argc, argv, \"ccons Interactive C Console\\n\",\n\t false\/*, \"ccons-\"*\/);\n\n\tif (DebugMode && !SerializedOutput) {\n\t\tstd::cerr << \"NOTE: Debugging information will be displayed.\\n\";\n\t\tllvm::sys::PrintStackTraceOnErrorSignal();\n\t}\n\n\tLLVMInitializeNativeTarget();\n\n\t\/\/ FIXME: This shouldn't be needed - it should have been done by llvm::InitializeNativeTarget().\n\t\/\/ TODO: Bisect builds and report a bug to LLVM if this doesn't disappear soon. I noticed the breakage at r139193 of LLVM.\n\tLLVMInitializeX86TargetMC();\n\n\tllvm::OwningPtr console(createConsole());\n\tllvm::OwningPtr reader(createReader());\n\n\tconst char *line = reader->readLine(console->prompt(), console->input());\n\twhile (line) {\n\t\tconsole->process(line);\n\t\tline = reader->readLine(console->prompt(), console->input());\n\t}\n\n\treturn 0;\n}\n\nremove FIXME\/TODO since the llvm bug has been fixed\/\/\n\/\/ Defines main() function and command-line arguments used by ccons.\n\/\/\n\/\/ Part of ccons, the interactive console for the C programming language.\n\/\/\n\/\/ Copyright (c) 2009 Alexei Svitkine. This file is distributed under the\n\/\/ terms of MIT Open Source License. See file LICENSE for details.\n\/\/\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \"Console.h\"\n#include \"EditLineReader.h\"\n#include \"InternalCommands.h\"\n#include \"RemoteConsole.h\"\n\nusing std::string;\nusing ccons::Console;\nusing ccons::IConsole;\nusing ccons::RemoteConsole;\nusing ccons::SerializedOutputConsole;\nusing ccons::LineReader;\nusing ccons::EditLineReader;\nusing ccons::StdInLineReader;\n\nstatic llvm::cl::opt\n\tDebugMode(\"ccons-debug\",\n\t\t\tllvm::cl::desc(\"Print debugging information\"));\nstatic llvm::cl::opt\n\tUseStdIo(\"ccons-use-std-io\",\n\t\t\tllvm::cl::desc(\"Use standard IO for input and output\"));\nstatic llvm::cl::opt\n\tSerializedOutput(\"ccons-serialized-output\",\n\t\t\tllvm::cl::desc(\"Output will be serialized\"));\nstatic llvm::cl::opt\n\tMultiProcess(\"ccons-multi-process\",\n\t\t\tllvm::cl::desc(\"Run in multi-process mode\"));\n\nstatic IConsole * createConsole()\n{\n\tif (MultiProcess)\n\t\treturn new RemoteConsole(DebugMode);\n\telse if (SerializedOutput)\n\t\treturn new SerializedOutputConsole(DebugMode);\t\t\n\telse\n\t\treturn new Console(DebugMode);\n}\n\nstatic LineReader * createReader()\n{\n\tif (UseStdIo)\n\t\treturn new StdInLineReader;\n\telse\n\t\treturn new EditLineReader;\n}\n\nextern \"C\" void LLVMInitializeX86TargetMC();\n\nint main(const int argc, char **argv)\n{\n\tllvm::cl::SetVersionPrinter(ccons::PrintVersionInformation);\n\tllvm::cl::ParseCommandLineOptions(argc, argv, \"ccons Interactive C Console\\n\",\n\t false\/*, \"ccons-\"*\/);\n\n\tif (DebugMode && !SerializedOutput) {\n\t\tstd::cerr << \"NOTE: Debugging information will be displayed.\\n\";\n\t\tllvm::sys::PrintStackTraceOnErrorSignal();\n\t}\n\n\tLLVMInitializeNativeTarget();\n\n\tllvm::OwningPtr console(createConsole());\n\tllvm::OwningPtr reader(createReader());\n\n\tconst char *line = reader->readLine(console->prompt(), console->input());\n\twhile (line) {\n\t\tconsole->process(line);\n\t\tline = reader->readLine(console->prompt(), console->input());\n\t}\n\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"\/** \\file find_tue_dups.cc\n * \\author Dr. Johannes Ruscheinski\n *\n * Local data blocks are embedded marc records inside of a record using LOK-Fields.\n * Each local data block belongs to an institution and is marked by the institution's sigil.\n * This tool filters for local data blocks of some institutions of the University of Tübingen\n * and deletes all other local blocks.\n *\/\n\n\/*\n Copyright (C) 2017, Library of the University of Tübingen\n\n This program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Affero General Public License as\n published by the Free Software Foundation, either version 3 of the\n License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with this program. If not, see .\n*\/\n\n#include \n#include \n#include \n#include \"Compiler.h\"\n#include \"TextUtil.h\"\n#include \"MarcRecord.h\"\n#include \"RegexMatcher.h\"\n#include \"util.h\"\n\n\nvoid Usage() {\n std::cerr << \"Usage: \" << ::progname << \" --input-format=(BSZ|UB_FREIBURG) marc_input\\n\";\n std::exit(EXIT_FAILURE);\n}\n\n\nstatic const RegexMatcher * const tue_sigil_matcher(RegexMatcher::RegexMatcherFactory(\"^DE-21.*\"));\n\n\nbool FindTueSigil(const MarcRecord * const record, const std::pair &block_start_and_end,\n std::string * const sigil)\n{\n std::vector field_indices;\n record->findFieldsInLocalBlock(\"852\", \"??\", block_start_and_end, &field_indices);\n\n for (size_t field_index : field_indices) {\n const std::string field_data(record->getFieldData(field_index));\n const Subfields subfields(field_data);\n if (subfields.extractSubfieldWithPattern('a', *tue_sigil_matcher, sigil))\n return true;\n }\n return false;\n}\n\n\nstd::string CSVEscape(const std::string &value) {\n std::string escaped_value;\n escaped_value.reserve(value.length());\n\n std::vector utf32_chars;\n if (unlikely(not TextUtil::UTF8ToUTF32(value, &utf32_chars)))\n return \"\";\n\n for (const uint32_t ch : utf32_chars) {\n if (unlikely(ch == '\"'))\n escaped_value += '\"';\n escaped_value += TextUtil::UTF32ToUTF8(ch);\n }\n\n return escaped_value;\n}\n\n\nenum InputFormat { BSZ, UB_FREIBURG };\n\n\nbool FindTueDups(const InputFormat input_format, const MarcRecord * const record) {\n std::vector sigils;\n if (input_format == BSZ) {\n std::vector> local_block_boundaries;\n ssize_t local_data_count = record->findAllLocalDataBlocks(&local_block_boundaries);\n if (local_data_count == 0)\n return false;\n\n for (const auto &block_start_and_end : local_block_boundaries) {\n std::string sigil;\n if (FindTueSigil(record, block_start_and_end, &sigil))\n sigils.emplace_back(sigil);\n }\n } else { \/\/ input_format == UB_FREIBURG\n std::vector _910_indices;\n record->getFieldIndices(\"910\", &_910_indices);\n for (const size_t _910_index : _910_indices) {\n const std::string _910_field_contents(record->getFieldData(_910_index));\n if (_910_field_contents.empty())\n continue;\n const Subfields subfields(_910_field_contents);\n const std::string sigil(subfields.getFirstSubfieldValue('c'));\n if (not sigil.empty())\n sigils.emplace_back(sigil);\n }\n }\n\n if (sigils.size() < 2)\n return false;\n\n const std::string _008_contents(record->getFieldData(\"008\"));\n std::string publication_year;\n if (likely(_008_contents.length() >= 11))\n publication_year = _008_contents.substr(7, 4);\n\n const std::string _079_contents(record->getFieldData(\"008\"));\n std::string area;\n if (not _079_contents.empty()) {\n const Subfields subfields(_079_contents);\n area = subfields.getFirstSubfieldValue('f');\n }\n\n const std::string _245_contents(record->getFieldData(\"245\"));\n std::string main_title;\n if (not _245_contents.empty()) {\n const Subfields subfields(_245_contents);\n main_title = subfields.getFirstSubfieldValue('a');\n }\n\n std::sort(sigils.begin(), sigils.end());\n std::cout << '\"' << record->getControlNumber() << \"\\\",\\\"\" << publication_year << \"\\\",\\\"\" << area <<\"\\\",\\\"\"\n << CSVEscape(main_title) << \"\\\",\\\"\" << StringUtil::Join(sigils, ',') << \"\\\"\\n\";\n\n return true;\n}\n\n\nvoid FindTueDups(const InputFormat input_format, MarcReader * const marc_reader) {\n unsigned count(0), dups_count(0), monograph_count(0), serial_count(0);\n while (MarcRecord record = marc_reader->read()) {\n ++count;\n\n \/\/ Only consider monographs and serials:\n const Leader &leader(record.getLeader());\n if (not (leader.isMonograph() or leader.isSerial()))\n continue;\n\n if (FindTueDups(input_format, &record)) {\n ++dups_count;\n if (leader.isMonograph())\n ++monograph_count;\n else\n ++serial_count;\n }\n }\n std::cerr << \"Processed \" << count << \" records and found \" << dups_count << \" dups (\" << monograph_count\n << \" monographs and \" << serial_count << \" serials).\\n\";\n}\n\n\nint main(int argc, char **argv) {\n ::progname = argv[0];\n\n if (argc != 3)\n Usage();\n\n InputFormat input_format;\n if (std::strcmp(argv[1], \"--input-format=BSZ\") == 0)\n input_format = BSZ;\n else if (std::strcmp(argv[1], \"--input-format=UB_FREIBURG\") == 0)\n input_format = UB_FREIBURG;\n else\n Error(\"invalid input format \\\"\" + std::string(argv[1]) + \"\\\"! (Must be either BSZ or UB_FREIBURG)\");\n\n std::unique_ptr marc_reader(MarcReader::Factory(argv[2], MarcReader::BINARY));\n\n try {\n FindTueDups(input_format, marc_reader.get());\n } catch (const std::exception &x) {\n Error(\"caught exception: \" + std::string(x.what()));\n }\n}\nSmall improvements.\/** \\file find_tue_dups.cc\n * \\author Dr. Johannes Ruscheinski\n *\/\n\n\/*\n Copyright (C) 2017, Library of the University of Tübingen\n\n This program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Affero General Public License as\n published by the Free Software Foundation, either version 3 of the\n License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with this program. If not, see .\n*\/\n\n#include \n#include \n#include \n#include \"Compiler.h\"\n#include \"TextUtil.h\"\n#include \"MarcRecord.h\"\n#include \"RegexMatcher.h\"\n#include \"util.h\"\n\n\nvoid Usage() {\n std::cerr << \"Usage: \" << ::progname << \" --input-format=(BSZ|UB_FREIBURG) marc_input\\n\";\n std::exit(EXIT_FAILURE);\n}\n\n\nstatic const RegexMatcher * const tue_sigil_matcher(RegexMatcher::RegexMatcherFactory(\"^DE-21.*\"));\n\n\nbool FindTueSigil(const MarcRecord * const record, const std::pair &block_start_and_end,\n std::string * const sigil)\n{\n std::vector field_indices;\n record->findFieldsInLocalBlock(\"852\", \"??\", block_start_and_end, &field_indices);\n\n for (size_t field_index : field_indices) {\n const std::string field_data(record->getFieldData(field_index));\n const Subfields subfields(field_data);\n if (subfields.extractSubfieldWithPattern('a', *tue_sigil_matcher, sigil))\n return true;\n }\n return false;\n}\n\n\nstd::string CSVEscape(const std::string &value) {\n std::string escaped_value;\n escaped_value.reserve(value.length());\n\n std::vector utf32_chars;\n if (unlikely(not TextUtil::UTF8ToUTF32(value, &utf32_chars)))\n return \"\";\n\n for (const uint32_t ch : utf32_chars) {\n if (unlikely(ch == '\"'))\n escaped_value += '\"';\n escaped_value += TextUtil::UTF32ToUTF8(ch);\n }\n\n return escaped_value;\n}\n\n\nenum InputFormat { BSZ, UB_FREIBURG };\n\n\nbool FindTueDups(const InputFormat input_format, const char bibliographic_level, const MarcRecord * const record) {\n std::vector sigils;\n if (input_format == BSZ) {\n std::vector> local_block_boundaries;\n ssize_t local_data_count = record->findAllLocalDataBlocks(&local_block_boundaries);\n if (local_data_count == 0)\n return false;\n\n for (const auto &block_start_and_end : local_block_boundaries) {\n std::string sigil;\n if (FindTueSigil(record, block_start_and_end, &sigil))\n sigils.emplace_back(sigil);\n }\n } else { \/\/ input_format == UB_FREIBURG\n std::vector _910_indices;\n record->getFieldIndices(\"910\", &_910_indices);\n for (const size_t _910_index : _910_indices) {\n const std::string _910_field_contents(record->getFieldData(_910_index));\n if (_910_field_contents.empty())\n continue;\n const Subfields subfields(_910_field_contents);\n const std::string sigil(subfields.getFirstSubfieldValue('c'));\n if (not sigil.empty())\n sigils.emplace_back(sigil);\n }\n }\n\n if (sigils.size() < 2)\n return false;\n\n const std::string _008_contents(record->getFieldData(\"008\"));\n std::string publication_year;\n if (likely(_008_contents.length() >= 11))\n publication_year = _008_contents.substr(7, 4);\n\n std::string area;\n\n \/\/ Only determine the area if we're have the sigil of the university main library:\n if (std::find(sigils.cbegin(), sigils.cend(), \"21\") != sigils.cend()) {\n const std::string _910_contents(record->getFieldData(\"910\"));\n if (not _910_contents.empty()) {\n const Subfields subfields(_910_contents);\n area = subfields.getFirstSubfieldValue('j');\n }\n }\n\n const std::string _245_contents(record->getFieldData(\"245\"));\n std::string main_title;\n if (not _245_contents.empty()) {\n const Subfields subfields(_245_contents);\n main_title = subfields.getFirstSubfieldValue('a');\n }\n\n std::sort(sigils.begin(), sigils.end());\n std::cout << '\"' << record->getControlNumber() << \"\\\",\\\"\" << bibliographic_level << \"\\\",\\\"\" << publication_year\n << \"\\\",\\\"\" << area <<\"\\\",\\\"\" << CSVEscape(main_title) << \"\\\",\\\"\" << StringUtil::Join(sigils, ',')\n << \"\\\"\\n\";\n\n return true;\n}\n\n\nvoid FindTueDups(const InputFormat input_format, MarcReader * const marc_reader) {\n unsigned count(0), dups_count(0), monograph_count(0), serial_count(0);\n while (MarcRecord record = marc_reader->read()) {\n ++count;\n\n \/\/ Only consider monographs and serials:\n const Leader &leader(record.getLeader());\n if (not (leader.isMonograph() or leader.isSerial()))\n continue;\n\n if (FindTueDups(input_format, leader.getBibliographicLevel(), &record)) {\n ++dups_count;\n if (leader.isMonograph())\n ++monograph_count;\n else\n ++serial_count;\n }\n }\n std::cerr << \"Processed \" << count << \" records and found \" << dups_count << \" dups (\" << monograph_count\n << \" monographs and \" << serial_count << \" serials).\\n\";\n}\n\n\nint main(int argc, char **argv) {\n ::progname = argv[0];\n\n if (argc != 3)\n Usage();\n\n InputFormat input_format;\n if (std::strcmp(argv[1], \"--input-format=BSZ\") == 0)\n input_format = BSZ;\n else if (std::strcmp(argv[1], \"--input-format=UB_FREIBURG\") == 0)\n input_format = UB_FREIBURG;\n else\n Error(\"invalid input format \\\"\" + std::string(argv[1]) + \"\\\"! (Must be either BSZ or UB_FREIBURG)\");\n\n std::unique_ptr marc_reader(MarcReader::Factory(argv[2], MarcReader::BINARY));\n\n try {\n FindTueDups(input_format, marc_reader.get());\n } catch (const std::exception &x) {\n Error(\"caught exception: \" + std::string(x.what()));\n }\n}\n<|endoftext|>"} {"text":"#ifndef ITER_CHAIN_HPP_\n#define ITER_CHAIN_HPP_\n\n#include \"internal\/iterbase.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace iter {\n namespace impl {\n template \n class Chained;\n\n template \n class ChainedFromIterable;\n\n \/\/ rather than a chain function, use a callable object to support\n \/\/ from_iterable\n class ChainMaker;\n }\n}\n\ntemplate \nclass iter::impl::Chained {\n private:\n friend class ChainMaker;\n\n static_assert(std::tuple_size>::value == sizeof...(Is),\n \"tuple size != sizeof Is\");\n\n static_assert(\n are_same>...>::value,\n \"All chained iterables must have iterators that \"\n \"dereference to the same type, including cv-qualifiers \"\n \"and references.\");\n\n using IterTupType = iterator_tuple_type;\n using DerefType = iterator_deref>;\n\n template \n static DerefType get_and_deref(IterTupType& iters) {\n return *std::get(iters);\n }\n\n template \n static void get_and_increment(IterTupType& iters) {\n ++std::get(iters);\n }\n\n template \n static bool get_and_check_not_equal(\n const IterTupType& lhs, const IterTupType& rhs) {\n return std::get(lhs) != std::get(rhs);\n }\n\n using DerefFunc = DerefType (*)(IterTupType&);\n using IncFunc = void (*)(IterTupType&);\n using NeqFunc = bool (*)(const IterTupType&, const IterTupType&);\n\n constexpr static std::array derefers{\n {get_and_deref...}};\n\n constexpr static std::array incrementers{\n {get_and_increment...}};\n\n constexpr static std::array neq_comparers{\n {get_and_check_not_equal...}};\n\n using TraitsValue = iterator_traits_deref>;\n\n private:\n TupType tup;\n\n public:\n Chained(Chained&&) = default;\n Chained(TupType&& t) : tup(std::move(t)) {}\n\n class Iterator : public std::iterator {\n private:\n std::size_t index;\n IterTupType iters;\n IterTupType ends;\n\n void check_for_end_and_adjust() {\n while (this->index < sizeof...(Is)\n && !(neq_comparers[this->index](this->iters, this->ends))) {\n ++this->index;\n }\n }\n\n public:\n Iterator(std::size_t i, IterTupType&& in_iters, IterTupType&& in_ends)\n : index{i}, iters(in_iters), ends(in_ends) {\n this->check_for_end_and_adjust();\n }\n\n decltype(auto) operator*() {\n return derefers[this->index](this->iters);\n }\n\n Iterator& operator++() {\n incrementers[this->index](this->iters);\n this->check_for_end_and_adjust();\n return *this;\n }\n\n Iterator operator++(int) {\n auto ret = *this;\n ++*this;\n return ret;\n }\n\n bool operator!=(const Iterator& other) const {\n return this->index != other.index\n || (this->index != sizeof...(Is)\n && neq_comparers[this->index](this->iters, other.iters));\n }\n\n bool operator==(const Iterator& other) const {\n return !(*this != other);\n }\n };\n\n Iterator begin() {\n return {0, IterTupType{std::begin(std::get(this->tup))...},\n IterTupType{std::end(std::get(this->tup))...}};\n }\n\n Iterator end() {\n return {sizeof...(Is), IterTupType{std::end(std::get(this->tup))...},\n IterTupType{std::end(std::get(this->tup))...}};\n }\n};\n\ntemplate \nconstexpr std::array::DerefFunc,\n sizeof...(Is)> iter::impl::Chained::derefers;\n\ntemplate \nconstexpr std::array::IncFunc,\n sizeof...(Is)> iter::impl::Chained::incrementers;\n\ntemplate \nconstexpr std::array::NeqFunc,\n sizeof...(Is)> iter::impl::Chained::neq_comparers;\n\ntemplate \nclass iter::impl::ChainedFromIterable {\n private:\n Container container;\n friend class ChainMaker;\n ChainedFromIterable(Container&& in_container)\n : container(std::forward(in_container)) {}\n\n public:\n class Iterator : public std::iterator>> {\n private:\n using SubContainer = iterator_deref;\n using SubIter = iterator_type;\n\n iterator_type top_level_iter;\n iterator_type top_level_end;\n std::unique_ptr sub_iter_p;\n std::unique_ptr sub_end_p;\n\n static std::unique_ptr clone_sub_pointer(const SubIter* sub_iter) {\n return sub_iter ? std::make_unique(*sub_iter) : nullptr;\n }\n\n bool sub_iters_differ(const Iterator& other) const {\n if (this->sub_iter_p == other.sub_iter_p) {\n return false;\n }\n if (this->sub_iter_p == nullptr || other.sub_iter_p == nullptr) {\n \/\/ since the first check tests if they're the same,\n \/\/ this will return if only one is nullptr\n return true;\n }\n return *this->sub_iter_p != *other.sub_iter_p;\n }\n\n public:\n Iterator(\n iterator_type&& top_iter, iterator_type&& top_end)\n : top_level_iter{std::move(top_iter)},\n top_level_end{std::move(top_end)},\n sub_iter_p{!(top_iter != top_end)\n ? \/\/ iter == end ?\n nullptr\n : std::make_unique(std::begin(*top_iter))},\n sub_end_p{!(top_iter != top_end)\n ? \/\/ iter == end ?\n nullptr\n : std::make_unique(std::end(*top_iter))} {}\n\n Iterator(const Iterator& other)\n : top_level_iter{other.top_level_iter},\n top_level_end{other.top_level_end},\n sub_iter_p{clone_sub_pointer(other.sub_iter_p.get())},\n sub_end_p{clone_sub_pointer(other.sub_end_p.get())} {}\n\n Iterator& operator=(const Iterator& other) {\n if (this == &other) return *this;\n\n this->top_level_iter = other.top_level_iter;\n this->top_level_end = other.top_level_end;\n this->sub_iter_p = clone_sub_pointer(other.sub_iter_p.get());\n this->sub_end_p = clone_sub_pointer(other.sub_end_p.get());\n\n return *this;\n }\n\n Iterator(Iterator&&) = default;\n Iterator& operator=(Iterator&&) = default;\n ~Iterator() = default;\n\n Iterator& operator++() {\n ++*this->sub_iter_p;\n if (!(*this->sub_iter_p != *this->sub_end_p)) {\n ++this->top_level_iter;\n if (this->top_level_iter != this->top_level_end) {\n sub_iter_p =\n std::make_unique(std::begin(*this->top_level_iter));\n sub_end_p =\n std::make_unique(std::end(*this->top_level_iter));\n } else {\n sub_iter_p.reset();\n sub_end_p.reset();\n }\n }\n return *this;\n }\n\n Iterator operator++(int) {\n auto ret = *this;\n ++*this;\n return ret;\n }\n\n bool operator!=(const Iterator& other) const {\n return this->top_level_iter != other.top_level_iter\n || this->sub_iters_differ(other);\n }\n\n bool operator==(const Iterator& other) const {\n return !(*this != other);\n }\n\n iterator_deref> operator*() {\n return **this->sub_iter_p;\n }\n };\n\n Iterator begin() {\n return {std::begin(this->container), std::end(this->container)};\n }\n\n Iterator end() {\n return {std::end(this->container), std::end(this->container)};\n }\n};\n\nclass iter::impl::ChainMaker {\n private:\n template \n Chained chain_impl(\n TupleType&& in_containers, std::index_sequence) const {\n return {std::move(in_containers)};\n }\n\n public:\n \/\/ expose regular call operator to provide usual chain()\n template \n auto operator()(Containers&&... cs) const {\n return this->chain_impl(\n std::tuple{std::forward(cs)...},\n std::index_sequence_for{});\n }\n\n \/\/ chain.from_iterable\n template \n ChainedFromIterable from_iterable(Container&& container) const {\n return {std::forward(container)};\n }\n};\n\nnamespace iter {\n namespace {\n constexpr auto chain = iter::impl::ChainMaker{};\n }\n}\n\n#endif\nimplements chain.from_iterable arrow#ifndef ITER_CHAIN_HPP_\n#define ITER_CHAIN_HPP_\n\n#include \"internal\/iterbase.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace iter {\n namespace impl {\n template \n class Chained;\n\n template \n class ChainedFromIterable;\n\n \/\/ rather than a chain function, use a callable object to support\n \/\/ from_iterable\n class ChainMaker;\n }\n}\n\ntemplate \nclass iter::impl::Chained {\n private:\n friend class ChainMaker;\n\n static_assert(std::tuple_size>::value == sizeof...(Is),\n \"tuple size != sizeof Is\");\n\n static_assert(\n are_same>...>::value,\n \"All chained iterables must have iterators that \"\n \"dereference to the same type, including cv-qualifiers \"\n \"and references.\");\n\n using IterTupType = iterator_tuple_type;\n using DerefType = iterator_deref>;\n\n template \n static DerefType get_and_deref(IterTupType& iters) {\n return *std::get(iters);\n }\n\n template \n static void get_and_increment(IterTupType& iters) {\n ++std::get(iters);\n }\n\n template \n static bool get_and_check_not_equal(\n const IterTupType& lhs, const IterTupType& rhs) {\n return std::get(lhs) != std::get(rhs);\n }\n\n using DerefFunc = DerefType (*)(IterTupType&);\n using IncFunc = void (*)(IterTupType&);\n using NeqFunc = bool (*)(const IterTupType&, const IterTupType&);\n\n constexpr static std::array derefers{\n {get_and_deref...}};\n\n constexpr static std::array incrementers{\n {get_and_increment...}};\n\n constexpr static std::array neq_comparers{\n {get_and_check_not_equal...}};\n\n using TraitsValue = iterator_traits_deref>;\n\n private:\n TupType tup;\n\n public:\n Chained(Chained&&) = default;\n Chained(TupType&& t) : tup(std::move(t)) {}\n\n class Iterator : public std::iterator {\n private:\n std::size_t index;\n IterTupType iters;\n IterTupType ends;\n\n void check_for_end_and_adjust() {\n while (this->index < sizeof...(Is)\n && !(neq_comparers[this->index](this->iters, this->ends))) {\n ++this->index;\n }\n }\n\n public:\n Iterator(std::size_t i, IterTupType&& in_iters, IterTupType&& in_ends)\n : index{i}, iters(in_iters), ends(in_ends) {\n this->check_for_end_and_adjust();\n }\n\n decltype(auto) operator*() {\n return derefers[this->index](this->iters);\n }\n\n Iterator& operator++() {\n incrementers[this->index](this->iters);\n this->check_for_end_and_adjust();\n return *this;\n }\n\n Iterator operator++(int) {\n auto ret = *this;\n ++*this;\n return ret;\n }\n\n bool operator!=(const Iterator& other) const {\n return this->index != other.index\n || (this->index != sizeof...(Is)\n && neq_comparers[this->index](this->iters, other.iters));\n }\n\n bool operator==(const Iterator& other) const {\n return !(*this != other);\n }\n };\n\n Iterator begin() {\n return {0, IterTupType{std::begin(std::get(this->tup))...},\n IterTupType{std::end(std::get(this->tup))...}};\n }\n\n Iterator end() {\n return {sizeof...(Is), IterTupType{std::end(std::get(this->tup))...},\n IterTupType{std::end(std::get(this->tup))...}};\n }\n};\n\ntemplate \nconstexpr std::array::DerefFunc,\n sizeof...(Is)> iter::impl::Chained::derefers;\n\ntemplate \nconstexpr std::array::IncFunc,\n sizeof...(Is)> iter::impl::Chained::incrementers;\n\ntemplate \nconstexpr std::array::NeqFunc,\n sizeof...(Is)> iter::impl::Chained::neq_comparers;\n\ntemplate \nclass iter::impl::ChainedFromIterable {\n private:\n Container container;\n friend class ChainMaker;\n ChainedFromIterable(Container&& in_container)\n : container(std::forward(in_container)) {}\n\n public:\n class Iterator : public std::iterator>> {\n private:\n using SubContainer = iterator_deref;\n using SubIter = iterator_type;\n\n iterator_type top_level_iter;\n iterator_type top_level_end;\n std::unique_ptr sub_iter_p;\n std::unique_ptr sub_end_p;\n\n static std::unique_ptr clone_sub_pointer(const SubIter* sub_iter) {\n return sub_iter ? std::make_unique(*sub_iter) : nullptr;\n }\n\n bool sub_iters_differ(const Iterator& other) const {\n if (this->sub_iter_p == other.sub_iter_p) {\n return false;\n }\n if (this->sub_iter_p == nullptr || other.sub_iter_p == nullptr) {\n \/\/ since the first check tests if they're the same,\n \/\/ this will return if only one is nullptr\n return true;\n }\n return *this->sub_iter_p != *other.sub_iter_p;\n }\n\n public:\n Iterator(\n iterator_type&& top_iter, iterator_type&& top_end)\n : top_level_iter{std::move(top_iter)},\n top_level_end{std::move(top_end)},\n sub_iter_p{!(top_iter != top_end)\n ? \/\/ iter == end ?\n nullptr\n : std::make_unique(std::begin(*top_iter))},\n sub_end_p{!(top_iter != top_end)\n ? \/\/ iter == end ?\n nullptr\n : std::make_unique(std::end(*top_iter))} {}\n\n Iterator(const Iterator& other)\n : top_level_iter{other.top_level_iter},\n top_level_end{other.top_level_end},\n sub_iter_p{clone_sub_pointer(other.sub_iter_p.get())},\n sub_end_p{clone_sub_pointer(other.sub_end_p.get())} {}\n\n Iterator& operator=(const Iterator& other) {\n if (this == &other) return *this;\n\n this->top_level_iter = other.top_level_iter;\n this->top_level_end = other.top_level_end;\n this->sub_iter_p = clone_sub_pointer(other.sub_iter_p.get());\n this->sub_end_p = clone_sub_pointer(other.sub_end_p.get());\n\n return *this;\n }\n\n Iterator(Iterator&&) = default;\n Iterator& operator=(Iterator&&) = default;\n ~Iterator() = default;\n\n Iterator& operator++() {\n ++*this->sub_iter_p;\n if (!(*this->sub_iter_p != *this->sub_end_p)) {\n ++this->top_level_iter;\n if (this->top_level_iter != this->top_level_end) {\n sub_iter_p =\n std::make_unique(std::begin(*this->top_level_iter));\n sub_end_p =\n std::make_unique(std::end(*this->top_level_iter));\n } else {\n sub_iter_p.reset();\n sub_end_p.reset();\n }\n }\n return *this;\n }\n\n Iterator operator++(int) {\n auto ret = *this;\n ++*this;\n return ret;\n }\n\n bool operator!=(const Iterator& other) const {\n return this->top_level_iter != other.top_level_iter\n || this->sub_iters_differ(other);\n }\n\n bool operator==(const Iterator& other) const {\n return !(*this != other);\n }\n\n iterator_deref> operator*() {\n return **this->sub_iter_p;\n }\n\n iterator_arrow> operator->() {\n return apply_arrow(*this->sub_iter_p);\n }\n };\n\n Iterator begin() {\n return {std::begin(this->container), std::end(this->container)};\n }\n\n Iterator end() {\n return {std::end(this->container), std::end(this->container)};\n }\n};\n\nclass iter::impl::ChainMaker {\n private:\n template \n Chained chain_impl(\n TupleType&& in_containers, std::index_sequence) const {\n return {std::move(in_containers)};\n }\n\n public:\n \/\/ expose regular call operator to provide usual chain()\n template \n auto operator()(Containers&&... cs) const {\n return this->chain_impl(\n std::tuple{std::forward(cs)...},\n std::index_sequence_for{});\n }\n\n \/\/ chain.from_iterable\n template \n ChainedFromIterable from_iterable(Container&& container) const {\n return {std::forward(container)};\n }\n};\n\nnamespace iter {\n namespace {\n constexpr auto chain = iter::impl::ChainMaker{};\n }\n}\n\n#endif\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2013 GitHub, Inc. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \n\n#include \"content\/public\/app\/content_main.h\"\n\nnamespace node {\nint Start(int argc, char *argv[]);\n}\n\n#if defined(OS_WIN)\n\n#include \/\/ NOLINT\n\n#include \"app\/atom_main_delegate.h\"\n#include \"content\/public\/app\/startup_helper_win.h\"\n#include \"sandbox\/win\/src\/sandbox_types.h\"\n\nint APIENTRY wWinMain(HINSTANCE instance, HINSTANCE, wchar_t* wargv, int argc) {\n const wchar_t* wargv1 = reinterpret_cast(wargv[1]);\n if (argc > 1 && wcscmp(wargv1, L\"--atom-child_process-fork\") == 0) {\n \/\/ Convert argv to to UTF8\n char** argv = new char*[argc];\n for (int i = 0; i < argc; i++) {\n const wchar_t* wargvi = reinterpret_cast(wargv[i]);\n \/\/ Compute the size of the required buffer\n DWORD size = WideCharToMultiByte(CP_UTF8,\n 0,\n wargvi,\n -1,\n NULL,\n 0,\n NULL,\n NULL);\n if (size == 0) {\n \/\/ This should never happen.\n fprintf(stderr, \"Could not convert arguments to utf8.\");\n exit(1);\n }\n \/\/ Do the actual conversion\n argv[i] = new char[size];\n DWORD result = WideCharToMultiByte(CP_UTF8,\n 0,\n wargvi,\n -1,\n argv[i],\n size,\n NULL,\n NULL);\n if (result == 0) {\n \/\/ This should never happen.\n fprintf(stderr, \"Could not convert arguments to utf8.\");\n exit(1);\n }\n }\n \/\/ Now that conversion is done, we can finally start.\n argv[1] = argv[0];\n return node::Start(argc - 1, argv + 1);\n }\n\n sandbox::SandboxInterfaceInfo sandbox_info = {0};\n content::InitializeSandboxInfo(&sandbox_info);\n atom::AtomMainDelegate delegate;\n return content::ContentMain(instance, &sandbox_info, &delegate);\n}\n\n#else \/\/ defined(OS_WIN)\n\n#include \"app\/atom_library_main.h\"\n\nint main(int argc, const char* argv[]) {\n if (argc > 1 && strcmp(argv[1], \"--atom-child_process-fork\") == 0) {\n argv[1] = argv[0];\n return node::Start(argc - 1, const_cast(argv + 1));\n }\n\n return AtomMain(argc, argv);\n}\n\n#endif\n[Win] Fix the command line spliting code.\/\/ Copyright (c) 2013 GitHub, Inc. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \n\n#include \"content\/public\/app\/content_main.h\"\n\nnamespace node {\nint Start(int argc, char *argv[]);\n}\n\n#if defined(OS_WIN)\n\n#include \/\/ NOLINT\n#include \/\/ NOLINT\n\n#include \"app\/atom_main_delegate.h\"\n#include \"content\/public\/app\/startup_helper_win.h\"\n#include \"sandbox\/win\/src\/sandbox_types.h\"\n\nint APIENTRY wWinMain(HINSTANCE instance, HINSTANCE, wchar_t* cmd, int) {\n int argc = 0;\n wchar_t** wargv = ::CommandLineToArgvW(cmd, &argc);\n if (argc > 1 && wcscmp(wargv[1], L\"--atom-child_process-fork\") == 0) {\n \/\/ Convert argv to to UTF8\n char** argv = new char*[argc];\n for (int i = 0; i < argc; i++) {\n \/\/ Compute the size of the required buffer\n DWORD size = WideCharToMultiByte(CP_UTF8,\n 0,\n wargv[i],\n -1,\n NULL,\n 0,\n NULL,\n NULL);\n if (size == 0) {\n \/\/ This should never happen.\n fprintf(stderr, \"Could not convert arguments to utf8.\");\n exit(1);\n }\n \/\/ Do the actual conversion\n argv[i] = new char[size];\n DWORD result = WideCharToMultiByte(CP_UTF8,\n 0,\n wargv[i],\n -1,\n argv[i],\n size,\n NULL,\n NULL);\n if (result == 0) {\n \/\/ This should never happen.\n fprintf(stderr, \"Could not convert arguments to utf8.\");\n exit(1);\n }\n }\n \/\/ Now that conversion is done, we can finally start.\n argv[1] = argv[0];\n return node::Start(argc - 1, argv + 1);\n }\n\n sandbox::SandboxInterfaceInfo sandbox_info = {0};\n content::InitializeSandboxInfo(&sandbox_info);\n atom::AtomMainDelegate delegate;\n return content::ContentMain(instance, &sandbox_info, &delegate);\n}\n\n#else \/\/ defined(OS_WIN)\n\n#include \"app\/atom_library_main.h\"\n\nint main(int argc, const char* argv[]) {\n if (argc > 1 && strcmp(argv[1], \"--atom-child_process-fork\") == 0) {\n argv[1] = argv[0];\n return node::Start(argc - 1, const_cast(argv + 1));\n }\n\n return AtomMain(argc, argv);\n}\n\n#endif\n<|endoftext|>"} {"text":"\/\/ cells.cpp\n\/\/ 3-D Rods\n\/\/ Author: Yuding Ai\n\/\/ Date: 2015.07.15\n\n\n#include \"cells.h\"\nextern const string EXC_INVALID_DESC = \"Not a valid description of cells!\";\n\nCells::Cells()\n{\n\tBoxlist.clear();\n\tPlanelist.clear();\n\tN0 = 1;\n\tN1 = 1;\n\tN2 = 1;\n\tsize = 1;\n\t\/\/initialize my cell\n\tarr = new Square[1];\n\tarr[0] = Square();\n}\n\n\nCells::Cells(int X, int Y, int Z, int init,int length)\n{\n\tBoxlist.clear(); \/\/ the list of subBox\n\tPlanelist.clear(); \/\/ the list of subplane\n\tN0 = X; \/\/ length\n\tN1 = Y; \/\/ width\n N2 = Z; \/\/ height\n size = (N0)*(N1)*(N2);\n arr = new Square[size];\n if (init == EMPTY)\n {\n \t\/\/initialize my cell with empty config\n\t\tfor(int i = 0; i < size; i++)\n\t\t{\n\t\t\tarr[i] = Square();\n\t\t}\n }\n\n else if (init == BOX)\n\t{\n\t\t\/\/initialize my cell with filling up with subboxes config\n\n \t\/\/firstly: initialize my cell with full config\n\t\tfor(int i = 0; i < size; i++)\n\t\t{\n\t\t\tarr[i] = Square(1);\n\t\t}\n\t\t\/\/then: randomly filling up it with subboxes\n\t\tsrand (time(NULL));\n \tfor(int i = 0; i < X\/length; i++)\n \t{ \n\t\t\tfor ( int j = 0; j < Y\/length; j++)\n\t\t\t{\n\t\t\t\tfor (int k = 0; k < Z\/length; k++)\n\t\t\t\t{\n\t\t\t\t\tint Or; \/\/pick a random config of subbox to add into Box\n\t\t\t\t\tOr = rand()%3; \n\t\t\t\t\tint l,m,n;\n\t\t\t\t\tl = i*length;\n\t\t\t\t\tm = j*length;\n\t\t\t\t\tn = k*length;\n\t\t\t\t\tBoxgen subox(l,m,n,Or,length);\n\t\t\t\t\tBoxlist.push_back(subox);\n\t\t\t\t}\n\t\t\t}\n \t}\n }\n\n else if (init == PLANE)\n {\n \t\/\/initialize my cell with filling up with subplane config\n \t\/\/firstly: initialize my cell with full config\n\t\tfor(int i = 0; i < size; i++)\n\t\t{\n\t\t\tarr[i] = Square(1);\n\t\t}\n\n\t\t\/\/then: randomly filling up it with subplanes\n\t\tsrand (time(NULL));\n\t\tint Pl; \/\/ pick an plane first\n\t\tPl = rand()%3;\n\n\t\tif (Pl == X_)\n\t\t{\n\t\t\tint Or;\/\/ Pick a random Orientation: in the case of X_plane, one can only choose from VER or UP\n\t\t\tfor (int i = 0; i < N0; i ++)\n\t\t\t{\t\t\t\t\n\t\t\t\tOr = 2*(rand()%2);\/\/ Or can be either 0 --> Ver or 2 --> UP;\t\t\t\t\n\t\t\t\tPlanegen subplane(X_, i, N0, Or, length);\n\t\t\t\t\/\/ Planegen(int Plane, int Lay, int L, int Orien,int Len); \n\t\t\t\tPlanelist.push_back(subplane);\n\t\t\t}\n\n\t\t}\n\n\t\telse if (Pl == Y_)\n\t\t{\n\t\t\tint Or;\/\/ Pick a random Orientation: in the case of Y_plane, one can only choose from HOR or UP\n\t\t\tfor (int i = 0; i< N1; i++)\n\t\t\t{\n\t\t\t\tOr = rand()%2 +1;\/\/ Or can be either 1 --> HOR or 2 --> UP;\n\t\t\t\tPlanegen subplane(Y_, i, N1, Or, length);\n\t\t\t\tPlanelist.push_back(subplane);\n\t\t\t}\t\t\t\n\t\t}\n\n\t\telse if (Pl == Z_)\n\t\t{\n\t\t\tint Or;\/\/ Pick a random Orientation: in the case of Z_plane, one can only choose from VER or HOR\n\t\t\tfor (int i = 0; i VER or 1 --> HOR;\n\t\t\t\tPlanegen subplane(Z_, i, N2, Or, length);\n\t\t\t\tPlanelist.push_back(subplane);\n\t\t\t}\n\t\t}\n }\n}\n\n\/*\n* Destructor\n*\/\nCells::~Cells()\n{ \n\tif(arr)\n\t{\n\t\tdelete [] arr;\n\t}\n}\n\n\/\/ *** Getters *** \/\/\nint Cells::getN0() const\n{\n\treturn N0;\n}\nint Cells::getN1() const\n{\n\treturn N1;\n}\n\nint Cells::getN2() const\n{\n\treturn N2;\n}\nint Cells::getSize() const\n{\n\treturn (N0)*(N1)*(N2);\n}\n\nconst vector& Cells::getBoxlist() const\n{\n\treturn Boxlist;\n}\n\nconst vector& Cells::getPlanelist() const\n{\n\treturn Planelist;\n}\n\/\/ *** Other Functionality *** \/\/\n\nint Cells::getIdx( int x, int y, int z) const\n{\n\treturn x + N0*y + N1*N0*z;\n}\n\nSquare& Cells::getSquare( int x, int y, int z) const\n{\n\tif (x >= N0 || y >= N1 || z >= N2)\n\t{\n\t\tthrow EXC_INVALID_DESC;\n\t}\n\n\tint idx = getIdx(x,y,z);\n\treturn arr[idx];\n}\n\nfix bug in cells.cpp\/\/ cells.cpp\n\/\/ 3-D Rods\n\/\/ Author: Yuding Ai\n\/\/ Date: 2015.07.15\n\n\n#include \"cells.h\"\nextern const string EXC_INVALID_DESC = \"Not a valid description of cells!\";\n\nCells::Cells()\n{\n\tBoxlist.clear();\n\tPlanelist.clear();\n\tN0 = 1;\n\tN1 = 1;\n\tN2 = 1;\n\tsize = 1;\n\t\/\/initialize my cell\n\tarr = new Square[1];\n\tarr[0] = Square();\n}\n\n\nCells::Cells(int X, int Y, int Z, int init,int length)\n{\n\tBoxlist.clear(); \/\/ the list of subBox\n\tPlanelist.clear(); \/\/ the list of subplane\n\tN0 = X; \/\/ length\n\tN1 = Y; \/\/ width\n N2 = Z; \/\/ height\n size = (N0)*(N1)*(N2);\n arr = new Square[size];\n if (init == EMPTY)\n {\n \t\/\/initialize my cell with empty config\n\t\tfor(int i = 0; i < size; i++)\n\t\t{\n\t\t\tarr[i] = Square();\n\t\t}\n }\n\n else if (init == BOX)\n\t{\n\t\t\/\/initialize my cell with filling up with subboxes config\n\n \t\/\/firstly: initialize my cell with full config\n\t\tfor(int i = 0; i < size; i++)\n\t\t{\n\t\t\tarr[i] = Square(1);\n\t\t}\n\t\t\/\/then: randomly filling up it with subboxes\n\t\tsrand (time(NULL));\n \tfor(int i = 0; i < X\/length; i++)\n \t{ \n\t\t\tfor ( int j = 0; j < Y\/length; j++)\n\t\t\t{\n\t\t\t\tfor (int k = 0; k < Z\/length; k++)\n\t\t\t\t{\n\t\t\t\t\tint Or; \/\/pick a random config of subbox to add into Box\n\t\t\t\t\tOr = rand()%3; \n\t\t\t\t\tint l,m,n;\n\t\t\t\t\tl = i*length;\n\t\t\t\t\tm = j*length;\n\t\t\t\t\tn = k*length;\n\t\t\t\t\tBoxgen subox(l,m,n,Or,length);\n\t\t\t\t\tBoxlist.push_back(subox);\n\t\t\t\t}\n\t\t\t}\n \t}\n }\n\n else if (init == PLANE)\n {\n \t\/\/initialize my cell with filling up with subplane config\n \t\/\/firstly: initialize my cell with full config\n\t\tfor(int i = 0; i < size; i++)\n\t\t{\n\t\t\tarr[i] = Square(1);\n\t\t}\n\n\t\t\/\/then: randomly filling up it with subplanes\n\t\tsrand (time(NULL));\n\t\tint Pl; \/\/ pick an plane first\n\t\tPl = rand()%3;\n\n\t\tif (Pl == X_)\n\t\t{\n\t\t\tint Or;\/\/ Pick a random Orientation: in the case of X_plane, one can only choose from VER or UP\n\t\t\tfor (int i = 0; i < N0; i ++)\n\t\t\t{\t\t\t\t\n\t\t\t\tOr = 2*(rand()%2);\/\/ Or can be either 0 --> Ver or 2 --> UP;\t\t\t\t\n\t\t\t\tPlanegen subplane(X_, i, N0, Or, length);\n\t\t\t\t\/\/ Planegen(int Plane, int Lay, int L, int Orien,int Len); \n\t\t\t\tPlanelist.push_back(subplane);\n\t\t\t}\n\n\t\t}\n\n\t\telse if (Pl == Y_)\n\t\t{\n\t\t\tint Or;\/\/ Pick a random Orientation: in the case of Y_plane, one can only choose from HOR or UP\n\t\t\tfor (int i = 0; i< N1; i++)\n\t\t\t{\n\t\t\t\tOr = rand()%2 +1;\/\/ Or can be either 1 --> HOR or 2 --> UP;\n\t\t\t\tPlanegen subplane(Y_, i, N1, Or, length);\n\t\t\t\tPlanelist.push_back(subplane);\n\t\t\t}\t\t\t\n\t\t}\n\n\t\telse if (Pl == Z_)\n\t\t{\n\t\t\tint Or;\/\/ Pick a random Orientation: in the case of Z_plane, one can only choose from VER or HOR\n\t\t\tfor (int i = 0; i VER or 1 --> HOR;\n\t\t\t\tPlanegen subplane(Z_, i, N2, Or, length);\n\t\t\t\tPlanelist.push_back(subplane);\n\t\t\t}\n\t\t}\n }\n}\n\n\/*\n* Destructor\n*\/\nCells::~Cells()\n{ \n\tdelete [] arr;\t\n}\n\n\/\/ *** Getters *** \/\/\nint Cells::getN0() const\n{\n\treturn N0;\n}\nint Cells::getN1() const\n{\n\treturn N1;\n}\n\nint Cells::getN2() const\n{\n\treturn N2;\n}\nint Cells::getSize() const\n{\n\treturn (N0)*(N1)*(N2);\n}\n\nconst vector& Cells::getBoxlist() const\n{\n\treturn Boxlist;\n}\n\nconst vector& Cells::getPlanelist() const\n{\n\treturn Planelist;\n}\n\/\/ *** Other Functionality *** \/\/\n\nint Cells::getIdx( int x, int y, int z) const\n{\n\treturn x + N0*y + N1*N0*z;\n}\n\nSquare& Cells::getSquare( int x, int y, int z) const\n{\n\tif (x >= N0 || y >= N1 || z >= N2)\n\t{\n\t\tthrow EXC_INVALID_DESC;\n\t}\n\n\tint idx = getIdx(x,y,z);\n\treturn arr[idx];\n}\n\n<|endoftext|>"} {"text":"\/* Copyright (c) 2013 Simeon Bird \n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *\/\n\n#include \n\n#define BOLTZMANN 1.3806504e-23 \/* m2 kg s-2 K-1 *\/\n#define LIGHT 2.99792458e8 \/*in km\/s*\/\n#define PROTONMASS 1.66053886e-27 \/* 1 a.m.u *\/\n#define KPC 3.08568025e19 \/*in m*\/\n#define SIGMA_T 6.652458558e-29 \/* Thompson cross-section in m^2*\/\n\nclass LineAbsorption\n{\n public:\n LineAbsorption(const double lambda, const double gamma, const double fosc, const double amumass):\n sigma_a( sqrt(3.0*M_PI*SIGMA_T\/8.0) * lambda * fosc ),\n bfac( sqrt(2.0*BOLTZMANN\/(amumass*PROTONMASS)) ),\n voigt_fac( gamma*lambda\/(4.*M_PI) )\n { }\n \n \/* Compute the absorption in a single bin, using \n * either straight Gaussian or a Voigt profile.\n * Arguments: \n * colden: column density of absorber in amu per m^2.\n * vdiff: the relative velocities between absorper and bin.\n * temp: temperature of absorber in K\n *\/\n inline double tau_single(const double colden, const double vdiff, const double temp)\n {\n \/* b has the units of velocity: km\/s*\/\n const double b_H1 = bfac*sqrt(temp);\n const double T0 = pow(vdiff\/b_H1,2);\n const double T1 = exp(-T0);\n \/* Voigt profile: Tepper-Garcia, 2006, MNRAS, 369, 2025\n * includes thermal and doppler broadening. *\/\n #ifdef VOIGT\n const double aa_H1 = voigt_fac\/b_H1;\n const double T2 = 1.5\/T0;\n const double profile_H1 = (T0 < 1.e-6 ? T1 : T1 - aa_H1\/sqrt(M_PI)\/T0*(T1*T1*(4.0*T0*T0 + 7.0*T0 + 4.0 + T2) - T2 -1.0));\n #else\n const double profile_H1 = T1;\n #endif\n return sigma_a \/ sqrt(M_PI) * (LIGHT\/b_H1) * colden * profile_H1;\n }\n \n \/* Absorption cross-sections m^2 *\/\n const double sigma_a;\n \/* Constant factor to turn sqrt(temperature) into velocity*\/\n const double bfac;\n \/* Factor to turn b into a dimensionless Voigt profile broadening factor, \n * giving the balance between doppler and thermal broadening. *\/\n const double voigt_fac;\n};\n\n\/*****************************************************************************\/\n\/* This function calculates absorption from a given integrated temperature, density\n * and line profile properties.\n * Note: a lot of variables are named _H1. This is historical: the function works for arbitrary species.\n * Arguments are:\n * tau_H1: Array to store the ouput optical depth\n * H1 : species with density, velocity and temperature arrays\n * Hz: conversion factor from linear to velocity space, Hubble(z) in km\/s\/Mpc\n * box100: box size in comoving kpc\/h\n * h100: hubble constant h (~ 0.7)\n * atime: a = 1\/(1+z)\n * lambda_lya, gamma_lya, fosc_lya: parameters of the atomic transition (use those from VPFIT)\n * mass: mass of the species in amu\n * *\/\nvoid Compute_Absorption(double * tau_H1, double * rho, double * veloc, double * temp, const int nbins, const double Hz, const double h100, const double box100, const double atime, const double lambda_lya, const double gamma_lya, const double fosc_lya, const double mass)\n{\n \/* Conversion factors from internal units *\/\n const double rscale = (KPC*atime)\/h100; \/* convert length to m *\/\n \/* Calculate the length scales to be used in the box *\/\n const double vmax = box100 * Hz * rscale\/ (1e3*KPC); \/* box size (kms^-1) *\/\n const double dzgrid = box100 * rscale \/ (double) nbins; \/* bin size m *\/\n const double dvbin = dzgrid * Hz \/ (1e3*KPC); \/* velocity bin size (kms^-1) *\/\n LineAbsorption line(lambda_lya, gamma_lya, fosc_lya, mass);\n \/* Compute the HI Lya spectra *\/\n for(int i=0;i (vmax\/2.0*1.0e3))\n vdiff_H1 = (vmax*1.0e3) - vdiff_H1;\n #endif\n tau_H1[j] += line.tau_single(dzgrid * rho[j]\/(mass*PROTONMASS), vdiff_H1, temp[j]);\n }\n } \/* Spectrum convolution *\/\n \n return;\n}\n\nExtend the LineAbsorption class with a new interpolation method that computes directly the optical depth from each particle, rather than averaging all particles into binned absorbers and computing the optical depth from them.\/* Copyright (c) 2013 Simeon Bird \n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *\/\n\n#include \n\n#define BOLTZMANN 1.3806504e-23 \/* m2 kg s-2 K-1 *\/\n#define LIGHT 2.99792458e8 \/*in km\/s*\/\n#define PROTONMASS 1.66053886e-27 \/* 1 a.m.u *\/\n#define KPC 3.08568025e19 \/*in m*\/\n#define SIGMA_T 6.652458558e-29 \/* Thompson cross-section in m^2*\/\n\nclass LineAbsorption\n{\n public:\n LineAbsorption(const double lambda, const double gamma, const double fosc, const double amumass):\n sigma_a( sqrt(3.0*M_PI*SIGMA_T\/8.0) * lambda * fosc ),\n bfac( sqrt(2.0*BOLTZMANN\/(amumass*PROTONMASS)) ),\n voigt_fac( gamma*lambda\/(4.*M_PI) )\n { }\n \n \/* Compute the absorption in a single bin, using \n * either straight Gaussian or a Voigt profile.\n * Arguments: \n * colden: column density of absorber in amu per m^2.\n * vdiff: the relative velocities between absorper and bin.\n * temp: temperature of absorber in K\n *\/\n inline double tau_single(const double colden, const double vdiff, const double temp)\n {\n \/* b has the units of velocity: km\/s*\/\n const double b_H1 = bfac*sqrt(temp);\n const double T0 = pow(vdiff\/b_H1,2);\n const double T1 = exp(-T0);\n \/* Voigt profile: Tepper-Garcia, 2006, MNRAS, 369, 2025\n * includes thermal and doppler broadening. *\/\n #ifdef VOIGT\n const double aa_H1 = voigt_fac\/b_H1;\n const double T2 = 1.5\/T0;\n const double profile_H1 = (T0 < 1.e-6 ? T1 : T1 - aa_H1\/sqrt(M_PI)\/T0*(T1*T1*(4.0*T0*T0 + 7.0*T0 + 4.0 + T2) - T2 -1.0));\n #else\n const double profile_H1 = T1;\n #endif\n return sigma_a \/ sqrt(M_PI) * (LIGHT\/b_H1) * colden * profile_H1;\n }\n \n \/* Absorption cross-sections m^2 *\/\n const double sigma_a;\n \/* Constant factor to turn sqrt(temperature) into velocity*\/\n const double bfac;\n \/* Factor to turn b into a dimensionless Voigt profile broadening factor, \n * giving the balance between doppler and thermal broadening. *\/\n const double voigt_fac;\n};\n\n\/*****************************************************************************\/\n\/* This function calculates absorption from a given integrated temperature, density\n * and line profile properties.\n * Note: a lot of variables are named _H1. This is historical: the function works for arbitrary species.\n * Arguments are:\n * tau_H1: Array to store the ouput optical depth\n * H1 : species with density, velocity and temperature arrays\n * Hz: conversion factor from linear to velocity space, Hubble(z) in km\/s\/Mpc\n * box100: box size in comoving kpc\/h\n * h100: hubble constant h (~ 0.7)\n * atime: a = 1\/(1+z)\n * lambda_lya, gamma_lya, fosc_lya: parameters of the atomic transition (use those from VPFIT)\n * mass: mass of the species in amu\n * *\/\nvoid Compute_Absorption(double * tau_H1, double * rho, double * veloc, double * temp, const int nbins, const double Hz, const double h100, const double box100, const double atime, const double lambda_lya, const double gamma_lya, const double fosc_lya, const double mass)\n{\n \/* Conversion factors from internal units *\/\n const double rscale = (KPC*atime)\/h100; \/* convert length to m *\/\n \/* Calculate the length scales to be used in the box *\/\n const double vmax = box100 * Hz * rscale\/ (1e3*KPC); \/* box size (kms^-1) *\/\n const double dzgrid = box100 * rscale \/ (double) nbins; \/* bin size m *\/\n const double dvbin = dzgrid * Hz \/ (1e3*KPC); \/* velocity bin size (kms^-1) *\/\n LineAbsorption line(lambda_lya, gamma_lya, fosc_lya, mass);\n \/* Compute the HI Lya spectra *\/\n for(int i=0;i (vmax\/2.0*1.0e3))\n vdiff_H1 = (vmax*1.0e3) - vdiff_H1;\n #endif\n tau_H1[j] += line.tau_single(dzgrid * rho[j]\/(mass*PROTONMASS), vdiff_H1, temp[j]);\n }\n } \/* Spectrum convolution *\/\n \n return;\n}\n\n#define NGRID 8\n\ninline double sph_kernel(const double q)\n{\n if(q<0.5)\n return 1-6*q*q+6*q*q*q;\n else\n return 2*pow(1.- q,3);\n}\n\n\/* Find the fraction of the total particle density in this pixel by integrating an SPH kernel\n * over the z direction. All distances in units of smoothing length.\n * Arguments:\n * zlow - Lower z limit for the integral (as z distance from particle center).\n * zhigh - Upper z limit for the integral (again as distance from particle center)\n * bb2 - transverse distance from particle to pixel, squared.\n * *\/\ndouble sph_kern_frac(double zlow, double zhigh, double bb2)\n{\n double total = sph_kernel(sqrt(bb2+zlow*zlow))\/2.;\n const double deltaz=(zhigh-zlow)\/NGRID;\n for(int i=1; i 1)\n break;\n total+=sph_kernel(q);\n }\n double qhigh = sqrt(bb2+zhigh*zhigh);\n if (qhigh < 1)\n total += sph_kernel(qhigh)\/2.;\n return 8*deltaz*total\/M_PI;\n}\n\n\n\/* Conversion factors from internal units *\/\n\/\/const double rscale = (KPC*atime)\/h100; \/* convert length to m *\/\n\/\/\nclass ComputeLineAbsorption: public LineAbsorption\n{\n public:\n \/*Dimensions:\n * velocities in km\/s (physical).\n * distances in kpc\/h (comoving)\n * velfac: factor to convert from distance to velocity units.\n * Should be h100 * atime * Hz\/1e3 (Hz in km\/s\/Mpc)\n * *\/\n \/\/This makes dvbin be in km\/s: the 1e3 converts Hz from km\/s\/Mpc to km\/s\/kpc\n \/\/ kpc \/h h km\/s\/kpc\n \/\/vbox = ( box100 * h100 * atime * Hz\/1e3 ) \/* box size (kms^-1) *\/\n ComputeLineAbsorption(const double lambda_lya, const double gamma_lya, const double fosc_lya, const double mass, const double velfac_i, const double boxsize):\n LineAbsorption(lambda_lya, gamma_lya, fosc_lya, mass),\n amumass(mass), velfac(velfac_i), vbox(boxsize*velfac_i)\n {\n }\n\n \/* Add the absorption from a particle to the spectrum in the array\n * tau, and the density from the particle to the array colden\n * The slightly C-style interface is so we can easily use the data in python.\n *\n * Output:\n * tau: array specifying the optical depth of the spectrum.\n * If this is NULL, just compute the column density.\n * colden: array specifying the column density of the spectrum. (atoms\/ (comoving kpc\/h)^2)\n * nbins: Size of above arrays\n *\n * Input:\n * dr2: transverse distance to spectra from particle (comoving kpc\/h)\n * mass: mass of particle in absorping species (kg)\n * ppos: particle distance from box edge parallel to spectrum (comoving kpc\/h)\n * pvel: particle velocity parallel to spectrum (physical km\/s)\n * temp: particle temperature (K)\n * smooth: particle smoothing length (comoving kpc\/h)\n *\/\n void add_particle(double * tau, double * colden, const int nbins, const double dr2, const double mass, const double ppos, const double pvel, const double temp, const double smooth)\n {\n \/*Factor to convert the dimensionless quantity found by sph_kern_frac to a column density.*\/\n const double avgdens = mass\/(amumass*PROTONMASS*pow(smooth,3));\n \/*Impact parameter in units of the smoothing length *\/\n const double bb2 = dr2\/smooth\/smooth;\n \/* Velocity of particle parallel to los: pos in *\/\n double vel = (velfac * ppos + pvel );\n if (vel > vbox ){\n vel -= vbox*floor(vel\/vbox);\n }\n const double vsmooth = velfac * smooth;\n const double zrange = sqrt(smooth*smooth - dr2);\n const int zlow = floor((nbins\/vbox) * velfac * (ppos - zrange));\n const int zhigh = ceil((nbins\/vbox) * velfac * (ppos + zrange));\n \/* Compute the HI Lya spectra *\/\n for(int z=zlow; z (vbox\/2.0))\n vdiff = vbox - vdiff;\n tau[i] += tau_single(colden_this, vdiff, temp);\n }\n }\n }\n\n return;\n }\n\n const double amumass, velfac, vbox;\n};\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: persist.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: hr $ $Date: 2003-03-18 13:48:51 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \n#include \n\n\/\/ NOT FULLY DECLARED SERVICES\n#include \n#include \n\n\n#ifdef WNT\n#include \n\nnamespace csv\n{\nnamespace ploc\n{\n\nbool\nPersistent::Exists() const\n{\n return access( StrPath(), 00) == 0;\n}\n\n} \/\/ namespace ploc\n} \/\/ namespace csv\n\n\n#elif defined(UNX)\n#include \n\n\/*\n#ifndef __SUNPRO_CC\n#include \n#else\n#define F_OK 0 \/\/ Test for existence of File\nextern int access(const char *, int);\n#endif\n*\/\n\nnamespace csv\n{\nnamespace ploc\n{\n\nbool\nPersistent::Exists() const\n{\n return access( StrPath(), F_OK ) == 0;\n}\n\n\n} \/\/ namespace ploc\n} \/\/ namespace csv\n\n#else\n#error For using csv::ploc there has to be defined: WNT or UNX.\n#endif\n\nnamespace csv\n{\nnamespace ploc\n{\n\nconst char *\nPersistent::StrPath() const\n{\n if (sPath.empty() )\n {\n#ifndef CSV_NO_MUTABLE\n StreamStr & rsPath = sPath;\n#else\n StreamStr & rsPath = const_cast< StreamStr& >(sPath);\n#endif\n rsPath.seekp(0);\n rsPath << MyPath();\n if (MyPath().IsDirectory())\n rsPath.pop_back(1); \/\/ Remove closing delimiter.\n }\n return sPath.c_str();\n}\n\n} \/\/ namespace ploc\n} \/\/ namespace csv\n\n\n\n\nINTEGRATION: CWS ooo19126 (1.2.86); FILE MERGED 2005\/09\/05 14:09:00 rt 1.2.86.1: #i54170# Change license header: remove SISSL\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: persist.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 08:06:50 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#include \n#include \n\n\/\/ NOT FULLY DECLARED SERVICES\n#include \n#include \n\n\n#ifdef WNT\n#include \n\nnamespace csv\n{\nnamespace ploc\n{\n\nbool\nPersistent::Exists() const\n{\n return access( StrPath(), 00) == 0;\n}\n\n} \/\/ namespace ploc\n} \/\/ namespace csv\n\n\n#elif defined(UNX)\n#include \n\n\/*\n#ifndef __SUNPRO_CC\n#include \n#else\n#define F_OK 0 \/\/ Test for existence of File\nextern int access(const char *, int);\n#endif\n*\/\n\nnamespace csv\n{\nnamespace ploc\n{\n\nbool\nPersistent::Exists() const\n{\n return access( StrPath(), F_OK ) == 0;\n}\n\n\n} \/\/ namespace ploc\n} \/\/ namespace csv\n\n#else\n#error For using csv::ploc there has to be defined: WNT or UNX.\n#endif\n\nnamespace csv\n{\nnamespace ploc\n{\n\nconst char *\nPersistent::StrPath() const\n{\n if (sPath.empty() )\n {\n#ifndef CSV_NO_MUTABLE\n StreamStr & rsPath = sPath;\n#else\n StreamStr & rsPath = const_cast< StreamStr& >(sPath);\n#endif\n rsPath.seekp(0);\n rsPath << MyPath();\n if (MyPath().IsDirectory())\n rsPath.pop_back(1); \/\/ Remove closing delimiter.\n }\n return sPath.c_str();\n}\n\n} \/\/ namespace ploc\n} \/\/ namespace csv\n\n\n\n\n<|endoftext|>"} {"text":"Revert \"Dupe code removal in cui\"<|endoftext|>"} {"text":"\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ version: $Id$\n\/\/ author: Axel Naumann \n\/\/------------------------------------------------------------------------------\n\n#include \"IncrementalParser.h\"\n\n#include \"ASTDumper.h\"\n#include \"ChainedConsumer.h\"\n#include \"DeclExtractor.h\"\n#include \"DynamicLookup.h\"\n#include \"ValuePrinterSynthesizer.h\"\n#include \"cling\/Interpreter\/CIFactory.h\"\n#include \"cling\/Interpreter\/Interpreter.h\"\n\n#include \"clang\/AST\/ASTContext.h\"\n#include \"clang\/AST\/Decl.h\"\n#include \"clang\/AST\/DeclGroup.h\"\n#include \"clang\/Basic\/FileManager.h\"\n#include \"clang\/CodeGen\/ModuleBuilder.h\"\n#include \"clang\/Parse\/Parser.h\"\n#include \"clang\/Lex\/Preprocessor.h\"\n#include \"clang\/Frontend\/CompilerInstance.h\"\n#include \"clang\/Serialization\/ASTWriter.h\"\n\n#include \"llvm\/LLVMContext.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/raw_os_ostream.h\"\n\n#include \n#include \n#include \n#include \n\nusing namespace clang;\n\nnamespace cling {\n IncrementalParser::IncrementalParser(Interpreter* interp, \n int argc, const char* const *argv,\n const char* llvmdir):\n m_Interpreter(interp),\n m_DynamicLookupEnabled(false),\n m_Consumer(0),\n m_FirstTopLevelDecl(0),\n m_LastTopLevelDecl(0),\n m_SyntaxOnly(false)\n {\n CompilerInstance* CI \n = CIFactory::createCI(llvm::MemoryBuffer::getMemBuffer(\"\", \"CLING\"), \n argc, argv, llvmdir);\n assert(CI && \"CompilerInstance is (null)!\");\n m_CI.reset(CI);\n m_SyntaxOnly = (CI->getFrontendOpts().ProgramAction == clang::frontend::ParseSyntaxOnly);\n\n CreateSLocOffsetGenerator();\n\n m_Consumer = dyn_cast(&CI->getASTConsumer());\n assert(m_Consumer && \"Expected ChainedConsumer!\");\n \/\/ Add consumers to the ChainedConsumer, which owns them\n EvaluateTSynthesizer* ES = new EvaluateTSynthesizer(interp);\n ES->Attach(m_Consumer);\n addConsumer(ChainedConsumer::kEvaluateTSynthesizer, ES);\n\n DeclExtractor* DE = new DeclExtractor();\n DE->Attach(m_Consumer);\n addConsumer(ChainedConsumer::kDeclExtractor, DE);\n\n ValuePrinterSynthesizer* VPS = new ValuePrinterSynthesizer(interp);\n VPS->Attach(m_Consumer);\n addConsumer(ChainedConsumer::kValuePrinterSynthesizer, VPS);\n addConsumer(ChainedConsumer::kASTDumper, new ASTDumper());\n if (!m_SyntaxOnly) {\n CodeGenerator* CG = CreateLLVMCodeGen(CI->getDiagnostics(), \n \"cling input\",\n CI->getCodeGenOpts(), \n \/*Owned by codegen*\/ * new llvm::LLVMContext()\n );\n assert(CG && \"No CodeGen?!\");\n addConsumer(ChainedConsumer::kCodeGenerator, CG);\n }\n m_Consumer->Initialize(CI->getASTContext());\n m_Consumer->InitializeSema(CI->getSema());\n \/\/ Initialize the parser.\n m_Parser.reset(new Parser(CI->getPreprocessor(), CI->getSema()));\n CI->getPreprocessor().EnterMainSourceFile();\n m_Parser->Initialize();\n }\n\n \/\/ Each input line is contained in separate memory buffer. The SourceManager\n \/\/ assigns sort-of invalid FileID for each buffer, i.e there is no FileEntry\n \/\/ for the MemoryBuffer's FileID. That in turn is problem because invalid\n \/\/ SourceLocations are given to the diagnostics. Thus the diagnostics cannot\n \/\/ order the overloads, for example\n \/\/\n \/\/ Our work-around is creating a virtual file, which doesn't exist on the disk\n \/\/ with enormous size (no allocation is done). That file has valid FileEntry \n \/\/ and so on... We use it for generating valid SourceLocations with valid\n \/\/ offsets so that it doesn't cause any troubles to the diagnostics.\n \/\/\n \/\/ +---------------------+\n \/\/ | Main memory buffer |\n \/\/ +---------------------+\n \/\/ | Virtual file SLoc |\n \/\/ | address space |<-----------------+\n \/\/ | ... |<------------+ |\n \/\/ | ... | | |\n \/\/ | ... |<----+ | |\n \/\/ | ... | | | |\n \/\/ +~~~~~~~~~~~~~~~~~~~~~+ | | |\n \/\/ | input_line_1 | ....+.......+..--+\n \/\/ +---------------------+ | | \n \/\/ | input_line_2 | ....+.....--+\n \/\/ +---------------------+ |\n \/\/ | ... | |\n \/\/ +---------------------+ |\n \/\/ | input_line_N | ..--+ \n \/\/ +---------------------+\n \/\/\n void IncrementalParser::CreateSLocOffsetGenerator() {\n SourceManager& SM = getCI()->getSourceManager();\n FileManager& FM = SM.getFileManager();\n const FileEntry* FE \n = FM.getVirtualFile(\"Interactrive\/InputLineIncluder\", 1U << 15U, time(0));\n m_VirtualFileID = SM.createFileID(FE, SourceLocation(), SrcMgr::C_User);\n\n assert(!m_VirtualFileID.isInvalid() && \"No VirtualFileID created?\");\n }\n\n IncrementalParser::~IncrementalParser() {\n if (GetCodeGenerator()) {\n GetCodeGenerator()->ReleaseModule();\n }\n }\n \n void IncrementalParser::Initialize() {\n\n \/\/ Init the consumers \n\n CompileAsIs(\"\"); \/\/ Consume initialization.\n }\n\n IncrementalParser::EParseResult \n IncrementalParser::CompileLineFromPrompt(llvm::StringRef input) {\n assert(input.str()[0] != '#' \n && \"Preprocessed line! Call CompilePreprocessed instead\");\n \n bool p, q;\n m_Consumer->RestorePreviousState(ChainedConsumer::kEvaluateTSynthesizer,\n isDynamicLookupEnabled());\n\n p = m_Consumer->EnableConsumer(ChainedConsumer::kDeclExtractor);\n q = m_Consumer->EnableConsumer(ChainedConsumer::kValuePrinterSynthesizer);\n EParseResult Result = Compile(input);\n m_Consumer->RestorePreviousState(ChainedConsumer::kDeclExtractor, p);\n m_Consumer->RestorePreviousState(ChainedConsumer::kValuePrinterSynthesizer, q);\n\n return Result;\n\n }\n\n IncrementalParser::EParseResult \n IncrementalParser::CompileAsIs(llvm::StringRef input) {\n bool p, q;\n m_Consumer->RestorePreviousState(ChainedConsumer::kEvaluateTSynthesizer,\n isDynamicLookupEnabled());\n\n p = m_Consumer->DisableConsumer(ChainedConsumer::kDeclExtractor);\n q = m_Consumer->DisableConsumer(ChainedConsumer::kValuePrinterSynthesizer);\n EParseResult Result = Compile(input);\n m_Consumer->RestorePreviousState(ChainedConsumer::kDeclExtractor, p);\n m_Consumer->RestorePreviousState(ChainedConsumer::kValuePrinterSynthesizer, q);\n\n return Result;\n }\n\n void IncrementalParser::Parse(llvm::StringRef input, \n llvm::SmallVector& DGRs){\n if (!m_SyntaxOnly)\n m_Consumer->DisableConsumer(ChainedConsumer::kCodeGenerator);\n\n Parse(input);\n for (llvm::SmallVector::iterator \n I = m_Consumer->DeclsQueue.begin(), E = m_Consumer->DeclsQueue.end(); \n I != E; ++I) {\n DGRs.push_back((*I).D);\n }\n\n if (!m_SyntaxOnly)\n m_Consumer->EnableConsumer(ChainedConsumer::kCodeGenerator);\n }\n\n IncrementalParser::EParseResult \n IncrementalParser::Compile(llvm::StringRef input) {\n \/\/ Just in case when Parse is called, we want to complete the transaction\n \/\/ coming from parse and then start new one.\n m_Consumer->HandleTranslationUnit(getCI()->getASTContext());\n\n \/\/ Reset the module builder to clean up global initializers, c'tors, d'tors:\n if (GetCodeGenerator()) {\n GetCodeGenerator()->Initialize(getCI()->getASTContext());\n }\n\n EParseResult Result = Parse(input);\n\n \/\/ Check for errors coming from our custom consumers.\n DiagnosticConsumer& DClient = m_CI->getDiagnosticClient();\n DClient.BeginSourceFile(getCI()->getLangOpts(), &getCI()->getPreprocessor());\n m_Consumer->HandleTranslationUnit(getCI()->getASTContext());\n\n DClient.EndSourceFile();\n m_CI->getDiagnostics().Reset();\n\n if (!m_SyntaxOnly) {\n m_Interpreter->runStaticInitializersOnce();\n }\n\n return Result;\n }\n\n IncrementalParser::EParseResult \n IncrementalParser::Parse(llvm::StringRef input) {\n\n \/\/ Add src to the memory buffer, parse it, and add it to\n \/\/ the AST. Returns the CompilerInstance (and thus the AST).\n \/\/ Diagnostics are reset for each call of parse: they are only covering\n \/\/ src.\n\n Preprocessor& PP = m_CI->getPreprocessor();\n DiagnosticConsumer& DClient = m_CI->getDiagnosticClient();\n\n PP.enableIncrementalProcessing();\n\n DClient.BeginSourceFile(m_CI->getLangOpts(), &PP);\n \/\/ Reset the transaction information\n getLastTransaction().setBeforeFirstDecl(getCI()->getSema().CurContext);\n \n\n if (input.size()) {\n std::ostringstream source_name;\n source_name << \"input_line_\" << (m_MemoryBuffer.size() + 1);\n m_MemoryBuffer.push_back(llvm::MemoryBuffer::getMemBufferCopy(input, source_name.str()));\n SourceManager& SM = getCI()->getSourceManager();\n\n \/\/ Create SourceLocation, which will allow clang to order the overload\n \/\/ candidates for example\n SourceLocation NewLoc = SM.getLocForStartOfFile(m_VirtualFileID);\n NewLoc = NewLoc.getLocWithOffset(m_MemoryBuffer.size() + 1);\n \n \/\/ Create FileID for the current buffer\n FileID FID = SM.createFileIDForMemBuffer(m_MemoryBuffer.back(),\n \/*LoadedID*\/0,\n \/*LoadedOffset*\/0, NewLoc);\n \n PP.EnterSourceFile(FID, 0, NewLoc);\n \n \/\/Token &tok = const_cast(m_Parser->getCurToken());\n \/\/tok.setKind(tok::semi);\n }\n\n Parser::DeclGroupPtrTy ADecl;\n\n while (!m_Parser->ParseTopLevelDecl(ADecl)) {\n \/\/ Not end of file.\n \/\/ If we got a null return and something *was* parsed, ignore it. This\n \/\/ is due to a top-level semicolon, an action override, or a parse error\n \/\/ skipping something.\n if (ADecl) {\n DeclGroupRef DGR = ADecl.getAsVal();\n for (DeclGroupRef::iterator i=DGR.begin(); i< DGR.end(); ++i) {\n if (!m_FirstTopLevelDecl)\n m_FirstTopLevelDecl = *((*i)->getDeclContext()->decls_begin());\n\n m_LastTopLevelDecl = *i;\n } \n m_Consumer->HandleTopLevelDecl(DGR);\n } \/\/ ADecl\n };\n \n \/\/ Process any TopLevelDecls generated by #pragma weak.\n for (llvm::SmallVector::iterator\n I = getCI()->getSema().WeakTopLevelDecls().begin(),\n E = getCI()->getSema().WeakTopLevelDecls().end(); I != E; ++I) {\n m_Consumer->HandleTopLevelDecl(DeclGroupRef(*I));\n }\n\n getCI()->getSema().PerformPendingInstantiations();\n\n DClient.EndSourceFile();\n\n PP.enableIncrementalProcessing(false);\n\n DiagnosticsEngine& Diag = getCI()->getSema().getDiagnostics();\n if (Diag.hasErrorOccurred())\n return IncrementalParser::kFailed;\n else if (Diag.getNumWarnings())\n return IncrementalParser::kSuccessWithWarnings;\n\n return IncrementalParser::kSuccess;\n }\n\n void IncrementalParser::enableDynamicLookup(bool value) {\n m_DynamicLookupEnabled = value;\n Sema& S = m_CI->getSema();\n if (isDynamicLookupEnabled()) {\n assert(!S.ExternalSource && \"Already set Sema ExternalSource\");\n S.ExternalSource = new DynamicIDHandler(&S);\n }\n else {\n delete S.ExternalSource;\n S.ExternalSource = 0;\n } \n }\n\n void IncrementalParser::addConsumer(ChainedConsumer::EConsumerIndex I, ASTConsumer* consumer) {\n if (m_Consumer->Exists(I))\n return;\n\n m_Consumer->Add(I, consumer);\n if (I == ChainedConsumer::kCodeGenerator)\n m_Consumer->EnableConsumer(I);\n }\n\n CodeGenerator* IncrementalParser::GetCodeGenerator() const { \n return \n (CodeGenerator*)m_Consumer->getConsumer(ChainedConsumer::kCodeGenerator); \n }\n\n} \/\/ namespace cling\nInitialize sema, which in turn initalizes the consumers.\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ version: $Id$\n\/\/ author: Axel Naumann \n\/\/------------------------------------------------------------------------------\n\n#include \"IncrementalParser.h\"\n\n#include \"ASTDumper.h\"\n#include \"ChainedConsumer.h\"\n#include \"DeclExtractor.h\"\n#include \"DynamicLookup.h\"\n#include \"ValuePrinterSynthesizer.h\"\n#include \"cling\/Interpreter\/CIFactory.h\"\n#include \"cling\/Interpreter\/Interpreter.h\"\n\n#include \"clang\/AST\/ASTContext.h\"\n#include \"clang\/AST\/Decl.h\"\n#include \"clang\/AST\/DeclGroup.h\"\n#include \"clang\/Basic\/FileManager.h\"\n#include \"clang\/CodeGen\/ModuleBuilder.h\"\n#include \"clang\/Parse\/Parser.h\"\n#include \"clang\/Lex\/Preprocessor.h\"\n#include \"clang\/Frontend\/CompilerInstance.h\"\n#include \"clang\/Serialization\/ASTWriter.h\"\n\n#include \"llvm\/LLVMContext.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/raw_os_ostream.h\"\n\n#include \n#include \n#include \n#include \n\nusing namespace clang;\n\nnamespace cling {\n IncrementalParser::IncrementalParser(Interpreter* interp, \n int argc, const char* const *argv,\n const char* llvmdir):\n m_Interpreter(interp),\n m_DynamicLookupEnabled(false),\n m_Consumer(0),\n m_FirstTopLevelDecl(0),\n m_LastTopLevelDecl(0),\n m_SyntaxOnly(false)\n {\n CompilerInstance* CI \n = CIFactory::createCI(llvm::MemoryBuffer::getMemBuffer(\"\", \"CLING\"), \n argc, argv, llvmdir);\n assert(CI && \"CompilerInstance is (null)!\");\n m_CI.reset(CI);\n m_SyntaxOnly = (CI->getFrontendOpts().ProgramAction == clang::frontend::ParseSyntaxOnly);\n\n CreateSLocOffsetGenerator();\n\n m_Consumer = dyn_cast(&CI->getASTConsumer());\n assert(m_Consumer && \"Expected ChainedConsumer!\");\n \/\/ Add consumers to the ChainedConsumer, which owns them\n EvaluateTSynthesizer* ES = new EvaluateTSynthesizer(interp);\n ES->Attach(m_Consumer);\n addConsumer(ChainedConsumer::kEvaluateTSynthesizer, ES);\n\n DeclExtractor* DE = new DeclExtractor();\n DE->Attach(m_Consumer);\n addConsumer(ChainedConsumer::kDeclExtractor, DE);\n\n ValuePrinterSynthesizer* VPS = new ValuePrinterSynthesizer(interp);\n VPS->Attach(m_Consumer);\n addConsumer(ChainedConsumer::kValuePrinterSynthesizer, VPS);\n addConsumer(ChainedConsumer::kASTDumper, new ASTDumper());\n if (!m_SyntaxOnly) {\n CodeGenerator* CG = CreateLLVMCodeGen(CI->getDiagnostics(), \n \"cling input\",\n CI->getCodeGenOpts(), \n \/*Owned by codegen*\/ * new llvm::LLVMContext()\n );\n assert(CG && \"No CodeGen?!\");\n addConsumer(ChainedConsumer::kCodeGenerator, CG);\n }\n m_Parser.reset(new Parser(CI->getPreprocessor(), CI->getSema()));\n CI->getPreprocessor().EnterMainSourceFile();\n \/\/ Initialize the parser after we have entered the main source file.\n m_Parser->Initialize();\n \/\/ Perform initialization that occurs after the parser has been initialized \n \/\/ but before it parses anything. Initializes the consumers too.\n CI->getSema().Initialize();\n }\n\n \/\/ Each input line is contained in separate memory buffer. The SourceManager\n \/\/ assigns sort-of invalid FileID for each buffer, i.e there is no FileEntry\n \/\/ for the MemoryBuffer's FileID. That in turn is problem because invalid\n \/\/ SourceLocations are given to the diagnostics. Thus the diagnostics cannot\n \/\/ order the overloads, for example\n \/\/\n \/\/ Our work-around is creating a virtual file, which doesn't exist on the disk\n \/\/ with enormous size (no allocation is done). That file has valid FileEntry \n \/\/ and so on... We use it for generating valid SourceLocations with valid\n \/\/ offsets so that it doesn't cause any troubles to the diagnostics.\n \/\/\n \/\/ +---------------------+\n \/\/ | Main memory buffer |\n \/\/ +---------------------+\n \/\/ | Virtual file SLoc |\n \/\/ | address space |<-----------------+\n \/\/ | ... |<------------+ |\n \/\/ | ... | | |\n \/\/ | ... |<----+ | |\n \/\/ | ... | | | |\n \/\/ +~~~~~~~~~~~~~~~~~~~~~+ | | |\n \/\/ | input_line_1 | ....+.......+..--+\n \/\/ +---------------------+ | | \n \/\/ | input_line_2 | ....+.....--+\n \/\/ +---------------------+ |\n \/\/ | ... | |\n \/\/ +---------------------+ |\n \/\/ | input_line_N | ..--+ \n \/\/ +---------------------+\n \/\/\n void IncrementalParser::CreateSLocOffsetGenerator() {\n SourceManager& SM = getCI()->getSourceManager();\n FileManager& FM = SM.getFileManager();\n const FileEntry* FE \n = FM.getVirtualFile(\"Interactrive\/InputLineIncluder\", 1U << 15U, time(0));\n m_VirtualFileID = SM.createFileID(FE, SourceLocation(), SrcMgr::C_User);\n\n assert(!m_VirtualFileID.isInvalid() && \"No VirtualFileID created?\");\n }\n\n IncrementalParser::~IncrementalParser() {\n if (GetCodeGenerator()) {\n GetCodeGenerator()->ReleaseModule();\n }\n }\n \n void IncrementalParser::Initialize() {\n CompileAsIs(\"\"); \/\/ Consume initialization.\n }\n\n IncrementalParser::EParseResult \n IncrementalParser::CompileLineFromPrompt(llvm::StringRef input) {\n assert(input.str()[0] != '#' \n && \"Preprocessed line! Call CompilePreprocessed instead\");\n \n bool p, q;\n m_Consumer->RestorePreviousState(ChainedConsumer::kEvaluateTSynthesizer,\n isDynamicLookupEnabled());\n\n p = m_Consumer->EnableConsumer(ChainedConsumer::kDeclExtractor);\n q = m_Consumer->EnableConsumer(ChainedConsumer::kValuePrinterSynthesizer);\n EParseResult Result = Compile(input);\n m_Consumer->RestorePreviousState(ChainedConsumer::kDeclExtractor, p);\n m_Consumer->RestorePreviousState(ChainedConsumer::kValuePrinterSynthesizer, q);\n\n return Result;\n\n }\n\n IncrementalParser::EParseResult \n IncrementalParser::CompileAsIs(llvm::StringRef input) {\n bool p, q;\n m_Consumer->RestorePreviousState(ChainedConsumer::kEvaluateTSynthesizer,\n isDynamicLookupEnabled());\n\n p = m_Consumer->DisableConsumer(ChainedConsumer::kDeclExtractor);\n q = m_Consumer->DisableConsumer(ChainedConsumer::kValuePrinterSynthesizer);\n EParseResult Result = Compile(input);\n m_Consumer->RestorePreviousState(ChainedConsumer::kDeclExtractor, p);\n m_Consumer->RestorePreviousState(ChainedConsumer::kValuePrinterSynthesizer, q);\n\n return Result;\n }\n\n void IncrementalParser::Parse(llvm::StringRef input, \n llvm::SmallVector& DGRs){\n if (!m_SyntaxOnly)\n m_Consumer->DisableConsumer(ChainedConsumer::kCodeGenerator);\n\n Parse(input);\n for (llvm::SmallVector::iterator \n I = m_Consumer->DeclsQueue.begin(), E = m_Consumer->DeclsQueue.end(); \n I != E; ++I) {\n DGRs.push_back((*I).D);\n }\n\n if (!m_SyntaxOnly)\n m_Consumer->EnableConsumer(ChainedConsumer::kCodeGenerator);\n }\n\n IncrementalParser::EParseResult \n IncrementalParser::Compile(llvm::StringRef input) {\n \/\/ Just in case when Parse is called, we want to complete the transaction\n \/\/ coming from parse and then start new one.\n m_Consumer->HandleTranslationUnit(getCI()->getASTContext());\n\n \/\/ Reset the module builder to clean up global initializers, c'tors, d'tors:\n if (GetCodeGenerator()) {\n GetCodeGenerator()->Initialize(getCI()->getASTContext());\n }\n\n EParseResult Result = Parse(input);\n\n \/\/ Check for errors coming from our custom consumers.\n DiagnosticConsumer& DClient = m_CI->getDiagnosticClient();\n DClient.BeginSourceFile(getCI()->getLangOpts(), &getCI()->getPreprocessor());\n m_Consumer->HandleTranslationUnit(getCI()->getASTContext());\n\n DClient.EndSourceFile();\n m_CI->getDiagnostics().Reset();\n\n if (!m_SyntaxOnly) {\n m_Interpreter->runStaticInitializersOnce();\n }\n\n return Result;\n }\n\n IncrementalParser::EParseResult \n IncrementalParser::Parse(llvm::StringRef input) {\n\n \/\/ Add src to the memory buffer, parse it, and add it to\n \/\/ the AST. Returns the CompilerInstance (and thus the AST).\n \/\/ Diagnostics are reset for each call of parse: they are only covering\n \/\/ src.\n\n Preprocessor& PP = m_CI->getPreprocessor();\n DiagnosticConsumer& DClient = m_CI->getDiagnosticClient();\n\n PP.enableIncrementalProcessing();\n\n DClient.BeginSourceFile(m_CI->getLangOpts(), &PP);\n \/\/ Reset the transaction information\n getLastTransaction().setBeforeFirstDecl(getCI()->getSema().CurContext);\n \n\n if (input.size()) {\n std::ostringstream source_name;\n source_name << \"input_line_\" << (m_MemoryBuffer.size() + 1);\n m_MemoryBuffer.push_back(llvm::MemoryBuffer::getMemBufferCopy(input, source_name.str()));\n SourceManager& SM = getCI()->getSourceManager();\n\n \/\/ Create SourceLocation, which will allow clang to order the overload\n \/\/ candidates for example\n SourceLocation NewLoc = SM.getLocForStartOfFile(m_VirtualFileID);\n NewLoc = NewLoc.getLocWithOffset(m_MemoryBuffer.size() + 1);\n \n \/\/ Create FileID for the current buffer\n FileID FID = SM.createFileIDForMemBuffer(m_MemoryBuffer.back(),\n \/*LoadedID*\/0,\n \/*LoadedOffset*\/0, NewLoc);\n \n PP.EnterSourceFile(FID, 0, NewLoc);\n \n \/\/Token &tok = const_cast(m_Parser->getCurToken());\n \/\/tok.setKind(tok::semi);\n }\n\n Parser::DeclGroupPtrTy ADecl;\n\n while (!m_Parser->ParseTopLevelDecl(ADecl)) {\n \/\/ Not end of file.\n \/\/ If we got a null return and something *was* parsed, ignore it. This\n \/\/ is due to a top-level semicolon, an action override, or a parse error\n \/\/ skipping something.\n if (ADecl) {\n DeclGroupRef DGR = ADecl.getAsVal();\n for (DeclGroupRef::iterator i=DGR.begin(); i< DGR.end(); ++i) {\n if (!m_FirstTopLevelDecl)\n m_FirstTopLevelDecl = *((*i)->getDeclContext()->decls_begin());\n\n m_LastTopLevelDecl = *i;\n } \n m_Consumer->HandleTopLevelDecl(DGR);\n } \/\/ ADecl\n };\n \n \/\/ Process any TopLevelDecls generated by #pragma weak.\n for (llvm::SmallVector::iterator\n I = getCI()->getSema().WeakTopLevelDecls().begin(),\n E = getCI()->getSema().WeakTopLevelDecls().end(); I != E; ++I) {\n m_Consumer->HandleTopLevelDecl(DeclGroupRef(*I));\n }\n\n getCI()->getSema().PerformPendingInstantiations();\n\n DClient.EndSourceFile();\n\n PP.enableIncrementalProcessing(false);\n\n DiagnosticsEngine& Diag = getCI()->getSema().getDiagnostics();\n if (Diag.hasErrorOccurred())\n return IncrementalParser::kFailed;\n else if (Diag.getNumWarnings())\n return IncrementalParser::kSuccessWithWarnings;\n\n return IncrementalParser::kSuccess;\n }\n\n void IncrementalParser::enableDynamicLookup(bool value) {\n m_DynamicLookupEnabled = value;\n Sema& S = m_CI->getSema();\n if (isDynamicLookupEnabled()) {\n assert(!S.ExternalSource && \"Already set Sema ExternalSource\");\n S.ExternalSource = new DynamicIDHandler(&S);\n }\n else {\n delete S.ExternalSource;\n S.ExternalSource = 0;\n } \n }\n\n void IncrementalParser::addConsumer(ChainedConsumer::EConsumerIndex I, ASTConsumer* consumer) {\n if (m_Consumer->Exists(I))\n return;\n\n m_Consumer->Add(I, consumer);\n if (I == ChainedConsumer::kCodeGenerator)\n m_Consumer->EnableConsumer(I);\n }\n\n CodeGenerator* IncrementalParser::GetCodeGenerator() const { \n return \n (CodeGenerator*)m_Consumer->getConsumer(ChainedConsumer::kCodeGenerator); \n }\n\n} \/\/ namespace cling\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\nint main(int argc, char **argv)\n{\n ::gflags::ParseCommandLineFlags(&argc, &argv, false);\n ::testing::GTEST_FLAG(throw_on_failure) = true;\n ::testing::InitGoogleMock(&argc, argv);\n\n return RUN_ALL_TESTS();\n}use ::google namespace#include \n#include \n#include \n#include \n\nint main(int argc, char **argv)\n{\n ::google::ParseCommandLineFlags(&argc, &argv, false);\n ::testing::GTEST_FLAG(throw_on_failure) = true;\n ::testing::InitGoogleMock(&argc, argv);\n\n return RUN_ALL_TESTS();\n}<|endoftext|>"} {"text":"#include \n#include \"..\/src\/Trie.h\"\n\nusing namespace std;\n\nint main() {\n Trie* trie = new Trie();\n trie->add(\"asparagus\");\n trie->add(\"aspen\");\n cout << \"This should be true: \" << trie->search(\"asparagus\") << endl;\n cout << \"This should be false: \" << trie->search(\"aaragus\") << endl;\n}\nAdd more tests#include \n#include \"..\/src\/Trie.h\"\n\nusing namespace std;\n\nint main() {\n Trie* trie = new Trie();\n trie->add(\"asparagus\");\n trie->add(\"aspen\");\n cout << \"This should be true: \" << trie->search(\"asparagus\") << endl;\n cout << \"This should be false: \" << trie->search(\"aaragus\") << endl;\n cout << \"This should be false: \" << trie->search(\"asparaguse\") << endl;\n}\n<|endoftext|>"} {"text":"\/** \\brief A MARC-21 filter utility that adds ACO tags with entry $a set to 1 for article collections.\n * \\author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)\n *\n * \\copyright 2017 Universitätsbibliothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see .\n *\/\n\n#include \n#include \n#include \n#include \"MarcReader.h\"\n#include \"MarcRecord.h\"\n#include \"MarcUtil.h\"\n#include \"MarcWriter.h\"\n\n\nvoid Usage() {\n std::cerr << \"Usage: \" << ::progname << \" marc_input marc_output\\n\";\n std::exit(EXIT_FAILURE);\n}\n\n\nvoid CollectArticleCollectionPPNs(MarcReader * const reader,\n std::unordered_set * const article_collection_ppns)\n{\n article_collection_ppns->clear();\n while (const MarcRecord record = reader->read()) {\n if (MarcUtil::IsArticle(record)) {\n const std::string parent_ppn(MarcUtil::GetParentPPN(record));\n if (not parent_ppn.empty())\n article_collection_ppns->insert(parent_ppn);\n }\n }\n}\n\n\nvoid MarkArticleCollections(MarcReader * const reader, MarcWriter * const writer,\n const std::unordered_set &article_collection_ppns)\n{\n unsigned count(0), modified_count(0);\n while (MarcRecord record = reader->read()) {\n ++count;\n\n bool is_article_collection(false);\n if (article_collection_ppns.find(record.getControlNumber()) != article_collection_ppns.end())\n is_article_collection = true;\n if (not is_article_collection and not MarcUtil::IsArticle(record)) {\n is_article_collection = MarcUtil::HasSubfieldWithValue(record, \"935\", 'c', \"fe\");\n if (not is_article_collection)\n is_article_collection = MarcUtil::HasSubfieldWithValue(record, \"655\", 'a', \"Festschrift\");\n if (not is_article_collection)\n is_article_collection = MarcUtil::HasSubfieldWithValue(record, \"655\", 'a', \"Konferenzschrift\");\n if (not is_article_collection)\n is_article_collection = MarcUtil::HasSubfieldWithValue(record, \"689\", 'a', \"Konferenzschrift\");\n if (not is_article_collection)\n is_article_collection = MarcUtil::HasSubfieldWithValue(record, \"689\", 'a', \"Kongress\");\n if (not is_article_collection)\n is_article_collection = MarcUtil::HasSubfieldWithValue(record, \"935\", 'c', \"gkko\");\n }\n\n if (is_article_collection) {\n record.insertSubfield(\"ACO\", 'a', \"1\");\n ++modified_count;\n }\n\n writer->write(record);\n }\n\n std::cerr << \"Read \" << count << \" records.\\n\";\n std::cerr << \"Identified \" << modified_count << \" record(s) as an article collection.\\n\";\n}\n\n\nint main(int argc, char **argv) {\n ::progname = argv[0];\n\n if (argc != 3)\n Usage();\n \n std::unique_ptr marc_reader(MarcReader::Factory(argv[1]));\n std::unique_ptr marc_writer(MarcWriter::Factory(argv[2]));\n try {\n std::unordered_set article_collection_ppns;\n CollectArticleCollectionPPNs(marc_reader.get(), &article_collection_ppns);\n marc_reader->rewind();\n MarkArticleCollections(marc_reader.get(), marc_writer.get(), article_collection_ppns);\n } catch (const std::exception &x) {\n Error(\"caught exception: \" + std::string(x.what()));\n }\n}\nUpdate flag_article_collections.cc\/** \\brief A MARC-21 filter utility that adds ACO tags with entry $a set to 1 for article collections.\n * \\author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)\n *\n * \\copyright 2017 Universitätsbibliothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see .\n *\/\n\n#include \n#include \n#include \n#include \"MarcReader.h\"\n#include \"MarcRecord.h\"\n#include \"MarcUtil.h\"\n#include \"MarcWriter.h\"\n\n\nvoid Usage() {\n std::cerr << \"Usage: \" << ::progname << \" marc_input marc_output\\n\";\n std::exit(EXIT_FAILURE);\n}\n\n\nvoid CollectArticleCollectionPPNs(MarcReader * const reader,\n std::unordered_set * const article_collection_ppns)\n{\n article_collection_ppns->clear();\n while (const MarcRecord record = reader->read()) {\n if (MarcUtil::IsArticle(record)) {\n const std::string parent_ppn(MarcUtil::GetParentPPN(record));\n if (not parent_ppn.empty())\n article_collection_ppns->insert(parent_ppn);\n }\n }\n}\n\n\nvoid MarkArticleCollections(MarcReader * const reader, MarcWriter * const writer,\n const std::unordered_set &article_collection_ppns)\n{\n unsigned count(0), modified_count(0);\n while (MarcRecord record = reader->read()) {\n ++count;\n\n bool is_article_collection(false);\n if (article_collection_ppns.find(record.getControlNumber()) != article_collection_ppns.end())\n is_article_collection = true;\n if (not is_article_collection and not MarcUtil::IsArticle(record)) {\n is_article_collection = MarcUtil::HasSubfieldWithValue(record, \"935\", 'c', \"fe\");\n if (not is_article_collection)\n is_article_collection = MarcUtil::HasSubfieldWithValue(record, \"655\", 'a', \"Aufsatzsammlung\");\n if (not is_article_collection)\n is_article_collection = MarcUtil::HasSubfieldWithValue(record, \"689\", 'a', \"Aufsatzsammlung\");\n if (not is_article_collection)\n is_article_collection = MarcUtil::HasSubfieldWithValue(record, \"655\", 'a', \"Festschrift\");\n if (not is_article_collection)\n is_article_collection = MarcUtil::HasSubfieldWithValue(record, \"655\", 'a', \"Konferenzschrift\");\n if (not is_article_collection)\n is_article_collection = MarcUtil::HasSubfieldWithValue(record, \"689\", 'a', \"Konferenzschrift\");\n if (not is_article_collection)\n is_article_collection = MarcUtil::HasSubfieldWithValue(record, \"689\", 'a', \"Kongress\");\n if (not is_article_collection)\n is_article_collection = MarcUtil::HasSubfieldWithValue(record, \"935\", 'c', \"gkko\");\n }\n\n if (is_article_collection) {\n record.insertSubfield(\"ACO\", 'a', \"1\");\n ++modified_count;\n }\n\n writer->write(record);\n }\n\n std::cerr << \"Read \" << count << \" records.\\n\";\n std::cerr << \"Identified \" << modified_count << \" record(s) as an article collection.\\n\";\n}\n\n\nint main(int argc, char **argv) {\n ::progname = argv[0];\n\n if (argc != 3)\n Usage();\n \n std::unique_ptr marc_reader(MarcReader::Factory(argv[1]));\n std::unique_ptr marc_writer(MarcWriter::Factory(argv[2]));\n try {\n std::unordered_set article_collection_ppns;\n CollectArticleCollectionPPNs(marc_reader.get(), &article_collection_ppns);\n marc_reader->rewind();\n MarkArticleCollections(marc_reader.get(), marc_writer.get(), article_collection_ppns);\n } catch (const std::exception &x) {\n Error(\"caught exception: \" + std::string(x.what()));\n }\n}\n<|endoftext|>"} {"text":"\/\/*****************************************************************************\n\/\/ Copyright 2017-2019 Intel Corporation\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/*****************************************************************************\n\n#include \n#include \n\n#include \"gtest\/gtest.h\"\n\n#include \"ngraph\/runtime\/aligned_buffer.hpp\"\n#include \"ngraph\/type\/bfloat16.hpp\"\n#include \"util\/float_util.hpp\"\n\nusing namespace std;\nusing namespace ngraph;\n\ntemplate \nstd::string to_hex(T value)\n{\n std::stringstream ss;\n ss << \"0x\" << std::hex << std::setw(sizeof(T) * 2) << std::setfill('0') << value;\n return ss.str();\n}\n\n\/\/***********************\n\/\/ NOTE\n\/\/***********************\n\/\/ This test uses exact comparisons of floating point values. It is testing for bit-exact\n\/\/ creation and truncation\/rounding of bfloat16 values.\nTEST(bfloat16, conversions)\n{\n bfloat16 bf;\n const char* source_string;\n std::string bf_string;\n\n \/\/ 1.f, the ground-truth value\n source_string = \"0 01111111 000 0000\";\n bf = test::bits_to_bfloat16(source_string);\n EXPECT_EQ(bf, bfloat16(1.0));\n bf_string = test::bfloat16_to_bits(bf);\n EXPECT_STREQ(source_string, bf_string.c_str());\n\n \/\/ 1.03125f, the exact upper bound\n source_string = \"0 01111111 000 0100\";\n bf = test::bits_to_bfloat16(source_string);\n EXPECT_EQ(bf, bfloat16(1.03125));\n bf_string = test::bfloat16_to_bits(bf);\n EXPECT_STREQ(source_string, bf_string.c_str());\n}\n\nTEST(bfloat16, round_to_nearest)\n{\n const char* fstring;\n std::string expected;\n float fvalue;\n uint16_t bf_round;\n\n fstring = \"0 01111111 000 0100 1000 0000 0000 0000\";\n fvalue = test::bits_to_float(fstring);\n bf_round = bfloat16::round_to_nearest(fvalue);\n EXPECT_EQ(bf_round, 0x3F85);\n\n fstring = \"0 01111111 000 0100 0000 0000 0000 0000\";\n fvalue = test::bits_to_float(fstring);\n bf_round = bfloat16::round_to_nearest(fvalue);\n EXPECT_EQ(bf_round, 0x3F84);\n\n fstring = \"0 01111111 111 1111 1000 0000 0000 0000\";\n fvalue = test::bits_to_float(fstring);\n bf_round = bfloat16::round_to_nearest(fvalue);\n EXPECT_EQ(bf_round, 0x4000);\n\n \/\/ 1.9921875f, the next representable number which should not round up\n fstring = \"0 01111111 111 1111 0000 0000 0000 0000\";\n fvalue = test::bits_to_float(fstring);\n bf_round = bfloat16::round_to_nearest(fvalue);\n EXPECT_EQ(bf_round, 0x3FFF);\n}\n\nTEST(bfloat16, round_to_nearest_even)\n{\n const char* fstring;\n float fvalue;\n uint16_t bf_round;\n\n fstring = \"0 01111111 000 0100 1000 0000 0000 0000\";\n fvalue = test::bits_to_float(fstring);\n bf_round = bfloat16::round_to_nearest_even(fvalue);\n EXPECT_EQ(bf_round, 0x3F84);\n\n fstring = \"0 01111111 000 0101 1000 0000 0000 0000\";\n fvalue = test::bits_to_float(fstring);\n bf_round = bfloat16::round_to_nearest_even(fvalue);\n EXPECT_EQ(bf_round, 0x3F86);\n\n fstring = \"0 01111111 000 0101 0000 0000 0000 0000\";\n fvalue = test::bits_to_float(fstring);\n bf_round = bfloat16::round_to_nearest_even(fvalue);\n EXPECT_EQ(bf_round, 0x3F85);\n\n fstring = \"0 01111111 111 1111 1000 0000 0000 0000\";\n fvalue = test::bits_to_float(fstring);\n bf_round = bfloat16::round_to_nearest_even(fvalue);\n EXPECT_EQ(bf_round, 0x4000);\n\n fstring = \"0 01111111 111 1111 0000 0000 0000 0000\";\n fvalue = test::bits_to_float(fstring);\n bf_round = bfloat16::round_to_nearest_even(fvalue);\n EXPECT_EQ(bf_round, 0x3FFF);\n}\n\nTEST(bfloat16, to_float)\n{\n bfloat16 bf;\n const char* source_string;\n\n \/\/ 1.f, the ground-truth value\n source_string = \"0 01111111 000 0000\";\n bf = test::bits_to_bfloat16(source_string);\n float f = static_cast(bf);\n EXPECT_EQ(f, 1.0f);\n\n \/\/ 1.03125f, the exact upper bound\n source_string = \"0 01111111 000 0100\";\n bf = test::bits_to_bfloat16(source_string);\n f = static_cast(bf);\n EXPECT_EQ(f, 1.03125f);\n}\n\nTEST(bfloat16, numeric_limits)\n{\n bfloat16 infinity = numeric_limits::infinity();\n bfloat16 neg_infinity = -numeric_limits::infinity();\n bfloat16 quiet_nan = numeric_limits::quiet_NaN();\n bfloat16 signaling_nan = numeric_limits::signaling_NaN();\n\n EXPECT_TRUE(isinf(infinity));\n EXPECT_TRUE(isinf(neg_infinity));\n EXPECT_TRUE(isnan(quiet_nan));\n EXPECT_TRUE(isnan(signaling_nan));\n}\n\nTEST(benchmark, bfloat16)\n{\n size_t buffer_size = 128 * 3 * 224 * 224;\n ngraph::runtime::AlignedBuffer data(buffer_size * sizeof(float), 4096);\n float* f = static_cast(data.get_ptr());\n \/\/ vector data(buffer_size);\n std::mt19937 rng(2112);\n std::uniform_real_distribution distribution(-300, 300);\n for (size_t i = 0; i < buffer_size; ++i)\n {\n f[i] = distribution(rng);\n }\n NGRAPH_INFO << \"buffer size \" << buffer_size << \" floats or \" << data.size() << \" bytes\";\n\n {\n ngraph::runtime::AlignedBuffer bf_data(buffer_size * sizeof(bfloat16), 4096);\n bfloat16* p = static_cast(bf_data.get_ptr());\n stopwatch timer;\n timer.start();\n for (size_t i = 0; i < buffer_size; ++i)\n {\n p[i] = bfloat16(f[i]);\n }\n timer.stop();\n NGRAPH_INFO << \"float to bfloat16 ctor \" << timer.get_milliseconds()\n << \"ms\";\n }\n\n {\n ngraph::runtime::AlignedBuffer bf_data(buffer_size * sizeof(bfloat16), 4096);\n bfloat16* p = static_cast(bf_data.get_ptr());\n stopwatch timer;\n timer.start();\n for (size_t i = 0; i < buffer_size; ++i)\n {\n p[i] = bfloat16::truncate(f[i]);\n }\n timer.stop();\n NGRAPH_INFO << \"float to bfloat16 truncate \" << timer.get_milliseconds()\n << \"ms\";\n }\n\n {\n ngraph::runtime::AlignedBuffer bf_data(buffer_size * sizeof(bfloat16), 4096);\n bfloat16* p = static_cast(bf_data.get_ptr());\n stopwatch timer;\n timer.start();\n for (size_t i = 0; i < buffer_size; ++i)\n {\n p[i] = bfloat16::round_to_nearest(f[i]);\n }\n timer.stop();\n NGRAPH_INFO << \"float to bfloat16 round to nearest \" << timer.get_milliseconds()\n << \"ms\";\n }\n\n {\n ngraph::runtime::AlignedBuffer bf_data(buffer_size * sizeof(bfloat16), 4096);\n bfloat16* p = static_cast(bf_data.get_ptr());\n stopwatch timer;\n timer.start();\n for (size_t i = 0; i < buffer_size; ++i)\n {\n p[i] = bfloat16::round_to_nearest_even(f[i]);\n }\n timer.stop();\n NGRAPH_INFO << \"float to bfloat16 round to nearest even \" << timer.get_milliseconds()\n << \"ms\";\n }\n}\nWork around problem with AppleClang's isinf (#2820)\/\/*****************************************************************************\n\/\/ Copyright 2017-2019 Intel Corporation\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/*****************************************************************************\n\n#include \n#include \n\n#include \"gtest\/gtest.h\"\n\n#include \"ngraph\/runtime\/aligned_buffer.hpp\"\n#include \"ngraph\/type\/bfloat16.hpp\"\n#include \"util\/float_util.hpp\"\n\nusing namespace std;\nusing namespace ngraph;\n\ntemplate \nstd::string to_hex(T value)\n{\n std::stringstream ss;\n ss << \"0x\" << std::hex << std::setw(sizeof(T) * 2) << std::setfill('0') << value;\n return ss.str();\n}\n\n\/\/***********************\n\/\/ NOTE\n\/\/***********************\n\/\/ This test uses exact comparisons of floating point values. It is testing for bit-exact\n\/\/ creation and truncation\/rounding of bfloat16 values.\nTEST(bfloat16, conversions)\n{\n bfloat16 bf;\n const char* source_string;\n std::string bf_string;\n\n \/\/ 1.f, the ground-truth value\n source_string = \"0 01111111 000 0000\";\n bf = test::bits_to_bfloat16(source_string);\n EXPECT_EQ(bf, bfloat16(1.0));\n bf_string = test::bfloat16_to_bits(bf);\n EXPECT_STREQ(source_string, bf_string.c_str());\n\n \/\/ 1.03125f, the exact upper bound\n source_string = \"0 01111111 000 0100\";\n bf = test::bits_to_bfloat16(source_string);\n EXPECT_EQ(bf, bfloat16(1.03125));\n bf_string = test::bfloat16_to_bits(bf);\n EXPECT_STREQ(source_string, bf_string.c_str());\n}\n\nTEST(bfloat16, round_to_nearest)\n{\n const char* fstring;\n std::string expected;\n float fvalue;\n uint16_t bf_round;\n\n fstring = \"0 01111111 000 0100 1000 0000 0000 0000\";\n fvalue = test::bits_to_float(fstring);\n bf_round = bfloat16::round_to_nearest(fvalue);\n EXPECT_EQ(bf_round, 0x3F85);\n\n fstring = \"0 01111111 000 0100 0000 0000 0000 0000\";\n fvalue = test::bits_to_float(fstring);\n bf_round = bfloat16::round_to_nearest(fvalue);\n EXPECT_EQ(bf_round, 0x3F84);\n\n fstring = \"0 01111111 111 1111 1000 0000 0000 0000\";\n fvalue = test::bits_to_float(fstring);\n bf_round = bfloat16::round_to_nearest(fvalue);\n EXPECT_EQ(bf_round, 0x4000);\n\n \/\/ 1.9921875f, the next representable number which should not round up\n fstring = \"0 01111111 111 1111 0000 0000 0000 0000\";\n fvalue = test::bits_to_float(fstring);\n bf_round = bfloat16::round_to_nearest(fvalue);\n EXPECT_EQ(bf_round, 0x3FFF);\n}\n\nTEST(bfloat16, round_to_nearest_even)\n{\n const char* fstring;\n float fvalue;\n uint16_t bf_round;\n\n fstring = \"0 01111111 000 0100 1000 0000 0000 0000\";\n fvalue = test::bits_to_float(fstring);\n bf_round = bfloat16::round_to_nearest_even(fvalue);\n EXPECT_EQ(bf_round, 0x3F84);\n\n fstring = \"0 01111111 000 0101 1000 0000 0000 0000\";\n fvalue = test::bits_to_float(fstring);\n bf_round = bfloat16::round_to_nearest_even(fvalue);\n EXPECT_EQ(bf_round, 0x3F86);\n\n fstring = \"0 01111111 000 0101 0000 0000 0000 0000\";\n fvalue = test::bits_to_float(fstring);\n bf_round = bfloat16::round_to_nearest_even(fvalue);\n EXPECT_EQ(bf_round, 0x3F85);\n\n fstring = \"0 01111111 111 1111 1000 0000 0000 0000\";\n fvalue = test::bits_to_float(fstring);\n bf_round = bfloat16::round_to_nearest_even(fvalue);\n EXPECT_EQ(bf_round, 0x4000);\n\n fstring = \"0 01111111 111 1111 0000 0000 0000 0000\";\n fvalue = test::bits_to_float(fstring);\n bf_round = bfloat16::round_to_nearest_even(fvalue);\n EXPECT_EQ(bf_round, 0x3FFF);\n}\n\nTEST(bfloat16, to_float)\n{\n bfloat16 bf;\n const char* source_string;\n\n \/\/ 1.f, the ground-truth value\n source_string = \"0 01111111 000 0000\";\n bf = test::bits_to_bfloat16(source_string);\n float f = static_cast(bf);\n EXPECT_EQ(f, 1.0f);\n\n \/\/ 1.03125f, the exact upper bound\n source_string = \"0 01111111 000 0100\";\n bf = test::bits_to_bfloat16(source_string);\n f = static_cast(bf);\n EXPECT_EQ(f, 1.03125f);\n}\n\nTEST(bfloat16, numeric_limits)\n{\n bfloat16 infinity = numeric_limits::infinity();\n bfloat16 neg_infinity = -numeric_limits::infinity();\n bfloat16 quiet_nan = numeric_limits::quiet_NaN();\n bfloat16 signaling_nan = numeric_limits::signaling_NaN();\n\n \/\/ Would be nice if we could have bfloat16 overloads for these, but it would require adding\n \/\/ overloads into ::std. So we just cast to float here. We can't rely on an implicit cast\n \/\/ because it fails with some versions of AppleClang.\n EXPECT_TRUE(isinf(static_cast(infinity)));\n EXPECT_TRUE(isinf(static_cast(neg_infinity)));\n EXPECT_TRUE(isnan(static_cast(quiet_nan)));\n EXPECT_TRUE(isnan(static_cast(signaling_nan)));\n}\n\nTEST(benchmark, bfloat16)\n{\n size_t buffer_size = 128 * 3 * 224 * 224;\n ngraph::runtime::AlignedBuffer data(buffer_size * sizeof(float), 4096);\n float* f = static_cast(data.get_ptr());\n \/\/ vector data(buffer_size);\n std::mt19937 rng(2112);\n std::uniform_real_distribution distribution(-300, 300);\n for (size_t i = 0; i < buffer_size; ++i)\n {\n f[i] = distribution(rng);\n }\n NGRAPH_INFO << \"buffer size \" << buffer_size << \" floats or \" << data.size() << \" bytes\";\n\n {\n ngraph::runtime::AlignedBuffer bf_data(buffer_size * sizeof(bfloat16), 4096);\n bfloat16* p = static_cast(bf_data.get_ptr());\n stopwatch timer;\n timer.start();\n for (size_t i = 0; i < buffer_size; ++i)\n {\n p[i] = bfloat16(f[i]);\n }\n timer.stop();\n NGRAPH_INFO << \"float to bfloat16 ctor \" << timer.get_milliseconds()\n << \"ms\";\n }\n\n {\n ngraph::runtime::AlignedBuffer bf_data(buffer_size * sizeof(bfloat16), 4096);\n bfloat16* p = static_cast(bf_data.get_ptr());\n stopwatch timer;\n timer.start();\n for (size_t i = 0; i < buffer_size; ++i)\n {\n p[i] = bfloat16::truncate(f[i]);\n }\n timer.stop();\n NGRAPH_INFO << \"float to bfloat16 truncate \" << timer.get_milliseconds()\n << \"ms\";\n }\n\n {\n ngraph::runtime::AlignedBuffer bf_data(buffer_size * sizeof(bfloat16), 4096);\n bfloat16* p = static_cast(bf_data.get_ptr());\n stopwatch timer;\n timer.start();\n for (size_t i = 0; i < buffer_size; ++i)\n {\n p[i] = bfloat16::round_to_nearest(f[i]);\n }\n timer.stop();\n NGRAPH_INFO << \"float to bfloat16 round to nearest \" << timer.get_milliseconds()\n << \"ms\";\n }\n\n {\n ngraph::runtime::AlignedBuffer bf_data(buffer_size * sizeof(bfloat16), 4096);\n bfloat16* p = static_cast(bf_data.get_ptr());\n stopwatch timer;\n timer.start();\n for (size_t i = 0; i < buffer_size; ++i)\n {\n p[i] = bfloat16::round_to_nearest_even(f[i]);\n }\n timer.stop();\n NGRAPH_INFO << \"float to bfloat16 round to nearest even \" << timer.get_milliseconds()\n << \"ms\";\n }\n}\n<|endoftext|>"} {"text":"#include \n\n#include \n\n#include \n\n\nnamespace {\n\nclass OpenMeshMeshCastTest: public testing::Test {\n};\n\nstruct TriTraits1: public OpenMesh::DefaultTraits {\n typedef OpenMesh::Vec3d Point;\n};\nstruct TriTraits2: public OpenMesh::DefaultTraits {\n typedef OpenMesh::Vec3d Point;\n};\n\nTEST_F(OpenMeshMeshCastTest, PerformCast) {\n OpenMesh::TriMesh_ArrayKernelT a;\n OpenMesh::TriMesh_ArrayKernelT &b =\n OpenMesh::mesh_cast&>(a);\n \/*\n OpenMesh::TriMesh_ArrayKernelT < TriTraits2 > &b =\n OpenMesh::MeshCast<\n TriMesh_ArrayKernelT&,\n OpenMesh::TriMesh_ArrayKernelT&\n >::cast(a);\n *\/\n}\n\n}\nFixed cppcheck unused variable#include \n\n#include \n\n#include \n\n\nnamespace {\n\nclass OpenMeshMeshCastTest: public testing::Test {\n};\n\nstruct TriTraits1: public OpenMesh::DefaultTraits {\n typedef OpenMesh::Vec3d Point;\n};\nstruct TriTraits2: public OpenMesh::DefaultTraits {\n typedef OpenMesh::Vec3d Point;\n};\n\nTEST_F(OpenMeshMeshCastTest, PerformCast) {\n OpenMesh::TriMesh_ArrayKernelT a;\n OpenMesh::TriMesh_ArrayKernelT &b =\n OpenMesh::mesh_cast&>(a);\n b.reserve(10,10,10);\n \/*\n OpenMesh::TriMesh_ArrayKernelT < TriTraits2 > &b =\n OpenMesh::MeshCast<\n TriMesh_ArrayKernelT&,\n OpenMesh::TriMesh_ArrayKernelT&\n >::cast(a);\n *\/\n}\n\n}\n<|endoftext|>"} {"text":"It was depthMask!<|endoftext|>"} {"text":"\/\/ Copyright (c) 2015 GitHub, Inc.\n\/\/ Use of this source code is governed by the MIT license that can be\n\/\/ found in the LICENSE file.\n\n#include \"atom\/browser\/api\/frame_subscriber.h\"\n\n#include \"atom\/common\/native_mate_converters\/gfx_converter.h\"\n#include \"base\/bind.h\"\n#include \"content\/public\/browser\/render_widget_host.h\"\n#include \"ui\/display\/display.h\"\n#include \"ui\/display\/screen.h\"\n\n#include \"atom\/common\/node_includes.h\"\n\nnamespace atom {\n\nnamespace {\n\nvoid CopyPixelsToBuffer(const SkBitmap& bitmap,\n const v8::Local& buffer) {\n size_t rgb_arr_size = bitmap.width() * bitmap.height() *\n bitmap.bytesPerPixel();\n\n memcpy(node::Buffer::Data(buffer), bitmap.getPixels(), rgb_arr_size);\n}\n\n} \/\/ namespace\n\nnamespace api {\n\nFrameSubscriber::FrameSubscriber(v8::Isolate* isolate,\n content::RenderWidgetHostView* view,\n const FrameCaptureCallback& callback,\n bool only_dirty)\n : isolate_(isolate),\n view_(view),\n callback_(callback),\n only_dirty_(only_dirty),\n source_id_for_copy_request_(base::UnguessableToken::Create()),\n weak_factory_(this) {\n}\n\nbool FrameSubscriber::ShouldCaptureFrame(\n const gfx::Rect& dirty_rect,\n base::TimeTicks present_time,\n scoped_refptr* storage,\n DeliverFrameCallback* callback) {\n if (!view_)\n return false;\n\n if (dirty_rect.IsEmpty())\n return false;\n\n gfx::Rect rect = gfx::Rect(view_->GetVisibleViewportSize());\n if (only_dirty_)\n rect = dirty_rect;\n\n gfx::Size view_size = rect.size();\n gfx::Size bitmap_size = view_size;\n gfx::NativeView native_view = view_->GetNativeView();\n const float scale =\n display::Screen::GetScreen()->GetDisplayNearestView(native_view)\n .device_scale_factor();\n if (scale > 1.0f)\n bitmap_size = gfx::ScaleToCeiledSize(view_size, scale);\n\n rect = gfx::Rect(rect.origin(), bitmap_size);\n\n view_->CopyFromSurface(\n rect,\n rect.size(),\n base::Bind(&FrameSubscriber::OnFrameDelivered,\n weak_factory_.GetWeakPtr(), callback_, rect),\n kBGRA_8888_SkColorType);\n\n return false;\n}\n\nconst base::UnguessableToken& FrameSubscriber::GetSourceIdForCopyRequest() {\n return source_id_for_copy_request_;\n}\n\nvoid FrameSubscriber::OnFrameDelivered(const FrameCaptureCallback& callback,\n const gfx::Rect& damage_rect,\n const SkBitmap& bitmap,\n content::ReadbackResponse response) {\n if (response != content::ReadbackResponse::READBACK_SUCCESS)\n return;\n\n v8::Locker locker(isolate_);\n v8::HandleScope handle_scope(isolate_);\n\n size_t rgb_arr_size = bitmap.width() * bitmap.height() *\n bitmap.bytesPerPixel();\n v8::MaybeLocal buffer = node::Buffer::New(isolate_, rgb_arr_size);\n if (buffer.IsEmpty())\n return;\n\n CopyPixelsToBuffer(bitmap, buffer.ToLocalChecked());\n\n v8::Local damage =\n mate::Converter::ToV8(isolate_, damage_rect);\n\n callback_.Run(buffer.ToLocalChecked(), damage);\n}\n\n} \/\/ namespace api\n\n} \/\/ namespace atom\nLock pixels before calling `SkBitmap::getPixels` and copy bitmap row-wise in case (stride != width)\/\/ Copyright (c) 2015 GitHub, Inc.\n\/\/ Use of this source code is governed by the MIT license that can be\n\/\/ found in the LICENSE file.\n\n#include \"atom\/browser\/api\/frame_subscriber.h\"\n\n#include \"atom\/common\/native_mate_converters\/gfx_converter.h\"\n#include \"base\/bind.h\"\n#include \"content\/public\/browser\/render_widget_host.h\"\n#include \"ui\/display\/display.h\"\n#include \"ui\/display\/screen.h\"\n\n#include \"atom\/common\/node_includes.h\"\n\nnamespace atom {\n\nnamespace api {\n\nFrameSubscriber::FrameSubscriber(v8::Isolate* isolate,\n content::RenderWidgetHostView* view,\n const FrameCaptureCallback& callback,\n bool only_dirty)\n : isolate_(isolate),\n view_(view),\n callback_(callback),\n only_dirty_(only_dirty),\n source_id_for_copy_request_(base::UnguessableToken::Create()),\n weak_factory_(this) {\n}\n\nbool FrameSubscriber::ShouldCaptureFrame(\n const gfx::Rect& dirty_rect,\n base::TimeTicks present_time,\n scoped_refptr* storage,\n DeliverFrameCallback* callback) {\n if (!view_)\n return false;\n\n if (dirty_rect.IsEmpty())\n return false;\n\n gfx::Rect rect = gfx::Rect(view_->GetVisibleViewportSize());\n if (only_dirty_)\n rect = dirty_rect;\n\n gfx::Size view_size = rect.size();\n gfx::Size bitmap_size = view_size;\n gfx::NativeView native_view = view_->GetNativeView();\n const float scale =\n display::Screen::GetScreen()->GetDisplayNearestView(native_view)\n .device_scale_factor();\n if (scale > 1.0f)\n bitmap_size = gfx::ScaleToCeiledSize(view_size, scale);\n\n rect = gfx::Rect(rect.origin(), bitmap_size);\n\n view_->CopyFromSurface(\n rect,\n rect.size(),\n base::Bind(&FrameSubscriber::OnFrameDelivered,\n weak_factory_.GetWeakPtr(), callback_, rect),\n kBGRA_8888_SkColorType);\n\n return false;\n}\n\nconst base::UnguessableToken& FrameSubscriber::GetSourceIdForCopyRequest() {\n return source_id_for_copy_request_;\n}\n\nvoid FrameSubscriber::OnFrameDelivered(const FrameCaptureCallback& callback,\n const gfx::Rect& damage_rect,\n const SkBitmap& bitmap,\n content::ReadbackResponse response) {\n if (response != content::ReadbackResponse::READBACK_SUCCESS)\n return;\n\n v8::Locker locker(isolate_);\n v8::HandleScope handle_scope(isolate_);\n\n size_t rgb_row_size = bitmap.width() * bitmap.bytesPerPixel();\n\n v8::MaybeLocal buffer =\n node::Buffer::New(isolate_, rgb_row_size * bitmap.height());\n\n if (buffer.IsEmpty())\n return;\n\n auto local_buffer = buffer.ToLocalChecked();\n\n {\n SkAutoLockPixels lock(bitmap);\n auto source = static_cast(bitmap.getPixels());\n auto target = node::Buffer::Data(local_buffer);\n\n for (int y = 0; y < bitmap.height(); ++y) {\n memcpy(target, source, rgb_row_size);\n source += bitmap.rowBytes();\n target += rgb_row_size;\n }\n }\n\n v8::Local damage =\n mate::Converter::ToV8(isolate_, damage_rect);\n\n callback_.Run(local_buffer, damage);\n}\n\n} \/\/ namespace api\n\n} \/\/ namespace atom\n<|endoftext|>"} {"text":"\n\/*\n * Copyright (c) 2015-2020 Agalmic Ventures LLC (www.agalmicventures.com)\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n#include \"CommandManager.hpp\"\n\n#include \n\n#include \"Command.hpp\"\n\nnamespace werk\n{\n\nbool CommandManager::execute(const std::string &commandLine)\n{\n\t\/\/History is only added here, from human executions. This enables neat stuff like the redo\n\t\/\/command and allows the command system to still be used in an automated fashion.\n\t_commandHistory.emplace_back(_clock.time(), commandLine);\n\n\t\/\/Parse the arguments, ignoring extra whitespace\n\tstd::vector arguments;\n\tboost::split(arguments, boost::trim_copy(commandLine), boost::is_any_of(\" \\t\"), boost::token_compress_on);\n\treturn arguments[0] == \"\" ? false : execute(arguments);\n}\n\nbool CommandManager::execute(const std::vector &arguments)\n{\n\tif (arguments.empty()) {\n\t\t_log->logRaw(LogLevel::CRITICAL, \"Got zero-length arguments to CommandManager::execute\");\n\t\treturn false;\n\t}\n\n\tconst std::string &commandName = arguments[0];\n\tauto commandIter = _commands.find(commandName);\n\tif (commandIter == _commands.end()) {\n\t\t_log->log(LogLevel::ERROR, \"Command not found: %s\", commandName.c_str());\n\t\treturn false;\n\t}\n\n\tCommand *command = commandIter->second;\n\treturn command->execute(arguments);\n}\n\nCommandAction *CommandManager::newCommandAction(const std::string &name, const std::string &commandLine)\n{\n\tstd::vector arguments;\n\tboost::split(arguments, commandLine, boost::is_any_of(\" \\t\"));\n\tconst std::string &commandName = arguments[0];\n\tauto commandIter = _commands.find(commandName);\n\tif (commandIter == _commands.end()) {\n\t\t_log->log(LogLevel::ERROR, \"Command not found for action: %s\", commandName.c_str());\n\t\treturn nullptr;\n\t}\n\n\tCommand *command = commandIter->second;\n\tCommandAction *commandAction = new CommandAction(name, command);\n\tcommandAction->arguments() = arguments;\n\treturn commandAction;\n}\n\nvoid CommandManager::logTo(Log *log) const\n{\n\tlog->log(LogLevel::INFO, \" Commands (%zu):\", _commands.size());\n\tfor (const auto &i : _commands) {\n\t\t_log->log(LogLevel::INFO, \" %16s %s\", i.first.c_str(), i.second->help().c_str());\n\t}\n}\n\n}\nFix build error on some linux distributions\n\/*\n * Copyright (c) 2015-2020 Agalmic Ventures LLC (www.agalmicventures.com)\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n#include \"CommandManager.hpp\"\n\n#include \n\n#include \"Command.hpp\"\n\nnamespace werk\n{\n\nbool CommandManager::execute(const std::string &commandLine)\n{\n\t\/\/History is only added here, from human executions. This enables neat stuff like the redo\n\t\/\/command and allows the command system to still be used in an automated fashion.\n\t_commandHistory.emplace_back(_clock.time(), commandLine);\n\n\t\/\/Parse the arguments, ignoring extra whitespace\n\tstd::string trimmedCommandLine = boost::trim_copy(commandLine);\n\tstd::vector arguments;\n\tboost::split(arguments, trimmedCommandLine, boost::is_any_of(\" \\t\"), boost::token_compress_on);\n\treturn arguments[0] == \"\" ? false : execute(arguments);\n}\n\nbool CommandManager::execute(const std::vector &arguments)\n{\n\tif (arguments.empty()) {\n\t\t_log->logRaw(LogLevel::CRITICAL, \"Got zero-length arguments to CommandManager::execute\");\n\t\treturn false;\n\t}\n\n\tconst std::string &commandName = arguments[0];\n\tauto commandIter = _commands.find(commandName);\n\tif (commandIter == _commands.end()) {\n\t\t_log->log(LogLevel::ERROR, \"Command not found: %s\", commandName.c_str());\n\t\treturn false;\n\t}\n\n\tCommand *command = commandIter->second;\n\treturn command->execute(arguments);\n}\n\nCommandAction *CommandManager::newCommandAction(const std::string &name, const std::string &commandLine)\n{\n\tstd::vector arguments;\n\tboost::split(arguments, commandLine, boost::is_any_of(\" \\t\"));\n\tconst std::string &commandName = arguments[0];\n\tauto commandIter = _commands.find(commandName);\n\tif (commandIter == _commands.end()) {\n\t\t_log->log(LogLevel::ERROR, \"Command not found for action: %s\", commandName.c_str());\n\t\treturn nullptr;\n\t}\n\n\tCommand *command = commandIter->second;\n\tCommandAction *commandAction = new CommandAction(name, command);\n\tcommandAction->arguments() = arguments;\n\treturn commandAction;\n}\n\nvoid CommandManager::logTo(Log *log) const\n{\n\tlog->log(LogLevel::INFO, \" Commands (%zu):\", _commands.size());\n\tfor (const auto &i : _commands) {\n\t\t_log->log(LogLevel::INFO, \" %16s %s\", i.first.c_str(), i.second->help().c_str());\n\t}\n}\n\n}\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Name: process.cpp\n\/\/ Purpose: Implementation of class wxExProcess\n\/\/ Author: Anton van Wezenbeek\n\/\/ Copyright: (c) 2012 Anton van Wezenbeek\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \n#ifndef WX_PRECOMP\n#include \n#endif\n#include \n#include \/\/ for wxTextInputStream\n#include \/\/ for wxGetEnv\n#include \n#include \n#include \n#include \n#include \/\/ for wxExConfigFirstOf\n\nBEGIN_EVENT_TABLE(wxExProcess, wxProcess)\n EVT_MENU(ID_SHELL_COMMAND, wxExProcess::OnCommand)\n EVT_MENU(ID_SHELL_COMMAND_STOP, wxExProcess::OnCommand)\n EVT_TIMER(-1, wxExProcess::OnTimer)\nEND_EVENT_TABLE()\n\nwxExSTCEntryDialog* wxExProcess::m_Dialog = NULL;\nwxString wxExProcess::m_WorkingDirKey = _(\"Process folder\");\n\nwxExProcess::wxExProcess()\n : wxProcess(wxPROCESS_REDIRECT)\n , m_Timer(new wxTimer(this))\n , m_Busy(false)\n , m_Error(false)\n , m_Sync(false)\n{\n m_Command = wxExConfigFirstOf(_(\"Process\"));\n}\n\nwxExProcess::~wxExProcess()\n{\n delete m_Timer;\n}\n\nwxExProcess::wxExProcess(const wxExProcess& process)\n{\n *this = process;\n}\n\nwxExProcess& wxExProcess::operator=(const wxExProcess& p)\n{\n m_Busy = p.m_Busy;\n m_Error = p.m_Error;\n m_Output = p.m_Output;\n m_Sync = p.m_Sync;\n m_Timer = new wxTimer(this);\n\n return *this;\n}\n\nbool wxExProcess::CheckInput()\n{\n if (m_Busy)\n {\n return false;\n }\n \n m_Busy = true;\n \n wxString output;\n \n if (IsInputAvailable())\n {\n wxTextInputStream tis(*GetInputStream());\n \n while (IsInputAvailable())\n {\n const wxChar c = tis.GetChar();\n \n if (c != 0)\n {\n output << c;\n }\n }\n }\n \n if (IsErrorAvailable())\n {\n wxTextInputStream tis(*GetErrorStream());\n \n while (IsErrorAvailable())\n {\n const wxChar c = tis.GetChar();\n \n if (c != 0)\n {\n output << c;\n }\n }\n }\n\n m_Busy = false;\n \n if (!output.empty())\n {\n m_Dialog->GetSTCShell()->AddText(output);\n \n return true;\n }\n else\n {\n return false;\n }\n}\n\nint wxExProcess::ConfigDialog(\n wxWindow* parent,\n const wxString& title,\n bool modal)\n{\n std::vector v;\n\n v.push_back(wxExConfigItem(\n _(\"Process\"), \n CONFIG_COMBOBOX, \n wxEmptyString,\n true));\n\n v.push_back(wxExConfigItem(\n m_WorkingDirKey, \n CONFIG_COMBOBOXDIR, \n wxEmptyString,\n true,\n 1000));\n\n if (modal)\n {\n return wxExConfigDialog(parent,\n v,\n title).ShowModal();\n }\n else\n {\n wxExConfigDialog* dlg = new wxExConfigDialog(\n parent,\n v,\n title);\n \n return dlg->Show();\n }\n}\n\nbool wxExProcess::Execute(\n const wxString& command_to_execute,\n int flags,\n const wxString& wd)\n{\n m_Error = false;\n \n struct wxExecuteEnv env;\n \n if (command_to_execute.empty())\n {\n if (wxExConfigFirstOf(_(\"Process\")).empty())\n {\n if (ConfigDialog(wxTheApp->GetTopWindow()) == wxID_CANCEL)\n {\n return false;\n }\n }\n \n m_Command = wxExConfigFirstOf(_(\"Process\"));\n env.cwd = wxExConfigFirstOf(m_WorkingDirKey);\n }\n else\n {\n m_Command = command_to_execute;\n env.cwd = wd;\n }\n\n m_Sync = (flags & wxEXEC_SYNC);\n\n \/\/ Construct the dialog.\n \/\/ This is necessary both in sync and async mode,\n \/\/ as for sync mode the dialog is used for presenting the \n \/\/ output member.\n if (m_Dialog == NULL)\n {\n m_Dialog = new wxExSTCEntryDialog(\n wxTheApp->GetTopWindow(),\n wxEmptyString,\n wxEmptyString,\n wxEmptyString,\n wxOK,\n true); \/\/ use_shell to force STCShell\n \n m_Dialog->SetProcess(this);\n m_Dialog->GetSTCShell()->SetEventHandler(this);\n }\n \n m_Dialog->GetSTCShell()->EnableShell(!m_Sync);\n \n if (!m_Sync)\n { \n m_Dialog->SetTitle(m_Command);\n m_Dialog->GetSTCShell()->ClearAll();\n \n \/\/ If we have entered a shell, then the shell\n \/\/ itself has no prompt. So put one here.\n if (m_Command == \"bash\" ||\n m_Command == \"csh\" ||\n m_Command == \"ksh\" ||\n m_Command == \"tcsh\" ||\n m_Command == \"sh\")\n {\n wxString host;\n wxGetEnv(\"HOST\", &host);\n m_Dialog->GetSTCShell()->SetPrompt(host + \">\");\n }\n else\n {\n m_Dialog->GetSTCShell()->SetPrompt(\"\");\n }\n\n \/\/ For asynchronous execution the return value is the process id and zero \n \/\/ value indicates that the command could not be executed.\n if (wxExecute(m_Command, flags, this, &env) > 0)\n {\n m_Dialog->Show();\n \n if (!CheckInput())\n {\n m_Dialog->GetSTCShell()->Prompt(wxEmptyString, false);\n }\n \n m_Timer->Start(100); \/\/ each 100 milliseconds\n }\n else\n {\n m_Dialog->Hide();\n \n m_Error = true;\n }\n }\n else\n {\n wxArrayString output;\n wxArrayString errors;\n \n \/\/ Call wxExecute to execute the command and\n \/\/ collect the output and the errors.\n if (wxExecute(\n m_Command,\n output,\n errors,\n flags,\n &env) == -1)\n {\n m_Output.clear();\n m_Error = true;\n }\n else\n {\n \/\/ Set output by converting array strings into normal strings.\n m_Output = wxJoin(errors, '\\n', '\\n') + wxJoin(output, '\\n', '\\n');\n }\n }\n \n return !m_Error;\n}\n\nbool wxExProcess::IsRunning() const\n{\n if (\n \/\/ If we executed a sync process, then it always ended,\n \/\/ so it is not running.\n m_Sync || \n GetPid() <= 0)\n {\n return false;\n }\n\n return Exists(GetPid());\n}\n\nwxKillError wxExProcess::Kill(wxSignal sig)\n{\n if (!IsRunning())\n {\n return wxKILL_NO_PROCESS;\n }\n \n const wxKillError result = wxProcess::Kill(GetPid(), sig);\n \n switch (result)\n {\n case wxKILL_OK:\n wxLogStatus(_(\"Stopped\"));\n DeletePendingEvents();\n m_Timer->Stop();\n m_Dialog->Hide();\n break;\n\n case wxKILL_BAD_SIGNAL:\n wxLogStatus(\"no such signal\");\n break;\n\n case wxKILL_ACCESS_DENIED:\n \twxLogStatus(\"permission denied\");\n break;\n\n case wxKILL_NO_PROCESS: \n wxLogStatus(\"no such process\");\n break;\n\n case wxKILL_ERROR:\n wxLogStatus(\"another, unspecified error\");\n break;\n \n default: wxFAIL;\n }\n \n return result;\n}\n\nvoid wxExProcess::OnCommand(wxCommandEvent& event)\n{\n switch (event.GetId())\n {\n case ID_SHELL_COMMAND:\n m_Timer->Stop();\n m_Dialog->GetSTCShell()->LineEnd();\n \n if (m_Command != \"cmd\")\n {\n m_Dialog->GetSTCShell()->AddText(m_Dialog->GetSTCShell()->GetEOL());\n }\n \n if (IsRunning()) \n {\n \/\/ send command to process\n wxOutputStream* os = GetOutputStream();\n \n if (os != NULL)\n {\n wxTextOutputStream os(*GetOutputStream());\n os.WriteString(event.GetString() + \"\\n\");\n } \n \n if (CheckInput())\n {\n m_Dialog->GetSTCShell()->Prompt(wxEmptyString, false);\n }\n \n m_Timer->Start();\n }\n else\n {\n wxLogStatus(\"Process is not running\");\n }\n break;\n\n case ID_SHELL_COMMAND_STOP:\n if (IsRunning())\n {\n Kill();\n }\n break;\n \n default: wxFAIL; break;\n }\n}\n \nvoid wxExProcess::OnTerminate(int pid, int status)\n{\n m_Timer->Stop();\n\n wxLogStatus(_(\"Ready\"));\n wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_TERMINATED_PROCESS);\n wxPostEvent(wxTheApp->GetTopWindow(), event);\n \n \/\/ Collect remaining input.\n CheckInput();\n}\n\nvoid wxExProcess::OnTimer(wxTimerEvent& event)\n{\n CheckInput();\n}\n\n#if wxUSE_GUI\nvoid wxExProcess::ShowOutput(const wxString& caption) const\n{\n if (!m_Sync)\n {\n wxLogStatus(\"Output only available for sync processes\");\n } \n else if (!m_Error)\n {\n if (m_Dialog != NULL)\n {\n m_Dialog->GetSTC()->SetText(m_Output);\n m_Dialog->SetTitle(caption.empty() ? m_Command: caption);\n m_Dialog->Show();\n }\n else if (!m_Output.empty())\n {\n wxLogMessage(m_Output);\n }\n else\n {\n wxLogStatus(\"No output available\");\n }\n }\n else\n {\n \/\/ Executing command failed, so no output,\n \/\/ show failing command.\n wxLogError(\"Could not execute: \" + m_Command);\n }\n}\n#endif\nmore process updates\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Name: process.cpp\n\/\/ Purpose: Implementation of class wxExProcess\n\/\/ Author: Anton van Wezenbeek\n\/\/ Copyright: (c) 2012 Anton van Wezenbeek\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \n#ifndef WX_PRECOMP\n#include \n#endif\n#include \n#include \/\/ for wxTextInputStream\n#include \/\/ for wxGetEnv\n#include \n#include \n#include \n#include \n#include \/\/ for wxExConfigFirstOf\n\nBEGIN_EVENT_TABLE(wxExProcess, wxProcess)\n EVT_MENU(ID_SHELL_COMMAND, wxExProcess::OnCommand)\n EVT_MENU(ID_SHELL_COMMAND_STOP, wxExProcess::OnCommand)\n EVT_TIMER(-1, wxExProcess::OnTimer)\nEND_EVENT_TABLE()\n\nwxExSTCEntryDialog* wxExProcess::m_Dialog = NULL;\nwxString wxExProcess::m_WorkingDirKey = _(\"Process folder\");\n\nwxExProcess::wxExProcess()\n : wxProcess(wxPROCESS_REDIRECT)\n , m_Timer(new wxTimer(this))\n , m_Busy(false)\n , m_Error(false)\n , m_Sync(false)\n{\n m_Command = wxExConfigFirstOf(_(\"Process\"));\n}\n\nwxExProcess::~wxExProcess()\n{\n delete m_Timer;\n}\n\nwxExProcess::wxExProcess(const wxExProcess& process)\n{\n *this = process;\n}\n\nwxExProcess& wxExProcess::operator=(const wxExProcess& p)\n{\n m_Busy = p.m_Busy;\n m_Error = p.m_Error;\n m_Output = p.m_Output;\n m_Sync = p.m_Sync;\n m_Timer = new wxTimer(this);\n\n return *this;\n}\n\nbool wxExProcess::CheckInput()\n{\n if (m_Busy)\n {\n return false;\n }\n \n m_Busy = true;\n \n wxString output;\n \n if (IsInputAvailable())\n {\n wxTextInputStream tis(*GetInputStream());\n \n while (IsInputAvailable())\n {\n const wxChar c = tis.GetChar();\n \n if (c != 0)\n {\n output << c;\n }\n }\n }\n \n if (IsErrorAvailable())\n {\n wxTextInputStream tis(*GetErrorStream());\n \n while (IsErrorAvailable())\n {\n const wxChar c = tis.GetChar();\n \n if (c != 0)\n {\n output << c;\n }\n }\n }\n\n m_Busy = false;\n \n if (!output.empty())\n {\n m_Dialog->GetSTCShell()->AddText(output);\n m_Dialog->GetSTCShell()->EnsureCaretVisible();\n \n return true;\n }\n else\n {\n return false;\n }\n}\n\nint wxExProcess::ConfigDialog(\n wxWindow* parent,\n const wxString& title,\n bool modal)\n{\n std::vector v;\n\n v.push_back(wxExConfigItem(\n _(\"Process\"), \n CONFIG_COMBOBOX, \n wxEmptyString,\n true));\n\n v.push_back(wxExConfigItem(\n m_WorkingDirKey, \n CONFIG_COMBOBOXDIR, \n wxEmptyString,\n true,\n 1000));\n\n if (modal)\n {\n return wxExConfigDialog(parent,\n v,\n title).ShowModal();\n }\n else\n {\n wxExConfigDialog* dlg = new wxExConfigDialog(\n parent,\n v,\n title);\n \n return dlg->Show();\n }\n}\n\nbool wxExProcess::Execute(\n const wxString& command_to_execute,\n int flags,\n const wxString& wd)\n{\n m_Error = false;\n \n struct wxExecuteEnv env;\n \n if (command_to_execute.empty())\n {\n if (wxExConfigFirstOf(_(\"Process\")).empty())\n {\n if (ConfigDialog(wxTheApp->GetTopWindow()) == wxID_CANCEL)\n {\n return false;\n }\n }\n \n m_Command = wxExConfigFirstOf(_(\"Process\"));\n env.cwd = wxExConfigFirstOf(m_WorkingDirKey);\n }\n else\n {\n m_Command = command_to_execute;\n env.cwd = wd;\n }\n\n m_Sync = (flags & wxEXEC_SYNC);\n\n \/\/ Construct the dialog.\n \/\/ This is necessary both in sync and async mode,\n \/\/ as for sync mode the dialog is used for presenting the \n \/\/ output member.\n if (m_Dialog == NULL)\n {\n m_Dialog = new wxExSTCEntryDialog(\n wxTheApp->GetTopWindow(),\n wxEmptyString,\n wxEmptyString,\n wxEmptyString,\n wxOK,\n true); \/\/ use_shell to force STCShell\n \n m_Dialog->SetProcess(this);\n m_Dialog->GetSTCShell()->SetEventHandler(this);\n }\n \n m_Dialog->GetSTCShell()->EnableShell(!m_Sync);\n \n if (!m_Sync)\n { \n m_Dialog->SetTitle(m_Command);\n m_Dialog->GetSTCShell()->ClearAll();\n \n \/\/ If we have entered a shell, then the shell\n \/\/ itself has no prompt. So put one here.\n if (m_Command == \"bash\" ||\n m_Command == \"csh\" ||\n m_Command == \"ksh\" ||\n m_Command == \"tcsh\" ||\n m_Command == \"sh\")\n {\n wxString host;\n wxGetEnv(\"HOST\", &host);\n m_Dialog->GetSTCShell()->SetPrompt(host + \">\", false);\n }\n else\n {\n m_Dialog->GetSTCShell()->SetPrompt(\"\");\n }\n\n \/\/ For asynchronous execution the return value is the process id and zero \n \/\/ value indicates that the command could not be executed.\n if (wxExecute(m_Command, flags, this, &env) > 0)\n {\n m_Dialog->Show();\n \n if (!CheckInput())\n {\n m_Dialog->GetSTCShell()->Prompt(wxEmptyString, false);\n }\n \n if (IsRunning())\n {\n m_Timer->Start(100); \/\/ each 100 milliseconds\n }\n }\n else\n {\n m_Dialog->Hide();\n \n m_Error = true;\n }\n }\n else\n {\n wxArrayString output;\n wxArrayString errors;\n \n \/\/ Call wxExecute to execute the command and\n \/\/ collect the output and the errors.\n if (wxExecute(\n m_Command,\n output,\n errors,\n flags,\n &env) == -1)\n {\n m_Output.clear();\n m_Error = true;\n }\n else\n {\n \/\/ Set output by converting array strings into normal strings.\n m_Output = wxJoin(errors, '\\n', '\\n') + wxJoin(output, '\\n', '\\n');\n }\n }\n \n return !m_Error;\n}\n\nbool wxExProcess::IsRunning() const\n{\n if (\n \/\/ If we executed a sync process, then it always ended,\n \/\/ so it is not running.\n m_Sync || \n GetPid() <= 0)\n {\n return false;\n }\n\n return Exists(GetPid());\n}\n\nwxKillError wxExProcess::Kill(wxSignal sig)\n{\n if (!IsRunning())\n {\n return wxKILL_NO_PROCESS;\n }\n \n const wxKillError result = wxProcess::Kill(GetPid(), sig);\n \n switch (result)\n {\n case wxKILL_OK:\n wxLogStatus(_(\"Stopped\"));\n DeletePendingEvents();\n m_Timer->Stop();\n m_Dialog->Hide();\n break;\n\n case wxKILL_BAD_SIGNAL:\n wxLogStatus(\"no such signal\");\n break;\n\n case wxKILL_ACCESS_DENIED:\n \twxLogStatus(\"permission denied\");\n break;\n\n case wxKILL_NO_PROCESS: \n wxLogStatus(\"no such process\");\n break;\n\n case wxKILL_ERROR:\n wxLogStatus(\"another, unspecified error\");\n break;\n \n default: wxFAIL;\n }\n \n return result;\n}\n\nvoid wxExProcess::OnCommand(wxCommandEvent& event)\n{\n switch (event.GetId())\n {\n case ID_SHELL_COMMAND:\n m_Timer->Stop();\n m_Dialog->GetSTCShell()->LineEnd();\n \n if (m_Command != \"cmd\")\n {\n m_Dialog->GetSTCShell()->AddText(m_Dialog->GetSTCShell()->GetEOL());\n }\n \n if (IsRunning()) \n {\n \/\/ send command to process\n wxOutputStream* os = GetOutputStream();\n \n if (os != NULL)\n {\n wxTextOutputStream os(*GetOutputStream());\n os.WriteString(event.GetString() + \"\\n\");\n } \n \n m_Dialog->GetSTCShell()->Prompt(wxEmptyString, false);\n \n m_Timer->Start();\n }\n else\n {\n wxLogStatus(\"Process is not running\");\n }\n break;\n\n case ID_SHELL_COMMAND_STOP:\n if (IsRunning())\n {\n Kill();\n }\n break;\n \n default: wxFAIL; break;\n }\n}\n \nvoid wxExProcess::OnTerminate(int pid, int status)\n{\n m_Timer->Stop();\n\n wxLogStatus(_(\"Ready\"));\n wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_TERMINATED_PROCESS);\n wxPostEvent(wxTheApp->GetTopWindow(), event);\n \n \/\/ Collect remaining input.\n CheckInput();\n}\n\nvoid wxExProcess::OnTimer(wxTimerEvent& event)\n{\n CheckInput();\n}\n\n#if wxUSE_GUI\nvoid wxExProcess::ShowOutput(const wxString& caption) const\n{\n if (!m_Sync)\n {\n wxLogStatus(\"Output only available for sync processes\");\n } \n else if (!m_Error)\n {\n if (m_Dialog != NULL)\n {\n m_Dialog->GetSTC()->SetText(m_Output);\n m_Dialog->SetTitle(caption.empty() ? m_Command: caption);\n m_Dialog->Show();\n }\n else if (!m_Output.empty())\n {\n wxLogMessage(m_Output);\n }\n else\n {\n wxLogStatus(\"No output available\");\n }\n }\n else\n {\n \/\/ Executing command failed, so no output,\n \/\/ show failing command.\n wxLogError(\"Could not execute: \" + m_Command);\n }\n}\n#endif\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Name: stcfile.cpp\n\/\/ Purpose: Implementation of class wxExSTCFile\n\/\/ Author: Anton van Wezenbeek\n\/\/ Copyright: (c) 2012 Anton van Wezenbeek\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \n#ifndef WX_PRECOMP\n#include \n#endif\n#include \n#include \n#include \n#include \n#include \/\/ for STAT_ etc.\n\n#if wxUSE_GUI\nwxExSTCFile::wxExSTCFile(wxExSTC* stc)\n : m_STC(stc)\n , m_PreviousLength(0)\n{\n}\n\nbool wxExSTCFile::DoFileLoad(bool synced)\n{\n if (GetContentsChanged())\n {\n wxExFileDialog dlg(m_STC, this);\n if (dlg.ShowModalIfChanged() == wxID_CANCEL) return false;\n }\n\n \/\/ Synchronizing by appending only new data only works for log files.\n \/\/ Other kind of files might get new data anywhere inside the file,\n \/\/ we cannot sync that by keeping pos. \n \/\/ Also only do it for reasonably large files.\n const bool isLog = (GetFileName().GetExt().CmpNoCase(\"log\") == 0);\n \n m_STC->UseModificationMarkers(false);\n\n ReadFromFile(\n synced &&\n isLog &&\n m_STC->GetTextLength() > 1024);\n\n m_STC->UseModificationMarkers(true);\n\n if (!synced)\n {\n m_STC->SetLexer(GetFileName().GetLexer().GetDisplayLexer(), true);\n\n \/\/ No edges for log files.\n if (isLog)\n {\n m_STC->SetEdgeMode(wxSTC_EDGE_NONE);\n }\n \n wxLogStatus(_(\"Opened\") + \": \" + GetFileName().GetFullPath());\n }\n \n m_STC->PropertiesMessage(synced ? STAT_SYNC: STAT_DEFAULT);\n \n return true;\n}\n\nvoid wxExSTCFile::DoFileNew()\n{\n m_STC->SetName(GetFileName().GetFullPath());\n m_STC->PropertiesMessage();\n m_STC->ClearDocument();\n m_STC->SetLexer(GetFileName().GetLexer().GetScintillaLexer());\n}\n\nvoid wxExSTCFile::DoFileSave(bool save_as)\n{\n size_t size;\n \n if (m_STC->HexMode())\n {\n \/\/ TODO: Does this allow NULLs?\n size = Write(m_STC->m_HexBuffer, m_STC->m_HexBuffer.size());\n }\n else\n {\n const wxCharBuffer& buffer = m_STC->GetTextRaw(); \n size = Write(buffer.data(), buffer.length());\n }\n \n if (size == 0)\n {\n wxLogStatus(\"could not save file\");\n return;\n }\n \n if (save_as)\n {\n m_STC->SetLexer(GetFileName().GetLexer().GetScintillaLexer());\n m_STC->SetName(GetFileName().GetFullPath());\n }\n \n m_STC->MarkerDeleteAllChange();\n \n wxLogStatus(_(\"Saved\") + \": \" + GetFileName().GetFullPath());\n}\n\nbool wxExSTCFile::GetContentsChanged() const \n{\n return m_STC->GetModify();\n}\n\nbool wxExSTCFile::Read(const wxString& name) const\n{\n wxFileName fn(name);\n\n if (fn.IsRelative())\n {\n fn.Normalize(wxPATH_NORM_ALL, GetFileName().GetPath());\n }\n \n wxExFile file;\n\n if (file.Exists(fn.GetFullPath()))\n {\n if (file.Open(fn.GetFullPath()))\n {\n const int SCI_ADDTEXT = 2001;\n const wxCharBuffer& buffer = file.Read();\n m_STC->SendMsg(\n SCI_ADDTEXT, buffer.length(), (wxIntPtr)(const char *)buffer.data());\n \n return true;\n }\n }\n \n wxLogStatus(_(\"file: %s does not exist\"), name);\n \n return false;\n}\n\nvoid wxExSTCFile::ReadFromFile(bool get_only_new_data)\n{\n \/\/ Be sure we can add text.\n m_STC->SetReadOnly(false);\n\n const bool pos_at_end = (m_STC->GetCurrentPos() >= m_STC->GetTextLength() - 1);\n\n int startPos, endPos;\n m_STC->GetSelection(&startPos, &endPos);\n\n wxFileOffset offset = 0;\n\n if (m_PreviousLength < Length() && get_only_new_data)\n {\n offset = m_PreviousLength;\n }\n\n if (offset == 0)\n {\n m_STC->ClearDocument();\n }\n\n m_PreviousLength = Length();\n\n const wxCharBuffer& buffer = wxExFile::Read(offset);\n\n if (!m_STC->HexMode())\n {\n \/\/ At least for toggling between hex and non-hex this is necessary to\n \/\/ reshow the edge line.\n m_STC->ConfigGet();\n\n m_STC->SetControlCharSymbol(0);\n\n const int SCI_ADDTEXT = 2001;\n const int SCI_APPENDTEXT = 2282;\n const int message = (get_only_new_data ? SCI_APPENDTEXT: SCI_ADDTEXT);\n\n \/\/ README: The stc.h equivalents AddText, AddTextRaw, InsertText, \n \/\/ InsertTextRaw do not add the length.\n \/\/ So for binary files this is the only way for opening.\n m_STC->SendMsg(message, buffer.length(), (wxIntPtr)(const char *)buffer.data());\n }\n else\n {\n m_STC->AppendTextHexMode(buffer);\n }\n\n if (get_only_new_data)\n {\n if (pos_at_end)\n {\n m_STC->DocumentEnd();\n }\n }\n else\n {\n m_STC->GuessType();\n m_STC->DocumentStart();\n }\n\n if (startPos != endPos)\n {\n m_STC->SetSelection(startPos, endPos);\n }\n \n if (m_STC->GetFlags() & m_STC->STC_WIN_READ_ONLY ||\n GetFileName().GetStat().IsReadOnly())\n {\n m_STC->SetReadOnly(true);\n }\n\n m_STC->EmptyUndoBuffer();\n}\n\nvoid wxExSTCFile::ResetContentsChanged()\n{\n m_STC->SetSavePoint();\n}\n\n#endif \/\/ wxUSE_GUI\nuse IsFileWritable\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Name: stcfile.cpp\n\/\/ Purpose: Implementation of class wxExSTCFile\n\/\/ Author: Anton van Wezenbeek\n\/\/ Copyright: (c) 2012 Anton van Wezenbeek\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \n#ifndef WX_PRECOMP\n#include \n#endif\n#include \n#include \n#include \n#include \n#include \/\/ for STAT_ etc.\n\n#if wxUSE_GUI\nwxExSTCFile::wxExSTCFile(wxExSTC* stc)\n : m_STC(stc)\n , m_PreviousLength(0)\n{\n}\n\nbool wxExSTCFile::DoFileLoad(bool synced)\n{\n if (GetContentsChanged())\n {\n wxExFileDialog dlg(m_STC, this);\n if (dlg.ShowModalIfChanged() == wxID_CANCEL) return false;\n }\n\n \/\/ Synchronizing by appending only new data only works for log files.\n \/\/ Other kind of files might get new data anywhere inside the file,\n \/\/ we cannot sync that by keeping pos. \n \/\/ Also only do it for reasonably large files.\n const bool isLog = (GetFileName().GetExt().CmpNoCase(\"log\") == 0);\n \n m_STC->UseModificationMarkers(false);\n\n ReadFromFile(\n synced &&\n isLog &&\n m_STC->GetTextLength() > 1024);\n\n m_STC->UseModificationMarkers(true);\n\n if (!synced)\n {\n m_STC->SetLexer(GetFileName().GetLexer().GetDisplayLexer(), true);\n\n \/\/ No edges for log files.\n if (isLog)\n {\n m_STC->SetEdgeMode(wxSTC_EDGE_NONE);\n }\n \n wxLogStatus(_(\"Opened\") + \": \" + GetFileName().GetFullPath());\n }\n \n m_STC->PropertiesMessage(synced ? STAT_SYNC: STAT_DEFAULT);\n \n return true;\n}\n\nvoid wxExSTCFile::DoFileNew()\n{\n m_STC->SetName(GetFileName().GetFullPath());\n m_STC->PropertiesMessage();\n m_STC->ClearDocument();\n m_STC->SetLexer(GetFileName().GetLexer().GetScintillaLexer());\n}\n\nvoid wxExSTCFile::DoFileSave(bool save_as)\n{\n size_t size;\n \n if (m_STC->HexMode())\n {\n \/\/ TODO: Does this allow NULLs?\n size = Write(m_STC->m_HexBuffer, m_STC->m_HexBuffer.size());\n }\n else\n {\n const wxCharBuffer& buffer = m_STC->GetTextRaw(); \n size = Write(buffer.data(), buffer.length());\n }\n \n if (size == 0)\n {\n wxLogStatus(\"could not save file\");\n return;\n }\n \n if (save_as)\n {\n m_STC->SetLexer(GetFileName().GetLexer().GetScintillaLexer());\n m_STC->SetName(GetFileName().GetFullPath());\n }\n \n m_STC->MarkerDeleteAllChange();\n \n wxLogStatus(_(\"Saved\") + \": \" + GetFileName().GetFullPath());\n}\n\nbool wxExSTCFile::GetContentsChanged() const \n{\n return m_STC->GetModify();\n}\n\nbool wxExSTCFile::Read(const wxString& name) const\n{\n wxFileName fn(name);\n\n if (fn.IsRelative())\n {\n fn.Normalize(wxPATH_NORM_ALL, GetFileName().GetPath());\n }\n \n wxExFile file;\n\n if (file.Exists(fn.GetFullPath()))\n {\n if (file.Open(fn.GetFullPath()))\n {\n const int SCI_ADDTEXT = 2001;\n const wxCharBuffer& buffer = file.Read();\n m_STC->SendMsg(\n SCI_ADDTEXT, buffer.length(), (wxIntPtr)(const char *)buffer.data());\n \n return true;\n }\n }\n \n wxLogStatus(_(\"file: %s does not exist\"), name);\n \n return false;\n}\n\nvoid wxExSTCFile::ReadFromFile(bool get_only_new_data)\n{\n \/\/ Be sure we can add text.\n m_STC->SetReadOnly(false);\n\n const bool pos_at_end = (m_STC->GetCurrentPos() >= m_STC->GetTextLength() - 1);\n\n int startPos, endPos;\n m_STC->GetSelection(&startPos, &endPos);\n\n wxFileOffset offset = 0;\n\n if (m_PreviousLength < Length() && get_only_new_data)\n {\n offset = m_PreviousLength;\n }\n\n if (offset == 0)\n {\n m_STC->ClearDocument();\n }\n\n m_PreviousLength = Length();\n\n const wxCharBuffer& buffer = wxExFile::Read(offset);\n\n if (!m_STC->HexMode())\n {\n \/\/ At least for toggling between hex and non-hex this is necessary to\n \/\/ reshow the edge line.\n m_STC->ConfigGet();\n\n m_STC->SetControlCharSymbol(0);\n\n const int SCI_ADDTEXT = 2001;\n const int SCI_APPENDTEXT = 2282;\n const int message = (get_only_new_data ? SCI_APPENDTEXT: SCI_ADDTEXT);\n\n \/\/ README: The stc.h equivalents AddText, AddTextRaw, InsertText, \n \/\/ InsertTextRaw do not add the length.\n \/\/ So for binary files this is the only way for opening.\n m_STC->SendMsg(message, buffer.length(), (wxIntPtr)(const char *)buffer.data());\n }\n else\n {\n m_STC->AppendTextHexMode(buffer);\n }\n\n if (get_only_new_data)\n {\n if (pos_at_end)\n {\n m_STC->DocumentEnd();\n }\n }\n else\n {\n m_STC->GuessType();\n m_STC->DocumentStart();\n }\n\n if (startPos != endPos)\n {\n m_STC->SetSelection(startPos, endPos);\n }\n \n if (( m_STC->GetFlags() & m_STC->STC_WIN_READ_ONLY) ||\n !GetFileName().IsFileWritable())\n {\n m_STC->SetReadOnly(true);\n }\n\n m_STC->EmptyUndoBuffer();\n}\n\nvoid wxExSTCFile::ResetContentsChanged()\n{\n m_STC->SetSavePoint();\n}\n\n#endif \/\/ wxUSE_GUI\n<|endoftext|>"} {"text":"#include \"common\/common.h\"\r\n#include \"common\/random_utils.h\"\r\n#include \"common\/cmd_options.h\"\r\n\r\n#include \"common\/graph\/dot_graph.h\"\r\n#include \"common\/graph\/dot_parser.h\"\r\n\r\n#include \"clustering.h\"\r\n#include \"metrics.h\"\r\n\r\n#include \r\n\r\nvoid PrepareCMDOptions(int argc, char** argv, CMDOptions& args)\r\n{\r\n\tstring msg;\r\n\tmsg += \"Usage: kmeans [options] input_file\\n\";\r\n\tmsg += \"When input_file is not supplied, the program reads from stdin.\\n\";\r\n\targs.SetUsageMessage(msg);\r\n\r\n\targs.AddAllowedOption(\"\", \"\", \"Input file name (stdin, if no input file is supplied)\");\r\n\targs.AddAllowedOption(\"-o\", \"\", \"Output file name (stdout, if no output file is supplied)\");\r\n\r\n\targs.AddAllowedOption(\"-action\", \"The program either computes a clustering for a given graph or calculates a set of quality measures (aesthetics)\");\r\n\targs.AddAllowedValue(\"-action\", \"clustering\");\r\n\targs.AddAllowedValue(\"-action\", \"metrics\");\r\n\r\n\targs.AddAllowedOption(\"-C\", \"Type of clustering\");\r\n\targs.AddAllowedValue(\"-C\", \"geometrickmeans\");\r\n\targs.AddAllowedValue(\"-C\", \"graphkmeans\");\r\n\targs.AddAllowedValue(\"-C\", \"geometrichierarchical\");\r\n\targs.AddAllowedValue(\"-C\", \"graphhierarchical\");\r\n\targs.AddAllowedValue(\"-C\", \"infomap\");\r\n\targs.AddAllowedValue(\"-C\", \"modularity\");\r\n\targs.AddAllowedValue(\"-C\", \"modularity-cont\");\r\n\r\n\targs.AddAllowedOption(\"-K\", \"\", \"Desired number of clusters (selected automatically, if no value is supplied)\");\r\n\r\n\targs.Parse(argc, argv);\r\n} \r\n\r\nvoid MetricsAction(const CMDOptions& options)\r\n{\r\n\tDotReader parser;\r\n\tDotGraph g = parser.ReadGraph(options.getOption(\"\"));\r\n\r\n\tMetrics m;\r\n\tm.Compute(g);\r\n\tm.Output(options.getOption(\"-o\"));\r\n}\r\n\r\nvoid ClusteringAction(const CMDOptions& options)\r\n{\r\n\tDotReader parser;\r\n\tDotGraph g = parser.ReadGraph(options.getOption(\"\"));\r\n\r\n\tstring algoName = options.getOption(\"-C\");\r\n\tClusterAlgorithm* algo = NULL;\r\n\r\n\tif (algoName == \"geometrickmeans\")\r\n\t\talgo = new GeometricKMeans();\r\n\telse if (algoName == \"graphkmeans\")\r\n\t\talgo = new GraphKMeans();\r\n\telse if (algoName == \"geometrichierarchical\")\r\n\t\talgo = new GeometricHierarchical();\r\n\telse if (algoName == \"graphhierarchical\")\r\n\t\talgo = new GraphHierarchical();\r\n\telse if (algoName == \"infomap\")\r\n\t\talgo = new InfoMap();\r\n\telse if (algoName == \"modularity\")\r\n\t\talgo = new Modularity(false);\r\n\telse if (algoName == \"modularity-cont\")\r\n\t\talgo = new Modularity(true);\r\n\r\n\tstring numberOfClusters = options.getOption(\"-K\");\r\n\tif (numberOfClusters == \"graph\")\r\n\t{\r\n\t\tint k = g.ClusterCount();\r\n\t\talgo->cluster(g, k);\r\n\t}\r\n\telse if (numberOfClusters == \"\")\r\n\t{\r\n\t\talgo->cluster(g);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tint k = toInt(numberOfClusters);\r\n\t\talgo->cluster(g, k);\r\n\t}\r\n\r\n\tdelete algo;\r\n\r\n\tDotWriter writer;\r\n\twriter.WriteGraph(options.getOption(\"-o\"), g);\r\n}\r\n\r\nint main(int argc, char **argv)\r\n{\r\n\tInitRand(123);\r\n\r\n\tauto options = CMDOptions::Create();\r\n\r\n\tint returnCode = 0;\r\n\ttry\r\n\t{\r\n\t\tPrepareCMDOptions(argc, argv, *options);\r\n\t\tstring action = options->getOption(\"-action\");\r\n\t\tif (action == \"clustering\")\r\n\t\t{\r\n\t\t\tClusteringAction(*options);\r\n\t\t}\r\n\t\telse if (action == \"metrics\")\r\n\t\t{\r\n\t\t\tMetricsAction(*options);\r\n\t\t}\r\n\t}\r\n\tcatch (int code)\r\n\t{\r\n\t\treturnCode = code;\t\t\r\n\t}\r\n\r\n\treturn returnCode;\r\n}\r\ncompute cluster-based and not embedding-based metrics#include \"common\/common.h\"\r\n#include \"common\/random_utils.h\"\r\n#include \"common\/cmd_options.h\"\r\n\r\n#include \"common\/graph\/dot_graph.h\"\r\n#include \"common\/graph\/dot_parser.h\"\r\n\r\n#include \"clustering.h\"\r\n#include \"metrics.h\"\r\n\r\n#include \r\n\r\nvoid PrepareCMDOptions(int argc, char** argv, CMDOptions& args)\r\n{\r\n\tstring msg;\r\n\tmsg += \"Usage: kmeans [options] input_file\\n\";\r\n\tmsg += \"When input_file is not supplied, the program reads from stdin.\\n\";\r\n\targs.SetUsageMessage(msg);\r\n\r\n\targs.AddAllowedOption(\"\", \"\", \"Input file name (stdin, if no input file is supplied)\");\r\n\targs.AddAllowedOption(\"-o\", \"\", \"Output file name (stdout, if no output file is supplied)\");\r\n\r\n\targs.AddAllowedOption(\"-action\", \"The program either computes a clustering for a given graph or calculates a set of quality measures (aesthetics)\");\r\n\targs.AddAllowedValue(\"-action\", \"clustering\");\r\n\targs.AddAllowedValue(\"-action\", \"metrics\");\r\n\r\n\targs.AddAllowedOption(\"-C\", \"Type of clustering\");\r\n\targs.AddAllowedValue(\"-C\", \"geometrickmeans\");\r\n\targs.AddAllowedValue(\"-C\", \"graphkmeans\");\r\n\targs.AddAllowedValue(\"-C\", \"geometrichierarchical\");\r\n\targs.AddAllowedValue(\"-C\", \"graphhierarchical\");\r\n\targs.AddAllowedValue(\"-C\", \"infomap\");\r\n\targs.AddAllowedValue(\"-C\", \"modularity\");\r\n\targs.AddAllowedValue(\"-C\", \"modularity-cont\");\r\n\r\n\targs.AddAllowedOption(\"-K\", \"\", \"Desired number of clusters (selected automatically, if no value is supplied)\");\r\n\r\n\targs.Parse(argc, argv);\r\n} \r\n\r\nvoid MetricsAction(const CMDOptions& options)\r\n{\r\n\tDotReader parser;\r\n\tDotGraph g = parser.ReadGraph(options.getOption(\"\"));\r\n\r\n\tMetrics m;\r\n\tm.ComputeCluster(g);\r\n\tm.Output(options.getOption(\"-o\"));\r\n}\r\n\r\nvoid ClusteringAction(const CMDOptions& options)\r\n{\r\n\tDotReader parser;\r\n\tDotGraph g = parser.ReadGraph(options.getOption(\"\"));\r\n\r\n\tstring algoName = options.getOption(\"-C\");\r\n\tClusterAlgorithm* algo = NULL;\r\n\r\n\tif (algoName == \"geometrickmeans\")\r\n\t\talgo = new GeometricKMeans();\r\n\telse if (algoName == \"graphkmeans\")\r\n\t\talgo = new GraphKMeans();\r\n\telse if (algoName == \"geometrichierarchical\")\r\n\t\talgo = new GeometricHierarchical();\r\n\telse if (algoName == \"graphhierarchical\")\r\n\t\talgo = new GraphHierarchical();\r\n\telse if (algoName == \"infomap\")\r\n\t\talgo = new InfoMap();\r\n\telse if (algoName == \"modularity\")\r\n\t\talgo = new Modularity(false);\r\n\telse if (algoName == \"modularity-cont\")\r\n\t\talgo = new Modularity(true);\r\n\r\n\tstring numberOfClusters = options.getOption(\"-K\");\r\n\tif (numberOfClusters == \"graph\")\r\n\t{\r\n\t\tint k = g.ClusterCount();\r\n\t\talgo->cluster(g, k);\r\n\t}\r\n\telse if (numberOfClusters == \"\")\r\n\t{\r\n\t\talgo->cluster(g);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tint k = toInt(numberOfClusters);\r\n\t\talgo->cluster(g, k);\r\n\t}\r\n\r\n\tdelete algo;\r\n\r\n\tDotWriter writer;\r\n\twriter.WriteGraph(options.getOption(\"-o\"), g);\r\n}\r\n\r\nint main(int argc, char **argv)\r\n{\r\n\tInitRand(123);\r\n\r\n\tauto options = CMDOptions::Create();\r\n\r\n\tint returnCode = 0;\r\n\ttry\r\n\t{\r\n\t\tPrepareCMDOptions(argc, argv, *options);\r\n\t\tstring action = options->getOption(\"-action\");\r\n\t\tif (action == \"clustering\")\r\n\t\t{\r\n\t\t\tClusteringAction(*options);\r\n\t\t}\r\n\t\telse if (action == \"metrics\")\r\n\t\t{\r\n\t\t\tMetricsAction(*options);\r\n\t\t}\r\n\t}\r\n\tcatch (int code)\r\n\t{\r\n\t\treturnCode = code;\t\t\r\n\t}\r\n\r\n\treturn returnCode;\r\n}\r\n<|endoftext|>"} {"text":"\/*\n * VehicleControlDeviceImplementation.cpp\n *\n * Created on: 10\/04\/2010\n * Author: victor\n *\/\n\n#include \"VehicleControlDevice.h\"\n#include \"VehicleControlObserver.h\"\n#include \"server\/zone\/managers\/objectcontroller\/ObjectController.h\"\n#include \"server\/zone\/objects\/creature\/CreatureObject.h\"\n#include \"server\/zone\/objects\/creature\/VehicleObject.h\"\n#include \"server\/zone\/ZoneServer.h\"\n#include \"server\/zone\/Zone.h\"\n#include \"tasks\/CallMountTask.h\"\n#include \"server\/zone\/objects\/region\/CityRegion.h\"\n#include \"server\/zone\/objects\/player\/sessions\/TradeSession.h\"\n\nvoid VehicleControlDeviceImplementation::generateObject(CreatureObject* player) {\n\tif (player->getParent() != NULL)\n\t\treturn;\n\n\tif (!isASubChildOf(player))\n\t\treturn;\n\n\tManagedReference controlledObject = this->controlledObject.get();\n\n\tif (controlledObject == NULL)\n\t\treturn;\n\n\tif (controlledObject->isInQuadTree())\n\t\treturn;\n\n\tif (player->isInCombat() || player->isDead() || player->isIncapacitated())\n\t\treturn;\n\n\tManagedReference tradeContainer = dynamic_cast(player->getActiveSession(SessionFacadeType::TRADE));\n\n\tif (tradeContainer != NULL) {\n\t\treturn;\n\t}\n\n\tif(player->getPendingTask(\"call_mount\") != NULL) {\n\t\tStringIdChatParameter waitTime(\"pet\/pet_menu\", \"call_delay_finish_vehicle\");\n\t\tTime nextExecution;\n\t\tCore::getTaskManager()->getNextExecutionTime(player->getPendingTask(\"call_mount\"), nextExecution);\n\t\tint timeLeft = (nextExecution.getMiliTime() \/ 1000) - System::getTime();\n\t\twaitTime.setDI(timeLeft);\n\n\t\tplayer->sendSystemMessage(waitTime);\n\t\treturn;\n\t}\n\n\tManagedReference datapad = player->getSlottedObject(\"datapad\");\n\n\tif (datapad == NULL)\n\t\treturn;\n\n\tint currentlySpawned = 0;\n\n\tfor (int i = 0; i < datapad->getContainerObjectsSize(); ++i) {\n\t\tManagedReference object = datapad->getContainerObject(i);\n\n\t\tif (object->isControlDevice()) {\n\t\t\tControlDevice* device = cast( object.get());\n\n\t\t\tManagedReference vehicle = device->getControlledObject();\n\n\t\t\tif (vehicle != NULL && vehicle->isInQuadTree()) {\n\t\t\t\tif (++currentlySpawned > 2)\n\t\t\t\t\tplayer->sendSystemMessage(\"@pet\/pet_menu:has_max_vehicle\");\n\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\n\tif(player->getCurrentCamp() == NULL && player->getCityRegion() == NULL) {\n\n\t\tReference callMount = new CallMountTask(_this.get(), player, \"call_mount\");\n\n\t\tStringIdChatParameter message(\"pet\/pet_menu\", \"call_vehicle_delay\");\n\t\tmessage.setDI(15);\n\t\tplayer->sendSystemMessage(message);\n\n\t\tplayer->addPendingTask(\"call_mount\", callMount, 15 * 1000);\n\n\t\tif (vehicleControlObserver == NULL) {\n\t\t\tvehicleControlObserver = new VehicleControlObserver(_this.get());\n\t\t\tvehicleControlObserver->deploy();\n\t\t}\n\n\t\tplayer->registerObserver(ObserverEventType::STARTCOMBAT, vehicleControlObserver);\n\n\t} else {\n\n\t\tLocker clocker(controlledObject, player);\n\t\tspawnObject(player);\n\t}\n\n}\n\nvoid VehicleControlDeviceImplementation::spawnObject(CreatureObject* player) {\n\tZoneServer* zoneServer = getZoneServer();\n\n\tManagedReference controlledObject = this->controlledObject.get();\n\n\tif (controlledObject == NULL)\n\t\treturn;\n\n\tif (!isASubChildOf(player))\n\t\treturn;\n\n\tManagedReference tradeContainer = dynamic_cast(player->getActiveSession(SessionFacadeType::TRADE));\n\n\tif (tradeContainer != NULL) {\n\t\treturn;\n\t}\n\n\tcontrolledObject->initializePosition(player->getPositionX(), player->getPositionZ(), player->getPositionY());\n\tManagedReference vehicle = NULL;\n\t\n\tif (controlledObject->isCreatureObject())\n\t{\n\t\n\t\tvehicle = cast(controlledObject.get());\n\t\tvehicle->setCreatureLink(player);\n\t\tvehicle->setControlDevice(_this.get());\n\t\t\n\t}\n\t\n\tZone* zone = player->getZone();\n\t\n\tif (zone == NULL)\n\t\treturn;\n\n\t\/\/controlledObject->insertToZone(player->getZone());\n\tzone->transferObject(controlledObject, -1, true);\n\tcontrolledObject->inflictDamage(player, 0, System::random(50), true);\n\t\n\tif (vehicle != NULL && controlledObject->getServerObjectCRC() == 0x32F87A54) \/\/ Jetpack\n\t{\n\t\n\t\tcontrolledObject->setCustomizationVariable(\"\/private\/index_hover_height\", 40, true); \/\/ Illusion of flying.\n\t\tplayer->executeObjectControllerAction(String(\"mount\").hashCode(), controlledObject->getObjectID(), \"\"); \/\/ Auto mount.\n\t\t\n\t}\n\n\tupdateStatus(1);\n\n\tif (vehicleControlObserver != NULL)\n\t\tplayer->dropObserver(ObserverEventType::STARTCOMBAT, vehicleControlObserver);\n}\n\nvoid VehicleControlDeviceImplementation::cancelSpawnObject(CreatureObject* player) {\n\n\tif(player->getPendingTask(\"call_mount\")) {\n\t\tplayer->getPendingTask(\"call_mount\")->cancel();\n\t\tplayer->removePendingTask(\"call_mount\");\n\t}\n\n\tif (vehicleControlObserver != NULL)\n\t\tplayer->dropObserver(ObserverEventType::STARTCOMBAT, vehicleControlObserver);\n}\n\nvoid VehicleControlDeviceImplementation::storeObject(CreatureObject* player) {\n\tManagedReference controlledObject = this->controlledObject.get();\n\n\tif (controlledObject == NULL)\n\t\treturn;\n\n\t\/*if (!controlledObject->isInQuadTree())\n\t\treturn;*\/\n\n\tif (player->isRidingMount() && player->getParent() == controlledObject) {\n\n\t\tif (!player->checkCooldownRecovery(\"mount_dismount\"))\n\t\t\treturn;\n\n\t\tplayer->executeObjectControllerAction(String(\"dismount\").hashCode());\n\n\t\tif (player->isRidingMount())\n\t\t\treturn;\n\t}\n\n\tcontrolledObject->destroyObjectFromWorld(true);\n\n\tif (controlledObject->isCreatureObject())\n\t\t(cast(controlledObject.get()))->setCreatureLink(NULL);\n\n\tupdateStatus(0);\n}\n\nvoid VehicleControlDeviceImplementation::destroyObjectFromDatabase(bool destroyContainedObjects) {\n\tManagedReference controlledObject = this->controlledObject.get();\n\n\tif (controlledObject != NULL) {\n\t\tLocker locker(controlledObject);\n\n\t\t\/\/ManagedReference object = controlledObject.castTo()->getLinkedCreature();\n\t\tManagedReference object = cast(controlledObject->getSlottedObject(\"rider\"));\n\n\t\tif (object != NULL) {\n\t\t\tLocker clocker(object, controlledObject);\n\n\t\t\tobject->executeObjectControllerAction(String(\"dismount\").hashCode());\n\n\t\t\tobject = cast(controlledObject->getSlottedObject(\"rider\"));\n\n\t\t\tif (object != NULL) {\n\t\t\t\tcontrolledObject->removeObject(object, NULL, true);\n\n\t\t\t\tZone* zone = getZone();\n\n\t\t\t\tif (zone != NULL)\n\t\t\t\t\tzone->transferObject(object, -1, false);\n\t\t\t}\n\t\t}\n\n\t\tcontrolledObject->destroyObjectFromDatabase(true);\n\t}\n\n\tIntangibleObjectImplementation::destroyObjectFromDatabase(destroyContainedObjects);\n}\n\nint VehicleControlDeviceImplementation::canBeDestroyed(CreatureObject* player) {\n\tManagedReference controlledObject = this->controlledObject.get();\n\n\tif (controlledObject != NULL) {\n\t\tif (controlledObject->isInQuadTree())\n\t\t\treturn 1;\n\t}\n\n\treturn IntangibleObjectImplementation::canBeDestroyed(player);\n}\n[fixed] trade bug\/*\n * VehicleControlDeviceImplementation.cpp\n *\n * Created on: 10\/04\/2010\n * Author: victor\n *\/\n\n#include \"VehicleControlDevice.h\"\n#include \"VehicleControlObserver.h\"\n#include \"server\/zone\/managers\/objectcontroller\/ObjectController.h\"\n#include \"server\/zone\/objects\/creature\/CreatureObject.h\"\n#include \"server\/zone\/objects\/creature\/VehicleObject.h\"\n#include \"server\/zone\/ZoneServer.h\"\n#include \"server\/zone\/Zone.h\"\n#include \"tasks\/CallMountTask.h\"\n#include \"server\/zone\/objects\/region\/CityRegion.h\"\n#include \"server\/zone\/objects\/player\/sessions\/TradeSession.h\"\n#include \"server\/zone\/managers\/player\/PlayerManager.h\"\n\nvoid VehicleControlDeviceImplementation::generateObject(CreatureObject* player) {\n\tif (player->getParent() != NULL)\n\t\treturn;\n\n\tif (!isASubChildOf(player))\n\t\treturn;\n\n\tManagedReference controlledObject = this->controlledObject.get();\n\n\tif (controlledObject == NULL)\n\t\treturn;\n\n\tif (controlledObject->isInQuadTree())\n\t\treturn;\n\n\tif (player->isInCombat() || player->isDead() || player->isIncapacitated())\n\t\treturn;\n\n\tManagedReference tradeContainer = dynamic_cast(player->getActiveSession(SessionFacadeType::TRADE));\n\n\tif (tradeContainer != NULL) {\n\t\tserver->getZoneServer()->getPlayerManager()->handleAbortTradeMessage(player);\n\t}\n\n\tif(player->getPendingTask(\"call_mount\") != NULL) {\n\t\tStringIdChatParameter waitTime(\"pet\/pet_menu\", \"call_delay_finish_vehicle\");\n\t\tTime nextExecution;\n\t\tCore::getTaskManager()->getNextExecutionTime(player->getPendingTask(\"call_mount\"), nextExecution);\n\t\tint timeLeft = (nextExecution.getMiliTime() \/ 1000) - System::getTime();\n\t\twaitTime.setDI(timeLeft);\n\n\t\tplayer->sendSystemMessage(waitTime);\n\t\treturn;\n\t}\n\n\tManagedReference datapad = player->getSlottedObject(\"datapad\");\n\n\tif (datapad == NULL)\n\t\treturn;\n\n\tint currentlySpawned = 0;\n\n\tfor (int i = 0; i < datapad->getContainerObjectsSize(); ++i) {\n\t\tManagedReference object = datapad->getContainerObject(i);\n\n\t\tif (object->isControlDevice()) {\n\t\t\tControlDevice* device = cast( object.get());\n\n\t\t\tManagedReference vehicle = device->getControlledObject();\n\n\t\t\tif (vehicle != NULL && vehicle->isInQuadTree()) {\n\t\t\t\tif (++currentlySpawned > 2)\n\t\t\t\t\tplayer->sendSystemMessage(\"@pet\/pet_menu:has_max_vehicle\");\n\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\n\tif(player->getCurrentCamp() == NULL && player->getCityRegion() == NULL) {\n\n\t\tReference callMount = new CallMountTask(_this.get(), player, \"call_mount\");\n\n\t\tStringIdChatParameter message(\"pet\/pet_menu\", \"call_vehicle_delay\");\n\t\tmessage.setDI(15);\n\t\tplayer->sendSystemMessage(message);\n\n\t\tplayer->addPendingTask(\"call_mount\", callMount, 15 * 1000);\n\n\t\tif (vehicleControlObserver == NULL) {\n\t\t\tvehicleControlObserver = new VehicleControlObserver(_this.get());\n\t\t\tvehicleControlObserver->deploy();\n\t\t}\n\n\t\tplayer->registerObserver(ObserverEventType::STARTCOMBAT, vehicleControlObserver);\n\n\t} else {\n\n\t\tLocker clocker(controlledObject, player);\n\t\tspawnObject(player);\n\t}\n\n}\n\nvoid VehicleControlDeviceImplementation::spawnObject(CreatureObject* player) {\n\tZoneServer* zoneServer = getZoneServer();\n\n\tManagedReference controlledObject = this->controlledObject.get();\n\n\tif (controlledObject == NULL)\n\t\treturn;\n\n\tif (!isASubChildOf(player))\n\t\treturn;\n\n\tManagedReference tradeContainer = dynamic_cast(player->getActiveSession(SessionFacadeType::TRADE));\n\n\tif (tradeContainer != NULL) {\n\t\tserver->getZoneServer()->getPlayerManager()->handleAbortTradeMessage(player);\n\t}\n\n\tcontrolledObject->initializePosition(player->getPositionX(), player->getPositionZ(), player->getPositionY());\n\tManagedReference vehicle = NULL;\n\t\n\tif (controlledObject->isCreatureObject())\n\t{\n\t\n\t\tvehicle = cast(controlledObject.get());\n\t\tvehicle->setCreatureLink(player);\n\t\tvehicle->setControlDevice(_this.get());\n\t\t\n\t}\n\t\n\tZone* zone = player->getZone();\n\t\n\tif (zone == NULL)\n\t\treturn;\n\n\t\/\/controlledObject->insertToZone(player->getZone());\n\tzone->transferObject(controlledObject, -1, true);\n\tcontrolledObject->inflictDamage(player, 0, System::random(50), true);\n\t\n\tif (vehicle != NULL && controlledObject->getServerObjectCRC() == 0x32F87A54) \/\/ Jetpack\n\t{\n\t\n\t\tcontrolledObject->setCustomizationVariable(\"\/private\/index_hover_height\", 40, true); \/\/ Illusion of flying.\n\t\tplayer->executeObjectControllerAction(String(\"mount\").hashCode(), controlledObject->getObjectID(), \"\"); \/\/ Auto mount.\n\t\t\n\t}\n\n\tupdateStatus(1);\n\n\tif (vehicleControlObserver != NULL)\n\t\tplayer->dropObserver(ObserverEventType::STARTCOMBAT, vehicleControlObserver);\n}\n\nvoid VehicleControlDeviceImplementation::cancelSpawnObject(CreatureObject* player) {\n\n\tif(player->getPendingTask(\"call_mount\")) {\n\t\tplayer->getPendingTask(\"call_mount\")->cancel();\n\t\tplayer->removePendingTask(\"call_mount\");\n\t}\n\n\tif (vehicleControlObserver != NULL)\n\t\tplayer->dropObserver(ObserverEventType::STARTCOMBAT, vehicleControlObserver);\n}\n\nvoid VehicleControlDeviceImplementation::storeObject(CreatureObject* player) {\n\tManagedReference controlledObject = this->controlledObject.get();\n\n\tif (controlledObject == NULL)\n\t\treturn;\n\n\t\/*if (!controlledObject->isInQuadTree())\n\t\treturn;*\/\n\n\tif (player->isRidingMount() && player->getParent() == controlledObject) {\n\n\t\tif (!player->checkCooldownRecovery(\"mount_dismount\"))\n\t\t\treturn;\n\n\t\tplayer->executeObjectControllerAction(String(\"dismount\").hashCode());\n\n\t\tif (player->isRidingMount())\n\t\t\treturn;\n\t}\n\n\tcontrolledObject->destroyObjectFromWorld(true);\n\n\tif (controlledObject->isCreatureObject())\n\t\t(cast(controlledObject.get()))->setCreatureLink(NULL);\n\n\tupdateStatus(0);\n}\n\nvoid VehicleControlDeviceImplementation::destroyObjectFromDatabase(bool destroyContainedObjects) {\n\tManagedReference controlledObject = this->controlledObject.get();\n\n\tif (controlledObject != NULL) {\n\t\tLocker locker(controlledObject);\n\n\t\t\/\/ManagedReference object = controlledObject.castTo()->getLinkedCreature();\n\t\tManagedReference object = cast(controlledObject->getSlottedObject(\"rider\"));\n\n\t\tif (object != NULL) {\n\t\t\tLocker clocker(object, controlledObject);\n\n\t\t\tobject->executeObjectControllerAction(String(\"dismount\").hashCode());\n\n\t\t\tobject = cast(controlledObject->getSlottedObject(\"rider\"));\n\n\t\t\tif (object != NULL) {\n\t\t\t\tcontrolledObject->removeObject(object, NULL, true);\n\n\t\t\t\tZone* zone = getZone();\n\n\t\t\t\tif (zone != NULL)\n\t\t\t\t\tzone->transferObject(object, -1, false);\n\t\t\t}\n\t\t}\n\n\t\tcontrolledObject->destroyObjectFromDatabase(true);\n\t}\n\n\tIntangibleObjectImplementation::destroyObjectFromDatabase(destroyContainedObjects);\n}\n\nint VehicleControlDeviceImplementation::canBeDestroyed(CreatureObject* player) {\n\tManagedReference controlledObject = this->controlledObject.get();\n\n\tif (controlledObject != NULL) {\n\t\tif (controlledObject->isInQuadTree())\n\t\t\treturn 1;\n\t}\n\n\treturn IntangibleObjectImplementation::canBeDestroyed(player);\n}\n<|endoftext|>"} {"text":"adds tcl binding for packet headerint protoname_pkt::offset_;\n\nstatic class ProtonameHeaderClass : public PacketHeaderClass {\n\tpublic:\n\tProtonameHeaderClass() : PacketHeaderClass(\"PacketHeader\/Adian\",\n\tsizeof(hdr_protoname_pkt)) {\n\t\tbind_offset(&hdr_protoname_pkt::offset_);\n\t}\n} class_rtProtoProtoname_hdr;<|endoftext|>"} {"text":"\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2012-2013 Esteban Tovagliari, Jupiter Jazz Limited\n\/\/ Copyright (c) 2014-2016 Esteban Tovagliari, The appleseedhq Organization\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ appleseed.python headers.\n#include \"pyseed.h\" \/\/ has to be first, to avoid redefinition warnings\n#include \"bindentitycontainers.h\"\n#include \"dict2dict.h\"\n\n\/\/ appleseed.renderer headers.\n#include \"renderer\/api\/display.h\"\n#include \"renderer\/api\/frame.h\"\n#include \"renderer\/api\/project.h\"\n#include \"renderer\/api\/scene.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/utility\/searchpaths.h\"\n\n\/\/ Standard headers.\n#include \n#include \n\nnamespace bpy = boost::python;\nusing namespace foundation;\nusing namespace renderer;\nusing namespace std;\n\n\/\/ Work around a regression in Visual Studio 2015 Update 3.\n#if defined(_MSC_VER) && _MSC_VER == 1900\nnamespace boost\n{\n template <> Configuration const volatile* get_pointer(Configuration const volatile* p) { return p; }\n template <> Project const volatile* get_pointer(Project const volatile* p) { return p; }\n}\n#endif\n\nnamespace\n{\n auto_release_ptr create_project(const string& name)\n {\n return ProjectFactory::create(name.c_str());\n }\n\n bpy::object create_default_project()\n {\n auto_release_ptr project(DefaultProjectFactory::create());\n return bpy::object(project);\n }\n\n bpy::object create_cornell_box_project()\n {\n auto_release_ptr project(CornellBoxProjectFactory::create());\n return bpy::object(project);\n }\n\n bpy::list project_get_search_paths(const Project* project)\n {\n bpy::list paths;\n\n const SearchPaths& search_paths = project->search_paths();\n\n for (size_t i = 0; i < search_paths.size(); ++i)\n paths.append(search_paths[i]);\n\n return paths;\n }\n\n void project_set_search_paths(Project* project, const bpy::list& paths)\n {\n project->search_paths().clear();\n\n for (bpy::ssize_t i = 0, e = bpy::len(paths); i < e; ++i)\n {\n const bpy::extract extractor(paths[i]);\n if (extractor.check())\n project->search_paths().push_back(extractor());\n else\n {\n PyErr_SetString(PyExc_TypeError, \"Incompatible type. Only strings accepted.\");\n bpy::throw_error_already_set();\n }\n }\n }\n\n ConfigurationContainer* project_get_configs(Project* project)\n {\n return &(project->configurations());\n }\n\n bool write_project_default_opts(\n const ProjectFileWriter* writer,\n const Project* project,\n const char* filepath)\n {\n return ProjectFileWriter::write(*project, filepath);\n }\n\n bool write_project_with_opts(\n const ProjectFileWriter* writer,\n const Project* project,\n const char* filepath,\n int opts)\n {\n return ProjectFileWriter::write(*project, filepath, opts);\n }\n\n auto_release_ptr create_config(const string& name)\n {\n return ConfigurationFactory::create(name.c_str());\n }\n\n auto_release_ptr create_config_with_params(\n const string& name,\n const bpy::dict& params)\n {\n return ConfigurationFactory::create(name.c_str(), bpy_dict_to_param_array(params));\n }\n\n bpy::object create_base_final_config()\n {\n auto_release_ptr config(BaseConfigurationFactory::create_base_final());\n return bpy::object(config);\n }\n\n bpy::object create_base_interactive_config()\n {\n auto_release_ptr config(BaseConfigurationFactory::create_base_interactive());\n return bpy::object(config);\n }\n\n bpy::dict config_get_inherited_parameters(const Configuration* config)\n {\n ParamArray params(config->get_inherited_parameters());\n return param_array_to_bpy_dict(params);\n }\n\n void config_insert_path(Configuration* config, const char* path, const bpy::object& value)\n {\n {\n bpy::extract extractor(value);\n if (extractor.check())\n {\n config->get_parameters().insert_path(path, extractor());\n return;\n }\n }\n\n if (PyBool_Check(value.ptr()))\n {\n bpy::extract extractor(value);\n if (extractor.check())\n {\n config->get_parameters().insert_path(path, extractor());\n return;\n }\n }\n\n#if PY_MAJOR_VERSION == 2\n if (PyInt_Check(value.ptr()))\n {\n bpy::extract extractor(value);\n if (extractor.check())\n {\n config->get_parameters().insert_path(path, extractor());\n return;\n }\n }\n#endif\n\n if (PyLong_Check(value.ptr()))\n {\n bpy::extract extractor(value);\n if (extractor.check())\n {\n config->get_parameters().insert_path(path, extractor());\n return;\n }\n }\n\n if (PyFloat_Check(value.ptr()))\n {\n bpy::extract extractor(value);\n if (extractor.check())\n {\n config->get_parameters().insert_path(path, extractor());\n return;\n }\n }\n\n PyErr_SetString(PyExc_TypeError, \"Unsupported value type.\");\n bpy::throw_error_already_set();\n }\n\n void config_remove_path(Configuration* config, const char* path)\n {\n config->get_parameters().remove_path(path);\n }\n\n bpy::dict config_get_metadata()\n {\n return dictionary_to_bpy_dict(Configuration::get_metadata());\n }\n\n bpy::object project_file_reader_read_default_opts(\n ProjectFileReader* reader,\n const char* project_filename,\n const char* schema_filename)\n {\n auto_release_ptr project(reader->read(project_filename, schema_filename));\n return bpy::object(project);\n }\n\n bpy::object project_file_reader_read_with_opts(\n ProjectFileReader* reader,\n const char* project_filename,\n const char* schema_filename,\n const ProjectFileReader::Options opts)\n {\n auto_release_ptr project(reader->read(project_filename, schema_filename, opts));\n return bpy::object(project);\n }\n\n bpy::object project_file_reader_load_builtin(ProjectFileReader* reader, const char* project_name)\n {\n auto_release_ptr project(reader->load_builtin(project_name));\n return bpy::object(project);\n }\n}\n\nvoid bind_project()\n{\n bpy::class_, bpy::bases, boost::noncopyable>(\"Configuration\", bpy::no_init)\n .def(\"create_base_final\", create_base_final_config).staticmethod(\"create_base_final\")\n .def(\"create_base_interactive\", create_base_interactive_config).staticmethod(\"create_base_interactive\")\n\n .def(\"__init__\", bpy::make_constructor(create_config))\n .def(\"__init__\", bpy::make_constructor(create_config_with_params))\n\n .def(\"set_base\", &Configuration::set_base)\n .def(\"get_base\", &Configuration::get_base, bpy::return_value_policy())\n .def(\"get_inherited_parameters\", config_get_inherited_parameters)\n\n .def(\"insert_path\", config_insert_path)\n .def(\"remove_path\", config_remove_path)\n\n .def(\"get_metadata\", config_get_metadata).staticmethod(\"get_metadata\");\n\n bind_typed_entity_map(\"ConfigurationContainer\");\n\n bpy::class_, bpy::bases, boost::noncopyable>(\"Project\", bpy::no_init)\n .def(\"create_default\", create_default_project).staticmethod(\"create_default\")\n .def(\"create_cornell_box\", create_cornell_box_project).staticmethod(\"create_cornell_box\")\n\n .def(\"__init__\", bpy::make_constructor(create_project))\n\n .def(\"add_default_configurations\", &Project::add_default_configurations)\n\n .def(\"has_path\", &Project::has_path)\n .def(\"set_path\", &Project::set_path)\n .def(\"get_path\", &Project::get_path)\n\n .def(\"get_search_paths\", project_get_search_paths)\n .def(\"set_search_paths\", project_set_search_paths)\n\n .def(\"set_scene\", &Project::set_scene)\n .def(\"get_scene\", &Project::get_scene, bpy::return_value_policy())\n\n .def(\"set_frame\", &Project::set_frame)\n .def(\"get_frame\", &Project::get_frame, bpy::return_value_policy())\n\n .def(\"get_display\", &Project::get_display, bpy::return_value_policy())\n .def(\"set_display\", &Project::set_display)\n\n .def(\"get_active_camera\", &Project::get_uncached_active_camera, bpy::return_value_policy())\n\n .def(\"configurations\", project_get_configs, bpy::return_value_policy())\n\n .def(\"create_aov_images\", &Project::create_aov_images);\n\n bpy::enum_(\"ProjectFileReaderOptions\")\n .value(\"Defaults\", ProjectFileReader::Defaults)\n .value(\"OmitReadingMeshFiles\", ProjectFileReader::OmitReadingMeshFiles)\n .value(\"OmitProjectFileUpdate\", ProjectFileReader::OmitProjectFileUpdate);\n\n bpy::class_(\"ProjectFileReader\")\n .def(\"read\", &project_file_reader_read_default_opts)\n .def(\"read\", &project_file_reader_read_with_opts)\n .def(\"load_builtin\", &project_file_reader_load_builtin);\n\n bpy::enum_(\"ProjectFileWriterOptions\")\n .value(\"Defaults\", ProjectFileWriter::Defaults)\n .value(\"OmitHeaderComment\", ProjectFileWriter::OmitHeaderComment)\n .value(\"OmitWritingGeometryFiles\", ProjectFileWriter::OmitWritingGeometryFiles)\n .value(\"OmitHandlingAssetFiles\", ProjectFileWriter::OmitHandlingAssetFiles)\n .value(\"CopyAllAssets\", ProjectFileWriter::CopyAllAssets);\n\n bpy::class_(\"ProjectFileWriter\")\n \/\/ These methods are static but for symmetry with ProjectFileReader we're exposing them as non-static.\n .def(\"write\", write_project_default_opts)\n .def(\"write\", write_project_with_opts);\n}\nUpdated python ProjectFileReader options.\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2012-2013 Esteban Tovagliari, Jupiter Jazz Limited\n\/\/ Copyright (c) 2014-2016 Esteban Tovagliari, The appleseedhq Organization\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ appleseed.python headers.\n#include \"pyseed.h\" \/\/ has to be first, to avoid redefinition warnings\n#include \"bindentitycontainers.h\"\n#include \"dict2dict.h\"\n\n\/\/ appleseed.renderer headers.\n#include \"renderer\/api\/display.h\"\n#include \"renderer\/api\/frame.h\"\n#include \"renderer\/api\/project.h\"\n#include \"renderer\/api\/scene.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/utility\/searchpaths.h\"\n\n\/\/ Standard headers.\n#include \n#include \n\nnamespace bpy = boost::python;\nusing namespace foundation;\nusing namespace renderer;\nusing namespace std;\n\n\/\/ Work around a regression in Visual Studio 2015 Update 3.\n#if defined(_MSC_VER) && _MSC_VER == 1900\nnamespace boost\n{\n template <> Configuration const volatile* get_pointer(Configuration const volatile* p) { return p; }\n template <> Project const volatile* get_pointer(Project const volatile* p) { return p; }\n}\n#endif\n\nnamespace\n{\n auto_release_ptr create_project(const string& name)\n {\n return ProjectFactory::create(name.c_str());\n }\n\n bpy::object create_default_project()\n {\n auto_release_ptr project(DefaultProjectFactory::create());\n return bpy::object(project);\n }\n\n bpy::object create_cornell_box_project()\n {\n auto_release_ptr project(CornellBoxProjectFactory::create());\n return bpy::object(project);\n }\n\n bpy::list project_get_search_paths(const Project* project)\n {\n bpy::list paths;\n\n const SearchPaths& search_paths = project->search_paths();\n\n for (size_t i = 0; i < search_paths.size(); ++i)\n paths.append(search_paths[i]);\n\n return paths;\n }\n\n void project_set_search_paths(Project* project, const bpy::list& paths)\n {\n project->search_paths().clear();\n\n for (bpy::ssize_t i = 0, e = bpy::len(paths); i < e; ++i)\n {\n const bpy::extract extractor(paths[i]);\n if (extractor.check())\n project->search_paths().push_back(extractor());\n else\n {\n PyErr_SetString(PyExc_TypeError, \"Incompatible type. Only strings accepted.\");\n bpy::throw_error_already_set();\n }\n }\n }\n\n ConfigurationContainer* project_get_configs(Project* project)\n {\n return &(project->configurations());\n }\n\n bool write_project_default_opts(\n const ProjectFileWriter* writer,\n const Project* project,\n const char* filepath)\n {\n return ProjectFileWriter::write(*project, filepath);\n }\n\n bool write_project_with_opts(\n const ProjectFileWriter* writer,\n const Project* project,\n const char* filepath,\n int opts)\n {\n return ProjectFileWriter::write(*project, filepath, opts);\n }\n\n auto_release_ptr create_config(const string& name)\n {\n return ConfigurationFactory::create(name.c_str());\n }\n\n auto_release_ptr create_config_with_params(\n const string& name,\n const bpy::dict& params)\n {\n return ConfigurationFactory::create(name.c_str(), bpy_dict_to_param_array(params));\n }\n\n bpy::object create_base_final_config()\n {\n auto_release_ptr config(BaseConfigurationFactory::create_base_final());\n return bpy::object(config);\n }\n\n bpy::object create_base_interactive_config()\n {\n auto_release_ptr config(BaseConfigurationFactory::create_base_interactive());\n return bpy::object(config);\n }\n\n bpy::dict config_get_inherited_parameters(const Configuration* config)\n {\n ParamArray params(config->get_inherited_parameters());\n return param_array_to_bpy_dict(params);\n }\n\n void config_insert_path(Configuration* config, const char* path, const bpy::object& value)\n {\n {\n bpy::extract extractor(value);\n if (extractor.check())\n {\n config->get_parameters().insert_path(path, extractor());\n return;\n }\n }\n\n if (PyBool_Check(value.ptr()))\n {\n bpy::extract extractor(value);\n if (extractor.check())\n {\n config->get_parameters().insert_path(path, extractor());\n return;\n }\n }\n\n#if PY_MAJOR_VERSION == 2\n if (PyInt_Check(value.ptr()))\n {\n bpy::extract extractor(value);\n if (extractor.check())\n {\n config->get_parameters().insert_path(path, extractor());\n return;\n }\n }\n#endif\n\n if (PyLong_Check(value.ptr()))\n {\n bpy::extract extractor(value);\n if (extractor.check())\n {\n config->get_parameters().insert_path(path, extractor());\n return;\n }\n }\n\n if (PyFloat_Check(value.ptr()))\n {\n bpy::extract extractor(value);\n if (extractor.check())\n {\n config->get_parameters().insert_path(path, extractor());\n return;\n }\n }\n\n PyErr_SetString(PyExc_TypeError, \"Unsupported value type.\");\n bpy::throw_error_already_set();\n }\n\n void config_remove_path(Configuration* config, const char* path)\n {\n config->get_parameters().remove_path(path);\n }\n\n bpy::dict config_get_metadata()\n {\n return dictionary_to_bpy_dict(Configuration::get_metadata());\n }\n\n bpy::object project_file_reader_read_default_opts(\n ProjectFileReader* reader,\n const char* project_filename,\n const char* schema_filename)\n {\n auto_release_ptr project(reader->read(project_filename, schema_filename));\n return bpy::object(project);\n }\n\n bpy::object project_file_reader_read_with_opts(\n ProjectFileReader* reader,\n const char* project_filename,\n const char* schema_filename,\n const ProjectFileReader::Options opts)\n {\n auto_release_ptr project(reader->read(project_filename, schema_filename, opts));\n return bpy::object(project);\n }\n\n bpy::object project_file_reader_load_builtin(ProjectFileReader* reader, const char* project_name)\n {\n auto_release_ptr project(reader->load_builtin(project_name));\n return bpy::object(project);\n }\n}\n\nvoid bind_project()\n{\n bpy::class_, bpy::bases, boost::noncopyable>(\"Configuration\", bpy::no_init)\n .def(\"create_base_final\", create_base_final_config).staticmethod(\"create_base_final\")\n .def(\"create_base_interactive\", create_base_interactive_config).staticmethod(\"create_base_interactive\")\n\n .def(\"__init__\", bpy::make_constructor(create_config))\n .def(\"__init__\", bpy::make_constructor(create_config_with_params))\n\n .def(\"set_base\", &Configuration::set_base)\n .def(\"get_base\", &Configuration::get_base, bpy::return_value_policy())\n .def(\"get_inherited_parameters\", config_get_inherited_parameters)\n\n .def(\"insert_path\", config_insert_path)\n .def(\"remove_path\", config_remove_path)\n\n .def(\"get_metadata\", config_get_metadata).staticmethod(\"get_metadata\");\n\n bind_typed_entity_map(\"ConfigurationContainer\");\n\n bpy::class_, bpy::bases, boost::noncopyable>(\"Project\", bpy::no_init)\n .def(\"create_default\", create_default_project).staticmethod(\"create_default\")\n .def(\"create_cornell_box\", create_cornell_box_project).staticmethod(\"create_cornell_box\")\n\n .def(\"__init__\", bpy::make_constructor(create_project))\n\n .def(\"add_default_configurations\", &Project::add_default_configurations)\n\n .def(\"has_path\", &Project::has_path)\n .def(\"set_path\", &Project::set_path)\n .def(\"get_path\", &Project::get_path)\n\n .def(\"get_search_paths\", project_get_search_paths)\n .def(\"set_search_paths\", project_set_search_paths)\n\n .def(\"set_scene\", &Project::set_scene)\n .def(\"get_scene\", &Project::get_scene, bpy::return_value_policy())\n\n .def(\"set_frame\", &Project::set_frame)\n .def(\"get_frame\", &Project::get_frame, bpy::return_value_policy())\n\n .def(\"get_display\", &Project::get_display, bpy::return_value_policy())\n .def(\"set_display\", &Project::set_display)\n\n .def(\"get_active_camera\", &Project::get_uncached_active_camera, bpy::return_value_policy())\n\n .def(\"configurations\", project_get_configs, bpy::return_value_policy())\n\n .def(\"create_aov_images\", &Project::create_aov_images);\n\n bpy::enum_(\"ProjectFileReaderOptions\")\n .value(\"Defaults\", ProjectFileReader::Defaults)\n .value(\"OmitReadingMeshFiles\", ProjectFileReader::OmitReadingMeshFiles)\n .value(\"OmitProjectFileUpdate\", ProjectFileReader::OmitProjectFileUpdate)\n .value(\"OmitSearchPaths\", ProjectFileReader::OmitSearchPaths)\n .value(\"OmitProjectSchemaValidation\", ProjectFileReader::OmitProjectSchemaValidation);\n\n bpy::class_(\"ProjectFileReader\")\n .def(\"read\", &project_file_reader_read_default_opts)\n .def(\"read\", &project_file_reader_read_with_opts)\n .def(\"load_builtin\", &project_file_reader_load_builtin);\n\n bpy::enum_(\"ProjectFileWriterOptions\")\n .value(\"Defaults\", ProjectFileWriter::Defaults)\n .value(\"OmitHeaderComment\", ProjectFileWriter::OmitHeaderComment)\n .value(\"OmitWritingGeometryFiles\", ProjectFileWriter::OmitWritingGeometryFiles)\n .value(\"OmitHandlingAssetFiles\", ProjectFileWriter::OmitHandlingAssetFiles)\n .value(\"CopyAllAssets\", ProjectFileWriter::CopyAllAssets);\n\n bpy::class_(\"ProjectFileWriter\")\n \/\/ These methods are static but for symmetry with ProjectFileReader we're exposing them as non-static.\n .def(\"write\", write_project_default_opts)\n .def(\"write\", write_project_with_opts);\n}\n<|endoftext|>"} {"text":"#pragma once\n\n#include \n\n#include \n#include \n\n#include \"..\/glew.detail\/c.hxx\"\n#include \"..\/glew.detail\/gl_type.hxx\"\n#include \"..\/glew.detail\/error.hxx\"\n\n#include \"..\/stblib.hxx\"\n\n\/\/ assimp::Importer\n#include \n\/\/ aiPostProcessSteps for assimp::Importer::ReadFile\n#include \n\/\/ aiScene, aiNode\n#include \n\nnamespace wonder_rabbit_project\n{\n namespace wonderland\n {\n namespace renderer\n {\n namespace model\n {\n class material_t\n {\n boost::optional< glm::vec3 > _diffuse;\n boost::optional< glm::vec3 > _ambient;\n boost::optional< glm::vec3 > _specular;\n boost::optional< glm::vec3 > _emissive;\n boost::optional< glm::vec1 > _transparent;\n boost::optional< glm::vec1 > _reflective;\n \n glew::gl_type::GLuint _texture_id;\n#ifdef GL_VERSION_3_3\n \/\/ need for modern GL3\n glew::gl_type::GLuint _sampler_id;\n#endif\n \n public:\n \n ~material_t()\n {\n glew::c::glDeleteTextures( 1, &_texture_id );\n }\n \n material_t( aiMaterial* material, const std::string& path_prefix = \"\" )\n {\n \/\/ マテリアルカラー\n {\n aiColor3D result;\n if( material -> Get( AI_MATKEY_COLOR_DIFFUSE, result ) == aiReturn_SUCCESS )\n _diffuse = { result.r, result.g, result.b };\n if( material -> Get( AI_MATKEY_COLOR_AMBIENT, result ) == aiReturn_SUCCESS )\n _ambient = { result.r, result.g, result.b };\n if( material -> Get( AI_MATKEY_COLOR_SPECULAR, result ) == aiReturn_SUCCESS )\n _specular = { result.r, result.g, result.b };\n if( material -> Get( AI_MATKEY_COLOR_EMISSIVE, result ) == aiReturn_SUCCESS )\n _emissive = { result.r, result.g, result.b };\n if( material -> Get( AI_MATKEY_COLOR_TRANSPARENT, result ) == aiReturn_SUCCESS )\n _transparent = result.r;\n if( material -> Get( AI_MATKEY_COLOR_REFLECTIVE, result ) == aiReturn_SUCCESS )\n _reflective = result.r;\n }\n \n \/\/ テクスチャー\n const auto count_of_textures = material -> GetTextureCount(aiTextureType_DIFFUSE);\n for ( auto number_of_texture = 0u; number_of_texture < count_of_textures; ++number_of_texture )\n {\n aiString path;\n material -> GetTexture( aiTextureType_DIFFUSE, number_of_texture, &path, nullptr, nullptr, nullptr, nullptr, nullptr );\n \n stblib::image_loader_t loader;\n \n try\n {\n stblib::image_loader_t loader_( path_prefix.size() ? path_prefix + \"\/\" + path.C_Str() : path.C_Str() );\n loader = std::move( loader_ );\n }\n catch( const std::runtime_error& e )\n {\n std::cerr << \"warn: \" << e.what() << \" \" << ( path_prefix.size() ? path_prefix + \"\/\" + path.C_Str() : path.C_Str() ) << \"; skip the texture.\\n\";\n continue;\n }\n \n glew::gl_type::GLenum internal_format;\n glew::gl_type::GLenum format;\n switch( loader.count_of_pixel_elements() )\n {\n case 4: internal_format = GL_RGBA8; format = GL_RGBA; break;\n case 3: internal_format = GL_RGB8; format = GL_RGB; break;\n case 2: internal_format = GL_RG8; format = GL_RG; break;\n case 1: internal_format = GL_R8; format = GL_R; break;\n default: throw std::runtime_error( \"unsupported count_of_pixel_elements\" );\n }\n const glew::gl_type::GLsizei width = loader.width();\n const glew::gl_type::GLsizei height = loader.height();\n constexpr glew::gl_type::GLenum type = GL_UNSIGNED_BYTE;\n const void* data = loader.data();\n \n glew::c::glPixelStorei( GL_UNPACK_ALIGNMENT, loader.count_of_pixel_elements() == 4 ? 4 : 1 );\n \n glew::test_error( __FILE__, __LINE__ );\n \n \/\/ step.1: generate texture buffer\n \/\/ glGenTextures \/ GL_1_1\n \/\/ http:\/\/www.opengl.org\/wiki\/GLAPI\/glGenTextures\n glew::c::glGenTextures( 1, &_texture_id );\n\n glew::test_error( __FILE__, __LINE__ );\n \n \/\/ glBindTexture \/ GL_1_1\n \/\/ http:\/\/www.opengl.org\/wiki\/GLAPI\/glBindTexture\n glew::c::glBindTexture( GL_TEXTURE_2D, _texture_id );\n\n glew::test_error( __FILE__, __LINE__ );\n \n \/\/ step.2: generate storage and load image\n#if defined( GL_VERSION_4_2 )\n \n const glew::gl_type::GLsizei level = glm::log2( std::min( width, height ) );\n \/\/ glTexStorage2D \/ GL_4_2\n \/\/ http:\/\/www.opengl.org\/wiki\/GLAPI\/glTexStorage2D\n \/\/static auto counter = 0;\n \/\/if ( counter++ == 0 ) internal_format = GL_RGB8; else internal_format = GL_RGB8;\n glew::c::glTexStorage2D( GL_TEXTURE_2D, level, internal_format, width, height );\n \n glew::test_error( __FILE__, __LINE__ );\n \n \/\/ glTexSubImage2D \/ GL_1_0\n \/\/ http:\/\/www.opengl.org\/wiki\/GLAPI\/glTexSubImage2D\n glew::c::glTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, width, height, format, type, data );\n \n glew::test_error( __FILE__, __LINE__ );\n \n#elif defined( GL_VERSION_3_0 )\n \n constexpr glew::gl_type::GLint border = 0; \/\/ this value must be 0: http:\/\/www.opengl.org\/sdk\/docs\/man\/html\/glTexImage2D.xhtml\n constexpr glew::gl_type::GLint level = 0;\n #if EMSCRIPTEN\n internal_format = format;\n #endif\n glew::c::glTexImage2D( GL_TEXTURE_2D, level, internal_format, width, height, border, format, type, data );\n glew::test_error( __FILE__, __LINE__ );\n \n#elif defined( GL_VERSION_1_4 )\n \n \/\/ warning: these medhod is deprecated in GL_3_0, removed in GL_3_1.\n \/\/ within throught step.3 and step.4.\n glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );\n glew::test_error( __FILE__, __LINE__ );\n glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );\n glew::test_error( __FILE__, __LINE__ );\n glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );\n glew::test_error( __FILE__, __LINE__ );\n glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );\n glew::test_error( __FILE__, __LINE__ );\n glew::c::glTexParameteri( GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE );\n glew::test_error( __FILE__, __LINE__ );\n glew::c::glTexImage2D( GL_TEXTURE_2D, level, internal_format, width, height, border, format, type, data );\n glew::test_error( __FILE__, __LINE__ );\n \n#else\n \n \/\/ no mipmap\n constexpr glew::gl_type::GLint level = 0;\n glew::c::glTexImage2D( GL_TEXTURE_2D, level, internal_format, width, height, border, format, type, data );\n \n glew::test_error( __FILE__, __LINE__ );\n \n#endif\n \n \/\/ step.3: generate mipmaps\n#if defined( GL_VERSION_3_0 )\n \n \/\/ glGenerateMipmap \/ GL_3_0\n \/\/ http:\/\/www.opengl.org\/wiki\/GLAPI\/glGenerateMipmap\n glew::c::glGenerateMipmap( GL_TEXTURE_2D );\n \n glew::test_error( __FILE__, __LINE__ );\n \n#endif\n \n \/\/ step.4: set sampler params\n#if defined( GL_VERSION_3_3 )\n \/\/ glGenSamplers \/ GL_3_3\n \/\/ http:\/\/www.opengl.org\/wiki\/GLAPI\/glGenSamplers\n glew::c::glGenSamplers( 1, &_sampler_id );\n \n glew::c::glSamplerParameteri( _sampler_id, GL_TEXTURE_WRAP_S, GL_REPEAT );\n glew::test_error( __FILE__, __LINE__ );\n glew::c::glSamplerParameteri( _sampler_id, GL_TEXTURE_WRAP_T, GL_REPEAT );\n glew::test_error( __FILE__, __LINE__ );\n glew::c::glSamplerParameteri( _sampler_id, GL_TEXTURE_MAG_FILTER, GL_LINEAR );\n glew::test_error( __FILE__, __LINE__ );\n glew::c::glSamplerParameteri( _sampler_id, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );\n glew::test_error( __FILE__, __LINE__ );\n \n#elif defined( GL_VERSION_3_0 )\n glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );\n glew::test_error( __FILE__, __LINE__ );\n glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );\n glew::test_error( __FILE__, __LINE__ );\n glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );\n glew::test_error( __FILE__, __LINE__ );\n glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );\n glew::test_error( __FILE__, __LINE__ );\n #elif defined( GL_VERSION_1_4 )\n \/\/ nothing to do. this step done before at this version.\n#else\n \/\/ no mipmap\n glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );\n glew::test_error( __FILE__, __LINE__ );\n glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );\n glew::test_error( __FILE__, __LINE__ );\n glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );\n glew::test_error( __FILE__, __LINE__ );\n glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );\n glew::test_error( __FILE__, __LINE__ );\n#endif\n \n }\n }\n \n auto draw() const -> void\n {\n glew::gl_type::GLint program_id;\n glew::c::glGetIntegerv( GL_CURRENT_PROGRAM, &program_id );\n \n if ( program_id )\n {\n\n#define WRP_TMP( WRP_TMP_X, WRP_TMP_Y, WRP_TMP_Z ) \\\n const auto location_of_ ## WRP_TMP_X = glew::c::glGetUniformLocation( program_id, # WRP_TMP_X ); \\\n if ( location_of_ ## WRP_TMP_X not_eq -1 ) \\\n { \\\n if ( _ ## WRP_TMP_X ) \\\n glew::c::glUniform ## WRP_TMP_Y ## fv( location_of_ ## WRP_TMP_X , 1, & _ ## WRP_TMP_X .get().x ); \\\n else \\\n glew::c::glUniform ## WRP_TMP_Y ## fv( location_of_ ## WRP_TMP_X , 1, & WRP_TMP_Z [0] ); \\\n }\n \n WRP_TMP( diffuse , 3, glm::vec3( 1.0f ) )\n WRP_TMP( ambient , 3, glm::vec3( 0.0f ) )\n WRP_TMP( specular , 3, glm::vec3( 0.0f ) )\n WRP_TMP( emissive , 3, glm::vec3( 0.0f ) )\n WRP_TMP( transparent, 1, glm::vec1( 1.0f ) )\n WRP_TMP( reflective , 1, glm::vec1( 0.0f ) )\n \n#undef WRP_TMP\n }\n#ifdef GL_VERSION_1_3\n glew::c::glActiveTexture( GL_TEXTURE0 );\n#endif\n \/\/ GL_1_1\n glew::c::glBindTexture( GL_TEXTURE_2D, _texture_id );\n#ifdef GL_VERSION_3_3\n glew::c::glBindSampler( 0, _sampler_id );\n#endif\n }\n };\n }\n }\n }\n}fix #20 SEGV if load .x generated from metaseq#pragma once\n\n#include \n\n#include \n#include \n\n#include \"..\/glew.detail\/c.hxx\"\n#include \"..\/glew.detail\/gl_type.hxx\"\n#include \"..\/glew.detail\/error.hxx\"\n\n#include \"..\/stblib.hxx\"\n\n\/\/ assimp::Importer\n#include \n\/\/ aiPostProcessSteps for assimp::Importer::ReadFile\n#include \n\/\/ aiScene, aiNode\n#include \n\nnamespace wonder_rabbit_project\n{\n namespace wonderland\n {\n namespace renderer\n {\n namespace model\n {\n class material_t\n {\n boost::optional< glm::vec3 > _diffuse;\n boost::optional< glm::vec3 > _ambient;\n boost::optional< glm::vec3 > _specular;\n boost::optional< glm::vec3 > _emissive;\n boost::optional< glm::vec1 > _transparent;\n boost::optional< glm::vec1 > _reflective;\n \n glew::gl_type::GLuint _texture_id;\n#ifdef GL_VERSION_3_3\n \/\/ need for modern GL3\n glew::gl_type::GLuint _sampler_id;\n#endif\n \n public:\n \n ~material_t()\n {\n glew::c::glDeleteTextures( 1, &_texture_id );\n }\n \n material_t( aiMaterial* material, const std::string& path_prefix = \"\" )\n {\n \/\/ マテリアルカラー\n {\n aiColor3D result;\n if( material -> Get( AI_MATKEY_COLOR_DIFFUSE, result ) == aiReturn_SUCCESS )\n _diffuse = { result.r, result.g, result.b };\n if( material -> Get( AI_MATKEY_COLOR_AMBIENT, result ) == aiReturn_SUCCESS )\n _ambient = { result.r, result.g, result.b };\n if( material -> Get( AI_MATKEY_COLOR_SPECULAR, result ) == aiReturn_SUCCESS )\n _specular = { result.r, result.g, result.b };\n if( material -> Get( AI_MATKEY_COLOR_EMISSIVE, result ) == aiReturn_SUCCESS )\n _emissive = { result.r, result.g, result.b };\n if( material -> Get( AI_MATKEY_COLOR_TRANSPARENT, result ) == aiReturn_SUCCESS )\n _transparent = result.r;\n if( material -> Get( AI_MATKEY_COLOR_REFLECTIVE, result ) == aiReturn_SUCCESS )\n _reflective = result.r;\n }\n \n \/\/ テクスチャー\n const auto count_of_textures = material -> GetTextureCount(aiTextureType_DIFFUSE);\n for ( auto number_of_texture = 0u; number_of_texture < count_of_textures; ++number_of_texture )\n {\n aiString path;\n material -> GetTexture( aiTextureType_DIFFUSE, number_of_texture, &path, nullptr, nullptr, nullptr, nullptr, nullptr );\n \n stblib::image_loader_t loader;\n \n try\n {\n stblib::image_loader_t loader_( path_prefix.size() ? path_prefix + \"\/\" + path.C_Str() : path.C_Str() );\n loader = std::move( loader_ );\n }\n catch( const std::runtime_error& e )\n {\n std::cerr << \"warn: \" << e.what() << \" \" << ( path_prefix.size() ? path_prefix + \"\/\" + path.C_Str() : path.C_Str() ) << \"; skip the texture.\\n\";\n continue;\n }\n \n glew::gl_type::GLenum internal_format;\n glew::gl_type::GLenum format;\n switch( loader.count_of_pixel_elements() )\n {\n case 4: internal_format = GL_RGBA8; format = GL_RGBA; break;\n case 3: internal_format = GL_RGB8; format = GL_RGB; break;\n case 2: internal_format = GL_RG8; format = GL_RG; break;\n case 1: internal_format = GL_R8; format = GL_R; break;\n default: throw std::runtime_error( \"unsupported count_of_pixel_elements\" );\n }\n const glew::gl_type::GLsizei width = loader.width();\n const glew::gl_type::GLsizei height = loader.height();\n constexpr glew::gl_type::GLenum type = GL_UNSIGNED_BYTE;\n const void* data = loader.data();\n \n glew::c::glPixelStorei( GL_UNPACK_ALIGNMENT, loader.count_of_pixel_elements() == 4 ? 4 : 1 );\n \n glew::test_error( __FILE__, __LINE__ );\n \n \/\/ step.1: generate texture buffer\n \/\/ glGenTextures \/ GL_1_1\n \/\/ http:\/\/www.opengl.org\/wiki\/GLAPI\/glGenTextures\n glew::c::glGenTextures( 1, &_texture_id );\n\n glew::test_error( __FILE__, __LINE__ );\n \n \/\/ glBindTexture \/ GL_1_1\n \/\/ http:\/\/www.opengl.org\/wiki\/GLAPI\/glBindTexture\n glew::c::glBindTexture( GL_TEXTURE_2D, _texture_id );\n\n glew::test_error( __FILE__, __LINE__ );\n \n \/\/ step.2: generate storage and load image\n#if defined( GL_VERSION_4_2 )\n \n const glew::gl_type::GLsizei level = glm::log2( std::min( width, height ) );\n \/\/ glTexStorage2D \/ GL_4_2\n \/\/ http:\/\/www.opengl.org\/wiki\/GLAPI\/glTexStorage2D\n \/\/static auto counter = 0;\n \/\/if ( counter++ == 0 ) internal_format = GL_RGB8; else internal_format = GL_RGB8;\n glew::c::glTexStorage2D( GL_TEXTURE_2D, level, internal_format, width, height );\n \n glew::test_error( __FILE__, __LINE__ );\n \n \/\/ glTexSubImage2D \/ GL_1_0\n \/\/ http:\/\/www.opengl.org\/wiki\/GLAPI\/glTexSubImage2D\n glew::c::glTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, width, height, format, type, data );\n \n glew::test_error( __FILE__, __LINE__ );\n \n#elif defined( GL_VERSION_3_0 )\n \n constexpr glew::gl_type::GLint border = 0; \/\/ this value must be 0: http:\/\/www.opengl.org\/sdk\/docs\/man\/html\/glTexImage2D.xhtml\n constexpr glew::gl_type::GLint level = 0;\n #if EMSCRIPTEN\n internal_format = format;\n #endif\n glew::c::glTexImage2D( GL_TEXTURE_2D, level, internal_format, width, height, border, format, type, data );\n glew::test_error( __FILE__, __LINE__ );\n \n#elif defined( GL_VERSION_1_4 )\n \n \/\/ warning: these medhod is deprecated in GL_3_0, removed in GL_3_1.\n \/\/ within throught step.3 and step.4.\n glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );\n glew::test_error( __FILE__, __LINE__ );\n glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );\n glew::test_error( __FILE__, __LINE__ );\n glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );\n glew::test_error( __FILE__, __LINE__ );\n glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );\n glew::test_error( __FILE__, __LINE__ );\n glew::c::glTexParameteri( GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE );\n glew::test_error( __FILE__, __LINE__ );\n glew::c::glTexImage2D( GL_TEXTURE_2D, level, internal_format, width, height, border, format, type, data );\n glew::test_error( __FILE__, __LINE__ );\n \n#else\n \n \/\/ no mipmap\n constexpr glew::gl_type::GLint level = 0;\n glew::c::glTexImage2D( GL_TEXTURE_2D, level, internal_format, width, height, border, format, type, data );\n \n glew::test_error( __FILE__, __LINE__ );\n \n#endif\n \n \/\/ step.3: generate mipmaps\n#if defined( GL_VERSION_3_0 )\n \n \/\/ glGenerateMipmap \/ GL_3_0\n \/\/ http:\/\/www.opengl.org\/wiki\/GLAPI\/glGenerateMipmap\n glew::c::glGenerateMipmap( GL_TEXTURE_2D );\n \n glew::test_error( __FILE__, __LINE__ );\n \n#endif\n \n \/\/ step.4: set sampler params\n#if defined( GL_VERSION_3_3 )\n \/\/ glGenSamplers \/ GL_3_3\n \/\/ http:\/\/www.opengl.org\/wiki\/GLAPI\/glGenSamplers\n glew::c::glGenSamplers( 1, &_sampler_id );\n \n glew::c::glSamplerParameteri( _sampler_id, GL_TEXTURE_WRAP_S, GL_REPEAT );\n glew::test_error( __FILE__, __LINE__ );\n glew::c::glSamplerParameteri( _sampler_id, GL_TEXTURE_WRAP_T, GL_REPEAT );\n glew::test_error( __FILE__, __LINE__ );\n glew::c::glSamplerParameteri( _sampler_id, GL_TEXTURE_MAG_FILTER, GL_LINEAR );\n glew::test_error( __FILE__, __LINE__ );\n glew::c::glSamplerParameteri( _sampler_id, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );\n glew::test_error( __FILE__, __LINE__ );\n \n#elif defined( GL_VERSION_3_0 )\n glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );\n glew::test_error( __FILE__, __LINE__ );\n glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );\n glew::test_error( __FILE__, __LINE__ );\n glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );\n glew::test_error( __FILE__, __LINE__ );\n glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );\n glew::test_error( __FILE__, __LINE__ );\n #elif defined( GL_VERSION_1_4 )\n \/\/ nothing to do. this step done before at this version.\n#else\n \/\/ no mipmap\n glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );\n glew::test_error( __FILE__, __LINE__ );\n glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );\n glew::test_error( __FILE__, __LINE__ );\n glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );\n glew::test_error( __FILE__, __LINE__ );\n glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );\n glew::test_error( __FILE__, __LINE__ );\n#endif\n \n }\n }\n \n auto draw() const -> void\n {\n glew::gl_type::GLint program_id;\n glew::c::glGetIntegerv( GL_CURRENT_PROGRAM, &program_id );\n \n if ( program_id )\n {\n\n#define WRP_TMP( WRP_TMP_X, WRP_TMP_Y, WRP_TMP_Z ) \\\n const auto location_of_ ## WRP_TMP_X = glew::c::glGetUniformLocation( program_id, # WRP_TMP_X ); \\\n if ( location_of_ ## WRP_TMP_X not_eq -1 ) \\\n { \\\n if ( _ ## WRP_TMP_X ) \\\n glew::c::glUniform ## WRP_TMP_Y ## fv( location_of_ ## WRP_TMP_X , 1, & _ ## WRP_TMP_X .get().x ); \\\n else \\\n glew::c::glUniform ## WRP_TMP_Y ## fv( location_of_ ## WRP_TMP_X , 1, & WRP_TMP_Z [0] ); \\\n }\n \n WRP_TMP( diffuse , 3, glm::vec3( 1.0f ) )\n WRP_TMP( ambient , 3, glm::vec3( 0.0f ) )\n WRP_TMP( specular , 3, glm::vec3( 0.0f ) )\n WRP_TMP( emissive , 3, glm::vec3( 0.0f ) )\n WRP_TMP( transparent, 1, glm::vec1( 1.0f ) )\n WRP_TMP( reflective , 1, glm::vec1( 0.0f ) )\n \n#undef WRP_TMP\n }\n \n#ifdef GL_VERSION_1_3\n glew::c::glActiveTexture( GL_TEXTURE0 );\n#endif\n \/\/ GL_1_1\n glew::c::glBindTexture( GL_TEXTURE_2D, _texture_id );\n#ifdef GL_VERSION_3_3\n glew::c::glBindSampler( 0, _sampler_id );\n#endif\n \n }\n };\n }\n }\n }\n}<|endoftext|>"} {"text":"\/\/===--- index-test.cpp - Indexing test bed -------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This utility may be invoked in the following manner:\n\/\/ index-test --help - Output help info.\n\/\/ index-test [options] - Read from stdin.\n\/\/ index-test [options] file - Read from \"file\".\n\/\/ index-test [options] file1 file2 - Read these files.\n\/\/\n\/\/ Files must be AST files.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ -point-at [file:column:line]\n\/\/ Point at a declaration\/statement\/expression. If no other operation is\n\/\/ specified, prints some info about it.\n\/\/\n\/\/ -print-refs\n\/\/ Print ASTLocations that reference the -point-at node\n\/\/\n\/\/ -print-defs\n\/\/ Print ASTLocations that define the -point-at node\n\/\/\n\/\/ -print-decls\n\/\/ Print ASTLocations that declare the -point-at node\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/Index\/Program.h\"\n#include \"clang\/Index\/IndexProvider.h\"\n#include \"clang\/Index\/Entity.h\"\n#include \"clang\/Index\/TranslationUnit.h\"\n#include \"clang\/Index\/ASTLocation.h\"\n#include \"clang\/Index\/DeclReferenceMap.h\"\n#include \"clang\/Index\/Utils.h\"\n#include \"clang\/Frontend\/ASTUnit.h\"\n#include \"clang\/Frontend\/CommandLineSourceLoc.h\"\n#include \"clang\/AST\/Decl.h\"\n#include \"clang\/AST\/Expr.h\"\n#include \"clang\/Basic\/FileManager.h\"\n#include \"clang\/Basic\/SourceManager.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/ManagedStatic.h\"\n#include \"llvm\/Support\/PrettyStackTrace.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/System\/Signals.h\"\nusing namespace clang;\nusing namespace idx;\n\nclass TUnit : public TranslationUnit {\npublic:\n TUnit(ASTUnit *ast, const std::string &filename)\n : AST(ast), Filename(filename) { }\n \n virtual ASTContext &getASTContext() { return AST->getASTContext(); }\n \n llvm::OwningPtr AST;\n std::string Filename;\n};\n\nstatic llvm::cl::list\nPointAtLocation(\"point-at\", llvm::cl::Optional,\n llvm::cl::value_desc(\"source-location\"),\n llvm::cl::desc(\"Point at the given source location of the first AST file\"));\n\nenum ProgActions {\n PrintPoint, \/\/ Just print the point-at node\n PrintRefs, \/\/ Print references of the point-at node\n PrintDefs, \/\/ Print definitions of the point-at node\n PrintDecls \/\/ Print declarations of the point-at node\n};\n\nstatic llvm::cl::opt \nProgAction(\n llvm::cl::desc(\"Choose action to perform on the pointed-at AST node:\"),\n llvm::cl::ZeroOrMore,\n llvm::cl::init(PrintPoint),\n llvm::cl::values(\n clEnumValN(PrintRefs, \"print-refs\",\n \"Print references\"),\n clEnumValN(PrintDefs, \"print-defs\",\n \"Print definitions\"),\n clEnumValN(PrintDecls, \"print-decls\",\n \"Print declarations\"),\n clEnumValEnd));\n\nstatic llvm::cl::opt\nDisableFree(\"disable-free\",\n llvm::cl::desc(\"Disable freeing of memory on exit\"),\n llvm::cl::init(false));\n\nstatic void ProcessDecl(Decl *D) {\n assert(D);\n llvm::raw_ostream &OS = llvm::outs();\n \n switch (ProgAction) {\n default: assert(0);\n case PrintRefs: {\n NamedDecl *ND = dyn_cast(D);\n if (!ND)\n return;\n\n DeclReferenceMap RefMap(ND->getASTContext());\n for (DeclReferenceMap::astlocation_iterator\n I = RefMap.refs_begin(ND), E = RefMap.refs_end(ND); I != E; ++I)\n I->print(OS);\n break;\n }\n \n case PrintDefs: {\n const Decl *DefD = 0;\n if (FunctionDecl *FD = dyn_cast(D)) {\n const FunctionDecl *DFD = 0;\n FD->getBody(DFD);\n DefD = DFD;\n } else if (VarDecl *VD = dyn_cast(D)) {\n const VarDecl *DVD = 0;\n VD->getDefinition(DVD);\n DefD = DVD;\n } \n\n if (DefD)\n ASTLocation(DefD).print(OS);\n break; \n }\n \n case PrintDecls :\n if (const FunctionDecl *FD = dyn_cast(D)) {\n while (FD) {\n ASTLocation(FD).print(OS);\n FD = FD->getPreviousDeclaration();\n }\n } else if (const VarDecl *VD = dyn_cast(D)) {\n while (VD) {\n ASTLocation(VD).print(OS);\n VD = VD->getPreviousDeclaration();\n }\n } else\n ASTLocation(D).print(OS);\n break;\n \n }\n}\n\nstatic void ProcessASTLocation(ASTLocation ASTLoc, IndexProvider &IdxProvider) {\n assert(ASTLoc.isValid());\n\n Decl *D = 0;\n if (ASTLoc.isStmt()) {\n if (DeclRefExpr *RefExpr = dyn_cast(ASTLoc.getStmt()))\n D = RefExpr->getDecl();\n } else {\n D = ASTLoc.getDecl();\n }\n assert(D);\n\n Entity *Ent = Entity::get(D, IdxProvider.getProgram());\n \/\/ If there is no Entity associated with this Decl, it means that it's not\n \/\/ visible to other translation units.\n if (!Ent)\n return ProcessDecl(D);\n\n \/\/ Find the \"same\" Decl in other translation units and print information.\n for (IndexProvider::translation_unit_iterator\n I = IdxProvider.translation_units_begin(Ent),\n E = IdxProvider.translation_units_end(Ent); I != E; ++I) {\n TUnit *TU = static_cast(*I);\n Decl *OtherD = Ent->getDecl(TU->getASTContext());\n assert(OtherD && \"Couldn't resolve Entity\");\n ProcessDecl(OtherD);\n }\n}\n\nstatic llvm::cl::list\nInputFilenames(llvm::cl::Positional, llvm::cl::desc(\"\"));\n\nint main(int argc, char **argv) {\n llvm::sys::PrintStackTraceOnErrorSignal();\n llvm::PrettyStackTraceProgram X(argc, argv);\n llvm::cl::ParseCommandLineOptions(argc, argv,\n \"LLVM 'Clang' Indexing Test Bed: http:\/\/clang.llvm.org\\n\");\n \n FileManager FileMgr;\n\n Program Prog;\n IndexProvider IdxProvider(Prog);\n llvm::SmallVector TUnits;\n \n \/\/ If no input was specified, read from stdin.\n if (InputFilenames.empty())\n InputFilenames.push_back(\"-\");\n\n for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {\n const std::string &InFile = InputFilenames[i];\n \n std::string ErrMsg;\n llvm::OwningPtr AST;\n\n AST.reset(ASTUnit::LoadFromPCHFile(InFile, FileMgr, &ErrMsg));\n if (!AST) {\n llvm::errs() << \"[\" << InFile << \"] Error: \" << ErrMsg << '\\n';\n return 1;\n }\n\n TUnit *TU = new TUnit(AST.take(), InFile);\n TUnits.push_back(TU);\n \n IdxProvider.IndexAST(TU);\n }\n\n ASTLocation ASTLoc;\n const std::string &FirstFile = TUnits[0]->Filename;\n ASTUnit *FirstAST = TUnits[0]->AST.get();\n\n if (!PointAtLocation.empty()) {\n const std::string &Filename = PointAtLocation[0].FileName;\n const FileEntry *File = FileMgr.getFile(Filename);\n\n \/\/ Safety check. Using an out-of-date AST file will only lead to crashes\n \/\/ or incorrect results.\n \/\/ FIXME: Check all the source files that make up the AST file.\n const FileEntry *ASTFile = FileMgr.getFile(FirstFile);\n if (File->getModificationTime() > ASTFile->getModificationTime()) {\n llvm::errs() << \"[\" << FirstFile << \"] Error: \" <<\n \"Pointing at a source file which was modified after creating \"\n \"the AST file\\n\";\n return 1;\n }\n\n if (File == 0) {\n llvm::errs() << \"File '\" << Filename << \"' does not exist\\n\";\n return 1;\n }\n unsigned Line = PointAtLocation[0].Line;\n unsigned Col = PointAtLocation[0].Column;\n\n SourceLocation Loc =\n FirstAST->getSourceManager().getLocation(File, Line, Col);\n if (Loc.isInvalid()) {\n llvm::errs() << \"[\" << FirstFile << \"] Error: \" <<\n \"Couldn't resolve source location (invalid location)\\n\";\n return 1;\n }\n \n ASTLoc = ResolveLocationInAST(FirstAST->getASTContext(), Loc);\n if (ASTLoc.isInvalid()) {\n llvm::errs() << \"[\" << FirstFile << \"] Error: \" <<\n \"Couldn't resolve source location (no declaration found)\\n\";\n return 1;\n }\n }\n \n if (ASTLoc.isValid()) {\n if (ProgAction == PrintPoint) {\n llvm::raw_ostream &OS = llvm::outs();\n ASTLoc.print(OS);\n if (const char *Comment =\n FirstAST->getASTContext().getCommentForDecl(ASTLoc.getDecl()))\n OS << \"Comment associated with this declaration:\\n\" << Comment << \"\\n\";\n } else {\n ProcessASTLocation(ASTLoc, IdxProvider);\n }\n }\n\n if (!DisableFree) {\n for (int i=0, e=TUnits.size(); i != e; ++i)\n delete TUnits[i];\n }\n\n \/\/ Managed static deconstruction. Useful for making things like\n \/\/ -time-passes usable.\n llvm::llvm_shutdown();\n \n return 0;\n}\nFix comment.\/\/===--- index-test.cpp - Indexing test bed -------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This utility may be invoked in the following manner:\n\/\/ index-test --help - Output help info.\n\/\/ index-test [options] - Read from stdin.\n\/\/ index-test [options] file - Read from \"file\".\n\/\/ index-test [options] file1 file2 - Read these files.\n\/\/\n\/\/ Files must be AST files.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ -point-at [file:line:column]\n\/\/ Point at a declaration\/statement\/expression. If no other operation is\n\/\/ specified, prints some info about it.\n\/\/\n\/\/ -print-refs\n\/\/ Print ASTLocations that reference the -point-at node\n\/\/\n\/\/ -print-defs\n\/\/ Print ASTLocations that define the -point-at node\n\/\/\n\/\/ -print-decls\n\/\/ Print ASTLocations that declare the -point-at node\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/Index\/Program.h\"\n#include \"clang\/Index\/IndexProvider.h\"\n#include \"clang\/Index\/Entity.h\"\n#include \"clang\/Index\/TranslationUnit.h\"\n#include \"clang\/Index\/ASTLocation.h\"\n#include \"clang\/Index\/DeclReferenceMap.h\"\n#include \"clang\/Index\/Utils.h\"\n#include \"clang\/Frontend\/ASTUnit.h\"\n#include \"clang\/Frontend\/CommandLineSourceLoc.h\"\n#include \"clang\/AST\/Decl.h\"\n#include \"clang\/AST\/Expr.h\"\n#include \"clang\/Basic\/FileManager.h\"\n#include \"clang\/Basic\/SourceManager.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/ManagedStatic.h\"\n#include \"llvm\/Support\/PrettyStackTrace.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/System\/Signals.h\"\nusing namespace clang;\nusing namespace idx;\n\nclass TUnit : public TranslationUnit {\npublic:\n TUnit(ASTUnit *ast, const std::string &filename)\n : AST(ast), Filename(filename) { }\n \n virtual ASTContext &getASTContext() { return AST->getASTContext(); }\n \n llvm::OwningPtr AST;\n std::string Filename;\n};\n\nstatic llvm::cl::list\nPointAtLocation(\"point-at\", llvm::cl::Optional,\n llvm::cl::value_desc(\"source-location\"),\n llvm::cl::desc(\"Point at the given source location of the first AST file\"));\n\nenum ProgActions {\n PrintPoint, \/\/ Just print the point-at node\n PrintRefs, \/\/ Print references of the point-at node\n PrintDefs, \/\/ Print definitions of the point-at node\n PrintDecls \/\/ Print declarations of the point-at node\n};\n\nstatic llvm::cl::opt \nProgAction(\n llvm::cl::desc(\"Choose action to perform on the pointed-at AST node:\"),\n llvm::cl::ZeroOrMore,\n llvm::cl::init(PrintPoint),\n llvm::cl::values(\n clEnumValN(PrintRefs, \"print-refs\",\n \"Print references\"),\n clEnumValN(PrintDefs, \"print-defs\",\n \"Print definitions\"),\n clEnumValN(PrintDecls, \"print-decls\",\n \"Print declarations\"),\n clEnumValEnd));\n\nstatic llvm::cl::opt\nDisableFree(\"disable-free\",\n llvm::cl::desc(\"Disable freeing of memory on exit\"),\n llvm::cl::init(false));\n\nstatic void ProcessDecl(Decl *D) {\n assert(D);\n llvm::raw_ostream &OS = llvm::outs();\n \n switch (ProgAction) {\n default: assert(0);\n case PrintRefs: {\n NamedDecl *ND = dyn_cast(D);\n if (!ND)\n return;\n\n DeclReferenceMap RefMap(ND->getASTContext());\n for (DeclReferenceMap::astlocation_iterator\n I = RefMap.refs_begin(ND), E = RefMap.refs_end(ND); I != E; ++I)\n I->print(OS);\n break;\n }\n \n case PrintDefs: {\n const Decl *DefD = 0;\n if (FunctionDecl *FD = dyn_cast(D)) {\n const FunctionDecl *DFD = 0;\n FD->getBody(DFD);\n DefD = DFD;\n } else if (VarDecl *VD = dyn_cast(D)) {\n const VarDecl *DVD = 0;\n VD->getDefinition(DVD);\n DefD = DVD;\n } \n\n if (DefD)\n ASTLocation(DefD).print(OS);\n break; \n }\n \n case PrintDecls :\n if (const FunctionDecl *FD = dyn_cast(D)) {\n while (FD) {\n ASTLocation(FD).print(OS);\n FD = FD->getPreviousDeclaration();\n }\n } else if (const VarDecl *VD = dyn_cast(D)) {\n while (VD) {\n ASTLocation(VD).print(OS);\n VD = VD->getPreviousDeclaration();\n }\n } else\n ASTLocation(D).print(OS);\n break;\n \n }\n}\n\nstatic void ProcessASTLocation(ASTLocation ASTLoc, IndexProvider &IdxProvider) {\n assert(ASTLoc.isValid());\n\n Decl *D = 0;\n if (ASTLoc.isStmt()) {\n if (DeclRefExpr *RefExpr = dyn_cast(ASTLoc.getStmt()))\n D = RefExpr->getDecl();\n } else {\n D = ASTLoc.getDecl();\n }\n assert(D);\n\n Entity *Ent = Entity::get(D, IdxProvider.getProgram());\n \/\/ If there is no Entity associated with this Decl, it means that it's not\n \/\/ visible to other translation units.\n if (!Ent)\n return ProcessDecl(D);\n\n \/\/ Find the \"same\" Decl in other translation units and print information.\n for (IndexProvider::translation_unit_iterator\n I = IdxProvider.translation_units_begin(Ent),\n E = IdxProvider.translation_units_end(Ent); I != E; ++I) {\n TUnit *TU = static_cast(*I);\n Decl *OtherD = Ent->getDecl(TU->getASTContext());\n assert(OtherD && \"Couldn't resolve Entity\");\n ProcessDecl(OtherD);\n }\n}\n\nstatic llvm::cl::list\nInputFilenames(llvm::cl::Positional, llvm::cl::desc(\"\"));\n\nint main(int argc, char **argv) {\n llvm::sys::PrintStackTraceOnErrorSignal();\n llvm::PrettyStackTraceProgram X(argc, argv);\n llvm::cl::ParseCommandLineOptions(argc, argv,\n \"LLVM 'Clang' Indexing Test Bed: http:\/\/clang.llvm.org\\n\");\n \n FileManager FileMgr;\n\n Program Prog;\n IndexProvider IdxProvider(Prog);\n llvm::SmallVector TUnits;\n \n \/\/ If no input was specified, read from stdin.\n if (InputFilenames.empty())\n InputFilenames.push_back(\"-\");\n\n for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {\n const std::string &InFile = InputFilenames[i];\n \n std::string ErrMsg;\n llvm::OwningPtr AST;\n\n AST.reset(ASTUnit::LoadFromPCHFile(InFile, FileMgr, &ErrMsg));\n if (!AST) {\n llvm::errs() << \"[\" << InFile << \"] Error: \" << ErrMsg << '\\n';\n return 1;\n }\n\n TUnit *TU = new TUnit(AST.take(), InFile);\n TUnits.push_back(TU);\n \n IdxProvider.IndexAST(TU);\n }\n\n ASTLocation ASTLoc;\n const std::string &FirstFile = TUnits[0]->Filename;\n ASTUnit *FirstAST = TUnits[0]->AST.get();\n\n if (!PointAtLocation.empty()) {\n const std::string &Filename = PointAtLocation[0].FileName;\n const FileEntry *File = FileMgr.getFile(Filename);\n\n \/\/ Safety check. Using an out-of-date AST file will only lead to crashes\n \/\/ or incorrect results.\n \/\/ FIXME: Check all the source files that make up the AST file.\n const FileEntry *ASTFile = FileMgr.getFile(FirstFile);\n if (File->getModificationTime() > ASTFile->getModificationTime()) {\n llvm::errs() << \"[\" << FirstFile << \"] Error: \" <<\n \"Pointing at a source file which was modified after creating \"\n \"the AST file\\n\";\n return 1;\n }\n\n if (File == 0) {\n llvm::errs() << \"File '\" << Filename << \"' does not exist\\n\";\n return 1;\n }\n unsigned Line = PointAtLocation[0].Line;\n unsigned Col = PointAtLocation[0].Column;\n\n SourceLocation Loc =\n FirstAST->getSourceManager().getLocation(File, Line, Col);\n if (Loc.isInvalid()) {\n llvm::errs() << \"[\" << FirstFile << \"] Error: \" <<\n \"Couldn't resolve source location (invalid location)\\n\";\n return 1;\n }\n \n ASTLoc = ResolveLocationInAST(FirstAST->getASTContext(), Loc);\n if (ASTLoc.isInvalid()) {\n llvm::errs() << \"[\" << FirstFile << \"] Error: \" <<\n \"Couldn't resolve source location (no declaration found)\\n\";\n return 1;\n }\n }\n \n if (ASTLoc.isValid()) {\n if (ProgAction == PrintPoint) {\n llvm::raw_ostream &OS = llvm::outs();\n ASTLoc.print(OS);\n if (const char *Comment =\n FirstAST->getASTContext().getCommentForDecl(ASTLoc.getDecl()))\n OS << \"Comment associated with this declaration:\\n\" << Comment << \"\\n\";\n } else {\n ProcessASTLocation(ASTLoc, IdxProvider);\n }\n }\n\n if (!DisableFree) {\n for (int i=0, e=TUnits.size(); i != e; ++i)\n delete TUnits[i];\n }\n\n \/\/ Managed static deconstruction. Useful for making things like\n \/\/ -time-passes usable.\n llvm::llvm_shutdown();\n \n return 0;\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: ZConnectionWrapper.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: oj $ $Date: 2002-08-23 09:57:53 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the License); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an AS IS basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _CONNECTIVITY_ZCONNECTIONWEAKWRAPPER_HXX_\n#define _CONNECTIVITY_ZCONNECTIONWEAKWRAPPER_HXX_\n\n#ifndef _CPPUHELPER_COMPBASE1_HXX_\n#include \n#endif\n#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_\n#include \n#endif\n#ifndef _COMPHELPER_BROADCASTHELPER_HXX_\n#include \n#endif\n#ifndef _COMPHELPER_UNO3_HXX_\n#include \n#endif\n#ifndef _CONNECTIVITY_ZCONNECTIONWRAPPER_HXX_\n#include \"connectivity\/ConnectionWrapper.hxx\"\n#endif\n\n#if SUPD < 643\n #define DECLARE_XINTERFACE( ) \\\n virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type& aType ) throw (::com::sun::star::uno::RuntimeException); \\\n virtual void SAL_CALL acquire() throw(); \\\n virtual void SAL_CALL release() throw();\n\n #define IMPLEMENT_FORWARD_REFCOUNT( classname, refcountbase ) \\\n void SAL_CALL classname::acquire() throw() { refcountbase::acquire(); } \\\n void SAL_CALL classname::release() throw() { refcountbase::release(); }\n\n #define IMPLEMENT_FORWARD_XINTERFACE2( classname, refcountbase, baseclass2 ) \\\n IMPLEMENT_FORWARD_REFCOUNT( classname, refcountbase ) \\\n ::com::sun::star::uno::Any SAL_CALL classname::queryInterface( const ::com::sun::star::uno::Type& _rType ) throw (::com::sun::star::uno::RuntimeException) \\\n { \\\n ::com::sun::star::uno::Any aReturn = refcountbase::queryInterface( _rType ); \\\n if ( !aReturn.hasValue() ) \\\n aReturn = baseclass2::queryInterface( _rType ); \\\n return aReturn; \\\n }\n\n #define IMPLEMENT_FORWARD_XINTERFACE3( classname, refcountbase, baseclass2, baseclass3 ) \\\n IMPLEMENT_FORWARD_REFCOUNT( classname, refcountbase ) \\\n ::com::sun::star::uno::Any SAL_CALL classname::queryInterface( const ::com::sun::star::uno::Type& _rType ) throw (::com::sun::star::uno::RuntimeException) \\\n { \\\n ::com::sun::star::uno::Any aReturn = refcountbase::queryInterface( _rType ); \\\n if ( !aReturn.hasValue() ) \\\n { \\\n aReturn = baseclass2::queryInterface( _rType ); \\\n if ( !aReturn.hasValue() ) \\\n aReturn = baseclass3::queryInterface( _rType ); \\\n } \\\n return aReturn; \\\n }\n \/\/=====================================================================\n \/\/= forwarding\/merging XTypeProvider funtionality\n \/\/=====================================================================\n #define DECLARE_XTYPEPROVIDER( ) \\\n virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw (::com::sun::star::uno::RuntimeException); \\\n virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId( ) throw (::com::sun::star::uno::RuntimeException);\n\n #define IMPLEMENT_GET_IMPLEMENTATION_ID( classname ) \\\n ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL classname::getImplementationId( ) throw (::com::sun::star::uno::RuntimeException) \\\n { \\\n static ::cppu::OImplementationId* pId = NULL; \\\n if (!pId) \\\n { \\\n ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); \\\n if (!pId) \\\n { \\\n static ::cppu::OImplementationId aId; \\\n pId = &aId; \\\n } \\\n } \\\n return pId->getImplementationId(); \\\n }\n\n #define IMPLEMENT_FORWARD_XTYPEPROVIDER2( classname, baseclass1, baseclass2 ) \\\n ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL classname::getTypes( ) throw (::com::sun::star::uno::RuntimeException) \\\n { \\\n return ::comphelper::concatSequences( \\\n baseclass1::getTypes(), \\\n baseclass2::getTypes() \\\n ); \\\n } \\\n \\\n IMPLEMENT_GET_IMPLEMENTATION_ID( classname )\n\n #define IMPLEMENT_FORWARD_XTYPEPROVIDER3( classname, baseclass1, baseclass2, baseclass3 ) \\\n ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL classname::getTypes( ) throw (::com::sun::star::uno::RuntimeException) \\\n { \\\n return ::comphelper::concatSequences( \\\n baseclass1::getTypes(), \\\n baseclass2::getTypes(), \\\n baseclass3::getTypes() \\\n ); \\\n } \\\n \\\n IMPLEMENT_GET_IMPLEMENTATION_ID( classname )\n#endif \/\/ SUPD < 643\n\nnamespace connectivity\n{\n\n \/\/==========================================================================\n \/\/= OConnectionWeakWrapper - wraps all methods to the real connection from the driver\n \/\/= but when disposed it doesn't dispose the real connection\n \/\/==========================================================================\n typedef ::cppu::WeakComponentImplHelper1< ::com::sun::star::sdbc::XConnection\n > OConnectionWeakWrapper_BASE;\n\n class OConnectionWeakWrapper : public ::comphelper::OBaseMutex\n ,public OConnectionWeakWrapper_BASE\n , public OConnectionWrapper\n {\n protected:\n \/\/ OComponentHelper\n virtual void SAL_CALL disposing(void);\n virtual ~OConnectionWeakWrapper();\n public:\n OConnectionWeakWrapper(::com::sun::star::uno::Reference< ::com::sun::star::uno::XAggregation >& _xConnection);\n\n \/\/ XServiceInfo\n DECLARE_SERVICE_INFO();\n DECLARE_XTYPEPROVIDER()\n DECLARE_XINTERFACE( )\n\n \/\/ XConnection\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XStatement > SAL_CALL createStatement( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareStatement( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareCall( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL nativeSQL( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setAutoCommit( sal_Bool autoCommit ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL getAutoCommit( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL commit( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL rollback( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isClosed( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData > SAL_CALL getMetaData( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setReadOnly( sal_Bool readOnly ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isReadOnly( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setCatalog( const ::rtl::OUString& catalog ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getCatalog( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setTransactionIsolation( sal_Int32 level ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL getTransactionIsolation( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > SAL_CALL getTypeMap( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setTypeMap( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n \/\/ XCloseable\n virtual void SAL_CALL close( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n };\n}\n#endif \/\/ _CONNECTIVITY_ZCONNECTIONWEAKWRAPPER_HXX_\n\nINTEGRATION: CWS dba22 (1.5.234); FILE MERGED 2004\/12\/16 09:03:38 oj 1.5.234.1: #i39123# some clean ups\/*************************************************************************\n *\n * $RCSfile: ZConnectionWrapper.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: kz $ $Date: 2005-01-21 16:39:01 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the License); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an AS IS basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _CONNECTIVITY_ZCONNECTIONWEAKWRAPPER_HXX_\n#define _CONNECTIVITY_ZCONNECTIONWEAKWRAPPER_HXX_\n\n#ifndef _CPPUHELPER_COMPBASE1_HXX_\n#include \n#endif\n#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_\n#include \n#endif\n#ifndef _COMPHELPER_BROADCASTHELPER_HXX_\n#include \n#endif\n#ifndef _COMPHELPER_UNO3_HXX_\n#include \n#endif\n#ifndef _CONNECTIVITY_ZCONNECTIONWRAPPER_HXX_\n#include \"connectivity\/ConnectionWrapper.hxx\"\n#endif\n\nnamespace connectivity\n{\n\n \/\/==========================================================================\n \/\/= OConnectionWeakWrapper - wraps all methods to the real connection from the driver\n \/\/= but when disposed it doesn't dispose the real connection\n \/\/==========================================================================\n typedef ::cppu::WeakComponentImplHelper1< ::com::sun::star::sdbc::XConnection\n > OConnectionWeakWrapper_BASE;\n\n class OConnectionWeakWrapper : public ::comphelper::OBaseMutex\n ,public OConnectionWeakWrapper_BASE\n , public OConnectionWrapper\n {\n protected:\n \/\/ OComponentHelper\n virtual void SAL_CALL disposing(void);\n virtual ~OConnectionWeakWrapper();\n public:\n OConnectionWeakWrapper(::com::sun::star::uno::Reference< ::com::sun::star::uno::XAggregation >& _xConnection);\n\n \/\/ XServiceInfo\n DECLARE_SERVICE_INFO();\n DECLARE_XTYPEPROVIDER()\n DECLARE_XINTERFACE( )\n\n \/\/ XConnection\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XStatement > SAL_CALL createStatement( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareStatement( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareCall( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL nativeSQL( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setAutoCommit( sal_Bool autoCommit ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL getAutoCommit( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL commit( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL rollback( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isClosed( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData > SAL_CALL getMetaData( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setReadOnly( sal_Bool readOnly ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isReadOnly( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setCatalog( const ::rtl::OUString& catalog ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getCatalog( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setTransactionIsolation( sal_Int32 level ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL getTransactionIsolation( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > SAL_CALL getTypeMap( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setTypeMap( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n \/\/ XCloseable\n virtual void SAL_CALL close( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n };\n}\n#endif \/\/ _CONNECTIVITY_ZCONNECTIONWEAKWRAPPER_HXX_\n\n<|endoftext|>"} {"text":"\/\/ -*- Mode: C++; tab-width: 2; -*-\n\/\/ vi: set ts=2:\n\/\/\n\/\/ $Id: MMFF94ConfigurationDialog.C,v 1.1.6.1 2007\/03\/25 22:00:39 oliver Exp $\n\/\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\nnamespace BALL\n{\n\tnamespace VIEW\n\t{\n\n\t\tMMFF94ConfigurationDialog::MMFF94ConfigurationDialog(QWidget* parent, const char* name)\n\t\t\t:\tQDialog(parent),\n\t\t\t\tUi_MMFF94ConfigurationDialogData(),\n\t\t\t\tPreferencesEntry(),\n\t\t\t\tmmff_(0)\n\t\t{\n\t\t\tsetupUi(this);\n\n\t\t\tsetINIFileSectionName(\"MMFF94\");\n\t\t\tsetObjectName(name);\n\t\t\tregisterWidgets_();\n\n\t\t\t\/\/ signals and slots connections\n\t\t\tconnect( close_button, SIGNAL( clicked() ), this, SLOT( accept() ) );\n\t\t\tconnect( cancel_button, SIGNAL( clicked() ), this, SLOT( reject() ) );\n\t\t\tconnect( reset_button, SIGNAL( clicked() ), this, SLOT( resetOptions() ) );\n\t\t\tconnect( browse_button, SIGNAL( clicked() ), this, SLOT( browseParameterFiles() ) );\n\t\t}\n\n\t\tMMFF94ConfigurationDialog::~MMFF94ConfigurationDialog()\n\t\t{\n\t\t}\n\n\t\tvoid MMFF94ConfigurationDialog::browseParameterFiles()\n\t\t{\n\t\t\t\/\/ look up the full path of the parameter file\n\t\t\tPath p;\n\t\t\tString filename = p.find(ascii(parameter_file_edit->text()));\n\n\t\t\tif (filename == \"\")\n\t\t\t{\n\t\t\t\tfilename = ascii(parameter_file_edit->text());\n\t\t\t}\n\t\t\tQString tmp = filename.c_str();\n\t\t\tQString result = QFileDialog::getExistingDirectory(0, \"Select a folder with the MMFF94 parameter files\", tmp);\n\t\t\tif (!result.isEmpty())\n\t\t\t{\n\t\t\t\t\/\/ store the new filename in the lineedit field\n\t\t\t\tparameter_file_edit->setText(result);\n\t\t\t}\n\t\t}\n\n\t\tvoid MMFF94ConfigurationDialog::reject()\n\t\t{\n\t\t\thide();\n\t\t\tPreferencesEntry::restoreValues();\n\t\t}\n\n\t\tvoid MMFF94ConfigurationDialog::accept()\n\t\t{\n\t\t\tif (mmff_ != 0) \n\t\t\t{\n\t\t\t\tapplyTo(*mmff_);\n\t\t\t}\n\t\t\thide();\n\t\t\tPreferencesEntry::storeValues();\n\t\t}\n\n\n\t\tString MMFF94ConfigurationDialog::getValue_(const QCheckBox* box) const\n\t\t{\n\t\t\tif (box->isChecked()) return \"true\";\n\t\t\telse \t\t\t\t\t\t\t\t\treturn \"false\";\n\t\t}\n\n\t\tfloat MMFF94ConfigurationDialog::getValue_(const QLineEdit* edit) const\n\t\t\tthrow(Exception::InvalidFormat)\n\t\t{\n\t\t\treturn ascii(edit->text()).toFloat();\n\t\t}\n\n\t\tvoid MMFF94ConfigurationDialog::applyTo(MMFF94& mmff)\n\t\t\tthrow()\n\t\t{\n\t\t\tmmff.options[MMFF94_STRETCHES_ENABLED] = getValue_(stretch_box);\n\t\t\tmmff.options[MMFF94_BENDS_ENABLED] = getValue_(bends_box);\n\t\t\tmmff.options[MMFF94_STRETCHBENDS_ENABLED] = getValue_(stretch_bends_box);\n\t\t\tmmff.options[MMFF94_TORSIONS_ENABLED] = getValue_(torsions_box);\n\t\t\tmmff.options[MMFF94_OUTOFPLANE_ENABLED] = getValue_(plane_box);\n\t\t\tmmff.options[MMFF94_VDW_ENABLED] = getValue_(vdw_box);\n\t\t\tmmff.options[MMFF94_ES_ENABLED] = getValue_(es_box);\n\n\t\t\ttry\n\t\t\t{\n\t\t\t\tmmff.options[MMFF94::Option::ASSIGN_TYPES] = getValue_(assign_types_checkBox);\n\t\t\t\tmmff.options[MMFF94::Option::ASSIGN_CHARGES] = getValue_(assign_charges_checkBox);\n\t\t\t\tmmff.options[MMFF94::Option::ASSIGN_TYPENAMES] = getValue_(assign_types_checkBox);\n\t\t\t\tmmff.options[MMFF94::Option::OVERWRITE_CHARGES] = getValue_(overwrite_charges_checkBox);\n\t\t\t\tmmff.options[MMFF94::Option::OVERWRITE_TYPENAMES] = getValue_(overwrite_typenames_checkBox);\n\n\/\/ \t\t\t\tbool value = distance_button->isChecked();\n\/\/ \t\t\t\tMMFF94.options[MMFF94::Option::DISTANCE_DEPENDENT_DIELECTRIC] = value ? \"true\" : \"false\";\n\n\t\t\t\tmmff.options[MMFF94::Option::FOLDER] = ascii(parameter_file_edit->text());\n\t\t\t\t\n\t\t\t\tbool error = false;\n\t\t\t\tif (ascii(max_unassigned_atoms->text()).toUnsignedInt() == 0) \n\t\t\t\t{\n\t\t\t\t\terror = true;\n\t\t\t\t}\n\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tmmff.setMaximumNumberOfErrors(ascii(max_unassigned_atoms->text()).toUnsignedInt());\n\t\t\t\t}\n\t\t\t\tcatch(...)\n\t\t\t\t{\n\t\t\t\t\terror = true;\n\t\t\t\t}\n\n\t\t\t\tif (error)\n\t\t\t\t{\n\t\t\t\t\tmax_unassigned_atoms->setText(\"10\");\n\t\t\t\t\tmmff.setMaximumNumberOfErrors(10);\n\t\t\t\t\tLog.error() << \"Invalid value for max number of unassigned atoms, using default value of 10\" << std::endl;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch(...)\n\t\t\t{\n\t\t\t\tLog.error() << \"Invalid values for MMFF94\" << std::endl;\n\t\t\t}\n\t\t}\n\n\t\tvoid MMFF94ConfigurationDialog::setMMFF94(MMFF94& mmff)\n\t\t\tthrow()\n\t\t{\n\t\t\tmmff_ = &mmff;\n\t\t}\n\t\n\t\tvoid MMFF94ConfigurationDialog::resetOptions()\n\t\t{\n\t\t\tPreferencesEntry::restoreDefaultValues();\n\t\t}\n\n\t}\/\/namespace VIEW\n}\/\/namespace BALL\nno message\/\/ -*- Mode: C++; tab-width: 2; -*-\n\/\/ vi: set ts=2:\n\/\/\n\/\/ $Id: MMFF94ConfigurationDialog.C,v 1.1.6.2 2007\/05\/10 00:05:18 amoll Exp $\n\/\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\nnamespace BALL\n{\n\tnamespace VIEW\n\t{\n\n\t\tMMFF94ConfigurationDialog::MMFF94ConfigurationDialog(QWidget* parent, const char* name)\n\t\t\t:\tQDialog(parent),\n\t\t\t\tUi_MMFF94ConfigurationDialogData(),\n\t\t\t\tPreferencesEntry(),\n\t\t\t\tmmff_(0)\n\t\t{\n\t\t\tsetupUi(this);\n\n\t\t\tsetINIFileSectionName(\"MMFF94\");\n\t\t\tsetObjectName(name);\n\t\t\tregisterWidgets_();\n\n\t\t\t\/\/ signals and slots connections\n\t\t\tconnect( close_button, SIGNAL( clicked() ), this, SLOT( accept() ) );\n\t\t\tconnect( cancel_button, SIGNAL( clicked() ), this, SLOT( reject() ) );\n\t\t\tconnect( reset_button, SIGNAL( clicked() ), this, SLOT( resetOptions() ) );\n\t\t\tconnect( browse_button, SIGNAL( clicked() ), this, SLOT( browseParameterFiles() ) );\n\t\t}\n\n\t\tMMFF94ConfigurationDialog::~MMFF94ConfigurationDialog()\n\t\t{\n\t\t}\n\n\t\tvoid MMFF94ConfigurationDialog::browseParameterFiles()\n\t\t{\n\t\t\t\/\/ look up the full path of the parameter file\n\t\t\tPath p;\n\t\t\tString filename = p.find(ascii(parameter_file_edit->text()));\n\n\t\t\tif (filename == \"\")\n\t\t\t{\n\t\t\t\tfilename = ascii(parameter_file_edit->text());\n\t\t\t}\n\t\t\tQString tmp = filename.c_str();\n\t\t\tQString result = QFileDialog::getExistingDirectory(0, \"Select a folder with the MMFF94 parameter files\", tmp);\n\t\t\tif (!result.isEmpty())\n\t\t\t{\n\t\t\t\t\/\/ store the new filename in the lineedit field\n\t\t\t\tparameter_file_edit->setText(result);\n\t\t\t}\n\t\t}\n\n\t\tvoid MMFF94ConfigurationDialog::reject()\n\t\t{\n\t\t\thide();\n\t\t\tPreferencesEntry::restoreValues();\n\t\t}\n\n\t\tvoid MMFF94ConfigurationDialog::accept()\n\t\t{\n\t\t\tif (mmff_ != 0) \n\t\t\t{\n\t\t\t\tapplyTo(*mmff_);\n\t\t\t}\n\t\t\thide();\n\t\t\tPreferencesEntry::storeValues();\n\t\t}\n\n\n\t\tString MMFF94ConfigurationDialog::getValue_(const QCheckBox* box) const\n\t\t{\n\t\t\tif (box->isChecked()) return \"true\";\n\t\t\telse \t\t\t\t\t\t\t\t\treturn \"false\";\n\t\t}\n\n\t\tfloat MMFF94ConfigurationDialog::getValue_(const QLineEdit* edit) const\n\t\t\tthrow(Exception::InvalidFormat)\n\t\t{\n\t\t\treturn ascii(edit->text()).toFloat();\n\t\t}\n\n\t\tvoid MMFF94ConfigurationDialog::applyTo(MMFF94& mmff)\n\t\t\tthrow()\n\t\t{\n\t\t\tmmff.options[MMFF94_STRETCHES_ENABLED] = getValue_(stretch_box);\n\t\t\tmmff.options[MMFF94_BENDS_ENABLED] = getValue_(bends_box);\n\t\t\tmmff.options[MMFF94_STRETCHBENDS_ENABLED] = getValue_(stretch_bends_box);\n\t\t\tmmff.options[MMFF94_TORSIONS_ENABLED] = getValue_(torsions_box);\n\t\t\tmmff.options[MMFF94_OUTOFPLANE_ENABLED] = getValue_(plane_box);\n\t\t\tmmff.options[MMFF94_VDW_ENABLED] = getValue_(vdw_box);\n\t\t\tmmff.options[MMFF94_ES_ENABLED] = getValue_(es_box);\n\n\t\t\ttry\n\t\t\t{\n\t\t\t\tmmff.options[MMFF94::Option::ASSIGN_TYPES] = getValue_(assign_types_checkBox);\n\t\t\t\tmmff.options[MMFF94::Option::ASSIGN_CHARGES] = getValue_(assign_charges_checkBox);\n\t\t\t\tmmff.options[MMFF94::Option::ASSIGN_TYPENAMES] = getValue_(assign_types_checkBox);\n\t\t\t\tmmff.options[MMFF94::Option::OVERWRITE_CHARGES] = getValue_(overwrite_charges_checkBox);\n\t\t\t\tmmff.options[MMFF94::Option::OVERWRITE_TYPENAMES] = getValue_(overwrite_typenames_checkBox);\n\n \t\t\t\tbool value = distance_button->isChecked();\n \t\t\t\tmmff.options[MMFF94::Option::DISTANCE_DEPENDENT_DIELECTRIC] = value ? \"true\" : \"false\";\n\n\t\t\t\tmmff.options[MMFF94::Option::FOLDER] = ascii(parameter_file_edit->text());\n\n\t\t\t\tmmff.options[MMFF94::Option::NONBONDED_CUTOFF] = getValue_(nonbonded_cutoff);\n\t\t\t\t\n\t\t\t\tbool error = false;\n\t\t\t\tif (ascii(max_unassigned_atoms->text()).toUnsignedInt() == 0) \n\t\t\t\t{\n\t\t\t\t\terror = true;\n\t\t\t\t}\n\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tmmff.setMaximumNumberOfErrors(ascii(max_unassigned_atoms->text()).toUnsignedInt());\n\t\t\t\t}\n\t\t\t\tcatch(...)\n\t\t\t\t{\n\t\t\t\t\terror = true;\n\t\t\t\t}\n\n\t\t\t\tif (error)\n\t\t\t\t{\n\t\t\t\t\tmax_unassigned_atoms->setText(\"10\");\n\t\t\t\t\tmmff.setMaximumNumberOfErrors(10);\n\t\t\t\t\tLog.error() << \"Invalid value for max number of unassigned atoms, using default value of 10\" << std::endl;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch(...)\n\t\t\t{\n\t\t\t\tLog.error() << \"Invalid values for MMFF94\" << std::endl;\n\t\t\t}\n\t\t}\n\n\t\tvoid MMFF94ConfigurationDialog::setMMFF94(MMFF94& mmff)\n\t\t\tthrow()\n\t\t{\n\t\t\tmmff_ = &mmff;\n\t\t}\n\t\n\t\tvoid MMFF94ConfigurationDialog::resetOptions()\n\t\t{\n\t\t\tPreferencesEntry::restoreDefaultValues();\n\t\t}\n\n\t}\/\/namespace VIEW\n}\/\/namespace BALL\n<|endoftext|>"} {"text":"\/\/ Licensed to the Apache Software Foundation (ASF) under one\n\/\/ or more contributor license agreements. See the NOTICE file\n\/\/ distributed with this work for additional information\n\/\/ regarding copyright ownership. The ASF licenses this file\n\/\/ to you under the Apache License, Version 2.0 (the\n\/\/ \"License\"); you may not use this file except in compliance\n\/\/ with the License. You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing,\n\/\/ software distributed under the License is distributed on an\n\/\/ \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n\/\/ KIND, either express or implied. See the License for the\n\/\/ specific language governing permissions and limitations\n\/\/ under the License.\n\n#include \"benchmark\/benchmark.h\"\n\n#include \n\n#include \"parquet\/arrow\/reader.h\"\n#include \"parquet\/arrow\/writer.h\"\n#include \"parquet\/column_reader.h\"\n#include \"parquet\/column_writer.h\"\n#include \"parquet\/file_reader.h\"\n#include \"parquet\/file_writer.h\"\n#include \"parquet\/platform.h\"\n\n#include \"arrow\/api.h\"\n\nusing arrow::BooleanBuilder;\nusing arrow::NumericBuilder;\n\n#define EXIT_NOT_OK(s) \\\n do { \\\n ::arrow::Status _s = (s); \\\n if (ARROW_PREDICT_FALSE(!_s.ok())) { \\\n std::cout << \"Exiting: \" << _s.ToString() << std::endl; \\\n exit(EXIT_FAILURE); \\\n } \\\n } while (0)\n\nnamespace parquet {\n\nusing arrow::FileReader;\nusing arrow::WriteTable;\nusing schema::PrimitiveNode;\n\nnamespace benchmark {\n\n\/\/ This should result in multiple pages for most primitive types\nconstexpr int64_t BENCHMARK_SIZE = 10 * 1024 * 1024;\n\ntemplate \nstruct benchmark_traits {};\n\ntemplate <>\nstruct benchmark_traits {\n using arrow_type = ::arrow::Int32Type;\n};\n\ntemplate <>\nstruct benchmark_traits {\n using arrow_type = ::arrow::Int64Type;\n};\n\ntemplate <>\nstruct benchmark_traits {\n using arrow_type = ::arrow::DoubleType;\n};\n\ntemplate <>\nstruct benchmark_traits {\n using arrow_type = ::arrow::BooleanType;\n};\n\ntemplate \nusing ArrowType = typename benchmark_traits::arrow_type;\n\ntemplate \nstd::shared_ptr MakeSchema(Repetition::type repetition) {\n auto node = PrimitiveNode::Make(\"int64\", repetition, ParquetType::type_num);\n return std::make_shared(node, repetition != Repetition::REQUIRED,\n repetition == Repetition::REPEATED);\n}\n\ntemplate \nvoid SetBytesProcessed(::benchmark::State& state) {\n int64_t bytes_processed =\n state.iterations() * BENCHMARK_SIZE * sizeof(typename ParquetType::c_type);\n if (nullable) {\n bytes_processed += state.iterations() * BENCHMARK_SIZE * sizeof(int16_t);\n }\n state.SetBytesProcessed(bytes_processed);\n}\n\ntemplate \nstd::shared_ptr<::arrow::Table> TableFromVector(\n const std::vector& vec, bool nullable) {\n std::shared_ptr<::arrow::DataType> type = std::make_shared>();\n NumericBuilder> builder;\n if (nullable) {\n std::vector valid_bytes(BENCHMARK_SIZE, 0);\n int n = {0};\n std::generate(valid_bytes.begin(), valid_bytes.end(), [&n] { return n++ % 2; });\n EXIT_NOT_OK(builder.AppendValues(vec.data(), vec.size(), valid_bytes.data()));\n } else {\n EXIT_NOT_OK(builder.AppendValues(vec.data(), vec.size(), nullptr));\n }\n std::shared_ptr<::arrow::Array> array;\n EXIT_NOT_OK(builder.Finish(&array));\n\n auto field = ::arrow::field(\"column\", type, nullable);\n auto schema = ::arrow::schema({field});\n return ::arrow::Table::Make(schema, {array});\n}\n\ntemplate <>\nstd::shared_ptr<::arrow::Table> TableFromVector(const std::vector& vec,\n bool nullable) {\n BooleanBuilder builder;\n if (nullable) {\n std::vector valid_bytes(BENCHMARK_SIZE, 0);\n int n = {0};\n std::generate(valid_bytes.begin(), valid_bytes.end(),\n [&n] { return (n++ % 2) != 0; });\n EXIT_NOT_OK(builder.AppendValues(vec, valid_bytes));\n } else {\n EXIT_NOT_OK(builder.AppendValues(vec));\n }\n std::shared_ptr<::arrow::Array> array;\n EXIT_NOT_OK(builder.Finish(&array));\n\n auto field = ::arrow::field(\"column\", ::arrow::boolean(), nullable);\n auto schema = std::make_shared<::arrow::Schema>(\n std::vector>({field}));\n return ::arrow::Table::Make(schema, {array});\n}\n\ntemplate \nstatic void BM_WriteColumn(::benchmark::State& state) {\n using T = typename ParquetType::c_type;\n std::vector values(BENCHMARK_SIZE, static_cast(128));\n std::shared_ptr<::arrow::Table> table = TableFromVector(values, nullable);\n\n while (state.KeepRunning()) {\n auto output = CreateOutputStream();\n EXIT_NOT_OK(\n WriteTable(*table, ::arrow::default_memory_pool(), output, BENCHMARK_SIZE));\n }\n SetBytesProcessed(state);\n}\n\nBENCHMARK_TEMPLATE2(BM_WriteColumn, false, Int32Type);\nBENCHMARK_TEMPLATE2(BM_WriteColumn, true, Int32Type);\n\nBENCHMARK_TEMPLATE2(BM_WriteColumn, false, Int64Type);\nBENCHMARK_TEMPLATE2(BM_WriteColumn, true, Int64Type);\n\nBENCHMARK_TEMPLATE2(BM_WriteColumn, false, DoubleType);\nBENCHMARK_TEMPLATE2(BM_WriteColumn, true, DoubleType);\n\nBENCHMARK_TEMPLATE2(BM_WriteColumn, false, BooleanType);\nBENCHMARK_TEMPLATE2(BM_WriteColumn, true, BooleanType);\n\ntemplate \nstatic void BM_ReadColumn(::benchmark::State& state) {\n using T = typename ParquetType::c_type;\n\n std::vector values(BENCHMARK_SIZE, static_cast(128));\n std::shared_ptr<::arrow::Table> table = TableFromVector(values, nullable);\n auto output = CreateOutputStream();\n EXIT_NOT_OK(WriteTable(*table, ::arrow::default_memory_pool(), output, BENCHMARK_SIZE));\n\n PARQUET_ASSIGN_OR_THROW(auto buffer, output->Finish());\n\n while (state.KeepRunning()) {\n auto reader =\n ParquetFileReader::Open(std::make_shared<::arrow::io::BufferReader>(buffer));\n std::unique_ptr arrow_reader;\n EXIT_NOT_OK(FileReader::Make(::arrow::default_memory_pool(), std::move(reader),\n &arrow_reader));\n std::shared_ptr<::arrow::Table> table;\n EXIT_NOT_OK(arrow_reader->ReadTable(&table));\n }\n SetBytesProcessed(state);\n}\n\nBENCHMARK_TEMPLATE2(BM_ReadColumn, false, Int32Type);\nBENCHMARK_TEMPLATE2(BM_ReadColumn, true, Int32Type);\n\nBENCHMARK_TEMPLATE2(BM_ReadColumn, false, Int64Type);\nBENCHMARK_TEMPLATE2(BM_ReadColumn, true, Int64Type);\n\nBENCHMARK_TEMPLATE2(BM_ReadColumn, false, DoubleType);\nBENCHMARK_TEMPLATE2(BM_ReadColumn, true, DoubleType);\n\nBENCHMARK_TEMPLATE2(BM_ReadColumn, false, BooleanType);\nBENCHMARK_TEMPLATE2(BM_ReadColumn, true, BooleanType);\n\nstatic void BM_ReadIndividualRowGroups(::benchmark::State& state) {\n std::vector values(BENCHMARK_SIZE, 128);\n std::shared_ptr<::arrow::Table> table = TableFromVector(values, true);\n auto output = CreateOutputStream();\n \/\/ This writes 10 RowGroups\n EXIT_NOT_OK(\n WriteTable(*table, ::arrow::default_memory_pool(), output, BENCHMARK_SIZE \/ 10));\n\n PARQUET_ASSIGN_OR_THROW(auto buffer, output->Finish());\n\n while (state.KeepRunning()) {\n auto reader =\n ParquetFileReader::Open(std::make_shared<::arrow::io::BufferReader>(buffer));\n std::unique_ptr arrow_reader;\n EXIT_NOT_OK(FileReader::Make(::arrow::default_memory_pool(), std::move(reader),\n &arrow_reader));\n\n std::vector> tables;\n for (int i = 0; i < arrow_reader->num_row_groups(); i++) {\n \/\/ Only read the even numbered RowGroups\n if ((i % 2) == 0) {\n std::shared_ptr<::arrow::Table> table;\n EXIT_NOT_OK(arrow_reader->RowGroup(i)->ReadTable(&table));\n tables.push_back(table);\n }\n }\n\n std::shared_ptr<::arrow::Table> final_table;\n PARQUET_ASSIGN_OR_THROW(final_table, ConcatenateTables(tables));\n }\n SetBytesProcessed(state);\n}\n\nBENCHMARK(BM_ReadIndividualRowGroups);\n\nstatic void BM_ReadMultipleRowGroups(::benchmark::State& state) {\n std::vector values(BENCHMARK_SIZE, 128);\n std::shared_ptr<::arrow::Table> table = TableFromVector(values, true);\n auto output = CreateOutputStream();\n \/\/ This writes 10 RowGroups\n EXIT_NOT_OK(\n WriteTable(*table, ::arrow::default_memory_pool(), output, BENCHMARK_SIZE \/ 10));\n PARQUET_ASSIGN_OR_THROW(auto buffer, output->Finish());\n\n while (state.KeepRunning()) {\n auto reader =\n ParquetFileReader::Open(std::make_shared<::arrow::io::BufferReader>(buffer));\n std::unique_ptr arrow_reader;\n EXIT_NOT_OK(FileReader::Make(::arrow::default_memory_pool(), std::move(reader),\n &arrow_reader));\n\n std::vector> tables;\n std::vector rgs;\n for (int i = 0; i < arrow_reader->num_row_groups(); i++) {\n \/\/ Only read the even numbered RowGroups\n if ((i % 2) == 0) {\n rgs.push_back(i);\n }\n }\n\n std::shared_ptr<::arrow::Table> table;\n EXIT_NOT_OK(arrow_reader->ReadRowGroups(rgs, &table));\n }\n SetBytesProcessed(state);\n}\n\nBENCHMARK(BM_ReadMultipleRowGroups);\n\n} \/\/ namespace benchmark\n\n} \/\/ namespace parquet\nARROW-8794: [C++] Expand performance coverage of parquet to arrow reading\/\/ Licensed to the Apache Software Foundation (ASF) under one\n\/\/ or more contributor license agreements. See the NOTICE file\n\/\/ distributed with this work for additional information\n\/\/ regarding copyright ownership. The ASF licenses this file\n\/\/ to you under the Apache License, Version 2.0 (the\n\/\/ \"License\"); you may not use this file except in compliance\n\/\/ with the License. You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing,\n\/\/ software distributed under the License is distributed on an\n\/\/ \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n\/\/ KIND, either express or implied. See the License for the\n\/\/ specific language governing permissions and limitations\n\/\/ under the License.\n\n#include \"benchmark\/benchmark.h\"\n\n#include \n#include \n\n#include \"parquet\/arrow\/reader.h\"\n#include \"parquet\/arrow\/writer.h\"\n#include \"parquet\/column_reader.h\"\n#include \"parquet\/column_writer.h\"\n#include \"parquet\/file_reader.h\"\n#include \"parquet\/file_writer.h\"\n#include \"parquet\/platform.h\"\n\n#include \"arrow\/api.h\"\n#include \"arrow\/util\/logging.h\"\n\nusing arrow::BooleanBuilder;\nusing arrow::NumericBuilder;\n\n#define EXIT_NOT_OK(s) \\\n do { \\\n ::arrow::Status _s = (s); \\\n if (ARROW_PREDICT_FALSE(!_s.ok())) { \\\n std::cout << \"Exiting: \" << _s.ToString() << std::endl; \\\n exit(EXIT_FAILURE); \\\n } \\\n } while (0)\n\nnamespace parquet {\n\nusing arrow::FileReader;\nusing arrow::WriteTable;\nusing schema::PrimitiveNode;\n\nnamespace benchmark {\n\n\/\/ This should result in multiple pages for most primitive types\nconstexpr int64_t BENCHMARK_SIZE = 10 * 1024 * 1024;\n\ntemplate \nstruct benchmark_traits {};\n\ntemplate <>\nstruct benchmark_traits {\n using arrow_type = ::arrow::Int32Type;\n};\n\ntemplate <>\nstruct benchmark_traits {\n using arrow_type = ::arrow::Int64Type;\n};\n\ntemplate <>\nstruct benchmark_traits {\n using arrow_type = ::arrow::DoubleType;\n};\n\ntemplate <>\nstruct benchmark_traits {\n using arrow_type = ::arrow::BooleanType;\n};\n\ntemplate \nusing ArrowType = typename benchmark_traits::arrow_type;\n\ntemplate \nstd::shared_ptr MakeSchema(Repetition::type repetition) {\n auto node = PrimitiveNode::Make(\"int64\", repetition, ParquetType::type_num);\n return std::make_shared(node, repetition != Repetition::REQUIRED,\n repetition == Repetition::REPEATED);\n}\n\ntemplate \nvoid SetBytesProcessed(::benchmark::State& state) {\n int64_t bytes_processed =\n state.iterations() * BENCHMARK_SIZE * sizeof(typename ParquetType::c_type);\n if (nullable) {\n bytes_processed += state.iterations() * BENCHMARK_SIZE * sizeof(int16_t);\n }\n state.SetBytesProcessed(bytes_processed);\n}\n\nconstexpr int64_t kAlternatingOrNa = -1;\n\ntemplate \nstd::vector RandomVector(int64_t true_percentage, int64_t vector_size,\n const std::array& sample_values) {\n std::vector values(BENCHMARK_SIZE, {});\n if (true_percentage == kAlternatingOrNa) {\n int n = {0};\n std::generate(values.begin(), values.end(), [&n] { return n++ % 2; });\n } else {\n std::default_random_engine rng(500);\n double true_probability = static_cast(true_percentage) \/ 100.0;\n std::bernoulli_distribution dist(true_probability);\n std::generate(values.begin(), values.end(), [&] { return sample_values[dist(rng)]; });\n }\n return values;\n}\n\ntemplate \nstd::shared_ptr<::arrow::Table> TableFromVector(\n const std::vector& vec, bool nullable,\n int64_t null_percentage = kAlternatingOrNa) {\n if (!nullable) {\n ARROW_CHECK_EQ(null_percentage, kAlternatingOrNa);\n }\n std::shared_ptr<::arrow::DataType> type = std::make_shared>();\n NumericBuilder> builder;\n if (nullable) {\n \/\/ Note true values select index 1 of sample_values\n auto valid_bytes = RandomVector(\/*true_percentage=*\/null_percentage,\n BENCHMARK_SIZE, \/*sample_values=*\/{1, 0});\n EXIT_NOT_OK(builder.AppendValues(vec.data(), vec.size(), valid_bytes.data()));\n } else {\n EXIT_NOT_OK(builder.AppendValues(vec.data(), vec.size(), nullptr));\n }\n std::shared_ptr<::arrow::Array> array;\n EXIT_NOT_OK(builder.Finish(&array));\n\n auto field = ::arrow::field(\"column\", type, nullable);\n auto schema = ::arrow::schema({field});\n return ::arrow::Table::Make(schema, {array});\n}\n\ntemplate <>\nstd::shared_ptr<::arrow::Table> TableFromVector(const std::vector& vec,\n bool nullable,\n int64_t null_percentage) {\n BooleanBuilder builder;\n if (nullable) {\n auto valid_bytes = RandomVector(\/*true_percentage=*\/null_percentage,\n BENCHMARK_SIZE, {true, false});\n EXIT_NOT_OK(builder.AppendValues(vec, valid_bytes));\n } else {\n EXIT_NOT_OK(builder.AppendValues(vec));\n }\n std::shared_ptr<::arrow::Array> array;\n EXIT_NOT_OK(builder.Finish(&array));\n\n auto field = ::arrow::field(\"column\", ::arrow::boolean(), nullable);\n auto schema = std::make_shared<::arrow::Schema>(\n std::vector>({field}));\n return ::arrow::Table::Make(schema, {array});\n}\n\ntemplate \nstatic void BM_WriteColumn(::benchmark::State& state) {\n using T = typename ParquetType::c_type;\n std::vector values(BENCHMARK_SIZE, 128);\n std::shared_ptr<::arrow::Table> table = TableFromVector(values, nullable);\n\n while (state.KeepRunning()) {\n auto output = CreateOutputStream();\n EXIT_NOT_OK(\n WriteTable(*table, ::arrow::default_memory_pool(), output, BENCHMARK_SIZE));\n }\n SetBytesProcessed(state);\n}\n\nBENCHMARK_TEMPLATE2(BM_WriteColumn, false, Int32Type);\nBENCHMARK_TEMPLATE2(BM_WriteColumn, true, Int32Type);\n\nBENCHMARK_TEMPLATE2(BM_WriteColumn, false, Int64Type);\nBENCHMARK_TEMPLATE2(BM_WriteColumn, true, Int64Type);\n\nBENCHMARK_TEMPLATE2(BM_WriteColumn, false, DoubleType);\nBENCHMARK_TEMPLATE2(BM_WriteColumn, true, DoubleType);\n\nBENCHMARK_TEMPLATE2(BM_WriteColumn, false, BooleanType);\nBENCHMARK_TEMPLATE2(BM_WriteColumn, true, BooleanType);\n\ntemplate \nstruct Examples {\n static constexpr std::array values() { return {127, 128}; }\n};\n\ntemplate <>\nstruct Examples {\n static constexpr std::array values() { return {false, true}; }\n};\n\ntemplate \nstatic void BM_ReadColumn(::benchmark::State& state) {\n using T = typename ParquetType::c_type;\n\n auto values = RandomVector(\/*percentage=*\/state.range(1), BENCHMARK_SIZE,\n Examples::values());\n\n std::shared_ptr<::arrow::Table> table =\n TableFromVector(values, nullable, state.range(0));\n auto output = CreateOutputStream();\n EXIT_NOT_OK(WriteTable(*table, ::arrow::default_memory_pool(), output, BENCHMARK_SIZE));\n\n PARQUET_ASSIGN_OR_THROW(auto buffer, output->Finish());\n\n while (state.KeepRunning()) {\n auto reader =\n ParquetFileReader::Open(std::make_shared<::arrow::io::BufferReader>(buffer));\n std::unique_ptr arrow_reader;\n EXIT_NOT_OK(FileReader::Make(::arrow::default_memory_pool(), std::move(reader),\n &arrow_reader));\n std::shared_ptr<::arrow::Table> table;\n EXIT_NOT_OK(arrow_reader->ReadTable(&table));\n }\n SetBytesProcessed(state);\n}\n\n\/\/ There are two parameters here that cover different data distributions.\n\/\/ null_percentage governs distribution and therefore runs of null values.\n\/\/ first_value_percentage governs distribution of values (we select from 1 of 2)\n\/\/ so when 0 or 100 RLE is triggered all the time. When a value in the range (0, 100)\n\/\/ there will be some percentage of RLE encoded values and some percentage of literal\n\/\/ encoded values (RLE is much less likely with percentages close to 50).\nBENCHMARK_TEMPLATE2(BM_ReadColumn, false, Int32Type)\n ->Args({\/*null_percentage=*\/kAlternatingOrNa, 1})\n ->Args({\/*null_percentage=*\/kAlternatingOrNa, 10})\n ->Args({\/*null_percentage=*\/kAlternatingOrNa, 50});\n\nBENCHMARK_TEMPLATE2(BM_ReadColumn, true, Int32Type)\n ->Args({\/*null_percentage=*\/kAlternatingOrNa, \/*first_value_percentage=*\/0})\n ->Args({\/*null_percentage=*\/1, \/*first_value_percentage=*\/1})\n ->Args({\/*null_percentage=*\/10, \/*first_value_percentage=*\/10})\n ->Args({\/*null_percentage=*\/25, \/*first_value_percentage=*\/5})\n ->Args({\/*null_percentage=*\/50, \/*first_value_percentage=*\/50})\n ->Args({\/*null_percentage=*\/50, \/*first_value_percentage=*\/0})\n ->Args({\/*null_percentage=*\/99, \/*first_value_percentage=*\/50})\n ->Args({\/*null_percentage=*\/99, \/*first_value_percentage=*\/0});\n\nBENCHMARK_TEMPLATE2(BM_ReadColumn, false, Int64Type)\n ->Args({\/*null_percentage=*\/kAlternatingOrNa, 1})\n ->Args({\/*null_percentage=*\/kAlternatingOrNa, 10})\n ->Args({\/*null_percentage=*\/kAlternatingOrNa, 50});\nBENCHMARK_TEMPLATE2(BM_ReadColumn, true, Int64Type)\n ->Args({\/*null_percentage=*\/kAlternatingOrNa, \/*first_value_percentage=*\/0})\n ->Args({\/*null_percentage=*\/1, \/*first_value_percentage=*\/1})\n ->Args({\/*null_percentage=*\/5, \/*first_value_percentage=*\/5})\n ->Args({\/*null_percentage=*\/10, \/*first_value_percentage=*\/5})\n ->Args({\/*null_percentage=*\/25, \/*first_value_percentage=*\/10})\n ->Args({\/*null_percentage=*\/30, \/*first_value_percentage=*\/10})\n ->Args({\/*null_percentage=*\/35, \/*first_value_percentage=*\/10})\n ->Args({\/*null_percentage=*\/45, \/*first_value_percentage=*\/25})\n ->Args({\/*null_percentage=*\/50, \/*first_value_percentage=*\/50})\n ->Args({\/*null_percentage=*\/50, \/*first_value_percentage=*\/1})\n ->Args({\/*null_percentage=*\/75, \/*first_value_percentage=*\/1})\n ->Args({\/*null_percentage=*\/99, \/*first_value_percentage=*\/50})\n ->Args({\/*null_percentage=*\/99, \/*first_value_percentage=*\/0});\n\nBENCHMARK_TEMPLATE2(BM_ReadColumn, false, DoubleType)\n ->Args({kAlternatingOrNa, 0})\n ->Args({kAlternatingOrNa, 20});\n\/\/ Less coverage because int64_t should be pretty good representation for nullability and\n\/\/ repeating values.\nBENCHMARK_TEMPLATE2(BM_ReadColumn, true, DoubleType)\n ->Args({\/*null_percentage=*\/kAlternatingOrNa, \/*first_value_percentage=*\/0})\n ->Args({\/*null_percentage=*\/10, \/*first_value_percentage=*\/50})\n ->Args({\/*null_percentage=*\/25, \/*first_value_percentage=*\/25});\n\nBENCHMARK_TEMPLATE2(BM_ReadColumn, false, BooleanType)\n ->Args({kAlternatingOrNa, 0})\n ->Args({1, 20});\nBENCHMARK_TEMPLATE2(BM_ReadColumn, true, BooleanType)\n ->Args({kAlternatingOrNa, 1})\n ->Args({5, 10});\n\nstatic void BM_ReadIndividualRowGroups(::benchmark::State& state) {\n std::vector values(BENCHMARK_SIZE, 128);\n std::shared_ptr<::arrow::Table> table = TableFromVector(values, true);\n auto output = CreateOutputStream();\n \/\/ This writes 10 RowGroups\n EXIT_NOT_OK(\n WriteTable(*table, ::arrow::default_memory_pool(), output, BENCHMARK_SIZE \/ 10));\n\n PARQUET_ASSIGN_OR_THROW(auto buffer, output->Finish());\n\n while (state.KeepRunning()) {\n auto reader =\n ParquetFileReader::Open(std::make_shared<::arrow::io::BufferReader>(buffer));\n std::unique_ptr arrow_reader;\n EXIT_NOT_OK(FileReader::Make(::arrow::default_memory_pool(), std::move(reader),\n &arrow_reader));\n\n std::vector> tables;\n for (int i = 0; i < arrow_reader->num_row_groups(); i++) {\n \/\/ Only read the even numbered RowGroups\n if ((i % 2) == 0) {\n std::shared_ptr<::arrow::Table> table;\n EXIT_NOT_OK(arrow_reader->RowGroup(i)->ReadTable(&table));\n tables.push_back(table);\n }\n }\n\n std::shared_ptr<::arrow::Table> final_table;\n PARQUET_ASSIGN_OR_THROW(final_table, ConcatenateTables(tables));\n }\n SetBytesProcessed(state);\n}\n\nBENCHMARK(BM_ReadIndividualRowGroups);\n\nstatic void BM_ReadMultipleRowGroups(::benchmark::State& state) {\n std::vector values(BENCHMARK_SIZE, 128);\n std::shared_ptr<::arrow::Table> table = TableFromVector(values, true);\n auto output = CreateOutputStream();\n \/\/ This writes 10 RowGroups\n EXIT_NOT_OK(\n WriteTable(*table, ::arrow::default_memory_pool(), output, BENCHMARK_SIZE \/ 10));\n PARQUET_ASSIGN_OR_THROW(auto buffer, output->Finish());\n\n while (state.KeepRunning()) {\n auto reader =\n ParquetFileReader::Open(std::make_shared<::arrow::io::BufferReader>(buffer));\n std::unique_ptr arrow_reader;\n EXIT_NOT_OK(FileReader::Make(::arrow::default_memory_pool(), std::move(reader),\n &arrow_reader));\n\n std::vector> tables;\n std::vector rgs;\n for (int i = 0; i < arrow_reader->num_row_groups(); i++) {\n \/\/ Only read the even numbered RowGroups\n if ((i % 2) == 0) {\n rgs.push_back(i);\n }\n }\n\n std::shared_ptr<::arrow::Table> table;\n EXIT_NOT_OK(arrow_reader->ReadRowGroups(rgs, &table));\n }\n SetBytesProcessed(state);\n}\n\nBENCHMARK(BM_ReadMultipleRowGroups);\n\n} \/\/ namespace benchmark\n\n} \/\/ namespace parquet\n<|endoftext|>"} {"text":"\/***********************************************************************\n manip.cpp - Implements MySQL++'s various quoting\/escaping stream\n\tmanipulators.\n\n Copyright (c) 1998 by Kevin Atkinson, (c) 1999, 2000 and 2001 by\n MySQL AB, and (c) 2004, 2005 by Educational Technology Resources, Inc.\n Others may also hold copyrights on code in this file. See the CREDITS\n file in the top directory of the distribution for details.\n\n This file is part of MySQL++.\n\n MySQL++ is free software; you can redistribute it and\/or modify it\n under the terms of the GNU Lesser General Public License as published\n by the Free Software Foundation; either version 2.1 of the License, or\n (at your option) any later version.\n\n MySQL++ is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\n License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with MySQL++; if not, write to the Free Software\n Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301\n USA\n***********************************************************************\/\n\n#include \"manip.h\"\n\n#include \"query.h\"\n\nusing namespace std;\n\n\/\/ Manipulator stuff is _always_ in namespace mysqlpp.\nnamespace mysqlpp {\n\n\/\/\/ \\brief Set to true if you want to suppress automatic quoting\n\/\/\/\n\/\/\/ Works only for ColData inserted into C++ streams.\n\nbool dont_quote_auto = false;\n\n\n\/\/\/ \\brief Inserts a SQLString into a stream, quoted and escaped.\n\/\/\/\n\/\/\/ If in.is_string is set and in.dont_escape is \\e not set, the string\n\/\/\/ is quoted and escaped.\n\/\/\/\n\/\/\/ If both in.is_string and in.dont_escape are set, the string is\n\/\/\/ quoted but not escaped.\n\/\/\/\n\/\/\/ If in.is_string is not set, the data is inserted as-is. This is\n\/\/\/ the case when you initialize SQLString with one of the constructors\n\/\/\/ taking an integral type, for instance.\n\nSQLQueryParms& operator <<(quote_type2 p, SQLString& in)\n{\n\tif (in.is_string) {\n\t\tSQLString in2('\\'');\n\t\tif (in.dont_escape) {\n\t\t\tin2 += in;\n\t\t\tin2 += '\\'';\n\t\t\tin2.processed = true;\n\t\t\treturn *p.qparms << in2;\n\t\t}\n\t\telse {\n\t\t\tchar* s = new char[in.length() * 2 + 1];\n\t\t\tsize_t len = mysql_escape_string(s, in.data(), in.length());\n\t\t\tin2.append(s, len);\n\t\t\tin2 += '\\'';\n\t\t\tin2.processed = true;\n\t\t\t*p.qparms << in2;\n\t\t\tdelete[] s;\n\t\t\treturn *p.qparms;\n\t\t}\n\t}\n\telse {\n\t\tin.processed = true;\n\t\treturn *p.qparms << in;\n\t}\n}\n\n\n\/\/\/ \\brief Inserts a C++ string into a stream, quoted and escaped\n\/\/\/\n\/\/\/ Because std::string lacks the type information we need, the string\n\/\/\/ is both quoted and escaped, always.\n\ntemplate <>\nostream& operator <<(quote_type1 o, const string& in)\n{\n\tchar* s = new char[in.length() * 2 + 1];\n\tsize_t len = mysql_escape_string(s, in.data(), in.length());\n\n\to.ostr->write(\"'\", 1);\n\to.ostr->write(s, len);\n\to.ostr->write(\"'\", 1);\n\n\tdelete[] s;\n\treturn *o.ostr;\n}\n\n\n\/\/\/ \\brief Inserts a C string into a stream, quoted and escaped\n\/\/\/\n\/\/\/ Because C strings lack the type information we need, the string\n\/\/\/ is both quoted and escaped, always.\n\ntemplate <>\nostream& operator <<(quote_type1 o, const char* const& in)\n{\n\tsize_t len = strlen(in);\n\tchar* s = new char[len * 2 + 1];\n\tlen = mysql_escape_string(s, in, len);\n\n\to.ostr->write(\"'\", 1);\n\to.ostr->write(s, len);\n\to.ostr->write(\"'\", 1);\n\n\tdelete[] s;\n\treturn *o.ostr;\n}\n\n\n\/\/\/ \\brief Inserts a ColData with const string into a stream, quoted and\n\/\/\/ escaped\n\/\/\/\n\/\/\/ Because ColData was designed to contain MySQL type data, we may\n\/\/\/ choose not to actually quote or escape the data, if it is not\n\/\/\/ needed.\n\ntemplate <>\nostream& operator <<(quote_type1 o, const ColData& in)\n{\n\tif (in.escape_q()) {\n\t\tchar* s = new char[in.length() * 2 + 1];\n\t\tsize_t len = mysql_escape_string(s, in.data(), in.length());\n\n\t\tif (in.quote_q()) o.ostr->write(\"'\", 1);\n\t\to.ostr->write(s, len);\n\t\tif (in.quote_q()) o.ostr->write(\"'\", 1);\n\n\t\tdelete[] s;\n\t}\n\telse {\n\t\tif (in.quote_q()) o.ostr->write(\"'\", 1);\n\t\to.ostr->write(in.data(), in.length());\n\t\tif (in.quote_q()) o.ostr->write(\"'\", 1);\n\t}\n\n\treturn *o.ostr;\n}\n\n\n\/\/\/ \\brief Inserts a ColData into a non-Query stream.\n\/\/\/\n\/\/\/ Although we know how to automatically quote and escape ColData\n\/\/\/ objects, we only do that when inserting them into Query streams\n\/\/\/ because this feature is only intended to make it easier to build\n\/\/\/ syntactically-correct SQL queries. You can force the library to\n\/\/\/ give you quoting and escaping with the quote manipulator:\n\/\/\/\n\/\/\/ \\code\n\/\/\/ mysqlpp::ColData cd(\"...\");\n\/\/\/ cout << mysqlpp::quote << cd << endl;\n\/\/\/ \\endcode\n\nostream& operator <<(ostream& o, const ColData& in)\n{\n\to.write(in.data(), in.length());\n\treturn o;\n}\n\n\n\/\/\/ \\brief Insert a ColData with const string into a SQLQuery\n\/\/\/\n\/\/\/ This operator appears to be a workaround for a weakness in one\n\/\/\/ compiler's implementation of the C++ type system. See Wishlist for\n\/\/\/ current plan on what to do about this.\n\nQuery& operator <<(Query& o, const ColData& in)\n{\n\tif (dont_quote_auto) {\n\t\to.write(in.data(), in.length());\n\t}\n\telse if (in.escape_q()) {\n\t\tchar* s = new char[in.length() * 2 + 1];\n\t\tsize_t len = mysql_escape_string(s, in.data(), in.length());\n\n\t\tif (in.quote_q()) o.write(\"'\", 1);\n\t\to.write(s, len);\n\t\tif (in.quote_q()) o.write(\"'\", 1);\n\n\t\tdelete[] s;\n\t}\n\telse {\n\t\tif (in.quote_q()) o.write(\"'\", 1);\n\t\to.write(in.data(), in.length());\n\t\tif (in.quote_q()) o.write(\"'\", 1);\n\t}\n\n\treturn o;\n}\n\n\n\/\/\/ \\brief Inserts a SQLString into a stream, quoting it unless it's\n\/\/\/ data that needs no quoting.\n\/\/\/\n\/\/\/ We make the decision to quote the data based on the in.is_string\n\/\/\/ flag. You can set it yourself, but SQLString's ctors should set\n\/\/\/ it correctly for you.\n\nSQLQueryParms& operator <<(quote_only_type2 p, SQLString& in)\n{\n\tif (in.is_string) {\n\t\tSQLString in2;\n\t\tin2 = '\\'' + in + '\\'';\n\t\tin2.processed = true;\n\t\treturn *p.qparms << in2;\n\t}\n\telse {\n\t\tin.processed = true;\n\t\treturn *p.qparms << in;\n\t}\n}\n\n\n\/\/\/ \\brief Inserts a ColData with const string into a stream, quoted\n\/\/\/\n\/\/\/ Because ColData was designed to contain MySQL type data, we may\n\/\/\/ choose not to actually quote the data, if it is not needed.\n\ntemplate <>\nostream& operator <<(quote_only_type1 o, const ColData& in)\n{\n\tif (in.quote_q()) o.ostr->write(\"'\", 1);\n\to.ostr->write(in.data(), in.length());\n\tif (in.quote_q()) o.ostr->write(\"'\", 1);\n\n\treturn *o.ostr;\n}\n\n\n\/\/\/ \\brief Inserts a SQLString into a stream, double-quoting it (\")\n\/\/\/ unless it's data that needs no quoting.\n\/\/\/\n\/\/\/ We make the decision to quote the data based on the in.is_string\n\/\/\/ flag. You can set it yourself, but SQLString's ctors should set\n\/\/\/ it correctly for you.\n\nSQLQueryParms& operator <<(quote_double_only_type2 p, SQLString& in)\n{\n\tif (in.is_string) {\n\t\tSQLString in2;\n\t\tin2 = \"\\\"\" + in + \"\\\"\";\n\t\tin2.processed = true;\n\t\treturn *p.qparms << in2;\n\t}\n\telse {\n\t\tin.processed = true;\n\t\treturn *p.qparms << in;\n\t}\n}\n\n\n\/\/\/ \\brief Inserts a ColData with const string into a stream,\n\/\/\/ double-quoted (\")\n\/\/\/\n\/\/\/ Because ColData was designed to contain MySQL type data, we may\n\/\/\/ choose not to actually quote the data, if it is not needed.\n\ntemplate <>\nostream& operator <<(quote_double_only_type1 o, const ColData& in)\n{\n\tif (in.quote_q()) o.ostr->write(\"'\", 1);\n\to.ostr->write(in.data(), in.length());\n\tif (in.quote_q()) o.ostr->write(\"'\", 1);\n\n\treturn *o.ostr;\n}\n\n\nSQLQueryParms& operator <<(escape_type2 p, SQLString& in)\n{\n\tif (in.is_string && !in.dont_escape) {\n\t\tchar* s = new char[in.length() * 2 + 1];\n\t\tsize_t len = mysql_escape_string(s, in.data(), in.length());\n\n\t\tSQLString in2(s, len);\n\t\tin2.processed = true;\n\t\t*p.qparms << in2;\n\n\t\tdelete[] s;\n\t\treturn *p.qparms;\n\t}\n\telse {\n\t\tin.processed = true;\n\t\treturn *p.qparms << in;\n\t}\n}\n\n\n\/\/\/ \\brief Inserts a C++ string into a stream, escaping special SQL\n\/\/\/ characters\n\/\/\/\n\/\/\/ Because std::string lacks the type information we need, the string\n\/\/\/ is always escaped, even if it doesn't need it.\n\ntemplate <>\nstd::ostream& operator <<(escape_type1 o, const std::string& in)\n{\n\tchar* s = new char[in.length() * 2 + 1];\n\tsize_t len = mysql_escape_string(s, in.data(), in.length());\n\to.ostr->write(s, len);\n\tdelete[] s;\n\treturn *o.ostr;\n}\n\n\n\/\/\/ \\brief Inserts a C string into a stream, escaping special SQL\n\/\/\/ characters\n\/\/\/\n\/\/\/ Because C's type system lacks the information we need to second-\n\/\/\/ guess this manipulator, we always run the escaping algorithm on\n\/\/\/ the data, even if it's not needed.\n\ntemplate <>\nostream& operator <<(escape_type1 o, const char* const& in)\n{\n\tsize_t len = strlen(in);\n\tchar* s = new char[len * 2 + 1];\n\tlen = mysql_escape_string(s, in, len);\n\to.ostr->write(s, len);\n\tdelete[] s;\n\treturn *o.ostr;\n}\n\n\n\/\/\/ \\brief Inserts a ColData with const string into a stream, escaping\n\/\/\/ special SQL characters\n\/\/\/\n\/\/\/ Because ColData was designed to contain MySQL type data, we may\n\/\/\/ choose not to escape the data, if it is not needed.\n\nstd::ostream& operator <<(escape_type1 o, const ColData& in)\n{\n\tif (in.escape_q()) {\n\t\tchar* s = new char[in.length() * 2 + 1];\n\t\tsize_t len = mysql_escape_string(s, in.data(), in.length());\n\t\to.ostr->write(s, len);\n\t\tdelete[] s;\n\t}\n\telse {\n\t\to.ostr->write(in.data(), in.length());\n\t}\n\n\treturn *o.ostr;\n}\n\n\n\/\/\/ \\brief Inserts a SQLString into a stream, with no escaping or\n\/\/\/ quoting.\n\nSQLQueryParms& operator <<(do_nothing_type2 p, SQLString& in)\n{\n\tin.processed = true;\n\treturn *p.qparms << in;\n}\n\n\n\/\/\/ \\brief Inserts a SQLString into a stream, with no escaping or\n\/\/\/ quoting, and without marking the string as having been \"processed\".\n\nSQLQueryParms& operator <<(ignore_type2 p, SQLString& in)\n{\n\treturn *p.qparms << in;\n}\n\n} \/\/ end namespace mysqlpp\n\nFixed a bug in quote_double_only manipulator for ColData: was using single quotes by mistake.\/***********************************************************************\n manip.cpp - Implements MySQL++'s various quoting\/escaping stream\n\tmanipulators.\n\n Copyright (c) 1998 by Kevin Atkinson, (c) 1999, 2000 and 2001 by\n MySQL AB, and (c) 2004, 2005 by Educational Technology Resources, Inc.\n Others may also hold copyrights on code in this file. See the CREDITS\n file in the top directory of the distribution for details.\n\n This file is part of MySQL++.\n\n MySQL++ is free software; you can redistribute it and\/or modify it\n under the terms of the GNU Lesser General Public License as published\n by the Free Software Foundation; either version 2.1 of the License, or\n (at your option) any later version.\n\n MySQL++ is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\n License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with MySQL++; if not, write to the Free Software\n Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301\n USA\n***********************************************************************\/\n\n#include \"manip.h\"\n\n#include \"query.h\"\n\nusing namespace std;\n\n\/\/ Manipulator stuff is _always_ in namespace mysqlpp.\nnamespace mysqlpp {\n\n\/\/\/ \\brief Set to true if you want to suppress automatic quoting\n\/\/\/\n\/\/\/ Works only for ColData inserted into C++ streams.\n\nbool dont_quote_auto = false;\n\n\n\/\/\/ \\brief Inserts a SQLString into a stream, quoted and escaped.\n\/\/\/\n\/\/\/ If in.is_string is set and in.dont_escape is \\e not set, the string\n\/\/\/ is quoted and escaped.\n\/\/\/\n\/\/\/ If both in.is_string and in.dont_escape are set, the string is\n\/\/\/ quoted but not escaped.\n\/\/\/\n\/\/\/ If in.is_string is not set, the data is inserted as-is. This is\n\/\/\/ the case when you initialize SQLString with one of the constructors\n\/\/\/ taking an integral type, for instance.\n\nSQLQueryParms& operator <<(quote_type2 p, SQLString& in)\n{\n\tif (in.is_string) {\n\t\tSQLString in2('\\'');\n\t\tif (in.dont_escape) {\n\t\t\tin2 += in;\n\t\t\tin2 += '\\'';\n\t\t\tin2.processed = true;\n\t\t\treturn *p.qparms << in2;\n\t\t}\n\t\telse {\n\t\t\tchar* s = new char[in.length() * 2 + 1];\n\t\t\tsize_t len = mysql_escape_string(s, in.data(), in.length());\n\t\t\tin2.append(s, len);\n\t\t\tin2 += '\\'';\n\t\t\tin2.processed = true;\n\t\t\t*p.qparms << in2;\n\t\t\tdelete[] s;\n\t\t\treturn *p.qparms;\n\t\t}\n\t}\n\telse {\n\t\tin.processed = true;\n\t\treturn *p.qparms << in;\n\t}\n}\n\n\n\/\/\/ \\brief Inserts a C++ string into a stream, quoted and escaped\n\/\/\/\n\/\/\/ Because std::string lacks the type information we need, the string\n\/\/\/ is both quoted and escaped, always.\n\ntemplate <>\nostream& operator <<(quote_type1 o, const string& in)\n{\n\tchar* s = new char[in.length() * 2 + 1];\n\tsize_t len = mysql_escape_string(s, in.data(), in.length());\n\n\to.ostr->write(\"'\", 1);\n\to.ostr->write(s, len);\n\to.ostr->write(\"'\", 1);\n\n\tdelete[] s;\n\treturn *o.ostr;\n}\n\n\n\/\/\/ \\brief Inserts a C string into a stream, quoted and escaped\n\/\/\/\n\/\/\/ Because C strings lack the type information we need, the string\n\/\/\/ is both quoted and escaped, always.\n\ntemplate <>\nostream& operator <<(quote_type1 o, const char* const& in)\n{\n\tsize_t len = strlen(in);\n\tchar* s = new char[len * 2 + 1];\n\tlen = mysql_escape_string(s, in, len);\n\n\to.ostr->write(\"'\", 1);\n\to.ostr->write(s, len);\n\to.ostr->write(\"'\", 1);\n\n\tdelete[] s;\n\treturn *o.ostr;\n}\n\n\n\/\/\/ \\brief Inserts a ColData with const string into a stream, quoted and\n\/\/\/ escaped\n\/\/\/\n\/\/\/ Because ColData was designed to contain MySQL type data, we may\n\/\/\/ choose not to actually quote or escape the data, if it is not\n\/\/\/ needed.\n\ntemplate <>\nostream& operator <<(quote_type1 o, const ColData& in)\n{\n\tif (in.escape_q()) {\n\t\tchar* s = new char[in.length() * 2 + 1];\n\t\tsize_t len = mysql_escape_string(s, in.data(), in.length());\n\n\t\tif (in.quote_q()) o.ostr->write(\"'\", 1);\n\t\to.ostr->write(s, len);\n\t\tif (in.quote_q()) o.ostr->write(\"'\", 1);\n\n\t\tdelete[] s;\n\t}\n\telse {\n\t\tif (in.quote_q()) o.ostr->write(\"'\", 1);\n\t\to.ostr->write(in.data(), in.length());\n\t\tif (in.quote_q()) o.ostr->write(\"'\", 1);\n\t}\n\n\treturn *o.ostr;\n}\n\n\n\/\/\/ \\brief Inserts a ColData into a non-Query stream.\n\/\/\/\n\/\/\/ Although we know how to automatically quote and escape ColData\n\/\/\/ objects, we only do that when inserting them into Query streams\n\/\/\/ because this feature is only intended to make it easier to build\n\/\/\/ syntactically-correct SQL queries. You can force the library to\n\/\/\/ give you quoting and escaping with the quote manipulator:\n\/\/\/\n\/\/\/ \\code\n\/\/\/ mysqlpp::ColData cd(\"...\");\n\/\/\/ cout << mysqlpp::quote << cd << endl;\n\/\/\/ \\endcode\n\nostream& operator <<(ostream& o, const ColData& in)\n{\n\to.write(in.data(), in.length());\n\treturn o;\n}\n\n\n\/\/\/ \\brief Insert a ColData with const string into a SQLQuery\n\/\/\/\n\/\/\/ This operator appears to be a workaround for a weakness in one\n\/\/\/ compiler's implementation of the C++ type system. See Wishlist for\n\/\/\/ current plan on what to do about this.\n\nQuery& operator <<(Query& o, const ColData& in)\n{\n\tif (dont_quote_auto) {\n\t\to.write(in.data(), in.length());\n\t}\n\telse if (in.escape_q()) {\n\t\tchar* s = new char[in.length() * 2 + 1];\n\t\tsize_t len = mysql_escape_string(s, in.data(), in.length());\n\n\t\tif (in.quote_q()) o.write(\"'\", 1);\n\t\to.write(s, len);\n\t\tif (in.quote_q()) o.write(\"'\", 1);\n\n\t\tdelete[] s;\n\t}\n\telse {\n\t\tif (in.quote_q()) o.write(\"'\", 1);\n\t\to.write(in.data(), in.length());\n\t\tif (in.quote_q()) o.write(\"'\", 1);\n\t}\n\n\treturn o;\n}\n\n\n\/\/\/ \\brief Inserts a SQLString into a stream, quoting it unless it's\n\/\/\/ data that needs no quoting.\n\/\/\/\n\/\/\/ We make the decision to quote the data based on the in.is_string\n\/\/\/ flag. You can set it yourself, but SQLString's ctors should set\n\/\/\/ it correctly for you.\n\nSQLQueryParms& operator <<(quote_only_type2 p, SQLString& in)\n{\n\tif (in.is_string) {\n\t\tSQLString in2;\n\t\tin2 = '\\'' + in + '\\'';\n\t\tin2.processed = true;\n\t\treturn *p.qparms << in2;\n\t}\n\telse {\n\t\tin.processed = true;\n\t\treturn *p.qparms << in;\n\t}\n}\n\n\n\/\/\/ \\brief Inserts a ColData with const string into a stream, quoted\n\/\/\/\n\/\/\/ Because ColData was designed to contain MySQL type data, we may\n\/\/\/ choose not to actually quote the data, if it is not needed.\n\ntemplate <>\nostream& operator <<(quote_only_type1 o, const ColData& in)\n{\n\tif (in.quote_q()) o.ostr->write(\"'\", 1);\n\to.ostr->write(in.data(), in.length());\n\tif (in.quote_q()) o.ostr->write(\"'\", 1);\n\n\treturn *o.ostr;\n}\n\n\n\/\/\/ \\brief Inserts a SQLString into a stream, double-quoting it (\")\n\/\/\/ unless it's data that needs no quoting.\n\/\/\/\n\/\/\/ We make the decision to quote the data based on the in.is_string\n\/\/\/ flag. You can set it yourself, but SQLString's ctors should set\n\/\/\/ it correctly for you.\n\nSQLQueryParms& operator <<(quote_double_only_type2 p, SQLString& in)\n{\n\tif (in.is_string) {\n\t\tSQLString in2;\n\t\tin2 = \"\\\"\" + in + \"\\\"\";\n\t\tin2.processed = true;\n\t\treturn *p.qparms << in2;\n\t}\n\telse {\n\t\tin.processed = true;\n\t\treturn *p.qparms << in;\n\t}\n}\n\n\n\/\/\/ \\brief Inserts a ColData with const string into a stream,\n\/\/\/ double-quoted (\")\n\/\/\/\n\/\/\/ Because ColData was designed to contain MySQL type data, we may\n\/\/\/ choose not to actually quote the data, if it is not needed.\n\ntemplate <>\nostream& operator <<(quote_double_only_type1 o, const ColData& in)\n{\n\tif (in.quote_q()) o.ostr->write(\"\\\"\", 1);\n\to.ostr->write(in.data(), in.length());\n\tif (in.quote_q()) o.ostr->write(\"\\\"\", 1);\n\n\treturn *o.ostr;\n}\n\n\nSQLQueryParms& operator <<(escape_type2 p, SQLString& in)\n{\n\tif (in.is_string && !in.dont_escape) {\n\t\tchar* s = new char[in.length() * 2 + 1];\n\t\tsize_t len = mysql_escape_string(s, in.data(), in.length());\n\n\t\tSQLString in2(s, len);\n\t\tin2.processed = true;\n\t\t*p.qparms << in2;\n\n\t\tdelete[] s;\n\t\treturn *p.qparms;\n\t}\n\telse {\n\t\tin.processed = true;\n\t\treturn *p.qparms << in;\n\t}\n}\n\n\n\/\/\/ \\brief Inserts a C++ string into a stream, escaping special SQL\n\/\/\/ characters\n\/\/\/\n\/\/\/ Because std::string lacks the type information we need, the string\n\/\/\/ is always escaped, even if it doesn't need it.\n\ntemplate <>\nstd::ostream& operator <<(escape_type1 o, const std::string& in)\n{\n\tchar* s = new char[in.length() * 2 + 1];\n\tsize_t len = mysql_escape_string(s, in.data(), in.length());\n\to.ostr->write(s, len);\n\tdelete[] s;\n\treturn *o.ostr;\n}\n\n\n\/\/\/ \\brief Inserts a C string into a stream, escaping special SQL\n\/\/\/ characters\n\/\/\/\n\/\/\/ Because C's type system lacks the information we need to second-\n\/\/\/ guess this manipulator, we always run the escaping algorithm on\n\/\/\/ the data, even if it's not needed.\n\ntemplate <>\nostream& operator <<(escape_type1 o, const char* const& in)\n{\n\tsize_t len = strlen(in);\n\tchar* s = new char[len * 2 + 1];\n\tlen = mysql_escape_string(s, in, len);\n\to.ostr->write(s, len);\n\tdelete[] s;\n\treturn *o.ostr;\n}\n\n\n\/\/\/ \\brief Inserts a ColData with const string into a stream, escaping\n\/\/\/ special SQL characters\n\/\/\/\n\/\/\/ Because ColData was designed to contain MySQL type data, we may\n\/\/\/ choose not to escape the data, if it is not needed.\n\nstd::ostream& operator <<(escape_type1 o, const ColData& in)\n{\n\tif (in.escape_q()) {\n\t\tchar* s = new char[in.length() * 2 + 1];\n\t\tsize_t len = mysql_escape_string(s, in.data(), in.length());\n\t\to.ostr->write(s, len);\n\t\tdelete[] s;\n\t}\n\telse {\n\t\to.ostr->write(in.data(), in.length());\n\t}\n\n\treturn *o.ostr;\n}\n\n\n\/\/\/ \\brief Inserts a SQLString into a stream, with no escaping or\n\/\/\/ quoting.\n\nSQLQueryParms& operator <<(do_nothing_type2 p, SQLString& in)\n{\n\tin.processed = true;\n\treturn *p.qparms << in;\n}\n\n\n\/\/\/ \\brief Inserts a SQLString into a stream, with no escaping or\n\/\/\/ quoting, and without marking the string as having been \"processed\".\n\nSQLQueryParms& operator <<(ignore_type2 p, SQLString& in)\n{\n\treturn *p.qparms << in;\n}\n\n} \/\/ end namespace mysqlpp\n\n<|endoftext|>"} {"text":"\/\/ sol2\n\n\/\/ The MIT License (MIT)\n\n\/\/ Copyright (c) 2013-2018 Rapptz, ThePhD and contributors\n\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy of\n\/\/ this software and associated documentation files (the \"Software\"), to deal in\n\/\/ the Software without restriction, including without limitation the rights to\n\/\/ use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\n\/\/ the Software, and to permit persons to whom the Software is furnished to do so,\n\/\/ subject to the following conditions:\n\n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n\/\/ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n\/\/ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n\/\/ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n\/\/ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#ifndef SOL_PROXY_HPP\n#define SOL_PROXY_HPP\n\n#include \"traits.hpp\"\n#include \"function.hpp\"\n#include \"protected_function.hpp\"\n#include \"proxy_base.hpp\"\n\nnamespace sol {\n\ttemplate \n\tstruct proxy : public proxy_base> {\n\tprivate:\n\t\ttypedef meta::condition, Key, std::tuple>, Key&, meta::unqualified_t>>> key_type;\n\n\t\ttemplate \n\t\tdecltype(auto) tuple_get(std::index_sequence) const {\n\t\t\treturn tbl.template traverse_get(std::get(key)...);\n\t\t}\n\n\t\ttemplate \n\t\tvoid tuple_set(std::index_sequence, T&& value) {\n\t\t\ttbl.traverse_set(std::get(key)..., std::forward(value));\n\t\t}\n\n\t\tauto setup_table(std::true_type) {\n\t\t\tauto p = stack::probe_get_field, global_table>::value>(lua_state(), key, tbl.stack_index());\n\t\t\tlua_pop(lua_state(), p.levels);\n\t\t\treturn p;\n\t\t}\n\n\t\tbool is_valid(std::false_type) {\n\t\t\tauto pp = stack::push_pop(tbl);\n\t\t\tauto p = stack::probe_get_field, global_table>::value>(lua_state(), key, lua_gettop(lua_state()));\n\t\t\tlua_pop(lua_state(), p.levels);\n\t\t\treturn p;\n\t\t}\n\n\tpublic:\n\t\tTable tbl;\n\t\tkey_type key;\n\n\t\ttemplate \n\t\tproxy(Table table, T&& k)\n\t\t: tbl(table), key(std::forward(k)) {\n\t\t}\n\n\t\ttemplate \n\t\tproxy& set(T&& item) {\n\t\t\ttuple_set(std::make_index_sequence>::value>(), std::forward(item));\n\t\t\treturn *this;\n\t\t}\n\n\t\ttemplate \n\t\tproxy& set_function(Args&&... args) {\n\t\t\ttbl.set_function(key, std::forward(args)...);\n\t\t\treturn *this;\n\t\t}\n\n\t\ttemplate >>, meta::is_callable>> = meta::enabler>\n\t\tproxy& operator=(U&& other) {\n\t\t\treturn set_function(std::forward(other));\n\t\t}\n\n\t\ttemplate >>, meta::is_callable>> = meta::enabler>\n\t\tproxy& operator=(U&& other) {\n\t\t\treturn set(std::forward(other));\n\t\t}\n\n\t\ttemplate \n\t\tproxy& operator=(std::initializer_list other) {\n\t\t\treturn set(std::move(other));\n\t\t}\n\n\t\ttemplate \n\t\tdecltype(auto) get() const {\n\t\t\treturn tuple_get(std::make_index_sequence>::value>());\n\t\t}\n\n\t\ttemplate \n\t\tdecltype(auto) get_or(T&& otherwise) const {\n\t\t\ttypedef decltype(get()) U;\n\t\t\toptional option = get>();\n\t\t\tif (option) {\n\t\t\t\treturn static_cast(option.value());\n\t\t\t}\n\t\t\treturn static_cast(std::forward(otherwise));\n\t\t}\n\n\t\ttemplate \n\t\tdecltype(auto) get_or(D&& otherwise) const {\n\t\t\toptional option = get>();\n\t\t\tif (option) {\n\t\t\t\treturn static_cast(option.value());\n\t\t\t}\n\t\t\treturn static_cast(std::forward(otherwise));\n\t\t}\n\n\t\t\n\t\ttemplate \n\t\tdecltype(auto) get_or_create() {\n\t\t\treturn get_or_create(new_table());\n\t\t}\n\n\t\ttemplate \n\t\tdecltype(auto) get_or_create(Otherwise&& other) {\n\t\t\tif (!this->valid()) {\n\t\t\t\tthis->set(std::forward(other));\n\t\t\t}\n\t\t\treturn get();\n\t\t}\n\n\t\ttemplate \n\t\tdecltype(auto) operator[](K&& k) const {\n\t\t\tauto keys = meta::tuplefy(key, std::forward(k));\n\t\t\treturn proxy(tbl, std::move(keys));\n\t\t}\n\n\t\ttemplate \n\t\tdecltype(auto) call(Args&&... args) {\n#if !defined(__clang__) && defined(_MSC_FULL_VER) && _MSC_FULL_VER >= 191200000\n\t\t\t\/\/ MSVC is ass sometimes\n\t\t\treturn get().call(std::forward(args)...);\n#else\n\t\t\treturn get().template call(std::forward(args)...);\n#endif\n\t\t}\n\n\t\ttemplate \n\t\tdecltype(auto) operator()(Args&&... args) {\n\t\t\treturn call<>(std::forward(args)...);\n\t\t}\n\n\t\tbool valid() const {\n\t\t\tauto pp = stack::push_pop(tbl);\n\t\t\tauto p = stack::probe_get_field, global_table>::value>(lua_state(), key, lua_gettop(lua_state()));\n\t\t\tlua_pop(lua_state(), p.levels);\n\t\t\treturn p;\n\t\t}\n\n\t\tint push() const noexcept {\n\t\t\treturn push(this->lua_state());\n\t\t}\n\n\t\tint push(lua_State* L) const noexcept {\n\t\t\treturn get().push(L);\n\t\t}\n\n\t\ttype get_type() const {\n\t\t\ttype t = type::none;\n\t\t\tauto pp = stack::push_pop(tbl);\n\t\t\tauto p = stack::probe_get_field, global_table>::value>(lua_state(), key, lua_gettop(lua_state()));\n\t\t\tif (p) {\n\t\t\t\tt = type_of(lua_state(), -1);\n\t\t\t}\n\t\t\tlua_pop(lua_state(), p.levels);\n\t\t\treturn t;\n\t\t}\n\n\t\tlua_State* lua_state() const {\n\t\t\treturn tbl.lua_state();\n\t\t}\n\n\t\tproxy& force() {\n\t\t\tif (this->valid()) {\n\t\t\t\tthis->set(new_table());\n\t\t\t}\n\t\t\treturn *this;\n\t\t}\n\t};\n\n\ttemplate \n\tinline bool operator==(T&& left, const proxy& right) {\n\t\ttypedef decltype(stack::get(nullptr, 0)) U;\n\t\treturn right.template get>() == left;\n\t}\n\n\ttemplate \n\tinline bool operator==(const proxy& right, T&& left) {\n\t\ttypedef decltype(stack::get(nullptr, 0)) U;\n\t\treturn right.template get>() == left;\n\t}\n\n\ttemplate \n\tinline bool operator!=(T&& left, const proxy& right) {\n\t\ttypedef decltype(stack::get(nullptr, 0)) U;\n\t\treturn right.template get>() != left;\n\t}\n\n\ttemplate \n\tinline bool operator!=(const proxy& right, T&& left) {\n\t\ttypedef decltype(stack::get(nullptr, 0)) U;\n\t\treturn right.template get>() != left;\n\t}\n\n\ttemplate \n\tinline bool operator==(lua_nil_t, const proxy& right) {\n\t\treturn !right.valid();\n\t}\n\n\ttemplate \n\tinline bool operator==(const proxy& right, lua_nil_t) {\n\t\treturn !right.valid();\n\t}\n\n\ttemplate \n\tinline bool operator!=(lua_nil_t, const proxy& right) {\n\t\treturn right.valid();\n\t}\n\n\ttemplate \n\tinline bool operator!=(const proxy& right, lua_nil_t) {\n\t\treturn right.valid();\n\t}\n\n\ttemplate \n\ttemplate \n\tbasic_reference& basic_reference::operator=(proxy_base&& r) {\n\t\tbasic_reference v = r;\n\t\tthis->operator=(std::move(v));\n\t\treturn *this;\n\t}\n\n\ttemplate \n\ttemplate \n\tbasic_reference& basic_reference::operator=(const proxy_base& r) {\n\t\tbasic_reference v = r;\n\t\tthis->operator=(std::move(v));\n\t\treturn *this;\n\t}\n\n\tnamespace stack {\n\t\ttemplate \n\t\tstruct pusher> {\n\t\t\tstatic int push(lua_State* L, const proxy& p) {\n\t\t\t\treference r = p;\n\t\t\t\treturn r.push(L);\n\t\t\t}\n\t\t};\n\t} \/\/ namespace stack\n} \/\/ namespace sol\n\n#endif \/\/ SOL_PROXY_HPP\nInvert boolean check in proxy::force()\/\/ sol2\n\n\/\/ The MIT License (MIT)\n\n\/\/ Copyright (c) 2013-2018 Rapptz, ThePhD and contributors\n\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy of\n\/\/ this software and associated documentation files (the \"Software\"), to deal in\n\/\/ the Software without restriction, including without limitation the rights to\n\/\/ use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\n\/\/ the Software, and to permit persons to whom the Software is furnished to do so,\n\/\/ subject to the following conditions:\n\n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n\/\/ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n\/\/ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n\/\/ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n\/\/ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#ifndef SOL_PROXY_HPP\n#define SOL_PROXY_HPP\n\n#include \"traits.hpp\"\n#include \"function.hpp\"\n#include \"protected_function.hpp\"\n#include \"proxy_base.hpp\"\n\nnamespace sol {\n\ttemplate \n\tstruct proxy : public proxy_base> {\n\tprivate:\n\t\ttypedef meta::condition, Key, std::tuple>, Key&, meta::unqualified_t>>> key_type;\n\n\t\ttemplate \n\t\tdecltype(auto) tuple_get(std::index_sequence) const {\n\t\t\treturn tbl.template traverse_get(std::get(key)...);\n\t\t}\n\n\t\ttemplate \n\t\tvoid tuple_set(std::index_sequence, T&& value) {\n\t\t\ttbl.traverse_set(std::get(key)..., std::forward(value));\n\t\t}\n\n\t\tauto setup_table(std::true_type) {\n\t\t\tauto p = stack::probe_get_field, global_table>::value>(lua_state(), key, tbl.stack_index());\n\t\t\tlua_pop(lua_state(), p.levels);\n\t\t\treturn p;\n\t\t}\n\n\t\tbool is_valid(std::false_type) {\n\t\t\tauto pp = stack::push_pop(tbl);\n\t\t\tauto p = stack::probe_get_field, global_table>::value>(lua_state(), key, lua_gettop(lua_state()));\n\t\t\tlua_pop(lua_state(), p.levels);\n\t\t\treturn p;\n\t\t}\n\n\tpublic:\n\t\tTable tbl;\n\t\tkey_type key;\n\n\t\ttemplate \n\t\tproxy(Table table, T&& k)\n\t\t: tbl(table), key(std::forward(k)) {\n\t\t}\n\n\t\ttemplate \n\t\tproxy& set(T&& item) {\n\t\t\ttuple_set(std::make_index_sequence>::value>(), std::forward(item));\n\t\t\treturn *this;\n\t\t}\n\n\t\ttemplate \n\t\tproxy& set_function(Args&&... args) {\n\t\t\ttbl.set_function(key, std::forward(args)...);\n\t\t\treturn *this;\n\t\t}\n\n\t\ttemplate >>, meta::is_callable>> = meta::enabler>\n\t\tproxy& operator=(U&& other) {\n\t\t\treturn set_function(std::forward(other));\n\t\t}\n\n\t\ttemplate >>, meta::is_callable>> = meta::enabler>\n\t\tproxy& operator=(U&& other) {\n\t\t\treturn set(std::forward(other));\n\t\t}\n\n\t\ttemplate \n\t\tproxy& operator=(std::initializer_list other) {\n\t\t\treturn set(std::move(other));\n\t\t}\n\n\t\ttemplate \n\t\tdecltype(auto) get() const {\n\t\t\treturn tuple_get(std::make_index_sequence>::value>());\n\t\t}\n\n\t\ttemplate \n\t\tdecltype(auto) get_or(T&& otherwise) const {\n\t\t\ttypedef decltype(get()) U;\n\t\t\toptional option = get>();\n\t\t\tif (option) {\n\t\t\t\treturn static_cast(option.value());\n\t\t\t}\n\t\t\treturn static_cast(std::forward(otherwise));\n\t\t}\n\n\t\ttemplate \n\t\tdecltype(auto) get_or(D&& otherwise) const {\n\t\t\toptional option = get>();\n\t\t\tif (option) {\n\t\t\t\treturn static_cast(option.value());\n\t\t\t}\n\t\t\treturn static_cast(std::forward(otherwise));\n\t\t}\n\n\t\t\n\t\ttemplate \n\t\tdecltype(auto) get_or_create() {\n\t\t\treturn get_or_create(new_table());\n\t\t}\n\n\t\ttemplate \n\t\tdecltype(auto) get_or_create(Otherwise&& other) {\n\t\t\tif (!this->valid()) {\n\t\t\t\tthis->set(std::forward(other));\n\t\t\t}\n\t\t\treturn get();\n\t\t}\n\n\t\ttemplate \n\t\tdecltype(auto) operator[](K&& k) const {\n\t\t\tauto keys = meta::tuplefy(key, std::forward(k));\n\t\t\treturn proxy(tbl, std::move(keys));\n\t\t}\n\n\t\ttemplate \n\t\tdecltype(auto) call(Args&&... args) {\n#if !defined(__clang__) && defined(_MSC_FULL_VER) && _MSC_FULL_VER >= 191200000\n\t\t\t\/\/ MSVC is ass sometimes\n\t\t\treturn get().call(std::forward(args)...);\n#else\n\t\t\treturn get().template call(std::forward(args)...);\n#endif\n\t\t}\n\n\t\ttemplate \n\t\tdecltype(auto) operator()(Args&&... args) {\n\t\t\treturn call<>(std::forward(args)...);\n\t\t}\n\n\t\tbool valid() const {\n\t\t\tauto pp = stack::push_pop(tbl);\n\t\t\tauto p = stack::probe_get_field, global_table>::value>(lua_state(), key, lua_gettop(lua_state()));\n\t\t\tlua_pop(lua_state(), p.levels);\n\t\t\treturn p;\n\t\t}\n\n\t\tint push() const noexcept {\n\t\t\treturn push(this->lua_state());\n\t\t}\n\n\t\tint push(lua_State* L) const noexcept {\n\t\t\treturn get().push(L);\n\t\t}\n\n\t\ttype get_type() const {\n\t\t\ttype t = type::none;\n\t\t\tauto pp = stack::push_pop(tbl);\n\t\t\tauto p = stack::probe_get_field, global_table>::value>(lua_state(), key, lua_gettop(lua_state()));\n\t\t\tif (p) {\n\t\t\t\tt = type_of(lua_state(), -1);\n\t\t\t}\n\t\t\tlua_pop(lua_state(), p.levels);\n\t\t\treturn t;\n\t\t}\n\n\t\tlua_State* lua_state() const {\n\t\t\treturn tbl.lua_state();\n\t\t}\n\n\t\tproxy& force() {\n\t\t\tif (!this->valid()) {\n\t\t\t\tthis->set(new_table());\n\t\t\t}\n\t\t\treturn *this;\n\t\t}\n\t};\n\n\ttemplate \n\tinline bool operator==(T&& left, const proxy& right) {\n\t\ttypedef decltype(stack::get(nullptr, 0)) U;\n\t\treturn right.template get>() == left;\n\t}\n\n\ttemplate \n\tinline bool operator==(const proxy& right, T&& left) {\n\t\ttypedef decltype(stack::get(nullptr, 0)) U;\n\t\treturn right.template get>() == left;\n\t}\n\n\ttemplate \n\tinline bool operator!=(T&& left, const proxy& right) {\n\t\ttypedef decltype(stack::get(nullptr, 0)) U;\n\t\treturn right.template get>() != left;\n\t}\n\n\ttemplate \n\tinline bool operator!=(const proxy& right, T&& left) {\n\t\ttypedef decltype(stack::get(nullptr, 0)) U;\n\t\treturn right.template get>() != left;\n\t}\n\n\ttemplate \n\tinline bool operator==(lua_nil_t, const proxy& right) {\n\t\treturn !right.valid();\n\t}\n\n\ttemplate \n\tinline bool operator==(const proxy& right, lua_nil_t) {\n\t\treturn !right.valid();\n\t}\n\n\ttemplate \n\tinline bool operator!=(lua_nil_t, const proxy& right) {\n\t\treturn right.valid();\n\t}\n\n\ttemplate \n\tinline bool operator!=(const proxy& right, lua_nil_t) {\n\t\treturn right.valid();\n\t}\n\n\ttemplate \n\ttemplate \n\tbasic_reference& basic_reference::operator=(proxy_base&& r) {\n\t\tbasic_reference v = r;\n\t\tthis->operator=(std::move(v));\n\t\treturn *this;\n\t}\n\n\ttemplate \n\ttemplate \n\tbasic_reference& basic_reference::operator=(const proxy_base& r) {\n\t\tbasic_reference v = r;\n\t\tthis->operator=(std::move(v));\n\t\treturn *this;\n\t}\n\n\tnamespace stack {\n\t\ttemplate \n\t\tstruct pusher> {\n\t\t\tstatic int push(lua_State* L, const proxy& p) {\n\t\t\t\treference r = p;\n\t\t\t\treturn r.push(L);\n\t\t\t}\n\t\t};\n\t} \/\/ namespace stack\n} \/\/ namespace sol\n\n#endif \/\/ SOL_PROXY_HPP\n<|endoftext|>"} {"text":"\/*\n * Copyright 2010, Nikhil Marathe All rights reserved.\n * See LICENSE for details.\n*\/\n#include \"sasljs.h\"\n\n#include \n#include \n#include \n#include \n\nusing namespace v8;\nusing namespace node;\n\n\/*\n * Macro from the sqlite3 bindings\n * http:\/\/github.com\/grumdrig\/node-sqlite\/blob\/master\/sqlite3_bindings.cc\n * by Eric Fredricksen\n *\/\n#define REQ_STR_ARG(I, VAR) \\\n if (args.Length() <= (I) || !args[I]->IsString()) \\\n return ThrowException(Exception::TypeError( \\\n String::New(\"Argument \" #I \" must be a string\"))); \\\n String::Utf8Value VAR(args[I]->ToString());\n\nnamespace sasljs {\nvoid ServerSession::Initialize ( Handle target )\n{\n v8::HandleScope scope;\n\n v8::Local t = v8::FunctionTemplate::New(New);\n\n t->InstanceTemplate()->SetInternalFieldCount(1);\n\n \/\/ error codes\n NODE_DEFINE_CONSTANT( target, GSASL_OK );\n NODE_DEFINE_CONSTANT( target, GSASL_NEEDS_MORE );\n NODE_DEFINE_CONSTANT( target, GSASL_UNKNOWN_MECHANISM );\n NODE_DEFINE_CONSTANT( target, GSASL_MECHANISM_CALLED_TOO_MANY_TIMES );\n NODE_DEFINE_CONSTANT( target, GSASL_MALLOC_ERROR );\n NODE_DEFINE_CONSTANT( target, GSASL_BASE64_ERROR );\n NODE_DEFINE_CONSTANT( target, GSASL_CRYPTO_ERROR );\n NODE_DEFINE_CONSTANT( target, GSASL_SASLPREP_ERROR );\n NODE_DEFINE_CONSTANT( target, GSASL_MECHANISM_PARSE_ERROR );\n NODE_DEFINE_CONSTANT( target, GSASL_AUTHENTICATION_ERROR );\n NODE_DEFINE_CONSTANT( target, GSASL_INTEGRITY_ERROR );\n NODE_DEFINE_CONSTANT( target, GSASL_NO_CLIENT_CODE );\n NODE_DEFINE_CONSTANT( target, GSASL_NO_SERVER_CODE );\n NODE_DEFINE_CONSTANT( target, GSASL_NO_CALLBACK );\n NODE_DEFINE_CONSTANT( target, GSASL_NO_ANONYMOUS_TOKEN );\n NODE_DEFINE_CONSTANT( target, GSASL_NO_AUTHID );\n NODE_DEFINE_CONSTANT( target, GSASL_NO_AUTHZID );\n NODE_DEFINE_CONSTANT( target, GSASL_NO_PASSWORD );\n NODE_DEFINE_CONSTANT( target, GSASL_NO_PASSCODE );\n NODE_DEFINE_CONSTANT( target, GSASL_NO_PIN );\n NODE_DEFINE_CONSTANT( target, GSASL_NO_SERVICE );\n NODE_DEFINE_CONSTANT( target, GSASL_NO_HOSTNAME );\n NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_RELEASE_BUFFER_ERROR );\n NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_IMPORT_NAME_ERROR );\n NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_INIT_SEC_CONTEXT_ERROR );\n NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_ACCEPT_SEC_CONTEXT_ERROR );\n NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_UNWRAP_ERROR );\n NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_WRAP_ERROR );\n NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_ACQUIRE_CRED_ERROR );\n NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_DISPLAY_NAME_ERROR );\n NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_UNSUPPORTED_PROTECTION_ERROR );\n NODE_DEFINE_CONSTANT( target, GSASL_KERBEROS_V5_INIT_ERROR );\n NODE_DEFINE_CONSTANT( target, GSASL_KERBEROS_V5_INTERNAL_ERROR );\n NODE_DEFINE_CONSTANT( target, GSASL_SHISHI_ERROR );\n NODE_DEFINE_CONSTANT( target, GSASL_SECURID_SERVER_NEED_ADDITIONAL_PASSCODE );\n NODE_DEFINE_CONSTANT( target, GSASL_SECURID_SERVER_NEED_NEW_PIN );\n\n \/\/ property constants\n NODE_DEFINE_CONSTANT( target, GSASL_AUTHID );\n NODE_DEFINE_CONSTANT( target, GSASL_AUTHZID );\n NODE_DEFINE_CONSTANT( target, GSASL_PASSWORD );\n NODE_DEFINE_CONSTANT( target, GSASL_ANONYMOUS_TOKEN );\n NODE_DEFINE_CONSTANT( target, GSASL_SERVICE );\n NODE_DEFINE_CONSTANT( target, GSASL_HOSTNAME );\n NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_DISPLAY_NAME );\n NODE_DEFINE_CONSTANT( target, GSASL_PASSCODE );\n NODE_DEFINE_CONSTANT( target, GSASL_SUGGESTED_PIN );\n NODE_DEFINE_CONSTANT( target, GSASL_PIN );\n NODE_DEFINE_CONSTANT( target, GSASL_REALM );\n NODE_DEFINE_CONSTANT( target, GSASL_DIGEST_MD5_HASHED_PASSWORD );\n NODE_DEFINE_CONSTANT( target, GSASL_QOPS );\n NODE_DEFINE_CONSTANT( target, GSASL_QOP );\n NODE_DEFINE_CONSTANT( target, GSASL_SCRAM_ITER );\n NODE_DEFINE_CONSTANT( target, GSASL_SCRAM_SALT );\n NODE_DEFINE_CONSTANT( target, GSASL_SCRAM_SALTED_PASSWORD );\n NODE_DEFINE_CONSTANT( target, GSASL_VALIDATE_SIMPLE );\n NODE_DEFINE_CONSTANT( target, GSASL_VALIDATE_EXTERNAL );\n NODE_DEFINE_CONSTANT( target, GSASL_VALIDATE_ANONYMOUS );\n NODE_DEFINE_CONSTANT( target, GSASL_VALIDATE_GSSAPI );\n NODE_DEFINE_CONSTANT( target, GSASL_VALIDATE_SECURID );\n\n NODE_SET_PROTOTYPE_METHOD( t, \"_mechanisms\", GetMechanisms );\n NODE_SET_PROTOTYPE_METHOD( t, \"start\", Start );\n NODE_SET_PROTOTYPE_METHOD( t, \"step\", Step );\n\n target->Set( v8::String::NewSymbol( \"ServerSession\"), t->GetFunction() );\n}\n\n\/*\n * Call in JS\n * new ServerSession( \"service name\" );\n * All other options default to NULL for now\n *\/\nv8::Handle\nServerSession::New (const v8::Arguments& args)\n{\n HandleScope scope;\n\n REQ_STR_ARG( 0, realm );\n\n if( args.Length() <= 1 || !args[1]->IsFunction() ) {\n return ThrowException(Exception::TypeError(\n String::New(\"Argument 1 must be a callback\")));\n }\n\n ServerSession *server = new ServerSession( *realm, cb_persist( args[1] ) );\n server->Wrap( args.This() );\n return args.This();\n}\n\nServerSession::ServerSession( const char *realm, Persistent *cb )\n : ObjectWrap()\n , m_session( NULL )\n , m_callback( cb )\n{\n}\n\nServerSession::~ServerSession()\n{\n}\n\nHandle\nServerSession::GetMechanisms( const v8::Arguments &args )\n{\n ServerSession *sc = Unwrap( args.This() );\n\n char *result;\n \n int mechres = gsasl_server_mechlist( ctx, &result );\n if( mechres != GSASL_OK ) {\n return String::New( \"\" );\n }\n\n Handle ret = String::New( result, strlen( result ) );\n free( result );\n return ret;\n}\n\nint\nServerSession::Callback( Gsasl *ctx, Gsasl_session *sctx, Gsasl_property prop )\n{\n ServerSession *sc = static_cast(gsasl_session_hook_get( sctx ));\n assert( sc );\n\n Local argv[] = { Integer::New( prop ) };\n Local ret = (*sc->m_callback)->Call( Context::GetCurrent()->Global(), 1, argv );\n if( ret->IsString() ) {\n gsasl_property_set( sctx, prop, *String::Utf8Value(ret->ToString()) );\n return GSASL_OK;\n }\n return GSASL_NO_CALLBACK;\n}\n\n\/**\n * Returns a map\n * { status: integer_error_code,\n * data : data to send to client if error == GSASL_OK }\n *\/\nv8::Handle\nServerSession::Start( const v8::Arguments &args )\n{\n REQ_STR_ARG( 0, mechanismString );\n\n int res;\n\n ServerSession *sc = Unwrap( args.This() );\n if( sc->m_session != NULL ) {\n return ThrowException( Exception::Error( String::New( \"sasljs: This session is already started!\" ) ) );\n }\n\n res = gsasl_server_start( ctx, *mechanismString, &sc->m_session );\n gsasl_session_hook_set( sc->m_session, sc );\n gsasl_callback_set( ctx, sc->Callback );\n\n return Integer::New( res );\n}\n\nv8::Handle\nServerSession::Step( const v8::Arguments &args )\n{\n REQ_STR_ARG( 0, clientinString );\n\n ServerSession *sc = Unwrap( args.This() );\n\n char *reply;\n size_t len;\n\n char *b64;\n size_t crap;\n gsasl_base64_from( *clientinString, strlen( *clientinString ), &b64, &crap );\n std::cerr << std::endl << \"sasljs: step: \" << b64 << std::endl;\n\n gsasl_base64_from( *clientinString, strlen(*clientinString), &reply, &len );\n int res = gsasl_step64( sc->m_session, *clientinString, &reply );\n\n Handle obj = Object::New();\n Local status = String::New( \"status\" );\n\n char *d64;\n gsasl_base64_from( reply, strlen(reply), &d64, &len );\n std::cerr << std::endl << \"sasljs: step OUT: \" << d64 << std::endl;\n\n if( res == GSASL_OK || res == GSASL_NEEDS_MORE ) {\n obj->Set( status, Integer::New( res ) );\n obj->Set( String::New( \"data\" ), String::New( reply, strlen( reply ) ) );\n\n return obj;\n }\n else {\n obj->Set( status, Integer::New( res ) );\n obj->Set( String::New( \"data\" ), String::New( gsasl_strerror( res ) ) );\n return obj;\n }\n}\n}\n\nextern \"C\" void\ninit (Handle target)\n{\n HandleScope scope;\n\n sasljs::ctx = NULL;\n int initres = gsasl_init( &sasljs::ctx );\n\n if( initres != GSASL_OK ) {\n fprintf( stderr, \"Could not initialize gsasl: %s\\n\", gsasl_strerror( initres ) );\n abort();\n }\n\n sasljs::ServerSession::Initialize(target);\n}\nSet 'this' of callback function to session object\/*\n * Copyright 2010, Nikhil Marathe All rights reserved.\n * See LICENSE for details.\n*\/\n#include \"sasljs.h\"\n\n#include \n#include \n#include \n#include \n\nusing namespace v8;\nusing namespace node;\n\n\/*\n * Macro from the sqlite3 bindings\n * http:\/\/github.com\/grumdrig\/node-sqlite\/blob\/master\/sqlite3_bindings.cc\n * by Eric Fredricksen\n *\/\n#define REQ_STR_ARG(I, VAR) \\\n if (args.Length() <= (I) || !args[I]->IsString()) \\\n return ThrowException(Exception::TypeError( \\\n String::New(\"Argument \" #I \" must be a string\"))); \\\n String::Utf8Value VAR(args[I]->ToString());\n\nnamespace sasljs {\nvoid ServerSession::Initialize ( Handle target )\n{\n v8::HandleScope scope;\n\n v8::Local t = v8::FunctionTemplate::New(New);\n\n t->InstanceTemplate()->SetInternalFieldCount(1);\n\n \/\/ error codes\n NODE_DEFINE_CONSTANT( target, GSASL_OK );\n NODE_DEFINE_CONSTANT( target, GSASL_NEEDS_MORE );\n NODE_DEFINE_CONSTANT( target, GSASL_UNKNOWN_MECHANISM );\n NODE_DEFINE_CONSTANT( target, GSASL_MECHANISM_CALLED_TOO_MANY_TIMES );\n NODE_DEFINE_CONSTANT( target, GSASL_MALLOC_ERROR );\n NODE_DEFINE_CONSTANT( target, GSASL_BASE64_ERROR );\n NODE_DEFINE_CONSTANT( target, GSASL_CRYPTO_ERROR );\n NODE_DEFINE_CONSTANT( target, GSASL_SASLPREP_ERROR );\n NODE_DEFINE_CONSTANT( target, GSASL_MECHANISM_PARSE_ERROR );\n NODE_DEFINE_CONSTANT( target, GSASL_AUTHENTICATION_ERROR );\n NODE_DEFINE_CONSTANT( target, GSASL_INTEGRITY_ERROR );\n NODE_DEFINE_CONSTANT( target, GSASL_NO_CLIENT_CODE );\n NODE_DEFINE_CONSTANT( target, GSASL_NO_SERVER_CODE );\n NODE_DEFINE_CONSTANT( target, GSASL_NO_CALLBACK );\n NODE_DEFINE_CONSTANT( target, GSASL_NO_ANONYMOUS_TOKEN );\n NODE_DEFINE_CONSTANT( target, GSASL_NO_AUTHID );\n NODE_DEFINE_CONSTANT( target, GSASL_NO_AUTHZID );\n NODE_DEFINE_CONSTANT( target, GSASL_NO_PASSWORD );\n NODE_DEFINE_CONSTANT( target, GSASL_NO_PASSCODE );\n NODE_DEFINE_CONSTANT( target, GSASL_NO_PIN );\n NODE_DEFINE_CONSTANT( target, GSASL_NO_SERVICE );\n NODE_DEFINE_CONSTANT( target, GSASL_NO_HOSTNAME );\n NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_RELEASE_BUFFER_ERROR );\n NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_IMPORT_NAME_ERROR );\n NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_INIT_SEC_CONTEXT_ERROR );\n NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_ACCEPT_SEC_CONTEXT_ERROR );\n NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_UNWRAP_ERROR );\n NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_WRAP_ERROR );\n NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_ACQUIRE_CRED_ERROR );\n NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_DISPLAY_NAME_ERROR );\n NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_UNSUPPORTED_PROTECTION_ERROR );\n NODE_DEFINE_CONSTANT( target, GSASL_KERBEROS_V5_INIT_ERROR );\n NODE_DEFINE_CONSTANT( target, GSASL_KERBEROS_V5_INTERNAL_ERROR );\n NODE_DEFINE_CONSTANT( target, GSASL_SHISHI_ERROR );\n NODE_DEFINE_CONSTANT( target, GSASL_SECURID_SERVER_NEED_ADDITIONAL_PASSCODE );\n NODE_DEFINE_CONSTANT( target, GSASL_SECURID_SERVER_NEED_NEW_PIN );\n\n \/\/ property constants\n NODE_DEFINE_CONSTANT( target, GSASL_AUTHID );\n NODE_DEFINE_CONSTANT( target, GSASL_AUTHZID );\n NODE_DEFINE_CONSTANT( target, GSASL_PASSWORD );\n NODE_DEFINE_CONSTANT( target, GSASL_ANONYMOUS_TOKEN );\n NODE_DEFINE_CONSTANT( target, GSASL_SERVICE );\n NODE_DEFINE_CONSTANT( target, GSASL_HOSTNAME );\n NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_DISPLAY_NAME );\n NODE_DEFINE_CONSTANT( target, GSASL_PASSCODE );\n NODE_DEFINE_CONSTANT( target, GSASL_SUGGESTED_PIN );\n NODE_DEFINE_CONSTANT( target, GSASL_PIN );\n NODE_DEFINE_CONSTANT( target, GSASL_REALM );\n NODE_DEFINE_CONSTANT( target, GSASL_DIGEST_MD5_HASHED_PASSWORD );\n NODE_DEFINE_CONSTANT( target, GSASL_QOPS );\n NODE_DEFINE_CONSTANT( target, GSASL_QOP );\n NODE_DEFINE_CONSTANT( target, GSASL_SCRAM_ITER );\n NODE_DEFINE_CONSTANT( target, GSASL_SCRAM_SALT );\n NODE_DEFINE_CONSTANT( target, GSASL_SCRAM_SALTED_PASSWORD );\n NODE_DEFINE_CONSTANT( target, GSASL_VALIDATE_SIMPLE );\n NODE_DEFINE_CONSTANT( target, GSASL_VALIDATE_EXTERNAL );\n NODE_DEFINE_CONSTANT( target, GSASL_VALIDATE_ANONYMOUS );\n NODE_DEFINE_CONSTANT( target, GSASL_VALIDATE_GSSAPI );\n NODE_DEFINE_CONSTANT( target, GSASL_VALIDATE_SECURID );\n\n NODE_SET_PROTOTYPE_METHOD( t, \"_mechanisms\", GetMechanisms );\n NODE_SET_PROTOTYPE_METHOD( t, \"start\", Start );\n NODE_SET_PROTOTYPE_METHOD( t, \"step\", Step );\n\n target->Set( v8::String::NewSymbol( \"ServerSession\"), t->GetFunction() );\n}\n\n\/*\n * Call in JS\n * new ServerSession( \"service name\" );\n * All other options default to NULL for now\n *\/\nv8::Handle\nServerSession::New (const v8::Arguments& args)\n{\n HandleScope scope;\n\n REQ_STR_ARG( 0, realm );\n\n if( args.Length() <= 1 || !args[1]->IsFunction() ) {\n return ThrowException(Exception::TypeError(\n String::New(\"Argument 1 must be a callback\")));\n }\n\n ServerSession *server = new ServerSession( *realm, cb_persist( args[1] ) );\n server->Wrap( args.This() );\n return args.This();\n}\n\nServerSession::ServerSession( const char *realm, Persistent *cb )\n : ObjectWrap()\n , m_session( NULL )\n , m_callback( cb )\n{\n}\n\nServerSession::~ServerSession()\n{\n}\n\nHandle\nServerSession::GetMechanisms( const v8::Arguments &args )\n{\n ServerSession *sc = Unwrap( args.This() );\n\n char *result;\n \n int mechres = gsasl_server_mechlist( ctx, &result );\n if( mechres != GSASL_OK ) {\n return String::New( \"\" );\n }\n\n Handle ret = String::New( result, strlen( result ) );\n free( result );\n return ret;\n}\n\nint\nServerSession::Callback( Gsasl *ctx, Gsasl_session *sctx, Gsasl_property prop )\n{\n ServerSession *sc = static_cast(gsasl_session_hook_get( sctx ));\n assert( sc );\n\n Local argv[] = { Integer::New( prop ) };\n Local ret = (*sc->m_callback)->Call( sc->handle_, 1, argv );\n if( ret->IsString() ) {\n gsasl_property_set( sctx, prop, *String::Utf8Value(ret->ToString()) );\n return GSASL_OK;\n }\n return GSASL_NO_CALLBACK;\n}\n\n\/**\n * Returns a map\n * { status: integer_error_code,\n * data : data to send to client if error == GSASL_OK }\n *\/\nv8::Handle\nServerSession::Start( const v8::Arguments &args )\n{\n REQ_STR_ARG( 0, mechanismString );\n\n int res;\n\n ServerSession *sc = Unwrap( args.This() );\n if( sc->m_session != NULL ) {\n return ThrowException( Exception::Error( String::New( \"sasljs: This session is already started!\" ) ) );\n }\n\n res = gsasl_server_start( ctx, *mechanismString, &sc->m_session );\n gsasl_session_hook_set( sc->m_session, sc );\n gsasl_callback_set( ctx, sc->Callback );\n\n return Integer::New( res );\n}\n\nv8::Handle\nServerSession::Step( const v8::Arguments &args )\n{\n REQ_STR_ARG( 0, clientinString );\n\n ServerSession *sc = Unwrap( args.This() );\n\n char *reply;\n size_t len;\n\n char *b64;\n size_t crap;\n gsasl_base64_from( *clientinString, strlen( *clientinString ), &b64, &crap );\n std::cerr << std::endl << \"sasljs: step: \" << b64 << std::endl;\n\n gsasl_base64_from( *clientinString, strlen(*clientinString), &reply, &len );\n int res = gsasl_step64( sc->m_session, *clientinString, &reply );\n\n Handle obj = Object::New();\n Local status = String::New( \"status\" );\n\n char *d64;\n gsasl_base64_from( reply, strlen(reply), &d64, &len );\n std::cerr << std::endl << \"sasljs: step OUT: \" << d64 << std::endl;\n\n if( res == GSASL_OK || res == GSASL_NEEDS_MORE ) {\n obj->Set( status, Integer::New( res ) );\n obj->Set( String::New( \"data\" ), String::New( reply, strlen( reply ) ) );\n\n return obj;\n }\n else {\n obj->Set( status, Integer::New( res ) );\n obj->Set( String::New( \"data\" ), String::New( gsasl_strerror( res ) ) );\n return obj;\n }\n}\n}\n\nextern \"C\" void\ninit (Handle target)\n{\n HandleScope scope;\n\n sasljs::ctx = NULL;\n int initres = gsasl_init( &sasljs::ctx );\n\n if( initres != GSASL_OK ) {\n fprintf( stderr, \"Could not initialize gsasl: %s\\n\", gsasl_strerror( initres ) );\n abort();\n }\n\n sasljs::ServerSession::Initialize(target);\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Visualization Library\n Module: Filter.cc\n Language: C++\n Date: $Date$\n Version: $Revision$\n\nThis file is part of the Visualization Library. No part of this file or its \ncontents may be copied, reproduced or altered in any way without the express\nwritten consent of the authors.\n\nCopyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 \n\n=========================================================================*\/\n#include \"Filter.hh\"\n\n\/\/ Description:\n\/\/ Construct new filter without start or end methods.\nvlFilter::vlFilter()\n{\n this->Input = NULL;\n\n this->StartMethod = NULL;\n this->StartMethodArgDelete = NULL;\n this->StartMethodArg = NULL;\n this->EndMethod = NULL;\n this->EndMethodArgDelete = NULL;\n this->EndMethodArg = NULL;\n\n this->Updating = 0;\n}\n\nint vlFilter::GetDataReleased()\n{\n vl_ErrorMacro(<<\"Method should be implemented by subclass!\");\n return 1;\n}\n\nvoid vlFilter::SetDataReleased(int flag)\n{\n vl_ErrorMacro(<<\"Method should be implemented by subclass!\");\n}\n\n\/\/ Description:\n\/\/ Update input to this filter and the filter itself.\nvoid vlFilter::UpdateFilter()\n{\n \/\/ make sure input is available\n if ( !this->Input )\n {\n vl_ErrorMacro(<< \"No input!\");\n return;\n }\n\n \/\/ prevent chasing our tail\n if (this->Updating) return;\n\n this->Updating = 1;\n this->Input->Update();\n this->Updating = 0;\n\n if (this->Input->GetMTime() > this->_GetMTime() || \n this->_GetMTime() > this->ExecuteTime ||\n this->GetDataReleased() )\n {\n if ( this->StartMethod ) (*this->StartMethod)(this->StartMethodArg);\n this->Execute();\n this->ExecuteTime.Modified();\n this->SetDataReleased(0);\n if ( this->EndMethod ) (*this->EndMethod)(this->EndMethodArg);\n }\n\n if ( this->Input->ShouldIReleaseData() ) this->Input->ReleaseData();\n}\n\n\/\/ Description:\n\/\/ Set the filter start method. The start method is invoked before the \n\/\/ filter executes.\nvoid vlFilter::SetStartMethod(void (*f)(void *), void *arg)\n{\n if ( f != this->StartMethod || arg != this->StartMethodArg )\n {\n \/\/ delete the current arg if there is one and a delete meth\n if ((this->StartMethodArg)&&(this->StartMethodArgDelete))\n {\n (*this->StartMethodArgDelete)(this->StartMethodArg);\n }\n this->StartMethod = f;\n this->StartMethodArg = arg;\n this->_Modified();\n }\n}\n\n\/\/ Description:\n\/\/ Set the filter end method. The end method is invoked after the \n\/\/ filter executes.\nvoid vlFilter::SetEndMethod(void (*f)(void *), void *arg)\n{\n if ( f != this->EndMethod || arg != this->EndMethodArg )\n {\n \/\/ delete the current arg if there is one and a delete meth\n if ((this->EndMethodArg)&&(this->EndMethodArgDelete))\n {\n (*this->EndMethodArgDelete)(this->EndMethodArg);\n }\n this->EndMethod = f;\n this->EndMethodArg = arg;\n this->_Modified();\n }\n}\n\n\/\/ Description:\n\/\/ Set the arg delete method. This is used to free user memory.\nvoid vlFilter::SetStartMethodArgDelete(void (*f)(void *))\n{\n if ( f != this->StartMethodArgDelete)\n {\n this->StartMethodArgDelete = f;\n this->_Modified();\n }\n}\n\n\/\/ Description:\n\/\/ Set the arg delete method. This is used to free user memory.\nvoid vlFilter::SetEndMethodArgDelete(void (*f)(void *))\n{\n if ( f != this->EndMethodArgDelete)\n {\n this->EndMethodArgDelete = f;\n this->_Modified();\n }\n}\n\nvoid vlFilter::Execute()\n{\n cerr << \"Execution of filter should be in derived class\" << \"\\n\";\n}\n\nvoid vlFilter::_PrintSelf(ostream& os, vlIndent indent)\n{\n vlLWObject::_PrintSelf(os,indent);\n\n if ( this->StartMethod )\n {\n os << indent << \"Start Method: (\" << (void *)this->StartMethod << \")\\n\";\n }\n else\n {\n os << indent << \"Start Method: (none)\\n\";\n }\n\n if ( this->EndMethod )\n {\n os << indent << \"End Method: (\" << (void *)this->EndMethod << \")\\n\";\n }\n else\n {\n os << indent << \"End Method: (none)\\n\";\n }\n\n os << indent << \"Execute Time: \" <ExecuteTime.GetMTime() << \"\\n\";\n\n if ( this->Input )\n {\n os << indent << \"Input: (\" << (void *)this->Input << \")\\n\";\n }\n else\n {\n os << indent << \"Input: (none)\\n\";\n }\n}\n\nERR: Use appropriate error macro.\/*=========================================================================\n\n Program: Visualization Library\n Module: Filter.cc\n Language: C++\n Date: $Date$\n Version: $Revision$\n\nThis file is part of the Visualization Library. No part of this file or its \ncontents may be copied, reproduced or altered in any way without the express\nwritten consent of the authors.\n\nCopyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 \n\n=========================================================================*\/\n#include \"Filter.hh\"\n\n\/\/ Description:\n\/\/ Construct new filter without start or end methods.\nvlFilter::vlFilter()\n{\n this->Input = NULL;\n\n this->StartMethod = NULL;\n this->StartMethodArgDelete = NULL;\n this->StartMethodArg = NULL;\n this->EndMethod = NULL;\n this->EndMethodArgDelete = NULL;\n this->EndMethodArg = NULL;\n\n this->Updating = 0;\n}\n\nint vlFilter::GetDataReleased()\n{\n vl_ErrorMacro(<<\"Method should be implemented by subclass!\");\n return 1;\n}\n\nvoid vlFilter::SetDataReleased(int flag)\n{\n vl_ErrorMacro(<<\"Method should be implemented by subclass!\");\n}\n\n\/\/ Description:\n\/\/ Update input to this filter and the filter itself.\nvoid vlFilter::UpdateFilter()\n{\n \/\/ make sure input is available\n if ( !this->Input )\n {\n vl_ErrorMacro(<< \"No input!\");\n return;\n }\n\n \/\/ prevent chasing our tail\n if (this->Updating) return;\n\n this->Updating = 1;\n this->Input->Update();\n this->Updating = 0;\n\n if (this->Input->GetMTime() > this->_GetMTime() || \n this->_GetMTime() > this->ExecuteTime ||\n this->GetDataReleased() )\n {\n if ( this->StartMethod ) (*this->StartMethod)(this->StartMethodArg);\n this->Execute();\n this->ExecuteTime.Modified();\n this->SetDataReleased(0);\n if ( this->EndMethod ) (*this->EndMethod)(this->EndMethodArg);\n }\n\n if ( this->Input->ShouldIReleaseData() ) this->Input->ReleaseData();\n}\n\n\/\/ Description:\n\/\/ Set the filter start method. The start method is invoked before the \n\/\/ filter executes.\nvoid vlFilter::SetStartMethod(void (*f)(void *), void *arg)\n{\n if ( f != this->StartMethod || arg != this->StartMethodArg )\n {\n \/\/ delete the current arg if there is one and a delete meth\n if ((this->StartMethodArg)&&(this->StartMethodArgDelete))\n {\n (*this->StartMethodArgDelete)(this->StartMethodArg);\n }\n this->StartMethod = f;\n this->StartMethodArg = arg;\n this->_Modified();\n }\n}\n\n\/\/ Description:\n\/\/ Set the filter end method. The end method is invoked after the \n\/\/ filter executes.\nvoid vlFilter::SetEndMethod(void (*f)(void *), void *arg)\n{\n if ( f != this->EndMethod || arg != this->EndMethodArg )\n {\n \/\/ delete the current arg if there is one and a delete meth\n if ((this->EndMethodArg)&&(this->EndMethodArgDelete))\n {\n (*this->EndMethodArgDelete)(this->EndMethodArg);\n }\n this->EndMethod = f;\n this->EndMethodArg = arg;\n this->_Modified();\n }\n}\n\n\/\/ Description:\n\/\/ Set the arg delete method. This is used to free user memory.\nvoid vlFilter::SetStartMethodArgDelete(void (*f)(void *))\n{\n if ( f != this->StartMethodArgDelete)\n {\n this->StartMethodArgDelete = f;\n this->_Modified();\n }\n}\n\n\/\/ Description:\n\/\/ Set the arg delete method. This is used to free user memory.\nvoid vlFilter::SetEndMethodArgDelete(void (*f)(void *))\n{\n if ( f != this->EndMethodArgDelete)\n {\n this->EndMethodArgDelete = f;\n this->_Modified();\n }\n}\n\nvoid vlFilter::Execute()\n{\n vl_ErrorMacro(<< \"Execution of filter should be in derived class\");\n}\n\nvoid vlFilter::_PrintSelf(ostream& os, vlIndent indent)\n{\n vlLWObject::_PrintSelf(os,indent);\n\n if ( this->StartMethod )\n {\n os << indent << \"Start Method: (\" << (void *)this->StartMethod << \")\\n\";\n }\n else\n {\n os << indent << \"Start Method: (none)\\n\";\n }\n\n if ( this->EndMethod )\n {\n os << indent << \"End Method: (\" << (void *)this->EndMethod << \")\\n\";\n }\n else\n {\n os << indent << \"End Method: (none)\\n\";\n }\n\n os << indent << \"Execute Time: \" <ExecuteTime.GetMTime() << \"\\n\";\n\n if ( this->Input )\n {\n os << indent << \"Input: (\" << (void *)this->Input << \")\\n\";\n }\n else\n {\n os << indent << \"Input: (none)\\n\";\n }\n}\n\n<|endoftext|>"} {"text":"\/* Copyright (C) 2005-2011, Thorvald Natvig \n\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions\n are met:\n\n - Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n - Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n - Neither the name of the Mumble Developers nor the names of its\n contributors may be used to endorse or promote products derived from this\n software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR\n CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"murmur_pch.h\"\n\n#include \"Group.h\"\n\n#include \"Channel.h\"\n#include \"User.h\"\n#ifdef MURMUR\n#include \"ServerUser.h\"\n#endif\n\nGroup::Group(Channel *assoc, const QString &name) {\n\tc = assoc;\n\tbInherit = true;\n\tbInheritable = true;\n\tqsName = name;\n\tif (c)\n\t\tc->qhGroups[name] = this;\n}\n\n#ifdef MURMUR\n\nQSet Group::members() {\n\tQStack s;\n\tQSet m;\n\tChannel *p;\n\tGroup *g;\n\tint i;\n\n\tp = c;\n\twhile (p) {\n\t\tg = p->qhGroups.value(qsName);\n\t\tif (g) {\n\t\t\tif ((p != c) && ! g->bInheritable)\n\t\t\t\tbreak;\n\t\t\ts.push(g);\n\t\t\tif (! g->bInherit)\n\t\t\t\tbreak;\n\t\t}\n\t\tp = p->cParent;\n\t}\n\n\twhile (! s.isEmpty()) {\n\t\tg = s.pop();\n\t\tforeach(i, g->qsAdd)\n\t\t\tm.insert(i);\n\t\tforeach(i, g->qsRemove)\n\t\t\tm.remove(i);\n\t}\n\n\treturn m;\n}\n\nGroup *Group::getGroup(Channel *chan, QString name) {\n\tChannel *p = chan;\n\twhile (p) {\n\t\tGroup *g = p->qhGroups.value(name);\n\t\tif (g) {\n\t\t\tif (chan == p)\n\t\t\t\treturn g;\n\t\t\telse if (g->bInheritable)\n\t\t\t\treturn g;\n\t\t\telse\n\t\t\t\treturn NULL;\n\t\t}\n\t\tp = p->cParent;\n\t}\n\treturn NULL;\n}\n\nQSet Group::groupNames(Channel *chan) {\n\tQStack s;\n\tQSet m;\n\tChannel *c = chan;\n\tGroup *g;\n\n\twhile (c) {\n\t\ts.push(c);\n\t\tc = c->cParent;\n\t}\n\n\twhile (! s.isEmpty()) {\n\t\tc = s.pop();\n\t\tforeach(g, c->qhGroups) {\n\t\t\tif ((chan != c) && (! g->bInheritable))\n\t\t\t\tm.remove(g->qsName);\n\t\t\telse\n\t\t\t\tm.insert(g->qsName);\n\t\t}\n\t}\n\n\treturn m;\n}\n\n#define RET_FALSE (invert ? true : false)\n#define RET_TRUE (invert ? false : true)\n\nbool Group::isMember(Channel *curChan, Channel *aclChan, QString name, ServerUser *pl) {\n\tChannel *p;\n\tChannel *c;\n\tGroup *g;\n\n\tbool m = false;\n\tbool invert = false;\n\tbool token = false;\n\tbool hash = false;\n\tc = curChan;\n\n\twhile (true) {\n\t\tif (name.isEmpty())\n\t\t\treturn false;\n\n\t\tif (name.startsWith(QChar::fromLatin1('!'))) {\n\t\t\tinvert = true;\n\t\t\tname = name.remove(0,1);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (name.startsWith(QChar::fromLatin1('~'))) {\n\t\t\tc = aclChan;\n\t\t\tname = name.remove(0,1);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (name.startsWith(QChar::fromLatin1('#'))) {\n\t\t\ttoken = true;\n\t\t\tname = name.remove(0,1);\n\t\t\tcontinue;\n\t\t}\n\t\tif (name.startsWith(QChar::fromLatin1('$'))) {\n\t\t\thash = true;\n\t\t\tname = name.remove(0,1);\n\t\t\tcontinue;\n\t\t}\n\n\t\tbreak;\n\t}\n\n\tif (token)\n\t\tm = pl->qslAccessTokens.contains(name, Qt::CaseInsensitive);\n\telse if (hash)\n\t\tm = pl->qsHash == name;\n\telse if (name == QLatin1String(\"none\"))\n\t\tm = false;\n\telse if (name == QLatin1String(\"all\"))\n\t\tm = true;\n\telse if (name == QLatin1String(\"auth\"))\n\t\tm = (pl->iId >= 0);\n\telse if (name == QLatin1String(\"strong\"))\n\t\tm = pl->bVerified;\n\telse if (name == QLatin1String(\"in\"))\n\t\tm = (pl->cChannel == c);\n\telse if (name == QLatin1String(\"out\"))\n\t\tm = !(pl->cChannel == c);\n\telse if (name.startsWith(QLatin1String(\"sub\"))) {\n\t\tname = name.remove(0,4);\n\t\tint mindesc = 1;\n\t\tint maxdesc = 1000;\n\t\tint minpath = 0;\n\t\tQStringList args = name.split(QLatin1String(\",\"));\n\t\tswitch (args.count()) {\n\t\t\tdefault:\n\t\t\tcase 3:\n\t\t\t\tmaxdesc = args[2].isEmpty() ? maxdesc : args[2].toInt();\n\t\t\tcase 2:\n\t\t\t\tmindesc = args[1].isEmpty() ? mindesc : args[1].toInt();\n\t\t\tcase 1:\n\t\t\t\tminpath = args[0].isEmpty() ? minpath : args[0].toInt();\n\t\t\tcase 0:\n\t\t\t\tbreak;\n\t\t}\n\n\t\tChannel *home = pl->cChannel;\n\t\tQList playerChain;\n\t\tQList groupChain;\n\n\t\tp = home;\n\t\twhile (p) {\n\t\t\tplayerChain.prepend(p);\n\t\t\tp = p->cParent;\n\t\t}\n\n\t\tp = curChan;\n\t\twhile (p) {\n\t\t\tgroupChain.prepend(p);\n\t\t\tp = p->cParent;\n\t\t}\n\n\t\tint cofs = groupChain.indexOf(c);\n\t\tQ_ASSERT(cofs != -1);\n\n\t\tcofs += minpath;\n\n\t\tif (cofs >= groupChain.count()) {\n\t\t\treturn RET_FALSE;\n\t\t} else if (cofs < 0) {\n\t\t\tcofs = 0;\n\t\t}\n\n\t\tChannel *needed = groupChain[cofs];\n\t\tif (playerChain.indexOf(needed) == -1) {\n\t\t\treturn RET_FALSE;\n\t\t}\n\n\t\tint mindepth = cofs + mindesc;\n\t\tint maxdepth = cofs + maxdesc;\n\n\t\tint pdepth = playerChain.count() - 1;\n\n\t\tm = (pdepth >= mindepth) && (pdepth <= maxdepth);\n\t} else {\n\t\tQStack s;\n\n\t\tp = c;\n\n\t\twhile (p) {\n\t\t\tg = p->qhGroups.value(name);\n\n\t\t\tif (g) {\n\t\t\t\tif ((p != c) && ! g->bInheritable)\n\t\t\t\t\tbreak;\n\t\t\t\ts.push(g);\n\t\t\t\tif (! g->bInherit)\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tp = p->cParent;\n\t\t}\n\n\t\twhile (! s.isEmpty()) {\n\t\t\tg = s.pop();\n\t\t\tif (g->qsAdd.contains(pl->iId) || g->qsTemporary.contains(pl->iId) || g->qsTemporary.contains(- static_cast(pl->uiSession)))\n\t\t\t\tm = true;\n\t\t\tif (g->qsRemove.contains(pl->iId))\n\t\t\t\tm = false;\n\t\t}\n\t}\n\treturn invert ? !m : m;\n}\n\n#endif\nFix murmur handling all groups starting with \"sub\" as special.\/* Copyright (C) 2005-2011, Thorvald Natvig \n\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions\n are met:\n\n - Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n - Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n - Neither the name of the Mumble Developers nor the names of its\n contributors may be used to endorse or promote products derived from this\n software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR\n CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"murmur_pch.h\"\n\n#include \"Group.h\"\n\n#include \"Channel.h\"\n#include \"User.h\"\n#ifdef MURMUR\n#include \"ServerUser.h\"\n#endif\n\nGroup::Group(Channel *assoc, const QString &name) {\n\tc = assoc;\n\tbInherit = true;\n\tbInheritable = true;\n\tqsName = name;\n\tif (c)\n\t\tc->qhGroups[name] = this;\n}\n\n#ifdef MURMUR\n\nQSet Group::members() {\n\tQStack s;\n\tQSet m;\n\tChannel *p;\n\tGroup *g;\n\tint i;\n\n\tp = c;\n\twhile (p) {\n\t\tg = p->qhGroups.value(qsName);\n\t\tif (g) {\n\t\t\tif ((p != c) && ! g->bInheritable)\n\t\t\t\tbreak;\n\t\t\ts.push(g);\n\t\t\tif (! g->bInherit)\n\t\t\t\tbreak;\n\t\t}\n\t\tp = p->cParent;\n\t}\n\n\twhile (! s.isEmpty()) {\n\t\tg = s.pop();\n\t\tforeach(i, g->qsAdd)\n\t\t\tm.insert(i);\n\t\tforeach(i, g->qsRemove)\n\t\t\tm.remove(i);\n\t}\n\n\treturn m;\n}\n\nGroup *Group::getGroup(Channel *chan, QString name) {\n\tChannel *p = chan;\n\twhile (p) {\n\t\tGroup *g = p->qhGroups.value(name);\n\t\tif (g) {\n\t\t\tif (chan == p)\n\t\t\t\treturn g;\n\t\t\telse if (g->bInheritable)\n\t\t\t\treturn g;\n\t\t\telse\n\t\t\t\treturn NULL;\n\t\t}\n\t\tp = p->cParent;\n\t}\n\treturn NULL;\n}\n\nQSet Group::groupNames(Channel *chan) {\n\tQStack s;\n\tQSet m;\n\tChannel *c = chan;\n\tGroup *g;\n\n\twhile (c) {\n\t\ts.push(c);\n\t\tc = c->cParent;\n\t}\n\n\twhile (! s.isEmpty()) {\n\t\tc = s.pop();\n\t\tforeach(g, c->qhGroups) {\n\t\t\tif ((chan != c) && (! g->bInheritable))\n\t\t\t\tm.remove(g->qsName);\n\t\t\telse\n\t\t\t\tm.insert(g->qsName);\n\t\t}\n\t}\n\n\treturn m;\n}\n\n#define RET_FALSE (invert ? true : false)\n#define RET_TRUE (invert ? false : true)\n\nbool Group::isMember(Channel *curChan, Channel *aclChan, QString name, ServerUser *pl) {\n\tChannel *p;\n\tChannel *c;\n\tGroup *g;\n\n\tbool m = false;\n\tbool invert = false;\n\tbool token = false;\n\tbool hash = false;\n\tc = curChan;\n\n\twhile (true) {\n\t\tif (name.isEmpty())\n\t\t\treturn false;\n\n\t\tif (name.startsWith(QChar::fromLatin1('!'))) {\n\t\t\tinvert = true;\n\t\t\tname = name.remove(0,1);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (name.startsWith(QChar::fromLatin1('~'))) {\n\t\t\tc = aclChan;\n\t\t\tname = name.remove(0,1);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (name.startsWith(QChar::fromLatin1('#'))) {\n\t\t\ttoken = true;\n\t\t\tname = name.remove(0,1);\n\t\t\tcontinue;\n\t\t}\n\t\tif (name.startsWith(QChar::fromLatin1('$'))) {\n\t\t\thash = true;\n\t\t\tname = name.remove(0,1);\n\t\t\tcontinue;\n\t\t}\n\n\t\tbreak;\n\t}\n\n\tif (token)\n\t\tm = pl->qslAccessTokens.contains(name, Qt::CaseInsensitive);\n\telse if (hash)\n\t\tm = pl->qsHash == name;\n\telse if (name == QLatin1String(\"none\"))\n\t\tm = false;\n\telse if (name == QLatin1String(\"all\"))\n\t\tm = true;\n\telse if (name == QLatin1String(\"auth\"))\n\t\tm = (pl->iId >= 0);\n\telse if (name == QLatin1String(\"strong\"))\n\t\tm = pl->bVerified;\n\telse if (name == QLatin1String(\"in\"))\n\t\tm = (pl->cChannel == c);\n\telse if (name == QLatin1String(\"out\"))\n\t\tm = !(pl->cChannel == c);\n\telse if (name == QLatin1String(\"sub\")\n\t\t\t|| name.startsWith(QLatin1String(\"sub,\"))) {\n\t\t\n\t\tname = name.remove(0,4);\n\t\tint mindesc = 1;\n\t\tint maxdesc = 1000;\n\t\tint minpath = 0;\n\t\tQStringList args = name.split(QLatin1String(\",\"));\n\t\tswitch (args.count()) {\n\t\t\tdefault:\n\t\t\tcase 3:\n\t\t\t\tmaxdesc = args[2].isEmpty() ? maxdesc : args[2].toInt();\n\t\t\tcase 2:\n\t\t\t\tmindesc = args[1].isEmpty() ? mindesc : args[1].toInt();\n\t\t\tcase 1:\n\t\t\t\tminpath = args[0].isEmpty() ? minpath : args[0].toInt();\n\t\t\tcase 0:\n\t\t\t\tbreak;\n\t\t}\n\n\t\tChannel *home = pl->cChannel;\n\t\tQList playerChain;\n\t\tQList groupChain;\n\n\t\tp = home;\n\t\twhile (p) {\n\t\t\tplayerChain.prepend(p);\n\t\t\tp = p->cParent;\n\t\t}\n\n\t\tp = curChan;\n\t\twhile (p) {\n\t\t\tgroupChain.prepend(p);\n\t\t\tp = p->cParent;\n\t\t}\n\n\t\tint cofs = groupChain.indexOf(c);\n\t\tQ_ASSERT(cofs != -1);\n\n\t\tcofs += minpath;\n\n\t\tif (cofs >= groupChain.count()) {\n\t\t\treturn RET_FALSE;\n\t\t} else if (cofs < 0) {\n\t\t\tcofs = 0;\n\t\t}\n\n\t\tChannel *needed = groupChain[cofs];\n\t\tif (playerChain.indexOf(needed) == -1) {\n\t\t\treturn RET_FALSE;\n\t\t}\n\n\t\tint mindepth = cofs + mindesc;\n\t\tint maxdepth = cofs + maxdesc;\n\n\t\tint pdepth = playerChain.count() - 1;\n\n\t\tm = (pdepth >= mindepth) && (pdepth <= maxdepth);\n\t} else {\n\t\tQStack s;\n\n\t\tp = c;\n\n\t\twhile (p) {\n\t\t\tg = p->qhGroups.value(name);\n\n\t\t\tif (g) {\n\t\t\t\tif ((p != c) && ! g->bInheritable)\n\t\t\t\t\tbreak;\n\t\t\t\ts.push(g);\n\t\t\t\tif (! g->bInherit)\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tp = p->cParent;\n\t\t}\n\n\t\twhile (! s.isEmpty()) {\n\t\t\tg = s.pop();\n\t\t\tif (g->qsAdd.contains(pl->iId) || g->qsTemporary.contains(pl->iId) || g->qsTemporary.contains(- static_cast(pl->uiSession)))\n\t\t\t\tm = true;\n\t\t\tif (g->qsRemove.contains(pl->iId))\n\t\t\t\tm = false;\n\t\t}\n\t}\n\treturn invert ? !m : m;\n}\n\n#endif\n<|endoftext|>"} {"text":"\/\/ Scintilla source code edit control\n\/** @file LexPB.cxx\n ** Lexer for PowerBasic by Roland Walter, roland@rowalt.de\n **\/\n\/\/\n\/\/ Necessary changes in Scintilla project:\n\/\/ - In SciLexer.h and Scintilla.iface:\n\/\/\n\/\/ #define SCLEX_PB 49\t\t\t\t\/\/Provisional inofficial ID for PowerBasic lexer,\n\/\/ (...)\n\/\/ #define SCE_B_DEFAULT 0\t\t\t\/\/in both VB and PB lexer\n\/\/ #define SCE_B_COMMENT 1\t\t\t\/\/in both VB and PB lexer\n\/\/ #define SCE_B_NUMBER 2\t\t\t\/\/in both VB and PB lexer\n\/\/ #define SCE_B_KEYWORD 3\t\t\t\/\/in both VB and PB lexer\n\/\/ #define SCE_B_STRING 4\t\t\t\/\/in both VB and PB lexer\n\/\/ #define SCE_B_PREPROCESSOR 5\t\t\/\/VB lexer only, unsupported by PB lexer\n\/\/ #define SCE_B_OPERATOR 6\t\t\t\/\/in both VB and PB lexer\n\/\/ #define SCE_B_IDENTIFIER 7\t\t\/\/in both VB and PB lexer\n\/\/ #define SCE_B_DATE 8\t\t\t\t\/\/VB lexer only, unsupported by PB lexer\n\n\/\/ - Statement added to KeyWords.cxx: 'LINK_LEXER(lmPB);'\n\/\/ - Statement added to scintilla_vc6.mak: '$(DIR_O)\\LexPB.obj: ..\\src\\LexPB.cxx $(LEX_HEADERS)'\n\/\/\n\/\/ Copyright for Scintilla: 1998-2001 by Neil Hodgson \n\/\/ The License.txt file describes the conditions under which this software may be distributed.\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"Platform.h\"\n\n#include \"PropSet.h\"\n#include \"Accessor.h\"\n#include \"StyleContext.h\"\n#include \"KeyWords.h\"\n#include \"Scintilla.h\"\n#include \"SciLexer.h\"\n\nstatic inline bool IsTypeCharacter(const int ch) {\n\treturn ch == '%' || ch == '&' || ch == '@' || ch == '!' || ch == '#' || ch == '$';\n}\n\nstatic inline bool IsAWordChar(const int ch) {\n\treturn (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_');\n}\n\nstatic inline bool IsAWordStart(const int ch) {\n\treturn (ch < 0x80) && (isalnum(ch) || ch == '_');\n}\n\nbool MatchUpperCase(Accessor &styler, int pos, const char *s) \/\/Same as styler.Match() but uppercase comparison (a-z,A-Z and space only)\n{\n\tchar ch;\n\tfor (int i=0; *s; i++)\n\t{\n\t\tch=styler.SafeGetCharAt(pos+i);\n\t\tif (ch > 0x60) ch -= '\\x20';\n\t\tif (*s != ch) return false;\n\t\ts++;\n\t}\n\treturn true;\n}\n\nstatic void ColourisePBDoc(unsigned int startPos, int length, int initStyle,WordList *keywordlists[],\n\t\t\t\t\t\t Accessor &styler) {\n\n\tWordList &keywords = *keywordlists[0];\n\n\tstyler.StartAt(startPos);\n\n\tStyleContext sc(startPos, length, initStyle, styler);\n\n\tfor (; sc.More(); sc.Forward()) {\n\n\t\tif (sc.state == SCE_B_OPERATOR)\n\t\t{\n\t\t\tsc.SetState(SCE_B_DEFAULT);\n\t\t}\n\t\telse if (sc.state == SCE_B_KEYWORD)\n\t\t{\n\t\t\tif (!IsAWordChar(sc.ch))\n\t\t\t{\n\t\t\t\tif (!IsTypeCharacter(sc.ch))\n\t\t\t\t{\n\t\t\t\t\tif (sc.ch == ']') {sc.Forward();}\n\t\t\t\t\tchar s[100];\n\t\t\t\t\tsc.GetCurrentLowered(s, sizeof(s));\n\t\t\t\t\tif (keywords.InList(s))\n\t\t\t\t\t{\n\t\t\t\t\t\tif (strcmp(s, \"rem\") == 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tsc.ChangeState(SCE_B_COMMENT);\n\t\t\t\t\t\t\tif (sc.atLineEnd) {sc.SetState(SCE_B_DEFAULT);}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tsc.SetState(SCE_B_DEFAULT);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tsc.ChangeState(SCE_B_IDENTIFIER);\n\t\t\t\t\t\tsc.SetState(SCE_B_DEFAULT);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if (sc.state == SCE_B_NUMBER)\n\t\t{\n\t\t\tif (!IsAWordChar(sc.ch)) {sc.SetState(SCE_B_DEFAULT);}\n\t\t}\n\t\telse if (sc.state == SCE_B_STRING)\n\t\t{\n\t\t\t\/\/ PB doubles quotes to preserve them, so just end this string\n\t\t\t\/\/ state now as a following quote will start again\n\t\t\tif (sc.ch == '\\\"')\n\t\t\t{\n\t\t\t\tif (tolower(sc.chNext) == 'c') {sc.Forward();}\n\t\t\t\tsc.ForwardSetState(SCE_B_DEFAULT);\n\t\t\t}\n\t\t}\n\t\telse if (sc.state == SCE_B_COMMENT)\n\t\t{\n\t\t\tif (sc.atLineEnd) {sc.SetState(SCE_B_DEFAULT);}\n\t\t}\n\n\t\tif (sc.state == SCE_B_DEFAULT)\n\t\t{\n\t\t\tif (sc.ch == '\\'') {sc.SetState(SCE_B_COMMENT);}\n\t\t\telse if (sc.ch == '\\\"') {sc.SetState(SCE_B_STRING);}\n\t\t\telse if (sc.ch == '#')\n\t\t\t{\tint n = 1;\n\t\t\t\tint chSeek = ' ';\n\t\t\t\twhile ((n < 100) && (chSeek == ' ' || chSeek == '\\t'))\n\t\t\t\t{\n\t\t\t\t\tchSeek = sc.GetRelative(n);\n\t\t\t\t\tn++;\n\t\t\t\t}\n\t\t\t\tsc.SetState(SCE_B_OPERATOR);\n\t\t\t}\n\t\t\telse if (sc.ch == '&' && tolower(sc.chNext) == 'h') {sc.SetState(SCE_B_NUMBER);}\n\t\t\telse if (sc.ch == '&' && tolower(sc.chNext) == 'b') {sc.SetState(SCE_B_NUMBER);}\n\t\t\telse if (sc.ch == '&' && tolower(sc.chNext) == 'o') {sc.SetState(SCE_B_NUMBER);}\n\t\t\telse if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {sc.SetState(SCE_B_NUMBER);}\n\t\t\telse if (IsAWordStart(sc.ch) || (sc.ch == '[')) {sc.SetState(SCE_B_KEYWORD);}\n\t\t\telse if (isoperator(static_cast(sc.ch)) || (sc.ch == '\\\\')) {sc.SetState(SCE_B_OPERATOR);}\n\t\t}\n\n\t}\n\tsc.Complete();\n}\n\nstatic void FoldPBDoc(unsigned int startPos, int length, int, WordList *[], Accessor &styler)\n{\n\t\/\/ No folding enabled, no reason to continue...\n\tif( styler.GetPropertyInt(\"fold\") == 0 )\n\t\treturn;\n\n\tunsigned int endPos = startPos + length;\n\tint lineCurrent = styler.GetLine(startPos);\n\tint levelCurrent = SC_FOLDLEVELBASE;\n\tif (lineCurrent > 0)\n\t\tlevelCurrent = styler.LevelAt(lineCurrent-1) >> 16;\n\tint levelNext = levelCurrent;\n\tchar chNext = styler[startPos];\n\n\tbool atEOL=1;\n\tfor (unsigned int i = startPos; i < endPos; i++)\n\t{\n\t\tchar ch = chNext;\n\t\tchNext = styler.SafeGetCharAt(i + 1);\n\t\t\/\/ Functions Start: Function, Sub\n\t\t\/\/ Functions End: End Function, End Sub\n\n\t\tif( atEOL )\t\t\t\/\/Begin of a new line (The Sub\/Function\/Macro keywords may occur at begin of line only)\n\t\t{\n\t\t\tif( MatchUpperCase(styler,i,\"END FUNCTION\") )\n\t\t\t\tlevelNext=SC_FOLDLEVELBASE;\n\t\t\telse if( MatchUpperCase(styler,i,\"FUNCTION\") )\n\t\t\t{\n\t\t\t\tstyler.SetLevel(lineCurrent, (SC_FOLDLEVELBASE << 16) | SC_FOLDLEVELHEADERFLAG);\n\t\t\t\tlevelNext=SC_FOLDLEVELBASE+1;\n\t\t\t}\n\t\t\telse if( MatchUpperCase(styler,i,\"CALLBACK FUNCTION\") )\n\t\t\t{\n\t\t\t\tstyler.SetLevel(lineCurrent, (SC_FOLDLEVELBASE << 16) | SC_FOLDLEVELHEADERFLAG);\n\t\t\t\tlevelNext=SC_FOLDLEVELBASE+1;\n\t\t\t}\n\t\t\telse if( MatchUpperCase(styler,i,\"STATIC FUNCTION\") )\n\t\t\t{\n\t\t\t\tstyler.SetLevel(lineCurrent, (SC_FOLDLEVELBASE << 16) | SC_FOLDLEVELHEADERFLAG);\n\t\t\t\tlevelNext=SC_FOLDLEVELBASE+1;\n\t\t\t}\n\t\t\telse if( MatchUpperCase(styler,i,\"END SUB\") )\n\t\t\t\tlevelNext=SC_FOLDLEVELBASE;\n\t\t\telse if( MatchUpperCase(styler,i,\"SUB\") )\n\t\t\t{\n\t\t\t\tstyler.SetLevel(lineCurrent, (SC_FOLDLEVELBASE << 16) | SC_FOLDLEVELHEADERFLAG);\n\t\t\t\tlevelNext=SC_FOLDLEVELBASE+1;\n\t\t\t}\n\t\t\telse if( MatchUpperCase(styler,i,\"STATIC SUB\") )\n\t\t\t{\n\t\t\t\tstyler.SetLevel(lineCurrent, (SC_FOLDLEVELBASE << 16) | SC_FOLDLEVELHEADERFLAG);\n\t\t\t\tlevelNext=SC_FOLDLEVELBASE+1;\n\t\t\t}\n\t\t\t\/\/else if( MatchUpperCase(styler,i,\"END MACRO\") )\n\t\t\t\/\/\tlevelNext--;\n\t\t\t\/\/else if( MatchUpperCase(styler,i,\"MACRO\") ) \/\/ToDo: What's with single-line macros?\n\t\t\t\/\/\tlevelNext++;\n\t\t}\n\n\t\tatEOL = (ch == '\\r' && chNext != '\\n') || (ch == '\\n');\n\t\tif( atEOL )\n\t\t{\n\t\t\tif (levelNext == SC_FOLDLEVELBASE)\n\t\t\t{\n\t\t\t\tint levelUse = levelCurrent;\n\t\t\t\tint lev = levelUse | levelNext << 16;\n\t\t\t\tstyler.SetLevel(lineCurrent, lev);\n\t\t\t}\n\t\t\tlineCurrent++;\n\t\t\tlevelCurrent = levelNext;\n\t\t}\n\t}\n\n\tif (levelNext == SC_FOLDLEVELBASE)\n\t{\n\t\tint levelUse = levelCurrent;\n\t\tint lev = levelUse | levelNext << 16;\n\t\tstyler.SetLevel(lineCurrent, lev);\n\t}\n}\n\nstatic const char * const pbWordListDesc[] = {\n\t\"Keywords\",\n\t0\n};\n\nLexerModule lmPB(SCLEX_POWERBASIC, ColourisePBDoc, \"powerbasic\", FoldPBDoc, pbWordListDesc);\nUpdated folder from Roland.\/\/ Scintilla source code edit control\n\/** @file LexPB.cxx\n ** Lexer for PowerBasic by Roland Walter, roland@rowalt.de\n ** Last update: 17.10.2003 (toggling of subs\/functions now until next sub\/functin - this gives better results)\n **\/\n\/\/\n\/\/ Necessary changes in Scintilla project:\n\/\/ - In SciLexer.h and Scintilla.iface:\n\/\/\n\/\/ #define SCLEX_PB 51\t\t\t\t\/\/ID for PowerBasic lexer\n\/\/ (...)\n\/\/ #define SCE_B_DEFAULT 0\t\t\t\/\/in both VB and PB lexer\n\/\/ #define SCE_B_COMMENT 1\t\t\t\/\/in both VB and PB lexer\n\/\/ #define SCE_B_NUMBER 2\t\t\t\/\/in both VB and PB lexer\n\/\/ #define SCE_B_KEYWORD 3\t\t\t\/\/in both VB and PB lexer\n\/\/ #define SCE_B_STRING 4\t\t\t\/\/in both VB and PB lexer\n\/\/ #define SCE_B_PREPROCESSOR 5\t\t\/\/VB lexer only, unsupported by PB lexer\n\/\/ #define SCE_B_OPERATOR 6\t\t\t\/\/in both VB and PB lexer\n\/\/ #define SCE_B_IDENTIFIER 7\t\t\/\/in both VB and PB lexer\n\/\/ #define SCE_B_DATE 8\t\t\t\t\/\/VB lexer only, unsupported by PB lexer\n\n\/\/ - Statement added to KeyWords.cxx: 'LINK_LEXER(lmPB);'\n\/\/ - Statement added to scintilla_vc6.mak: '$(DIR_O)\\LexPB.obj: ...\\src\\LexPB.cxx $(LEX_HEADERS)'\n\/\/\n\/\/ Copyright for Scintilla: 1998-2001 by Neil Hodgson \n\/\/ The License.txt file describes the conditions under which this software may be distributed.\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"Platform.h\"\n\n#include \"PropSet.h\"\n#include \"Accessor.h\"\n#include \"StyleContext.h\"\n#include \"KeyWords.h\"\n#include \"Scintilla.h\"\n#include \"SciLexer.h\"\n\nstatic inline bool IsTypeCharacter(const int ch) {\n\treturn ch == '%' || ch == '&' || ch == '@' || ch == '!' || ch == '#' || ch == '$';\n}\n\nstatic inline bool IsAWordChar(const int ch) {\n\treturn (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_');\n}\n\nstatic inline bool IsAWordStart(const int ch) {\n\treturn (ch < 0x80) && (isalnum(ch) || ch == '_');\n}\n\nbool MatchUpperCase(Accessor &styler, int pos, const char *s) \/\/Same as styler.Match() but uppercase comparison (a-z,A-Z and space only)\n{\n\tchar ch;\n\tfor (int i=0; *s; i++)\n\t{\n\t\tch=styler.SafeGetCharAt(pos+i);\n\t\tif (ch > 0x60) ch -= '\\x20';\n\t\tif (*s != ch) return false;\n\t\ts++;\n\t}\n\treturn true;\n}\n\nstatic void ColourisePBDoc(unsigned int startPos, int length, int initStyle,WordList *keywordlists[],\n\t\t\t\t\t\t Accessor &styler) {\n\n\tWordList &keywords = *keywordlists[0];\n\n\tstyler.StartAt(startPos);\n\n\tStyleContext sc(startPos, length, initStyle, styler);\n\n\tfor (; sc.More(); sc.Forward()) {\n\n\t\tif (sc.state == SCE_B_OPERATOR)\n\t\t{\n\t\t\tsc.SetState(SCE_B_DEFAULT);\n\t\t}\n\t\telse if (sc.state == SCE_B_KEYWORD)\n\t\t{\n\t\t\tif (!IsAWordChar(sc.ch))\n\t\t\t{\n\t\t\t\tif (!IsTypeCharacter(sc.ch))\n\t\t\t\t{\n\t\t\t\t\tif (sc.ch == ']') {sc.Forward();}\n\t\t\t\t\tchar s[100];\n\t\t\t\t\tsc.GetCurrentLowered(s, sizeof(s));\n\t\t\t\t\tif (keywords.InList(s))\n\t\t\t\t\t{\n\t\t\t\t\t\tif (strcmp(s, \"rem\") == 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tsc.ChangeState(SCE_B_COMMENT);\n\t\t\t\t\t\t\tif (sc.atLineEnd) {sc.SetState(SCE_B_DEFAULT);}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tsc.SetState(SCE_B_DEFAULT);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tsc.ChangeState(SCE_B_IDENTIFIER);\n\t\t\t\t\t\tsc.SetState(SCE_B_DEFAULT);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if (sc.state == SCE_B_NUMBER)\n\t\t{\n\t\t\tif (!IsAWordChar(sc.ch)) {sc.SetState(SCE_B_DEFAULT);}\n\t\t}\n\t\telse if (sc.state == SCE_B_STRING)\n\t\t{\n\t\t\t\/\/ PB doubles quotes to preserve them, so just end this string\n\t\t\t\/\/ state now as a following quote will start again\n\t\t\tif (sc.ch == '\\\"')\n\t\t\t{\n\t\t\t\tif (tolower(sc.chNext) == 'c') {sc.Forward();}\n\t\t\t\tsc.ForwardSetState(SCE_B_DEFAULT);\n\t\t\t}\n\t\t}\n\t\telse if (sc.state == SCE_B_COMMENT)\n\t\t{\n\t\t\tif (sc.atLineEnd) {sc.SetState(SCE_B_DEFAULT);}\n\t\t}\n\n\t\tif (sc.state == SCE_B_DEFAULT)\n\t\t{\n\t\t\tif (sc.ch == '\\'') {sc.SetState(SCE_B_COMMENT);}\n\t\t\telse if (sc.ch == '\\\"') {sc.SetState(SCE_B_STRING);}\n\t\t\telse if (sc.ch == '#')\n\t\t\t{\tint n = 1;\n\t\t\t\tint chSeek = ' ';\n\t\t\t\twhile ((n < 100) && (chSeek == ' ' || chSeek == '\\t'))\n\t\t\t\t{\n\t\t\t\t\tchSeek = sc.GetRelative(n);\n\t\t\t\t\tn++;\n\t\t\t\t}\n\t\t\t\tsc.SetState(SCE_B_OPERATOR);\n\t\t\t}\n\t\t\telse if (sc.ch == '&' && tolower(sc.chNext) == 'h') {sc.SetState(SCE_B_NUMBER);}\n\t\t\telse if (sc.ch == '&' && tolower(sc.chNext) == 'b') {sc.SetState(SCE_B_NUMBER);}\n\t\t\telse if (sc.ch == '&' && tolower(sc.chNext) == 'o') {sc.SetState(SCE_B_NUMBER);}\n\t\t\telse if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {sc.SetState(SCE_B_NUMBER);}\n\t\t\telse if (IsAWordStart(sc.ch) || (sc.ch == '[')) {sc.SetState(SCE_B_KEYWORD);}\n\t\t\telse if (isoperator(static_cast(sc.ch)) || (sc.ch == '\\\\')) {sc.SetState(SCE_B_OPERATOR);}\n\t\t}\n\n\t}\n\tsc.Complete();\n}\n\nstatic void FoldPBDoc(unsigned int startPos, int length, int, WordList *[], Accessor &styler)\n{\n\t\/\/ No folding enabled, no reason to continue...\n\tif( styler.GetPropertyInt(\"fold\") == 0 )\n\t\treturn;\n\n\tunsigned int endPos = startPos + length;\n\tint lineCurrent = styler.GetLine(startPos);\n\tint levelCurrent = SC_FOLDLEVELBASE;\n\tif (lineCurrent > 0)\n\t\tlevelCurrent = styler.LevelAt(lineCurrent-1) >> 16;\n\tint levelNext = levelCurrent;\n\tchar chNext = styler[startPos];\n\n\tbool atEOL=1;\n\tfor (unsigned int i = startPos; i < endPos; i++)\n\t{\n\t\tchar ch = chNext;\n\t\tchNext = styler.SafeGetCharAt(i + 1);\n\n\t\tif( atEOL )\t\t\t\/\/Begin of a new line (The Sub\/Function\/Macro keywords may occur at begin of line only)\n\t\t{\n\t\t\tif( MatchUpperCase(styler,i,\"FUNCTION\") ) \/\/else if(\n\t\t\t{\n\t\t\t\tstyler.SetLevel(lineCurrent, (SC_FOLDLEVELBASE << 16) | SC_FOLDLEVELHEADERFLAG);\n\t\t\t\tlevelNext=SC_FOLDLEVELBASE+1;\n\t\t\t}\n\t\t\telse if( MatchUpperCase(styler,i,\"CALLBACK FUNCTION\") )\n\t\t\t{\n\t\t\t\tstyler.SetLevel(lineCurrent, (SC_FOLDLEVELBASE << 16) | SC_FOLDLEVELHEADERFLAG);\n\t\t\t\tlevelNext=SC_FOLDLEVELBASE+1;\n\t\t\t}\n\t\t\telse if( MatchUpperCase(styler,i,\"STATIC FUNCTION\") )\n\t\t\t{\n\t\t\t\tstyler.SetLevel(lineCurrent, (SC_FOLDLEVELBASE << 16) | SC_FOLDLEVELHEADERFLAG);\n\t\t\t\tlevelNext=SC_FOLDLEVELBASE+1;\n\t\t\t}\n\t\t\telse if( MatchUpperCase(styler,i,\"SUB\") )\n\t\t\t{\n\t\t\t\tstyler.SetLevel(lineCurrent, (SC_FOLDLEVELBASE << 16) | SC_FOLDLEVELHEADERFLAG);\n\t\t\t\tlevelNext=SC_FOLDLEVELBASE+1;\n\t\t\t}\n\t\t\telse if( MatchUpperCase(styler,i,\"STATIC SUB\") )\n\t\t\t{\n\t\t\t\tstyler.SetLevel(lineCurrent, (SC_FOLDLEVELBASE << 16) | SC_FOLDLEVELHEADERFLAG);\n\t\t\t\tlevelNext=SC_FOLDLEVELBASE+1;\n\t\t\t}\n\t\t\t\/\/else if( MatchUpperCase(styler,i,\"MACRO\") ) \/\/ToDo: What's with single-line macros?\n\t\t}\n\n\t\tatEOL = (ch == '\\r' && chNext != '\\n') || (ch == '\\n');\n\t\tif( atEOL )\n\t\t{\n\t\t\tlineCurrent++;\n\t\t\tlevelCurrent = levelNext;\n\t\t}\n\t}\n\n\tif (levelNext == SC_FOLDLEVELBASE)\n\t{\n\t\tint levelUse = levelCurrent;\n\t\tint lev = levelUse | levelNext << 16;\n\t\tstyler.SetLevel(lineCurrent, lev);\n\t}\n}\n\nstatic const char * const pbWordListDesc[] = {\n\t\"Keywords\",\n\t0\n};\n\nLexerModule lmPB(SCLEX_POWERBASIC, ColourisePBDoc, \"powerbasic\", FoldPBDoc, pbWordListDesc);\n<|endoftext|>"} {"text":"\/***********************************\n Copyright 2017 Ravishankar Mathur\n \n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n \n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n \n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n ***********************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace OpenFrames\n{\n \n Model::Model( const std::string &name)\n : ReferenceFrame(name)\n {\n init();\n }\n \n Model::Model( const std::string &name, const osg::Vec3 &color)\n : ReferenceFrame(name, color)\n {\n init();\n }\n \n Model::Model( const std::string &name, const osg::Vec4 &color)\n : ReferenceFrame(name, color)\n {\n init();\n }\n \n Model::Model( const std::string &name, float r, float g, float b, float a)\n : ReferenceFrame(name, r, g, b, a)\n {\n init();\n }\n \n Model::~Model() { }\n \n void Model::init()\n {\n _group = new osg::Group;\n _extras = new osg::Geode;\n _extras->setName(_name + \" extras\");\n _group->addChild(_xform.get());\n _modelXform = new FrameTransform;\n }\n \n osg::Group* Model::getGroup()\n {\n return _group.get();\n }\n \n \/********************************************************\/\n bool Model::setModel( const std::string& filename, bool force_reload )\n {\n \/\/ First check if we are reloading the same model file (assuming it has the same name)\n if(_model.valid() && (_model->getName() == filename) && !force_reload) return true;\n \n \/\/ Read the new model file (if a filename is given)\n osg::Node *newModel = NULL;\n if(filename.length() > 0)\n {\n newModel = osgDB::readNodeFile(filename);\n }\n \n \/\/ Next, remove existing data if needed\n if((filename.length() == 0) || (newModel != NULL))\n {\n \/\/ Remove current model\n _xform->removeChild(_modelXform.get());\n _modelXform->removeChild(_model.get());\n _model = NULL;\n \n \/\/ Remove existing ParticleSystems\n _group->removeChild(_extras.get());\n _extras->removeDrawables(0, _extras->getNumDrawables());\n \n \/\/ No filename given, so just reset axes and quit\n if(filename.length() == 0)\n {\n moveXAxis(osg::Vec3d(), 1);\n moveYAxis(osg::Vec3d(), 1);\n moveZAxis(osg::Vec3d(), 1);\n return true;\n }\n }\n else\n {\n std::cerr<< \"Model ERROR: Model file \\'\" << filename << \"\\' could not be loaded!\" << std::endl;\n return false; \/\/ Model could not be loaded\n }\n \n _model = newModel; \/\/ Set new model\n \n \/* If the model's root node is a group, iterate through its children\n to find any osg::ParticleSystem children. Then move those children\n to our group so they are not affected by this frame's transform.\n This is done because ParticleSystems need to be in world space. *\/\n osg::Group *modelGroup = dynamic_cast(_model.get());\n if(modelGroup)\n {\n osg::Geode *modelGeode;\n osgParticle::ParticleSystem *ps;\n \n \/\/ Find each Geode, since that could contain a ParticleSystem\n for(unsigned int i = 0; i < modelGroup->getNumChildren(); ++i)\n {\n modelGeode = dynamic_cast(modelGroup->getChild(i));\n if(modelGeode)\n {\n \/\/ Search through the Geode for a ParticleSystem\n for(unsigned int j = 0; j < modelGeode->getNumDrawables(); ++j)\n {\n ps = dynamic_cast(modelGeode->getDrawable(j));\n if(ps) \/\/ ParticleSystem found\n {\n _extras->addDrawable(ps);\n modelGeode->removeDrawable(ps);\n --j;\n }\n }\n \n \/\/ Delete the Geode if it's empty\n if(modelGeode->getNumDrawables() == 0)\n {\n modelGroup->removeChild(modelGeode);\n --i;\n }\n }\n }\n \n \/\/ If ParticleSystems exist, add them to the group\n if(_extras->getNumDrawables() > 0)\n _group->addChild(_extras.get());\n }\n \n \/\/ Add the new model to this frame\n _modelXform->addChild(_model.get());\n _xform->addChild(_modelXform.get());\n \n \/\/ Rescale normals in case we want to scale the model\n _model->getOrCreateStateSet()->setMode( GL_RESCALE_NORMAL, osg::StateAttribute::ON );\n \n \/\/ Set the model pivot at its geometric center, so that scales\/rotations will make sense.\n osg::Vec3d center = _model->getBound()._center;\n _modelXform->setPivot(center[0], center[1], center[2]);\n \n repositionAxes(); \/\/ Reset the x\/y\/z axes\n \n return true;\n }\n \n \/********************************************************\/\n bool Model::shareModel( const Model* otherModel )\n {\n if(!setModel(\"\")) return false; \/\/ Clear any existing data\n \n _model = otherModel->getModel(); \/\/ Get model data\n if(!_model.valid()) return true; \/\/ No model to share\n \n \/\/ Add the new model to this frame\n _modelXform->addChild(_model.get());\n _xform->addChild(_modelXform.get());\n \n \/\/ Set the model pivot at its geometric center, so that scales\/rotations will make sense.\n osg::Vec3d center = _model->getBound()._center;\n _modelXform->setPivot(center[0], center[1], center[2]);\n \n repositionAxes(); \/\/ Reset the x\/y\/z axes\n \n \/\/ Get any extras such as ParticleSystems\n osg::Geode *otherExtras = otherModel->getExtras();\n if(otherExtras->getNumDrawables() > 0)\n {\n \/\/ Get all drawables\n for(unsigned int i = 0; i < otherExtras->getNumDrawables(); ++i)\n {\n _extras->addDrawable(otherExtras->getDrawable(i));\n }\n \n \/\/ If extras exist, add them to the group\n _group->addChild(_extras.get());\n }\n \n return true;\n }\n \n \/** Set the position of the model wrt its own ReferenceFrame. *\/\n void Model::setModelPosition( const double &x, const double &y, const double &z)\n {\n _modelXform->setPosition(x, y, z);\n \n repositionAxes(); \/\/ Reset the x\/y\/z axes\n }\n \n \/** Set the scale of the model wrt the pivot point. *\/\n void Model::setModelScale( const double &sx, const double &sy, const double &sz)\n {\n if((sx == 0.0) || (sy == 0.0) || (sz == 0.0)) return;\n \n _modelXform->setScale(sx, sy, sz);\n \n repositionAxes(); \/\/ Reset the x\/y\/z axes\n }\n \n \/** Move the model's x\/y\/z axes to default positions. *\/\n void Model::repositionAxes()\n {\n if(_model) \/\/ If model exists, move its axes to the model's scaled bounds\n {\n \/\/ Get the center point, radius, and scale of the model\n double px, py, pz;\n double sx, sy, sz;\n double radius, scale;\n _modelXform->getPosition(px, py, pz);\n _modelXform->getScale(sx, sy, sz);\n scale = std::max(std::max(sx, sy), sz); \/\/ Get the largest scale\n radius = _model->getBound()._radius;\n \n \/\/ We want to place the x\/y\/z axes around the circle that fits the\n \/\/ scaled model, so we use the largest scale.\n moveXAxis(osg::Vec3(scale*radius + px, py, pz), 0.5*scale*radius);\n moveYAxis(osg::Vec3(px, scale*radius + py, pz), 0.5*scale*radius);\n moveZAxis(osg::Vec3(px, py, scale*radius + pz), 0.5*scale*radius);\n }\n else \/\/ Otherwise move its axes to the origin\n {\n moveXAxis(osg::Vec3(0, 0, 0), 1.0);\n moveYAxis(osg::Vec3(0, 0, 0), 1.0);\n moveZAxis(osg::Vec3(0, 0, 0), 1.0);\n }\n }\n \n const osg::BoundingSphere& Model::getBound() const\n {\n \/\/ If model exists, have bounding sphere encompass it and the\n \/\/ axes\/labels, but keep it centered on the model since that is\n \/\/ the object of interest.\n ReferenceFrame::getBound();\n if(_model.valid()) \n {\n osg::BoundingSphere bs = _modelXform->getBound();\n bs.expandRadiusBy(_bound);\n _bound = bs;\n }\n \n return _bound;\n }\n \n} \/\/ !namespace OpenFrames\nForgot to commit file\/***********************************\n Copyright 2017 Ravishankar Mathur\n \n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n \n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n \n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n ***********************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace OpenFrames\n{\n \n Model::Model( const std::string &name)\n : ReferenceFrame(name)\n {\n init();\n }\n \n Model::Model( const std::string &name, const osg::Vec3 &color)\n : ReferenceFrame(name, color)\n {\n init();\n }\n \n Model::Model( const std::string &name, const osg::Vec4 &color)\n : ReferenceFrame(name, color)\n {\n init();\n }\n \n Model::Model( const std::string &name, float r, float g, float b, float a)\n : ReferenceFrame(name, r, g, b, a)\n {\n init();\n }\n \n Model::~Model() { }\n \n void Model::init()\n {\n _group = new osg::Group;\n _extras = new osg::Geode;\n _extras->setName(_name + \" extras\");\n _group->addChild(_xform.get());\n _modelXform = new FrameTransform;\n }\n \n osg::Group* Model::getGroup()\n {\n return _group.get();\n }\n \n \/********************************************************\/\n bool Model::setModel( const std::string& filename, bool force_reload )\n {\n \/\/ First check if we are reloading the same model file (assuming it has the same name)\n if(_model.valid() && (_model->getName() == filename) && !force_reload) return true;\n \n \/\/ Read the new model file (if a filename is given)\n osg::Node *newModel = NULL;\n if(filename.length() > 0)\n {\n newModel = osgDB::readNodeFile(filename);\n }\n \n \/\/ Next, remove existing data if needed\n if((filename.length() == 0) || (newModel != NULL))\n {\n \/\/ Remove current model\n _xform->removeChild(_modelXform.get());\n _modelXform->removeChild(_model.get());\n _model = NULL;\n \n \/\/ Remove existing ParticleSystems\n _group->removeChild(_extras.get());\n _extras->removeDrawables(0, _extras->getNumDrawables());\n \n \/\/ No filename given, so just reset axes and quit\n if(filename.length() == 0)\n {\n moveXAxis(osg::Vec3d(), 1);\n moveYAxis(osg::Vec3d(), 1);\n moveZAxis(osg::Vec3d(), 1);\n return true;\n }\n }\n else\n {\n std::cerr<< \"Model ERROR: Model file \\'\" << filename << \"\\' could not be loaded!\" << std::endl;\n return false; \/\/ Model could not be loaded\n }\n \n _model = newModel; \/\/ Set new model\n \n \/* If the model's root node is a group, iterate through its children\n to find any osg::ParticleSystem children. Then move those children\n to our group so they are not affected by this frame's transform.\n This is done because ParticleSystems need to be in world space. *\/\n osg::Group *modelGroup = dynamic_cast(_model.get());\n if(modelGroup)\n {\n osg::Geode *modelGeode;\n osgParticle::ParticleSystem *ps;\n \n \/\/ Find each Geode, since that could contain a ParticleSystem\n for(unsigned int i = 0; i < modelGroup->getNumChildren(); ++i)\n {\n modelGeode = dynamic_cast(modelGroup->getChild(i));\n if(modelGeode)\n {\n \/\/ Search through the Geode for a ParticleSystem\n for(unsigned int j = 0; j < modelGeode->getNumDrawables(); ++j)\n {\n ps = dynamic_cast(modelGeode->getDrawable(j));\n if(ps) \/\/ ParticleSystem found\n {\n _extras->addDrawable(ps);\n modelGeode->removeDrawable(ps);\n --j;\n }\n }\n \n \/\/ Delete the Geode if it's empty\n if(modelGeode->getNumDrawables() == 0)\n {\n modelGroup->removeChild(modelGeode);\n --i;\n }\n }\n }\n \n \/\/ If ParticleSystems exist, add them to the group\n if(_extras->getNumDrawables() > 0)\n _group->addChild(_extras.get());\n }\n \n \/\/ Add the new model to this frame\n _modelXform->addChild(_model.get());\n _xform->addChild(_modelXform.get());\n \n \/\/ Rescale normals in case we want to scale the model\n _model->getOrCreateStateSet()->setMode( GL_RESCALE_NORMAL, osg::StateAttribute::ON );\n \n \/\/ Set the model pivot at its geometric center, so that scales\/rotations will make sense.\n osg::Vec3d center = _model->getBound()._center;\n setModelPivot(center[0], center[1], center[2]);\n \n return true;\n }\n \n \/********************************************************\/\n bool Model::shareModel( const Model* otherModel )\n {\n if(!setModel(\"\")) return false; \/\/ Clear any existing data\n \n _model = otherModel->getModel(); \/\/ Get model data\n if(!_model.valid()) return true; \/\/ No model to share\n \n \/\/ Add the new model to this frame\n _modelXform->addChild(_model.get());\n _xform->addChild(_modelXform.get());\n \n \/\/ Set the model pivot at its geometric center, so that scales\/rotations will make sense.\n osg::Vec3d center = _model->getBound()._center;\n setModelPivot(center[0], center[1], center[2]);\n\n \/\/ Get any extras such as ParticleSystems\n osg::Geode *otherExtras = otherModel->getExtras();\n if(otherExtras->getNumDrawables() > 0)\n {\n \/\/ Get all drawables\n for(unsigned int i = 0; i < otherExtras->getNumDrawables(); ++i)\n {\n _extras->addDrawable(otherExtras->getDrawable(i));\n }\n \n \/\/ If extras exist, add them to the group\n _group->addChild(_extras.get());\n }\n \n return true;\n }\n \n \/** Set the position of the model wrt its own ReferenceFrame. *\/\n void Model::setModelPosition( const double &x, const double &y, const double &z)\n {\n _modelXform->setPosition(x, y, z);\n \n repositionAxes(); \/\/ Reset the x\/y\/z axes\n }\n \n \/** Set the scale of the model wrt the pivot point. *\/\n void Model::setModelScale( const double &sx, const double &sy, const double &sz)\n {\n if((sx == 0.0) || (sy == 0.0) || (sz == 0.0)) return;\n \n _modelXform->setScale(sx, sy, sz);\n \n repositionAxes(); \/\/ Reset the x\/y\/z axes\n }\n\n \/** Set\/get the pivot point of the model. *\/\n void Model::setModelPivot(const double &px, const double &py, const double &pz)\n {\n _modelXform->setPivot(px, py, pz);\n\n repositionAxes(); \/\/ Reset the x\/y\/z axes\n }\n \n \/** Move the model's x\/y\/z axes to default positions. *\/\n void Model::repositionAxes()\n {\n if(_model) \/\/ If model exists, move the axes to the its bounds\n {\n \/\/ Get the model's transformed bounding sphere\n osg::BoundingSphere bs = _modelXform->getBound();\n \n \/\/ Place the axes at the edge of the bounding sphere\n moveXAxis(bs._center + osg::Vec3(bs._radius, 0, 0), 0.5*bs._radius);\n moveYAxis(bs._center + osg::Vec3(0, bs._radius, 0), 0.5*bs._radius);\n moveZAxis(bs._center + osg::Vec3(0, 0, bs._radius), 0.5*bs._radius);\n }\n else \/\/ Otherwise move its axes to the origin\n {\n moveXAxis(osg::Vec3(0, 0, 0), 1.0);\n moveYAxis(osg::Vec3(0, 0, 0), 1.0);\n moveZAxis(osg::Vec3(0, 0, 0), 1.0);\n }\n }\n \n const osg::BoundingSphere& Model::getBound() const\n {\n \/\/ If model exists, have bounding sphere encompass it and the\n \/\/ axes\/labels, but keep it centered on the model since that is\n \/\/ the object of interest.\n ReferenceFrame::getBound();\n if(_model.valid()) \n {\n osg::BoundingSphere bs = _modelXform->getBound();\n bs.expandRadiusBy(_bound);\n _bound = bs;\n }\n \n return _bound;\n }\n \n} \/\/ !namespace OpenFrames\n<|endoftext|>"} {"text":"\/*==LICENSE==\nThis file is part of Musec.\nCopyright (C) 2013 Florian Meißner\n\nThis program is free software: you can redistribute it and\/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program. If not, see .\n==LICENSE==*\/\n\n#include \"Musec.h\"\n#include \n#include \n#include \n#include \n\n#define POINTS_TITLE 2\n#define POINTS_ARTIST 2\n#define POINTS_ALBUM 1\n\nMusec::Musec(QWidget* parent) : QWidget(parent)\n{\n setupUi(this);\n setWindowFlags(Qt::CustomizeWindowHint | Qt::WindowTitleHint |\n Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint |\n Qt::MSWindowsFixedSizeDialogHint);\n fPlayer = new QMediaPlayer(this, QMediaPlayer::LowLatency);\n fTimer = new QTimer(this);\n fTimer->setSingleShot(true);\n fDir = QDir::homePath();\n fScore = 0;\n fSongsPlayed = 0;\n fIsActive = false;\n\n fExtensions << \"*.mp3\" << \"*.m4a\"; \/\/ These should contain meta data\n\n connect(fTimer, &QTimer::timeout, this, &Musec::timeout);\n connect(fPlayer, &QMediaPlayer::durationChanged, this, &Musec::durationChanged);\n\n qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));\n}\n\nvoid Musec::shuffleList()\n{\n \/\/ Shuffle song list\n for (int i = fSongs.size() - 1; i > 0; i--) {\n int random = qrand() % fSongs.size();\n QString str = fSongs[i];\n fSongs[i] = fSongs[random];\n fSongs[random] = str;\n }\n\n \/\/ Load first song\n lblInfo->setText(QString::number(fSongs.size()) + tr(\" Songs loaded (total)\"));\n loadSong(fSongs.first());\n}\n\nvoid Musec::loadSong(QString filename)\n{\n fStartTime = 0;\n fPlayer->setMedia(QUrl::fromLocalFile(filename));\n}\n\nvoid Musec::playSong()\n{\n lblInfo->setText(QTime(0,0,0).addSecs(fStartTime).toString(\"mm:ss\"));\n fPlayer->setPosition(fStartTime * 1000);\n fPlayer->play();\n fTimer->start(1000);\n}\n\nvoid Musec::evaluate()\n{\n QString title = fPlayer->metaData(QMediaMetaData::Title).toString();\n QString artist = fPlayer->metaData(QMediaMetaData::Author).toString();\n QString album = fPlayer->metaData(QMediaMetaData::AlbumTitle).toString();\n\n if (match(edTitle->text(), title)) {\n fScore += POINTS_TITLE;\n chkTitle->setChecked(true);\n }\n if (match(edArtist->text(), artist)) {\n fScore += POINTS_ARTIST;\n chkArtist->setChecked(true);\n }\n if (match(edAlbum->text(), album)) {\n fScore += POINTS_ALBUM;\n chkAlbum->setChecked(true);\n }\n\n edTitle->setText(title);\n edArtist->setText(artist);\n edAlbum->setText(album);\n\n fSongsPlayed++;\n quint32 maxScore = fSongsPlayed * (POINTS_TITLE +\n POINTS_ARTIST + POINTS_ALBUM);\n lblScore->setText(tr(\"Score: \") + QString::number(fScore) +\n \" (\" + QString::number(fScore * 100 \/ maxScore) + \"%)\");\n}\n\nbool Musec::match(QString str1, QString str2)\n{\n \/\/ Cast to lower case\n str1 = str1.toLower();\n str2 = str2.toLower();\n \/\/ Remove (...), [...] and non-alphabetic characters\n QRegularExpression regex(\"(\\\\(.*\\\\))|(\\\\[.*\\\\])|[^a-zA-Z]\");\n str1.remove(regex);\n str2.remove(regex);\n\n \/\/ Exact match\n if (str1 == str2)\n return true;\n return false;\n}\n\nvoid Musec::resetForm()\n{\n fIsActive = false;\n btnPlay->setText(tr(\"Play\"));\n btnPlay->setDisabled(true);\n btnNext->setDisabled(true);\n edTitle->setDisabled(true);\n edArtist->setDisabled(true);\n edAlbum->setDisabled(true);\n}\n\nvoid Musec::activateForm()\n{\n fIsActive = true;\n edTitle->clear();\n edArtist->clear();\n edAlbum->clear();\n btnPlay->setText(tr(\"Play Again\"));\n btnNext->setEnabled(true);\n edTitle->setEnabled(true);\n edArtist->setEnabled(true);\n edAlbum->setEnabled(true);\n chkTitle->setChecked(false);\n chkArtist->setChecked(false);\n chkAlbum->setChecked(false);\n}\n\nvoid Musec::timeout()\n{\n fPlayer->stop();\n}\n\nvoid Musec::durationChanged(qint64 duration)\n{\n if (duration <= 0)\n return;\n duration \/= 1000;\n qint64 startRange = duration * 0.1f;\n qint64 timeRange = duration * 0.8f;\n qint64 random = qrand() % timeRange;\n fStartTime = startRange + random;\n qDebug() << fPlayer->metaData(QMediaMetaData::Title).toString();\n qDebug() << fPlayer->metaData(QMediaMetaData::Author).toString();\n qDebug() << fPlayer->metaData(QMediaMetaData::AlbumTitle).toString();\n btnPlay->setEnabled(true);\n}\n\nvoid Musec::on_btnPlay_clicked()\n{\n if (!fIsActive)\n activateForm();\n playSong();\n}\n\nvoid Musec::on_btnNext_clicked()\n{\n evaluate();\n resetForm();\n\n \/\/ Remove song from queue\n if (!fSongs.isEmpty())\n fSongs.pop_front();\n\n \/\/ Load next song\n if (!fSongs.isEmpty())\n loadSong(fSongs.first());\n else\n lblInfo->setText(tr(\"No more songs left\"));\n}\n\nvoid Musec::on_btnAddDir_clicked()\n{\n lblInfo->setText(tr(\"Loading...\"));\n\n \/\/ Open dir and add music files to fSongs\n QString dir = QFileDialog::getExistingDirectory(this, tr(\"Select Directory\"),\n fDir, QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);\n if (dir.isEmpty()) {\n lblInfo->clear();\n return;\n }\n QDirIterator it(dir, fExtensions, QDir::Files, QDirIterator::Subdirectories);\n while (it.hasNext())\n fSongs << it.next();\n fDir = dir;\n if (fSongs.isEmpty()) {\n lblInfo->setText(tr(\"No Songs found\"));\n return;\n }\n\n shuffleList();\n}\n\nvoid Musec::on_btnAddFiles_clicked()\n{\n lblInfo->setText(tr(\"Loading...\"));\n\n \/\/ Add music files to fSongs\n QStringList files = QFileDialog::getOpenFileNames(this, tr(\"Select Files\"),\n fDir, \"Music (\" + fExtensions.join(\" \") + \")\");\n if (files.isEmpty()) {\n lblInfo->clear();\n return;\n }\n fDir = QFileInfo(files[0]).absolutePath();\n fSongs += files;\n if (fSongs.isEmpty()) {\n lblInfo->setText(tr(\"No Songs found\"));\n return;\n }\n\n shuffleList();\n}\n\nvoid Musec::on_btnClear_clicked()\n{\n resetForm();\n fSongs.clear();\n lblInfo->setText(tr(\"No more songs left\"));\n}\nAdjust points + minor fixes\/*==LICENSE==\nThis file is part of Musec.\nCopyright (C) 2013 Florian Meißner\n\nThis program is free software: you can redistribute it and\/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program. If not, see .\n==LICENSE==*\/\n\n#include \"Musec.h\"\n#include \n#include \n#include \n#include \n\n#define POINTS_TITLE 3\n#define POINTS_ARTIST 1\n#define POINTS_ALBUM 2\n\nMusec::Musec(QWidget* parent) : QWidget(parent)\n{\n setupUi(this);\n setWindowFlags(Qt::CustomizeWindowHint | Qt::WindowTitleHint |\n Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint |\n Qt::MSWindowsFixedSizeDialogHint);\n fPlayer = new QMediaPlayer(this, QMediaPlayer::LowLatency);\n fTimer = new QTimer(this);\n fTimer->setSingleShot(true);\n fDir = QDir::homePath();\n fScore = 0;\n fSongsPlayed = 0;\n fIsActive = false;\n\n fExtensions << \"*.mp3\" << \"*.m4a\"; \/\/ These should contain meta data\n\n connect(fTimer, &QTimer::timeout, this, &Musec::timeout);\n connect(fPlayer, &QMediaPlayer::durationChanged, this, &Musec::durationChanged);\n\n qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));\n}\n\nvoid Musec::shuffleList()\n{\n \/\/ Shuffle song list\n for (int i = fSongs.size() - 1; i >= 0; i--) {\n int random = qrand() % fSongs.size();\n QString str = fSongs[i];\n fSongs[i] = fSongs[random];\n fSongs[random] = str;\n }\n\n \/\/ Load first song\n lblInfo->setText(QString::number(fSongs.size()) + tr(\" Songs loaded (total)\"));\n loadSong(fSongs.first());\n}\n\nvoid Musec::loadSong(QString filename)\n{\n fStartTime = 0;\n fPlayer->setMedia(QUrl::fromLocalFile(filename));\n}\n\nvoid Musec::playSong()\n{\n lblInfo->setText(QTime(0,0,0).addSecs(fStartTime).toString(\"mm:ss\"));\n fPlayer->setPosition(fStartTime * 1000);\n fPlayer->play();\n fTimer->start(1000);\n}\n\nvoid Musec::evaluate()\n{\n QString title = fPlayer->metaData(QMediaMetaData::Title).toString();\n QString artist = fPlayer->metaData(QMediaMetaData::Author).toString();\n QString album = fPlayer->metaData(QMediaMetaData::AlbumTitle).toString();\n\n if (match(edTitle->text(), title)) {\n fScore += POINTS_TITLE;\n chkTitle->setChecked(true);\n }\n if (match(edArtist->text(), artist)) {\n fScore += POINTS_ARTIST;\n chkArtist->setChecked(true);\n }\n if (match(edAlbum->text(), album)) {\n fScore += POINTS_ALBUM;\n chkAlbum->setChecked(true);\n }\n\n edTitle->setText(title);\n edArtist->setText(artist);\n edAlbum->setText(album);\n\n fSongsPlayed++;\n quint32 maxScore = fSongsPlayed * (POINTS_TITLE +\n POINTS_ARTIST + POINTS_ALBUM);\n lblScore->setText(tr(\"Score: \") + QString::number(fScore) +\n \" (\" + QString::number(fScore * 100 \/ maxScore) + \"%)\");\n}\n\nbool Musec::match(QString str1, QString str2)\n{\n \/\/ Cast to lower case\n str1 = str1.toLower();\n str2 = str2.toLower();\n \/\/ Remove (...), [...] and non-alphabetic characters\n QRegularExpression regex(\"(\\\\(.*\\\\))|(\\\\[.*\\\\])|[^a-zA-Z]\");\n str1.remove(regex);\n str2.remove(regex);\n\n \/\/ Exact match\n if (str1 == str2)\n return true;\n return false;\n}\n\nvoid Musec::resetForm()\n{\n fIsActive = false;\n btnPlay->setText(tr(\"Play\"));\n btnPlay->setDisabled(true);\n btnNext->setDisabled(true);\n edTitle->setDisabled(true);\n edArtist->setDisabled(true);\n edAlbum->setDisabled(true);\n}\n\nvoid Musec::activateForm()\n{\n fIsActive = true;\n edTitle->clear();\n edArtist->clear();\n edAlbum->clear();\n btnPlay->setText(tr(\"Play Again\"));\n btnNext->setEnabled(true);\n edTitle->setEnabled(true);\n edArtist->setEnabled(true);\n edAlbum->setEnabled(true);\n chkTitle->setChecked(false);\n chkArtist->setChecked(false);\n chkAlbum->setChecked(false);\n}\n\nvoid Musec::timeout()\n{\n fPlayer->stop();\n}\n\nvoid Musec::durationChanged(qint64 duration)\n{\n if (duration <= 0)\n return;\n duration \/= 1000;\n qint64 startRange = duration * 0.1f;\n qint64 timeRange = duration * 0.8f;\n qint64 random = qrand() % timeRange;\n fStartTime = startRange + random;\n qDebug() << fPlayer->metaData(QMediaMetaData::Title).toString();\n qDebug() << fPlayer->metaData(QMediaMetaData::Author).toString();\n qDebug() << fPlayer->metaData(QMediaMetaData::AlbumTitle).toString();\n btnPlay->setEnabled(true);\n}\n\nvoid Musec::on_btnPlay_clicked()\n{\n if (!fIsActive)\n activateForm();\n playSong();\n}\n\nvoid Musec::on_btnNext_clicked()\n{\n evaluate();\n resetForm();\n\n \/\/ Remove song from queue\n if (!fSongs.isEmpty())\n fSongs.pop_front();\n\n \/\/ Load next song\n if (!fSongs.isEmpty())\n loadSong(fSongs.first());\n else\n lblInfo->setText(tr(\"No more songs left\"));\n}\n\nvoid Musec::on_btnAddDir_clicked()\n{\n lblInfo->setText(tr(\"Loading...\"));\n\n \/\/ Open dir and add music files to fSongs\n QString dir = QFileDialog::getExistingDirectory(this, tr(\"Select Directory\"),\n fDir, QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);\n if (dir.isEmpty()) {\n lblInfo->clear();\n return;\n }\n QDirIterator it(dir, fExtensions, QDir::Files, QDirIterator::Subdirectories);\n while (it.hasNext())\n fSongs << it.next();\n fDir = dir;\n if (fSongs.isEmpty()) {\n lblInfo->setText(tr(\"No Songs found\"));\n return;\n }\n\n shuffleList();\n}\n\nvoid Musec::on_btnAddFiles_clicked()\n{\n lblInfo->setText(tr(\"Loading...\"));\n\n \/\/ Add music files to fSongs\n QStringList files = QFileDialog::getOpenFileNames(this, tr(\"Select Files\"),\n fDir, \"Music (\" + fExtensions.join(\" \") + \")\");\n if (files.isEmpty()) {\n lblInfo->clear();\n return;\n }\n fDir = QFileInfo(files[0]).absolutePath();\n fSongs += files;\n if (fSongs.isEmpty()) {\n lblInfo->setText(tr(\"No Songs found\"));\n return;\n }\n\n shuffleList();\n}\n\nvoid Musec::on_btnClear_clicked()\n{\n resetForm();\n fSongs.clear();\n lblInfo->setText(tr(\"No more songs left\"));\n}\n<|endoftext|>"} {"text":"#include \"pch.h\"\r\n#include \"MyPin.h\"\r\n\r\n#include \"AudioRenderer.h\"\r\n\r\nnamespace SaneAudioRenderer\r\n{\r\n MyPin::MyPin(AudioRenderer& renderer, CBaseFilter* pFilter, CAMEvent& bufferFilled, HRESULT& result)\r\n : CBaseInputPin(L\"SaneAudioRenderer::MyPin\", pFilter, this, &result, L\"Input0\")\r\n , m_bufferFilled(bufferFilled)\r\n , m_renderer(renderer)\r\n {\r\n if (FAILED(result))\r\n return;\r\n\r\n if (static_cast(m_bufferFilled) == NULL)\r\n result = E_OUTOFMEMORY;\r\n }\r\n\r\n HRESULT MyPin::CheckMediaType(const CMediaType* pmt)\r\n {\r\n CheckPointer(pmt, E_POINTER);\r\n\r\n if (pmt->majortype == MEDIATYPE_Audio &&\r\n pmt->formattype == FORMAT_WaveFormatEx)\r\n {\r\n auto pFormat = reinterpret_cast(pmt->pbFormat);\r\n\r\n if (!pFormat ||\r\n pmt->cbFormat < sizeof(WAVEFORMATEX) ||\r\n pmt->cbFormat != sizeof(WAVEFORMATEX) + pFormat->cbSize)\r\n {\r\n return E_INVALIDARG;\r\n }\r\n\r\n try\r\n {\r\n if (m_renderer.CheckFormat(CopyWaveFormat(*pFormat)))\r\n return S_OK;\r\n }\r\n catch (std::bad_alloc&)\r\n {\r\n return E_OUTOFMEMORY;\r\n }\r\n }\r\n\r\n return S_FALSE;\r\n }\r\n\r\n HRESULT MyPin::SetMediaType(const CMediaType* pmt)\r\n {\r\n assert(CritCheckIn(this));\r\n\r\n ReturnIfFailed(CBaseInputPin::SetMediaType(pmt));\r\n\r\n auto pFormat = reinterpret_cast(pmt->pbFormat);\r\n\r\n \/\/ No point in doing integrity checks, that was done in CheckMediaType().\r\n assert(pFormat);\r\n assert(pmt->cbFormat == sizeof(WAVEFORMATEX) + pFormat->cbSize);\r\n\r\n try\r\n {\r\n m_renderer.SetFormat(CopyWaveFormat(*pFormat));\r\n }\r\n catch (std::bad_alloc&)\r\n {\r\n return E_OUTOFMEMORY;\r\n }\r\n\r\n return S_OK;\r\n }\r\n\r\n HRESULT MyPin::CompleteConnect(IPin* pPin)\r\n {\r\n assert(CritCheckIn(this));\r\n\r\n IAMGraphStreamsPtr graphStreams;\r\n IAMPushSourcePtr pushSource;\r\n if (SUCCEEDED(m_pFilter->GetFilterGraph()->QueryInterface(IID_PPV_ARGS(&graphStreams))) &&\r\n SUCCEEDED(graphStreams->FindUpstreamInterface(pPin, IID_PPV_ARGS(&pushSource), AM_INTF_SEARCH_OUTPUT_PIN)))\r\n {\r\n ULONG flags;\r\n if (SUCCEEDED(pushSource->GetPushSourceFlags(&flags)))\r\n {\r\n if (flags & AM_PUSHSOURCECAPS_INTERNAL_RM)\r\n DebugOut(\"MyPin upstream live pin has AM_PUSHSOURCECAPS_INTERNAL_RM flag\");\r\n\r\n if (flags & AM_PUSHSOURCECAPS_NOT_LIVE)\r\n DebugOut(\"MyPin upstream live pin has AM_PUSHSOURCECAPS_NOT_LIVE flag\");\r\n\r\n if (flags & AM_PUSHSOURCECAPS_PRIVATE_CLOCK)\r\n DebugOut(\"MyPin upstream live pin has AM_PUSHSOURCECAPS_PRIVATE_CLOCK flag\");\r\n\r\n if (flags & AM_PUSHSOURCEREQS_USE_STREAM_CLOCK)\r\n DebugOut(\"MyPin upstream live pin has AM_PUSHSOURCEREQS_USE_STREAM_CLOCK flag\");\r\n\r\n if (!flags)\r\n DebugOut(\"MyPin upstream live pin has no flags\");\r\n }\r\n }\r\n\r\n return S_OK;\r\n }\r\n\r\n STDMETHODIMP MyPin::NewSegment(REFERENCE_TIME startTime, REFERENCE_TIME stopTime, double rate)\r\n {\r\n CAutoLock receiveLock(&m_receiveMutex);\r\n CAutoLock objectLock(this);\r\n\r\n CBaseInputPin::NewSegment(startTime, stopTime, rate);\r\n m_renderer.NewSegment(rate);\r\n\r\n return S_OK;\r\n }\r\n\r\n STDMETHODIMP MyPin::Receive(IMediaSample* pSample)\r\n {\r\n CAutoLock receiveLock(&m_receiveMutex);\r\n\r\n {\r\n CAutoLock objectLock(this);\r\n\r\n if (m_state == State_Stopped)\r\n return VFW_E_WRONG_STATE;\r\n\r\n ReturnIfNotEquals(S_OK, CBaseInputPin::Receive(pSample));\r\n\r\n if (m_eosUp)\r\n return S_FALSE;\r\n }\r\n\r\n \/\/ Raise Receive() thread priority, once.\r\n if (m_hReceiveThread != GetCurrentThread())\r\n {\r\n m_hReceiveThread = GetCurrentThread();\r\n if (GetThreadPriority(m_hReceiveThread) < THREAD_PRIORITY_ABOVE_NORMAL)\r\n SetThreadPriority(m_hReceiveThread, THREAD_PRIORITY_ABOVE_NORMAL);\r\n }\r\n\r\n if (m_SampleProps.dwSampleFlags & AM_SAMPLE_TYPECHANGED)\r\n {\r\n m_renderer.Finish(false);\r\n ReturnIfFailed(SetMediaType(static_cast(m_SampleProps.pMediaType)));\r\n }\r\n\r\n return m_renderer.Enqueue(pSample, m_SampleProps) ? S_OK : S_FALSE;\r\n }\r\n\r\n STDMETHODIMP MyPin::EndOfStream()\r\n {\r\n CAutoLock receiveLock(&m_receiveMutex);\r\n\r\n {\r\n CAutoLock objectLock(this);\r\n\r\n if (m_state == State_Stopped)\r\n return VFW_E_WRONG_STATE;\r\n\r\n if (m_bFlushing)\r\n return S_FALSE;\r\n\r\n m_eosUp = true;\r\n }\r\n\r\n \/\/ We ask audio renderer to block until all samples are played.\r\n \/\/ The method returns 'false' in case of interruption.\r\n bool eosDown = m_renderer.Finish(true);\r\n\r\n {\r\n CAutoLock objectLock(this);\r\n\r\n m_eosDown = eosDown;\r\n\r\n if (m_eosDown)\r\n {\r\n m_pFilter->NotifyEvent(EC_COMPLETE, S_OK, (LONG_PTR)m_pFilter);\r\n m_bufferFilled.Set();\r\n }\r\n }\r\n\r\n return S_OK;\r\n }\r\n\r\n STDMETHODIMP MyPin::BeginFlush()\r\n {\r\n \/\/ Parent method locks the object before modifying it, all is good.\r\n CBaseInputPin::BeginFlush();\r\n\r\n m_renderer.BeginFlush();\r\n\r\n \/\/ Barrier for any present Receive() and EndOfStream() calls.\r\n \/\/ Subsequent ones will be rejected because m_bFlushing == TRUE.\r\n CAutoLock receiveLock(&m_receiveMutex);\r\n\r\n {\r\n CAutoLock objectLock(this);\r\n\r\n m_eosUp = false;\r\n m_eosDown = false;\r\n }\r\n\r\n m_hReceiveThread = NULL;\r\n\r\n m_renderer.EndFlush();\r\n\r\n return S_OK;\r\n }\r\n\r\n STDMETHODIMP MyPin::EndFlush()\r\n {\r\n \/\/ Parent method locks the object before modifying it, all is good.\r\n CBaseInputPin::EndFlush();\r\n\r\n return S_OK;\r\n }\r\n\r\n HRESULT MyPin::Active()\r\n {\r\n CAutoLock objectLock(this);\r\n\r\n assert(m_state != State_Paused);\r\n m_state = State_Paused;\r\n\r\n if (IsConnected())\r\n {\r\n m_renderer.Pause();\r\n }\r\n else\r\n {\r\n m_eosUp = true;\r\n m_eosDown = true;\r\n }\r\n\r\n return S_OK;\r\n }\r\n\r\n HRESULT MyPin::Run(REFERENCE_TIME startTime)\r\n {\r\n CAutoLock objectLock(this);\r\n\r\n assert(m_state == State_Paused);\r\n m_state = State_Running;\r\n\r\n if (m_eosDown)\r\n {\r\n m_pFilter->NotifyEvent(EC_COMPLETE, S_OK, (LONG_PTR)m_pFilter);\r\n }\r\n else\r\n {\r\n assert(IsConnected());\r\n m_renderer.Play(startTime);\r\n }\r\n\r\n return S_OK;\r\n }\r\n\r\n HRESULT MyPin::Inactive()\r\n {\r\n {\r\n CAutoLock objectLock(this);\r\n\r\n assert(m_state != State_Stopped);\r\n m_state = State_Stopped;\r\n\r\n CBaseInputPin::Inactive();\r\n }\r\n\r\n m_renderer.BeginFlush();\r\n\r\n \/\/ Barrier for any present Receive() and EndOfStream() calls.\r\n \/\/ Subsequent ones will be rejected because m_state == State_Stopped.\r\n CAutoLock receiveLock(&m_receiveMutex);\r\n\r\n {\r\n CAutoLock objectLock(this);\r\n\r\n m_eosUp = false;\r\n m_eosDown = false;\r\n }\r\n\r\n m_hReceiveThread = NULL;\r\n\r\n m_renderer.Stop();\r\n m_renderer.EndFlush();\r\n\r\n return S_OK;\r\n }\r\n\r\n bool MyPin::StateTransitionFinished(uint32_t timeoutMilliseconds)\r\n {\r\n {\r\n CAutoLock objectLock(this);\r\n\r\n if (!IsConnected() || m_state == State_Stopped)\r\n return true;\r\n }\r\n\r\n \/\/ Don't lock the object, we don't want to block Receive() method.\r\n\r\n \/\/ There won't be any state transitions during the wait,\r\n \/\/ because MyFilter always locks itself before calling this method.\r\n\r\n return !!m_bufferFilled.Wait(timeoutMilliseconds);\r\n }\r\n}\r\nMinor cosmetics in MyPin comments#include \"pch.h\"\r\n#include \"MyPin.h\"\r\n\r\n#include \"AudioRenderer.h\"\r\n\r\nnamespace SaneAudioRenderer\r\n{\r\n MyPin::MyPin(AudioRenderer& renderer, CBaseFilter* pFilter, CAMEvent& bufferFilled, HRESULT& result)\r\n : CBaseInputPin(L\"SaneAudioRenderer::MyPin\", pFilter, this, &result, L\"Input0\")\r\n , m_bufferFilled(bufferFilled)\r\n , m_renderer(renderer)\r\n {\r\n if (FAILED(result))\r\n return;\r\n\r\n if (static_cast(m_bufferFilled) == NULL)\r\n result = E_OUTOFMEMORY;\r\n }\r\n\r\n HRESULT MyPin::CheckMediaType(const CMediaType* pmt)\r\n {\r\n CheckPointer(pmt, E_POINTER);\r\n\r\n if (pmt->majortype == MEDIATYPE_Audio &&\r\n pmt->formattype == FORMAT_WaveFormatEx)\r\n {\r\n auto pFormat = reinterpret_cast(pmt->pbFormat);\r\n\r\n if (!pFormat ||\r\n pmt->cbFormat < sizeof(WAVEFORMATEX) ||\r\n pmt->cbFormat != sizeof(WAVEFORMATEX) + pFormat->cbSize)\r\n {\r\n return E_INVALIDARG;\r\n }\r\n\r\n try\r\n {\r\n if (m_renderer.CheckFormat(CopyWaveFormat(*pFormat)))\r\n return S_OK;\r\n }\r\n catch (std::bad_alloc&)\r\n {\r\n return E_OUTOFMEMORY;\r\n }\r\n }\r\n\r\n return S_FALSE;\r\n }\r\n\r\n HRESULT MyPin::SetMediaType(const CMediaType* pmt)\r\n {\r\n assert(CritCheckIn(this));\r\n\r\n ReturnIfFailed(CBaseInputPin::SetMediaType(pmt));\r\n\r\n auto pFormat = reinterpret_cast(pmt->pbFormat);\r\n\r\n \/\/ No point in doing integrity checks, that was done in CheckMediaType().\r\n assert(pFormat);\r\n assert(pmt->cbFormat == sizeof(WAVEFORMATEX) + pFormat->cbSize);\r\n\r\n try\r\n {\r\n m_renderer.SetFormat(CopyWaveFormat(*pFormat));\r\n }\r\n catch (std::bad_alloc&)\r\n {\r\n return E_OUTOFMEMORY;\r\n }\r\n\r\n return S_OK;\r\n }\r\n\r\n HRESULT MyPin::CompleteConnect(IPin* pPin)\r\n {\r\n assert(CritCheckIn(this));\r\n\r\n IAMGraphStreamsPtr graphStreams;\r\n IAMPushSourcePtr pushSource;\r\n if (SUCCEEDED(m_pFilter->GetFilterGraph()->QueryInterface(IID_PPV_ARGS(&graphStreams))) &&\r\n SUCCEEDED(graphStreams->FindUpstreamInterface(pPin, IID_PPV_ARGS(&pushSource), AM_INTF_SEARCH_OUTPUT_PIN)))\r\n {\r\n ULONG flags;\r\n if (SUCCEEDED(pushSource->GetPushSourceFlags(&flags)))\r\n {\r\n if (flags & AM_PUSHSOURCECAPS_INTERNAL_RM)\r\n DebugOut(\"MyPin upstream live pin has AM_PUSHSOURCECAPS_INTERNAL_RM flag\");\r\n\r\n if (flags & AM_PUSHSOURCECAPS_NOT_LIVE)\r\n DebugOut(\"MyPin upstream live pin has AM_PUSHSOURCECAPS_NOT_LIVE flag\");\r\n\r\n if (flags & AM_PUSHSOURCECAPS_PRIVATE_CLOCK)\r\n DebugOut(\"MyPin upstream live pin has AM_PUSHSOURCECAPS_PRIVATE_CLOCK flag\");\r\n\r\n if (flags & AM_PUSHSOURCEREQS_USE_STREAM_CLOCK)\r\n DebugOut(\"MyPin upstream live pin has AM_PUSHSOURCEREQS_USE_STREAM_CLOCK flag\");\r\n\r\n if (!flags)\r\n DebugOut(\"MyPin upstream live pin has no flags\");\r\n }\r\n }\r\n\r\n return S_OK;\r\n }\r\n\r\n STDMETHODIMP MyPin::NewSegment(REFERENCE_TIME startTime, REFERENCE_TIME stopTime, double rate)\r\n {\r\n CAutoLock receiveLock(&m_receiveMutex);\r\n CAutoLock objectLock(this);\r\n\r\n CBaseInputPin::NewSegment(startTime, stopTime, rate);\r\n m_renderer.NewSegment(rate);\r\n\r\n return S_OK;\r\n }\r\n\r\n STDMETHODIMP MyPin::Receive(IMediaSample* pSample)\r\n {\r\n CAutoLock receiveLock(&m_receiveMutex);\r\n\r\n {\r\n CAutoLock objectLock(this);\r\n\r\n if (m_state == State_Stopped)\r\n return VFW_E_WRONG_STATE;\r\n\r\n ReturnIfNotEquals(S_OK, CBaseInputPin::Receive(pSample));\r\n\r\n if (m_eosUp)\r\n return S_FALSE;\r\n }\r\n\r\n \/\/ Raise Receive() thread priority, once.\r\n if (m_hReceiveThread != GetCurrentThread())\r\n {\r\n m_hReceiveThread = GetCurrentThread();\r\n if (GetThreadPriority(m_hReceiveThread) < THREAD_PRIORITY_ABOVE_NORMAL)\r\n SetThreadPriority(m_hReceiveThread, THREAD_PRIORITY_ABOVE_NORMAL);\r\n }\r\n\r\n if (m_SampleProps.dwSampleFlags & AM_SAMPLE_TYPECHANGED)\r\n {\r\n m_renderer.Finish(false);\r\n ReturnIfFailed(SetMediaType(static_cast(m_SampleProps.pMediaType)));\r\n }\r\n\r\n \/\/ Enqueue() returns 'false' in case of interruption.\r\n return m_renderer.Enqueue(pSample, m_SampleProps) ? S_OK : S_FALSE;\r\n }\r\n\r\n STDMETHODIMP MyPin::EndOfStream()\r\n {\r\n CAutoLock receiveLock(&m_receiveMutex);\r\n\r\n {\r\n CAutoLock objectLock(this);\r\n\r\n if (m_state == State_Stopped)\r\n return VFW_E_WRONG_STATE;\r\n\r\n if (m_bFlushing)\r\n return S_FALSE;\r\n\r\n m_eosUp = true;\r\n }\r\n\r\n \/\/ We ask audio renderer to block until all samples are played.\r\n \/\/ Finish() returns 'false' in case of interruption.\r\n bool eosDown = m_renderer.Finish(true);\r\n\r\n {\r\n CAutoLock objectLock(this);\r\n\r\n m_eosDown = eosDown;\r\n\r\n if (m_eosDown)\r\n {\r\n m_pFilter->NotifyEvent(EC_COMPLETE, S_OK, (LONG_PTR)m_pFilter);\r\n m_bufferFilled.Set();\r\n }\r\n }\r\n\r\n return S_OK;\r\n }\r\n\r\n STDMETHODIMP MyPin::BeginFlush()\r\n {\r\n \/\/ Parent method locks the object before modifying it, all is good.\r\n CBaseInputPin::BeginFlush();\r\n\r\n m_renderer.BeginFlush();\r\n\r\n \/\/ Barrier for any present Receive() and EndOfStream() calls.\r\n \/\/ Subsequent ones will be rejected because m_bFlushing == TRUE.\r\n CAutoLock receiveLock(&m_receiveMutex);\r\n\r\n {\r\n CAutoLock objectLock(this);\r\n\r\n m_eosUp = false;\r\n m_eosDown = false;\r\n }\r\n\r\n m_hReceiveThread = NULL;\r\n\r\n m_renderer.EndFlush();\r\n\r\n return S_OK;\r\n }\r\n\r\n STDMETHODIMP MyPin::EndFlush()\r\n {\r\n \/\/ Parent method locks the object before modifying it, all is good.\r\n CBaseInputPin::EndFlush();\r\n\r\n return S_OK;\r\n }\r\n\r\n HRESULT MyPin::Active()\r\n {\r\n CAutoLock objectLock(this);\r\n\r\n assert(m_state != State_Paused);\r\n m_state = State_Paused;\r\n\r\n if (IsConnected())\r\n {\r\n m_renderer.Pause();\r\n }\r\n else\r\n {\r\n m_eosUp = true;\r\n m_eosDown = true;\r\n }\r\n\r\n return S_OK;\r\n }\r\n\r\n HRESULT MyPin::Run(REFERENCE_TIME startTime)\r\n {\r\n CAutoLock objectLock(this);\r\n\r\n assert(m_state == State_Paused);\r\n m_state = State_Running;\r\n\r\n if (m_eosDown)\r\n {\r\n m_pFilter->NotifyEvent(EC_COMPLETE, S_OK, (LONG_PTR)m_pFilter);\r\n }\r\n else\r\n {\r\n assert(IsConnected());\r\n m_renderer.Play(startTime);\r\n }\r\n\r\n return S_OK;\r\n }\r\n\r\n HRESULT MyPin::Inactive()\r\n {\r\n {\r\n CAutoLock objectLock(this);\r\n\r\n assert(m_state != State_Stopped);\r\n m_state = State_Stopped;\r\n\r\n CBaseInputPin::Inactive();\r\n }\r\n\r\n m_renderer.BeginFlush();\r\n\r\n \/\/ Barrier for any present Receive() and EndOfStream() calls.\r\n \/\/ Subsequent ones will be rejected because m_state == State_Stopped.\r\n CAutoLock receiveLock(&m_receiveMutex);\r\n\r\n {\r\n CAutoLock objectLock(this);\r\n\r\n m_eosUp = false;\r\n m_eosDown = false;\r\n }\r\n\r\n m_hReceiveThread = NULL;\r\n\r\n m_renderer.Stop();\r\n m_renderer.EndFlush();\r\n\r\n return S_OK;\r\n }\r\n\r\n bool MyPin::StateTransitionFinished(uint32_t timeoutMilliseconds)\r\n {\r\n {\r\n CAutoLock objectLock(this);\r\n\r\n if (!IsConnected() || m_state == State_Stopped)\r\n return true;\r\n }\r\n\r\n \/\/ Don't lock the object, we don't want to block Receive() method.\r\n\r\n \/\/ There won't be any state transitions during the wait,\r\n \/\/ because MyFilter always locks itself before calling this method.\r\n\r\n return !!m_bufferFilled.Wait(timeoutMilliseconds);\r\n }\r\n}\r\n<|endoftext|>"} {"text":"\/* TMP36 library\r\n \r\n Copyright 2017 Isaac100\r\n\r\n Licensed under the Apache License, Version 2.0 (the \"License\");\r\n you may not use this file except in compliance with the License.\r\n You may obtain a copy of the License at\r\n\r\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\r\n \r\n Unless required by applicable law or agreed to in writing,\r\n software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n See the License for the specific language governing permissions and\r\n limitations under the License.\r\n \r\n This library converts the analog values from a TMP36 temperature\r\n sensor directly into Celcius and Fahrenheit so you don't have to. \r\n *\/\r\n\r\n#include \"Arduino.h\"\r\n#include \"TMP36.h\"\r\n\r\nTMP36::TMP36(int pin)\r\n{\r\n pinMode(pin, INPUT);\r\n _pin = pin; \r\n}\r\n\r\nfloat TMP36::getVoltage()\r\n{\r\n _value = analogRead(_pin);\r\n _voltage = (_value\/1024.0) * 5.0;\r\n return _voltage;\r\n}\r\n\r\nfloat TMP36::getTempC()\r\n{\r\n _value = analogRead(_pin);\r\n _voltage = (_value\/1024.0) * 5.0;\r\n _tempC = (_voltage - .5) * 100; \r\n return _tempC;\r\n}\r\n\r\nfloat TMP36::getTempF()\r\n{\r\n _value = analogRead(_pin);\r\n _voltage = (_value\/1024.0) * 5.0;\r\n _tempC = (_voltage - .5) * 100; \r\n _tempF = (_tempC * 1.8) + 32; \r\n return _tempF;\r\n}\r\n\r\n\r\nUpdate TMP36.cpp\/* TMP36 library\r\n \r\n Copyright 2017 Isaac100\r\n\r\n Licensed under the Apache License, Version 2.0 (the \"License\");\r\n you may not use this file except in compliance with the License.\r\n You may obtain a copy of the License at\r\n\r\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\r\n \r\n Unless required by applicable law or agreed to in writing,\r\n software distributed under the License is distributed on an \"AS IS\" BASIS, \r\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n See the License for the specific language governing permissions and\r\n limitations under the License.\r\n \r\n This library converts the analog values from a TMP36 temperature\r\n sensor directly into Celcius and Fahrenheit so you don't have to. \r\n *\/\r\n\r\n#include \"Arduino.h\"\r\n#include \"TMP36.h\"\r\n\r\nTMP36::TMP36(int pin)\r\n{\r\n pinMode(pin, INPUT);\r\n _pin = pin; \r\n}\r\n\r\nfloat TMP36::getVoltage()\r\n{\r\n _value = analogRead(_pin);\r\n _voltage = (_value\/1024.0) * 5.0;\r\n return _voltage;\r\n}\r\n\r\nfloat TMP36::getTempC()\r\n{\r\n _value = analogRead(_pin);\r\n _voltage = (_value\/1024.0) * 5.0;\r\n _tempC = (_voltage - .5) * 100; \r\n return _tempC;\r\n}\r\n\r\nfloat TMP36::getTempF()\r\n{\r\n _value = analogRead(_pin);\r\n _voltage = (_value\/1024.0) * 5.0;\r\n _tempC = (_voltage - .5) * 100; \r\n _tempF = (_tempC * 1.8) + 32; \r\n return _tempF;\r\n}\r\n\r\n\r\n<|endoftext|>"} {"text":"\/**\n * @file Timer.hpp\n * @author Denis Kotov\n * @date 10 Jun 2017\n * @brief Thread safe version of Timer class\n * It is based on boost::asio::deadline_timer\n * @copyright Denis Kotov, MIT License. Open source: https:\/\/github.com\/redradist\/Inter-Component-Communication.git\n *\/\n\n#ifndef ICC_TIMER_HPP\n#define ICC_TIMER_HPP\n\n#include \n#include \n#include \"IComponent.hpp\"\n#include \"ITimerListener.hpp\"\n\nnamespace icc {\n\nclass Timer\n : protected virtual IComponent,\n public Event {\n public:\n enum : int32_t {\n \/**\n * Should be used for setting continuous mode\n *\/\n Infinite = -1,\n \/**\n * Should be used for setting one time mode\n *\/\n OneTime = 0,\n };\n\n public:\n Timer(IComponent *_parent)\n : IComponent(_parent),\n timer_(*service_) {\n }\n\n public:\n \/**\n * Enable continuous mode\n *\/\n void enableContinuous() {\n push([=] {\n counter_ = Infinite;\n });\n }\n\n \/**\n * Disable continuous mode\n *\/\n void disableContinuous() {\n push([=] {\n if (Infinite == counter_) {\n counter_ = OneTime;\n }\n });\n }\n\n \/**\n * Setting number of repetitions\n * @param number Number of repetition\n *\/\n void setNumberOfRepetition(const int32_t &number) {\n push([=] {\n if (number < 0) {\n counter_ = Infinite;\n } else {\n counter_ = number;\n }\n });\n }\n\n \/**\n * Setting interval mode for the timer\n * @param _duration Timeout duration\n *\/\n void setInterval(const boost::posix_time::time_duration &_duration) {\n push([=] {\n duration_ = _duration;\n });\n }\n\n \/**\n * Method is used to start async waiting timer\n *\/\n void start() {\n push([=] {\n timer_.expires_from_now(duration_);\n operator()(TimerEvents::STARTED);\n timer_.async_wait(std::bind(&Timer::timerExpired, this, std::placeholders::_1));\n });\n }\n\n \/**\n * Method is used to stop waiting timer\n *\/\n void stop() {\n push([=] {\n operator()(TimerEvents::STOPPED);\n timer_.cancel();\n });\n }\n\n \/**\n * Method is used to add the listener\n * @param _listener Listener that is being adding\n *\/\n template\n void addListener(_Listener *_listener) {\n static_assert(std::is_base_of::value,\n \"_listener is not derived from IComponent\");\n static_assert(std::is_base_of::value,\n \"_listener is not derived from ITimerLisener\");\n if (_listener) {\n this->connect(&_Listener::processEvent, _listener);\n }\n }\n\n \/**\n * Method is used to add the listener\n * @param _listener Listener that is being adding\n *\/\n template\n void addListener(std::shared_ptr<_Listener> _listener) {\n static_assert(std::is_base_of::value,\n \"_listener is not derived from IComponent\");\n static_assert(std::is_base_of::value,\n \"_listener is not derived from ITimerLisener\");\n if (_listener) {\n this->connect(&_Listener::processEvent, _listener);\n }\n }\n\n \/**\n * Method is used to remove the listener\n * @param _listener Listener that is being removing\n *\/\n template\n void removeListener(_Listener *_listener) {\n static_assert(std::is_base_of::value,\n \"_listener is not derived from IComponent\");\n static_assert(std::is_base_of::value,\n \"_listener is not derived from ITimerLisener\");\n if (_listener) {\n this->disconnect(&_Listener::processEvent, _listener);\n }\n }\n\n \/**\n * Method is used to remove the listener\n * @param _listener Listener that is being removing\n *\/\n template\n void removeListener(std::shared_ptr<_Listener> _listener) {\n static_assert(std::is_base_of::value,\n \"_listener is not derived from IComponent\");\n static_assert(std::is_base_of::value,\n \"_listener is not derived from ITimerLisener\");\n if (_listener) {\n this->disconnect(&_Listener::processEvent, _listener);\n }\n }\n\n \/**\n * Overrided function to specify exit event\n *\/\n void exit() override {\n push([=] {\n IComponent::exit();\n stop();\n });\n }\n\n protected:\n \/**\n * Method that handle Timer expire event\n * @param _error\n *\/\n virtual void timerExpired(const boost::system::error_code &_error) {\n if (!_error) {\n operator()(TimerEvents::EXPIRED);\n if (counter_ > 0) {\n --counter_;\n }\n if (Infinite == counter_ ||\n counter_ > 0) {\n start();\n }\n }\n }\n\n protected:\n int32_t counter_;\n boost::posix_time::time_duration duration_;\n boost::asio::deadline_timer timer_;\n};\n\n}\n\n#endif \/\/ICC_TIMER_HPP\nReplaced psuh method with send from IComponent in Timer\/**\n * @file Timer.hpp\n * @author Denis Kotov\n * @date 10 Jun 2017\n * @brief Thread safe version of Timer class\n * It is based on boost::asio::deadline_timer\n * @copyright Denis Kotov, MIT License. Open source: https:\/\/github.com\/redradist\/Inter-Component-Communication.git\n *\/\n\n#ifndef ICC_TIMER_HPP\n#define ICC_TIMER_HPP\n\n#include \n#include \n#include \"IComponent.hpp\"\n#include \"ITimerListener.hpp\"\n\nnamespace icc {\n\nclass Timer\n : protected virtual IComponent,\n public Event {\n public:\n enum : int32_t {\n \/**\n * Should be used for setting continuous mode\n *\/\n Infinite = -1,\n \/**\n * Should be used for setting one time mode\n *\/\n OneTime = 0,\n };\n\n public:\n Timer(IComponent *_parent)\n : IComponent(_parent),\n timer_(*service_) {\n }\n\n public:\n \/**\n * Enable continuous mode\n *\/\n void enableContinuous() {\n send([=] {\n counter_ = Infinite;\n });\n }\n\n \/**\n * Disable continuous mode\n *\/\n void disableContinuous() {\n send([=] {\n if (Infinite == counter_) {\n counter_ = OneTime;\n }\n });\n }\n\n \/**\n * Setting number of repetitions\n * @param number Number of repetition\n *\/\n void setNumberOfRepetition(const int32_t &number) {\n send([=] {\n if (number < 0) {\n counter_ = Infinite;\n } else {\n counter_ = number;\n }\n });\n }\n\n \/**\n * Setting interval mode for the timer\n * @param _duration Timeout duration\n *\/\n void setInterval(const boost::posix_time::time_duration &_duration) {\n send([=] {\n duration_ = _duration;\n });\n }\n\n \/**\n * Method is used to start async waiting timer\n *\/\n void start() {\n send([=] {\n timer_.expires_from_now(duration_);\n operator()(TimerEvents::STARTED);\n timer_.async_wait(std::bind(&Timer::timerExpired, this, std::placeholders::_1));\n });\n }\n\n \/**\n * Method is used to stop waiting timer\n *\/\n void stop() {\n send([=] {\n operator()(TimerEvents::STOPPED);\n timer_.cancel();\n });\n }\n\n \/**\n * Method is used to add the listener\n * @param _listener Listener that is being adding\n *\/\n template\n void addListener(_Listener *_listener) {\n static_assert(std::is_base_of::value,\n \"_listener is not derived from IComponent\");\n static_assert(std::is_base_of::value,\n \"_listener is not derived from ITimerLisener\");\n if (_listener) {\n this->connect(&_Listener::processEvent, _listener);\n }\n }\n\n \/**\n * Method is used to add the listener\n * @param _listener Listener that is being adding\n *\/\n template\n void addListener(std::shared_ptr<_Listener> _listener) {\n static_assert(std::is_base_of::value,\n \"_listener is not derived from IComponent\");\n static_assert(std::is_base_of::value,\n \"_listener is not derived from ITimerLisener\");\n if (_listener) {\n this->connect(&_Listener::processEvent, _listener);\n }\n }\n\n \/**\n * Method is used to remove the listener\n * @param _listener Listener that is being removing\n *\/\n template\n void removeListener(_Listener *_listener) {\n static_assert(std::is_base_of::value,\n \"_listener is not derived from IComponent\");\n static_assert(std::is_base_of::value,\n \"_listener is not derived from ITimerLisener\");\n if (_listener) {\n this->disconnect(&_Listener::processEvent, _listener);\n }\n }\n\n \/**\n * Method is used to remove the listener\n * @param _listener Listener that is being removing\n *\/\n template\n void removeListener(std::shared_ptr<_Listener> _listener) {\n static_assert(std::is_base_of::value,\n \"_listener is not derived from IComponent\");\n static_assert(std::is_base_of::value,\n \"_listener is not derived from ITimerLisener\");\n if (_listener) {\n this->disconnect(&_Listener::processEvent, _listener);\n }\n }\n\n \/**\n * Overrided function to specify exit event\n *\/\n void exit() override {\n push([=] {\n IComponent::exit();\n stop();\n });\n }\n\n protected:\n \/**\n * Method that handle Timer expire event\n * @param _error\n *\/\n virtual void timerExpired(const boost::system::error_code &_error) {\n if (!_error) {\n operator()(TimerEvents::EXPIRED);\n if (counter_ > 0) {\n --counter_;\n }\n if (Infinite == counter_ ||\n counter_ > 0) {\n start();\n }\n }\n }\n\n protected:\n int32_t counter_;\n boost::posix_time::time_duration duration_;\n boost::asio::deadline_timer timer_;\n};\n\n}\n\n#endif \/\/ICC_TIMER_HPP\n<|endoftext|>"} {"text":"\/\/\n\/\/ Alert system\n\/\/\n\n#include \n#include \n\n#include \"alert.h\"\n#include \"key.h\"\n#include \"net.h\"\n#include \"sync.h\"\n#include \"ui_interface.h\"\n\nusing namespace std;\n\nmap mapAlerts;\nCCriticalSection cs_mapAlerts;\n\n\/\/ old alert keys\n\/\/ static const char* pszMainKey = \"049b3c00249474820bc073896202bf04448e4391e445149b077d6eacccb9902d1b15e891fd8d24bfa43ccef05707797c6871292e145acbec6017d7d818b3748579\";\n\/\/ TestNet\n\/\/ static const char* pszTestKey = \"044d5253cb7c6fcb7b790365ac5aeeef359fc52de23f1ce9bffc092c16dd0372444b75ba328ddf4ebb73257e7c882c9bf81d86d1938ad36ac280214ba72aa9aca6\";\n\n\/\/ new alert keys ofeefee 2014-07-10 05:59:14\n static const char* pszMainKey = \"049b47fd94bc88f642beb798c61611527cb4a22171084eccafd57bae512762e01351fc46eb3b9030e18ac10903b9ebb17a91742a400701c3bfbc3d0238bb124daa\";\n\/\/ TestNet\n static const char* pszTestKey = \"0442968405805c5ade077461e4b83f30919e9fdef2133d2b64a05acaa28e2dcc60656e021daecfa35e50d2dd770f600082989d346c81aef97bc42b372afd4edc06\";\n\nvoid CUnsignedAlert::SetNull()\n{\n nVersion = 1;\n nRelayUntil = 0;\n nExpiration = 0;\n nID = 0;\n nCancel = 0;\n setCancel.clear();\n nMinVer = 0;\n nMaxVer = 0;\n setSubVer.clear();\n nPriority = 0;\n\n strComment.clear();\n strStatusBar.clear();\n strReserved.clear();\n}\n\nstd::string CUnsignedAlert::ToString() const\n{\n std::string strSetCancel;\n BOOST_FOREACH(int n, setCancel)\n strSetCancel += strprintf(\"%d \", n);\n std::string strSetSubVer;\n BOOST_FOREACH(std::string str, setSubVer)\n strSetSubVer += \"\\\"\" + str + \"\\\" \";\n return strprintf(\n \"CAlert(\\n\"\n \" nVersion = %d\\n\"\n \" nRelayUntil = %\"PRI64d\"\\n\"\n \" nExpiration = %\"PRI64d\"\\n\"\n \" nID = %d\\n\"\n \" nCancel = %d\\n\"\n \" setCancel = %s\\n\"\n \" nMinVer = %d\\n\"\n \" nMaxVer = %d\\n\"\n \" setSubVer = %s\\n\"\n \" nPriority = %d\\n\"\n \" strComment = \\\"%s\\\"\\n\"\n \" strStatusBar = \\\"%s\\\"\\n\"\n \")\\n\",\n nVersion,\n nRelayUntil,\n nExpiration,\n nID,\n nCancel,\n strSetCancel.c_str(),\n nMinVer,\n nMaxVer,\n strSetSubVer.c_str(),\n nPriority,\n strComment.c_str(),\n strStatusBar.c_str());\n}\n\nvoid CUnsignedAlert::print() const\n{\n printf(\"%s\", ToString().c_str());\n}\n\nvoid CAlert::SetNull()\n{\n CUnsignedAlert::SetNull();\n vchMsg.clear();\n vchSig.clear();\n}\n\nbool CAlert::IsNull() const\n{\n return (nExpiration == 0);\n}\n\nuint256 CAlert::GetHash() const\n{\n return Hash(this->vchMsg.begin(), this->vchMsg.end());\n}\n\nbool CAlert::IsInEffect() const\n{\n return (GetAdjustedTime() < nExpiration);\n}\n\nbool CAlert::Cancels(const CAlert& alert) const\n{\n if (!IsInEffect())\n return false; \/\/ this was a no-op before 31403\n return (alert.nID <= nCancel || setCancel.count(alert.nID));\n}\n\nbool CAlert::AppliesTo(int nVersion, std::string strSubVerIn) const\n{\n \/\/ TODO: rework for client-version-embedded-in-strSubVer ?\n return (IsInEffect() &&\n nMinVer <= nVersion && nVersion <= nMaxVer &&\n (setSubVer.empty() || setSubVer.count(strSubVerIn)));\n}\n\nbool CAlert::AppliesToMe() const\n{\n return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector()));\n}\n\nbool CAlert::RelayTo(CNode* pnode) const\n{\n if (!IsInEffect())\n return false;\n \/\/ returns true if wasn't already contained in the set\n if (pnode->setKnown.insert(GetHash()).second)\n {\n if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||\n AppliesToMe() ||\n GetAdjustedTime() < nRelayUntil)\n {\n pnode->PushMessage(\"alert\", *this);\n return true;\n }\n }\n return false;\n}\n\nbool CAlert::CheckSignature() const\n{\n CKey key;\n if (!key.SetPubKey(ParseHex(fTestNet ? pszTestKey : pszMainKey)))\n return error(\"CAlert::CheckSignature() : SetPubKey failed\");\n if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))\n return error(\"CAlert::CheckSignature() : verify signature failed\");\n\n \/\/ Now unserialize the data\n CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);\n sMsg >> *(CUnsignedAlert*)this;\n return true;\n}\n\nCAlert CAlert::getAlertByHash(const uint256 &hash)\n{\n CAlert retval;\n {\n LOCK(cs_mapAlerts);\n map::iterator mi = mapAlerts.find(hash);\n if(mi != mapAlerts.end())\n retval = mi->second;\n }\n return retval;\n}\n\nbool CAlert::ProcessAlert()\n{\n if (!CheckSignature())\n return false;\n if (!IsInEffect())\n return false;\n\n \/\/ alert.nID=max is reserved for if the alert key is\n \/\/ compromised. It must have a pre-defined message,\n \/\/ must never expire, must apply to all versions,\n \/\/ and must cancel all previous\n \/\/ alerts or it will be ignored (so an attacker can't\n \/\/ send an \"everything is OK, don't panic\" version that\n \/\/ cannot be overridden):\n int maxInt = std::numeric_limits::max();\n if (nID == maxInt)\n {\n if (!(\n nExpiration == maxInt &&\n nCancel == (maxInt-1) &&\n nMinVer == 0 &&\n nMaxVer == maxInt &&\n setSubVer.empty() &&\n nPriority == maxInt &&\n strStatusBar == \"URGENT: Alert key compromised, upgrade required\"\n ))\n return false;\n }\n\n {\n LOCK(cs_mapAlerts);\n \/\/ Cancel previous alerts\n for (map::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)\n {\n const CAlert& alert = (*mi).second;\n if (Cancels(alert))\n {\n printf(\"cancelling alert %d\\n\", alert.nID);\n uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED);\n mapAlerts.erase(mi++);\n }\n else if (!alert.IsInEffect())\n {\n printf(\"expiring alert %d\\n\", alert.nID);\n uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED);\n mapAlerts.erase(mi++);\n }\n else\n mi++;\n }\n\n \/\/ Check if this alert has been cancelled\n BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)\n {\n const CAlert& alert = item.second;\n if (alert.Cancels(*this))\n {\n printf(\"alert already cancelled by %d\\n\", alert.nID);\n return false;\n }\n }\n\n \/\/ Add to mapAlerts\n mapAlerts.insert(make_pair(GetHash(), *this));\n \/\/ Notify UI if it applies to me\n if(AppliesToMe())\n uiInterface.NotifyAlertChanged(GetHash(), CT_NEW);\n }\n\n printf(\"accepted alert %d, AppliesToMe()=%d\\n\", nID, AppliesToMe());\n return true;\n}\nalertkeys\/\/\n\/\/ Alert system\n\/\/\n\n#include \n#include \n\n#include \"alert.h\"\n#include \"key.h\"\n#include \"net.h\"\n#include \"sync.h\"\n#include \"ui_interface.h\"\n\nusing namespace std;\n\nmap mapAlerts;\nCCriticalSection cs_mapAlerts;\n\n\/\/ old alert keys\n\/\/ static const char* pszMainKey = \"049b3c00249474820bc073896202bf04448e4391e445149b077d6eacccb9902d1b15e891fd8d24bfa43ccef05707797c6871292e145acbec6017d7d818b3748579\";\n\/\/ TestNet\n\/\/ static const char* pszTestKey = \"044d5253cb7c6fcb7b790365ac5aeeef359fc52de23f1ce9bffc092c16dd0372444b75ba328ddf4ebb73257e7c882c9bf81d86d1938ad36ac280214ba72aa9aca6\";\n\n\/\/ new alert keys ofeefee 2014-07-10 05:59:14\n static const char* pszMainKey = \"0404043f174b220c2109da3babc7f0dcf582dd8f77b4041abb6a815baab6f30b6b5babd4dffd65f5a7058a6b3accf743e87643fce3c5b13aaded21815459c1f30d\";\n\/\/ TestNet\n static const char* pszTestKey = \"04ce4131eaaec4f00927609034dc86ce9b712784444294fcaf5c098bed4802ff4533845f8ebc8408291dfedd463f2c5878af73eb652101d5b5877ca826c940a06a\";\n\nvoid CUnsignedAlert::SetNull()\n{\n nVersion = 1;\n nRelayUntil = 0;\n nExpiration = 0;\n nID = 0;\n nCancel = 0;\n setCancel.clear();\n nMinVer = 0;\n nMaxVer = 0;\n setSubVer.clear();\n nPriority = 0;\n\n strComment.clear();\n strStatusBar.clear();\n strReserved.clear();\n}\n\nstd::string CUnsignedAlert::ToString() const\n{\n std::string strSetCancel;\n BOOST_FOREACH(int n, setCancel)\n strSetCancel += strprintf(\"%d \", n);\n std::string strSetSubVer;\n BOOST_FOREACH(std::string str, setSubVer)\n strSetSubVer += \"\\\"\" + str + \"\\\" \";\n return strprintf(\n \"CAlert(\\n\"\n \" nVersion = %d\\n\"\n \" nRelayUntil = %\"PRI64d\"\\n\"\n \" nExpiration = %\"PRI64d\"\\n\"\n \" nID = %d\\n\"\n \" nCancel = %d\\n\"\n \" setCancel = %s\\n\"\n \" nMinVer = %d\\n\"\n \" nMaxVer = %d\\n\"\n \" setSubVer = %s\\n\"\n \" nPriority = %d\\n\"\n \" strComment = \\\"%s\\\"\\n\"\n \" strStatusBar = \\\"%s\\\"\\n\"\n \")\\n\",\n nVersion,\n nRelayUntil,\n nExpiration,\n nID,\n nCancel,\n strSetCancel.c_str(),\n nMinVer,\n nMaxVer,\n strSetSubVer.c_str(),\n nPriority,\n strComment.c_str(),\n strStatusBar.c_str());\n}\n\nvoid CUnsignedAlert::print() const\n{\n printf(\"%s\", ToString().c_str());\n}\n\nvoid CAlert::SetNull()\n{\n CUnsignedAlert::SetNull();\n vchMsg.clear();\n vchSig.clear();\n}\n\nbool CAlert::IsNull() const\n{\n return (nExpiration == 0);\n}\n\nuint256 CAlert::GetHash() const\n{\n return Hash(this->vchMsg.begin(), this->vchMsg.end());\n}\n\nbool CAlert::IsInEffect() const\n{\n return (GetAdjustedTime() < nExpiration);\n}\n\nbool CAlert::Cancels(const CAlert& alert) const\n{\n if (!IsInEffect())\n return false; \/\/ this was a no-op before 31403\n return (alert.nID <= nCancel || setCancel.count(alert.nID));\n}\n\nbool CAlert::AppliesTo(int nVersion, std::string strSubVerIn) const\n{\n \/\/ TODO: rework for client-version-embedded-in-strSubVer ?\n return (IsInEffect() &&\n nMinVer <= nVersion && nVersion <= nMaxVer &&\n (setSubVer.empty() || setSubVer.count(strSubVerIn)));\n}\n\nbool CAlert::AppliesToMe() const\n{\n return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector()));\n}\n\nbool CAlert::RelayTo(CNode* pnode) const\n{\n if (!IsInEffect())\n return false;\n \/\/ returns true if wasn't already contained in the set\n if (pnode->setKnown.insert(GetHash()).second)\n {\n if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||\n AppliesToMe() ||\n GetAdjustedTime() < nRelayUntil)\n {\n pnode->PushMessage(\"alert\", *this);\n return true;\n }\n }\n return false;\n}\n\nbool CAlert::CheckSignature() const\n{\n CKey key;\n if (!key.SetPubKey(ParseHex(fTestNet ? pszTestKey : pszMainKey)))\n return error(\"CAlert::CheckSignature() : SetPubKey failed\");\n if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))\n return error(\"CAlert::CheckSignature() : verify signature failed\");\n\n \/\/ Now unserialize the data\n CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);\n sMsg >> *(CUnsignedAlert*)this;\n return true;\n}\n\nCAlert CAlert::getAlertByHash(const uint256 &hash)\n{\n CAlert retval;\n {\n LOCK(cs_mapAlerts);\n map::iterator mi = mapAlerts.find(hash);\n if(mi != mapAlerts.end())\n retval = mi->second;\n }\n return retval;\n}\n\nbool CAlert::ProcessAlert()\n{\n if (!CheckSignature())\n return false;\n if (!IsInEffect())\n return false;\n\n \/\/ alert.nID=max is reserved for if the alert key is\n \/\/ compromised. It must have a pre-defined message,\n \/\/ must never expire, must apply to all versions,\n \/\/ and must cancel all previous\n \/\/ alerts or it will be ignored (so an attacker can't\n \/\/ send an \"everything is OK, don't panic\" version that\n \/\/ cannot be overridden):\n int maxInt = std::numeric_limits::max();\n if (nID == maxInt)\n {\n if (!(\n nExpiration == maxInt &&\n nCancel == (maxInt-1) &&\n nMinVer == 0 &&\n nMaxVer == maxInt &&\n setSubVer.empty() &&\n nPriority == maxInt &&\n strStatusBar == \"URGENT: Alert key compromised, upgrade required\"\n ))\n return false;\n }\n\n {\n LOCK(cs_mapAlerts);\n \/\/ Cancel previous alerts\n for (map::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)\n {\n const CAlert& alert = (*mi).second;\n if (Cancels(alert))\n {\n printf(\"cancelling alert %d\\n\", alert.nID);\n uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED);\n mapAlerts.erase(mi++);\n }\n else if (!alert.IsInEffect())\n {\n printf(\"expiring alert %d\\n\", alert.nID);\n uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED);\n mapAlerts.erase(mi++);\n }\n else\n mi++;\n }\n\n \/\/ Check if this alert has been cancelled\n BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)\n {\n const CAlert& alert = item.second;\n if (alert.Cancels(*this))\n {\n printf(\"alert already cancelled by %d\\n\", alert.nID);\n return false;\n }\n }\n\n \/\/ Add to mapAlerts\n mapAlerts.insert(make_pair(GetHash(), *this));\n \/\/ Notify UI if it applies to me\n if(AppliesToMe())\n uiInterface.NotifyAlertChanged(GetHash(), CT_NEW);\n }\n\n printf(\"accepted alert %d, AppliesToMe()=%d\\n\", nID, AppliesToMe());\n return true;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2008-2010 The QXmpp developers\n *\n * Author:\n *\tManjeet Dahiya\n *\n * Source:\n *\thttp:\/\/code.google.com\/p\/qxmpp\n *\n * This file is a part of QXmpp library.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n *\/\n\n#include \n\n#include \"QXmppMessage.h\"\n#include \"QXmppRosterManager.h\"\n\n#include \"xmppClient.h\"\n\nxmppClient::xmppClient(QObject *parent)\n : QXmppClient(parent)\n{\n bool check = connect(this, SIGNAL(connected()),\n SLOT(clientConnected()));\n Q_ASSERT(check);\n\n check = connect(&this->rosterManager(), SIGNAL(rosterReceived()),\n SLOT(rosterReceived()));\n Q_ASSERT(check);\n\n \/\/\/ Then QXmppRoster::presenceChanged() is emitted whenever presence of someone\n \/\/\/ in roster changes\n check = connect(&this->rosterManager(),\n SIGNAL(presenceChanged(const QString&, const QString&)),\n SLOT(presenceChanged(const QString&, const QString&)));\n Q_ASSERT(check);\n}\n\nxmppClient::~xmppClient()\n{\n\n}\n\nvoid xmppClient::clientConnected()\n{\n std::cout<<\"example_2_rosterHandling:: CONNECTED\"<display name also\/*\n * Copyright (C) 2008-2010 The QXmpp developers\n *\n * Author:\n *\tManjeet Dahiya\n *\n * Source:\n *\thttp:\/\/code.google.com\/p\/qxmpp\n *\n * This file is a part of QXmpp library.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n *\/\n\n#include \n\n#include \"QXmppMessage.h\"\n#include \"QXmppRosterManager.h\"\n\n#include \"xmppClient.h\"\n\nxmppClient::xmppClient(QObject *parent)\n : QXmppClient(parent)\n{\n bool check = connect(this, SIGNAL(connected()),\n SLOT(clientConnected()));\n Q_ASSERT(check);\n\n check = connect(&this->rosterManager(), SIGNAL(rosterReceived()),\n SLOT(rosterReceived()));\n Q_ASSERT(check);\n\n \/\/\/ Then QXmppRoster::presenceChanged() is emitted whenever presence of someone\n \/\/\/ in roster changes\n check = connect(&this->rosterManager(),\n SIGNAL(presenceChanged(const QString&, const QString&)),\n SLOT(presenceChanged(const QString&, const QString&)));\n Q_ASSERT(check);\n}\n\nxmppClient::~xmppClient()\n{\n\n}\n\nvoid xmppClient::clientConnected()\n{\n std::cout<<\"example_2_rosterHandling:: CONNECTED\"<"} {"text":"\/\/C++ source file - Open Producer - Copyright (C) 2002 Don Burns\n\/\/Distributed under the terms of the GNU LIBRARY GENERAL PUBLIC LICENSE (LGPL)\n\/\/as published by the Free Software Foundation.\n\n\/\/ Simple example of use of Producer::RenderSurface\n\/\/ The myGraphics class is a simple sample of how one would implement\n\/\/ graphics drawing with Producer::RenderSurface\n\n#include \n\n#include \n\n#include \n#include \n\n#include \n\n#include \"DepthPartitionNode.h\"\n\nconst double r_earth = 6378.137;\nconst double r_sun = 695990.0;\nconst double AU = 149697900.0;\n\nosg::Node* createScene()\n{\n \/\/ Create the Earth, in blue\n osg::ShapeDrawable *earth_sd = new osg::ShapeDrawable;\n osg::Sphere* earth_sphere = new osg::Sphere;\n earth_sphere->setRadius(r_earth);\n earth_sd->setShape(earth_sphere);\n earth_sd->setColor(osg::Vec4(0, 0, 1.0, 1.0));\n\n osg::Geode* earth = new osg::Geode;\n earth->setName(\"earth\");\n earth->addDrawable(earth_sd);\n\n \/\/ Create the Sun, in yellow\n osg::ShapeDrawable *sun_sd = new osg::ShapeDrawable;\n osg::Sphere* sun_sphere = new osg::Sphere;\n sun_sphere->setRadius(r_sun);\n sun_sd->setShape(sun_sphere);\n sun_sd->setColor(osg::Vec4(1.0, 0.0, 0.0, 1.0));\n\n osg::Geode* sun = new osg::Geode;\n sun->setName(\"sun\");\n sun->addDrawable(sun_sd);\n\n \/\/ Move the sun behind the earth\n osg::PositionAttitudeTransform *pat = new osg::PositionAttitudeTransform;\n pat->setPosition(osg::Vec3d(0.0, AU, 0.0));\n\n osg::Group* scene = new osg::Group;\n scene->addChild(earth);\n scene->addChild(pat);\n pat->addChild(sun);\n\n return scene;\n}\n\nint main( int argc, char **argv )\n{\n\n \/\/ use an ArgumentParser object to manage the program arguments.\n osg::ArgumentParser arguments(&argc,argv);\n \n \/\/ set up the usage document, in case we need to print out how to use this program.\n arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());\n arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+\" is the standard example of using osgProducer::CameraGroup.\");\n arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+\" [options] ...\");\n arguments.getApplicationUsage()->addCommandLineOption(\"-h or --help\",\"Display this information\");\n\n \/\/ construct the viewer.\n osgProducer::Viewer viewer(arguments);\n\n \/\/ set up the value with sensible default event handlers.\n viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);\n\n \/\/ if user request help write it out to cout.\n if (arguments.read(\"-h\") || arguments.read(\"--help\"))\n {\n arguments.getApplicationUsage()->write(std::cout);\n return 1;\n }\n\n \/\/ any option left unread are converted into errors to write out later.\n arguments.reportRemainingOptionsAsUnrecognized();\n\n \/\/ report any errors if they have occured when parsing the program aguments.\n if (arguments.errors())\n {\n arguments.writeErrorMessages(std::cout);\n return 1;\n }\n\n\n bool needToSetHomePosition = false;\n\n \/\/ read the scene from the list of file specified commandline args.\n osg::ref_ptr scene = osgDB::readNodeFiles(arguments);\n\n \/\/ if one hasn't been loaded create an earth and sun test model.\n if (!scene) \n {\n scene = createScene(); \n needToSetHomePosition = true;\n }\n \n \/\/ Create a DepthPartitionNode to manage partitioning of the scene\n osg::ref_ptr dpn = new DepthPartitionNode;\n dpn->addChild(scene.get());\n dpn->setActive(true); \/\/ Control whether the node analyzes the scene\n \n \/\/ pass the loaded scene graph to the viewer.\n viewer.setSceneData(dpn.get());\n\n if (needToSetHomePosition)\n {\n viewer.getKeySwitchMatrixManipulator()->setHomePosition(osg::Vec3d(0.0,-5.0*r_earth,0.0),osg::Vec3d(0.0,0.0,0.0),osg::Vec3d(0.0,0.0,1.0));\n }\n\n \/\/ create the windows and run the threads.\n viewer.realize();\n\n while( !viewer.done() )\n {\n \/\/ wait for all cull and draw threads to complete.\n viewer.sync();\n\n \/\/ update the scene by traversing it with the the update visitor which will\n \/\/ call all node update callbacks and animations.\n viewer.update();\n \n \/\/ fire off the cull and draw traversals of the scene.\n viewer.frame();\n \n }\n \n \/\/ wait for all cull and draw threads to complete before exit.\n viewer.sync();\n\n \/\/ run a clean up frame to delete all OpenGL objects.\n viewer.cleanup_frame();\n\n \/\/ wait for all the clean up frame to complete.\n viewer.sync();\n\n return 0;\n}\n\nFrom Keith Steffen, changed instance of sun to sun_geode to avoid Solaris10 build issue with it defining \"sun\"?#!\/\/C++ source file - Open Producer - Copyright (C) 2002 Don Burns\n\/\/Distributed under the terms of the GNU LIBRARY GENERAL PUBLIC LICENSE (LGPL)\n\/\/as published by the Free Software Foundation.\n\n\/\/ Simple example of use of Producer::RenderSurface\n\/\/ The myGraphics class is a simple sample of how one would implement\n\/\/ graphics drawing with Producer::RenderSurface\n\n#include \n\n#include \n\n#include \n#include \n\n#include \n\n#include \"DepthPartitionNode.h\"\n\nconst double r_earth = 6378.137;\nconst double r_sun = 695990.0;\nconst double AU = 149697900.0;\n\nosg::Node* createScene()\n{\n \/\/ Create the Earth, in blue\n osg::ShapeDrawable *earth_sd = new osg::ShapeDrawable;\n osg::Sphere* earth_sphere = new osg::Sphere;\n earth_sphere->setRadius(r_earth);\n earth_sd->setShape(earth_sphere);\n earth_sd->setColor(osg::Vec4(0, 0, 1.0, 1.0));\n\n osg::Geode* earth = new osg::Geode;\n earth->setName(\"earth\");\n earth->addDrawable(earth_sd);\n\n \/\/ Create the Sun, in yellow\n osg::ShapeDrawable *sun_sd = new osg::ShapeDrawable;\n osg::Sphere* sun_sphere = new osg::Sphere;\n sun_sphere->setRadius(r_sun);\n sun_sd->setShape(sun_sphere);\n sun_sd->setColor(osg::Vec4(1.0, 0.0, 0.0, 1.0));\n\n osg::Geode* sun_geode = new osg::Geode;\n sun_geode->setName(\"sun\");\n sun_geode->addDrawable(sun_sd);\n\n \/\/ Move the sun behind the earth\n osg::PositionAttitudeTransform *pat = new osg::PositionAttitudeTransform;\n pat->setPosition(osg::Vec3d(0.0, AU, 0.0));\n\n osg::Group* scene = new osg::Group;\n scene->addChild(earth);\n scene->addChild(pat);\n pat->addChild(sun_geode);\n\n return scene;\n}\n\nint main( int argc, char **argv )\n{\n\n \/\/ use an ArgumentParser object to manage the program arguments.\n osg::ArgumentParser arguments(&argc,argv);\n \n \/\/ set up the usage document, in case we need to print out how to use this program.\n arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());\n arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+\" is the standard example of using osgProducer::CameraGroup.\");\n arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+\" [options] ...\");\n arguments.getApplicationUsage()->addCommandLineOption(\"-h or --help\",\"Display this information\");\n\n \/\/ construct the viewer.\n osgProducer::Viewer viewer(arguments);\n\n \/\/ set up the value with sensible default event handlers.\n viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);\n\n \/\/ if user request help write it out to cout.\n if (arguments.read(\"-h\") || arguments.read(\"--help\"))\n {\n arguments.getApplicationUsage()->write(std::cout);\n return 1;\n }\n\n \/\/ any option left unread are converted into errors to write out later.\n arguments.reportRemainingOptionsAsUnrecognized();\n\n \/\/ report any errors if they have occured when parsing the program aguments.\n if (arguments.errors())\n {\n arguments.writeErrorMessages(std::cout);\n return 1;\n }\n\n\n bool needToSetHomePosition = false;\n\n \/\/ read the scene from the list of file specified commandline args.\n osg::ref_ptr scene = osgDB::readNodeFiles(arguments);\n\n \/\/ if one hasn't been loaded create an earth and sun test model.\n if (!scene) \n {\n scene = createScene(); \n needToSetHomePosition = true;\n }\n \n \/\/ Create a DepthPartitionNode to manage partitioning of the scene\n osg::ref_ptr dpn = new DepthPartitionNode;\n dpn->addChild(scene.get());\n dpn->setActive(true); \/\/ Control whether the node analyzes the scene\n \n \/\/ pass the loaded scene graph to the viewer.\n viewer.setSceneData(dpn.get());\n\n if (needToSetHomePosition)\n {\n viewer.getKeySwitchMatrixManipulator()->setHomePosition(osg::Vec3d(0.0,-5.0*r_earth,0.0),osg::Vec3d(0.0,0.0,0.0),osg::Vec3d(0.0,0.0,1.0));\n }\n\n \/\/ create the windows and run the threads.\n viewer.realize();\n\n while( !viewer.done() )\n {\n \/\/ wait for all cull and draw threads to complete.\n viewer.sync();\n\n \/\/ update the scene by traversing it with the the update visitor which will\n \/\/ call all node update callbacks and animations.\n viewer.update();\n \n \/\/ fire off the cull and draw traversals of the scene.\n viewer.frame();\n \n }\n \n \/\/ wait for all cull and draw threads to complete before exit.\n viewer.sync();\n\n \/\/ run a clean up frame to delete all OpenGL objects.\n viewer.cleanup_frame();\n\n \/\/ wait for all the clean up frame to complete.\n viewer.sync();\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"#include \n#include \"..\/stm32f4_discovery.hpp\"\n\n#include \n#include \n#include \n\n\nstruct DeviceConfiguration\n{\n\t\/\/ shared memory for both devices as a cheap way\n\t\/\/ to `tag` the current configuration of the peripheral\n\t\/\/ so we do not need to configure it unnecessarily.\n\tstatic char tag;\n\n\t\/\/\/ 100kHz I2C configuration\n\tstatic void\n\tstandard_configuration()\n\t{\n\t\tif (tag != 's') {\n\t\t\tI2cMaster1::initialize();\n\t\t\ttag = 's';\n\t\t}\n\t}\n\n\t\/\/\/ 400kHz I2C configuration\n\tstatic void\n\tfast_configuration()\n\t{\n\t\tif (tag != 'f') {\n\t\t\tI2cMaster1::initialize();\n\t\t\ttag = 'f';\n\t\t}\n\t}\n};\nchar DeviceConfiguration::tag = 0;\n\n\nclass ProtofaceTemperatureOne : public xpcc::pt::Protothread\n{\npublic:\n\tProtofaceTemperatureOne()\n\t:\ttemperature(temperatureData, 0x48)\n\t{\n\t\t\/\/ this i2c device will be driven with only 100kHz\n\t\ttemperature.attachPeripheralConfiguration(DeviceConfiguration::standard_configuration);\n\t}\n\n\tbool\n\tupdate()\n\t{\n\t\tPT_BEGIN();\n\n\t\t\/\/ we need to configure the device before we can use it\n\t\t\/\/ so we wait until the task started\n\t\tPT_WAIT_UNTIL(temperature.startConfigure());\n\t\t\/\/ and we wait until it finished\n\t\tPT_WAIT_UNTIL(temperature.runConfigure());\n\n\t\twhile (true)\n\t\t{\n\t\t\t\/\/ lets wait until we can read out the device\n\t\t\tPT_WAIT_UNTIL(temperature.startReadTemperature());\n\t\t\t\/\/ and until this task finishes\n\t\t\tPT_WAIT_UNTIL(temperature.runReadTemperature());\n\t\t\t\/\/ did we succeed with the readout?\n\t\t\tif (temperature.isSuccessful()) {\n\t\t\t\ttf = temperature.getTemperature();\n\t\t\t} else {\n\t\t\t\ttf = NAN;\n\t\t\t}\n\n\t\t\tthis->timer.restart(200);\n\t\t\tPT_WAIT_UNTIL(this->timer.isExpired());\n\t\t}\n\n\t\tPT_END();\n\t}\n\nprivate:\n\tfloat tf;\n\txpcc::Timeout<> timer;\n\tuint8_t temperatureData[2];\n\txpcc::Tmp102 temperature;\n};\n\n\nclass ProtofaceTemperatureTwo : public xpcc::pt::Protothread\n{\npublic:\n\tProtofaceTemperatureTwo()\n\t:\ttemperature(temperatureData, 0x49)\n\t{\n\t\t\/\/ this device will be clocked at 400kHz\n\t\ttemperature.attachPeripheralConfiguration(DeviceConfiguration::fast_configuration);\n\t}\n\n\tbool\n\tupdate()\n\t{\n\t\tPT_BEGIN();\n\n\t\t\/\/\n\t\tPT_WAIT_UNTIL(temperature.startConfigure());\n\t\tPT_WAIT_UNTIL(temperature.runConfigure());\n\n\t\twhile (true)\n\t\t{\n\t\t\tPT_WAIT_UNTIL(temperature.startReadTemperature());\n\t\t\tPT_WAIT_UNTIL(temperature.runReadTemperature());\n\t\t\tif (temperature.isSuccessful()) {\n\t\t\t\ttf = temperature.getTemperature();\n\t\t\t} else {\n\t\t\t\ttf = NAN;\n\t\t\t}\n\n\t\t\tthis->timer.restart(500);\n\t\t\tPT_WAIT_UNTIL(this->timer.isExpired());\n\t\t}\n\n\t\tPT_END();\n\t}\n\nprivate:\n\tfloat tf;\n\txpcc::Timeout<> timer;\n\tuint8_t temperatureData[2];\n\txpcc::Tmp102 temperature;\n};\n\nProtofaceTemperatureOne one;\nProtofaceTemperatureTwo two;\n\n\/\/ ----------------------------------------------------------------------------\nMAIN_FUNCTION\n{\n\tdefaultSystemClock::enable();\n\n\tLedOrange::setOutput(xpcc::Gpio::High);\n\tLedGreen::setOutput(xpcc::Gpio::Low);\n\tLedRed::setOutput(xpcc::Gpio::High);\n\tLedBlue::setOutput(xpcc::Gpio::High);\n\n\twhile (1)\n\t{\n\t\tone.update();\n\t\ttwo.update();\n\t}\n\n\treturn 0;\n}\nUpdate Protoface example with debug transaction and master. This is tested in hardware and worked.#include \n#include \"..\/stm32f4_discovery.hpp\"\n\n#include \n#include \n#include \n\n#include \n\nxpcc::IODeviceWrapper device;\nxpcc::IOStream stream(device);\n\n\/\/ example of a debug transaction, which outputs the wrapped transactions choices.\nclass CustomI2cTransaction : public xpcc::I2cTransaction\n{\n\txpcc::I2cTransaction *transaction;\n\npublic:\n\tCustomI2cTransaction()\n\t\t\t:\ttransaction(nullptr)\n\t{}\n\n\tvoid\n\tsetTransaction(xpcc::I2cTransaction *transaction)\n\t{\n\t\tthis->transaction = transaction;\n\t}\n\nprotected:\n\tvirtual bool\n\tattaching()\n\t{\n\t\tbool result = transaction->attaching();\n\t\tstream << \"T: attaching: \" << result << xpcc::endl;\n\t\treturn result;\n\t}\n\n\tvirtual Starting\n\tstarting()\n\t{\n\t\txpcc::I2cTransaction::Starting result = transaction->starting();\n\t\tstream << \"T: starting: addr=\" << result.address << \" next=\" << (int)result.next << xpcc::endl;\n\t\treturn result;\n\t}\n\n\tvirtual Writing\n\twriting()\n\t{\n\t\txpcc::I2cTransaction::Writing result = transaction->writing();\n\t\tstream << \"T: writing: length=\" << result.length << \" next=\" << (int)result.next << xpcc::endl;\n\t\treturn result;\n\t}\n\n\tvirtual Reading\n\treading()\n\t{\n\t\txpcc::I2cTransaction::Reading result = transaction->reading();\n\t\tstream << \"T: reading: length=\" << result.length << \" next=\" << (int)result.next << xpcc::endl;\n\t\treturn result;\n\t}\n\n\tvirtual void\n\tdetaching(DetachCause cause)\n\t{\n\t\ttransaction->detaching(cause);\n\t\tstream << \"T: detaching: cause=\" << (int)cause << xpcc::endl;\n\t}\n};\nstatic CustomI2cTransaction myTransaction;\n\n\n\/\/ this custom I2c Master wraps the original transaction into the above debug transaction.\nclass MyI2cMaster2 : public I2cMaster1\n{\npublic:\n\tstatic bool\n\tstart(xpcc::I2cTransaction *transaction, xpcc::I2c::Configuration_t configuration = nullptr)\n\t{\n\t\tmyTransaction.setTransaction(transaction);\n\t\tstream << \"st\" << xpcc::endl;\n\t\treturn I2cMaster1::start(&myTransaction, configuration);\n\t}\n\n\tstatic bool\n\tstartBlocking(xpcc::I2cTransaction *transaction, xpcc::I2c::Configuration_t configuration = nullptr)\n\t{\n\t\tmyTransaction.setTransaction(transaction);\n\t\tstream << \"stBl\" << xpcc::endl;\n\t\treturn I2cMaster1::start(&myTransaction, configuration);\n\t}\n};\n\ntypedef I2cMaster1 MyI2cMaster;\n\nstruct DeviceConfiguration\n{\n\t\/\/ shared memory for both devices as a cheap way\n\t\/\/ to `tag` the current configuration of the peripheral\n\t\/\/ so we do not need to configure it unnecessarily.\n\tstatic char tag;\n\n\t\/\/\/ 100kHz I2C configuration\n\tstatic void\n\tstandard_configuration()\n\t{\n\t\tif (tag != 's') {\n\t\t\tstream << \"config: 20kHz\" << xpcc::endl;\n\t\t\tMyI2cMaster::initialize();\n\t\t\ttag = 's';\n\t\t}\n\t}\n\n\t\/\/\/ 400kHz I2C configuration\n\tstatic void\n\tfast_configuration()\n\t{\n\t\tif (tag != 'f') {\n\t\t\tstream << \"config: 100kHz\" << xpcc::endl;\n\t\t\tMyI2cMaster::initialize();\n\t\t\ttag = 'f';\n\t\t}\n\t}\n};\nchar DeviceConfiguration::tag = 0;\n\n\nclass ProtofaceTemperatureOne : public xpcc::pt::Protothread\n{\npublic:\n\tProtofaceTemperatureOne()\n\t:\ttemperature(temperatureData, 0x48)\n\t{\n\t\t\/\/ this i2c device will be driven with only 20kHz\n\t\ttemperature.attachPeripheralConfiguration(DeviceConfiguration::standard_configuration);\n\t}\n\n\tbool\n\tupdate()\n\t{\n\t\tPT_BEGIN();\n\n\t\t\/\/ we need to configure the device before we can use it\n\t\t\/\/ so we wait until the task started\n\t\tPT_WAIT_UNTIL(temperature.startConfigure());\n\t\t\/\/ and we wait until it finished\n\t\tPT_WAIT_UNTIL(temperature.runConfigure());\n\n\t\twhile (true)\n\t\t{\n\t\t\t\/\/ lets wait until we can read out the device\n\t\t\tPT_WAIT_UNTIL(temperature.startReadTemperature());\n\t\t\t\/\/ and until this task finishes\n\t\t\tPT_WAIT_UNTIL(temperature.runReadTemperature());\n\t\t\t\/\/ did we succeed with the readout?\n\t\t\tif (temperature.isSuccessful()) {\n\t\t\t\ttf = temperature.getTemperature();\n\t\t\t\tstream << \"t1: \" << (int)tf << xpcc::endl;\n\t\t\t} else {\n\t\t\t\ttf = NAN;\n\t\t\t\tstream << \"t1: NACK\"<< xpcc::endl;\n\t\t\t}\n\n\t\t\tthis->timer.restart(200);\n\t\t\tPT_WAIT_UNTIL(this->timer.isExpired());\n\t\t\tLedRed::toggle();\n\t\t}\n\n\t\tPT_END();\n\t}\n\nprivate:\n\tfloat tf;\n\txpcc::Timeout<> timer;\n\tuint8_t temperatureData[2];\n\txpcc::Tmp102 temperature;\n};\n\n\nclass ProtofaceTemperatureTwo : public xpcc::pt::Protothread\n{\npublic:\n\tProtofaceTemperatureTwo()\n\t:\ttemperature(temperatureData, 0x48)\n\t{\n\t\t\/\/ this device will be clocked at 100kHz\n\t\ttemperature.attachPeripheralConfiguration(DeviceConfiguration::fast_configuration);\n\t}\n\n\tbool\n\tupdate()\n\t{\n\t\tPT_BEGIN();\n\n\t\tPT_WAIT_UNTIL(temperature.startConfigure());\n\t\tPT_WAIT_UNTIL(temperature.runConfigure());\n\n\t\twhile (true)\n\t\t{\n\t\t\tPT_WAIT_UNTIL(temperature.startReadTemperature());\n\t\t\tPT_WAIT_UNTIL(temperature.runReadTemperature());\n\t\t\tif (temperature.isSuccessful()) {\n\t\t\t\ttf = temperature.getTemperature();\n\t\t\t\tstream << \"t2: \" << (int)tf << xpcc::endl;\n\t\t\t} else {\n\t\t\t\ttf = NAN;\n\t\t\t\tstream << \"t2: NACK\"<< xpcc::endl;\n\t\t\t}\n\n\t\t\tthis->timer.restart(500);\n\t\t\tPT_WAIT_UNTIL(this->timer.isExpired());\n\t\t\tLedGreen::toggle();\n\t\t}\n\n\t\tPT_END();\n\t}\n\nprivate:\n\tfloat tf;\n\txpcc::Timeout<> timer;\n\tuint8_t temperatureData[2];\n\txpcc::Tmp102 temperature;\n};\n\nProtofaceTemperatureOne one;\nProtofaceTemperatureTwo two;\n\n\/\/ ----------------------------------------------------------------------------\nMAIN_FUNCTION\n{\n\tdefaultSystemClock::enable();\n\txpcc::cortex::SysTickTimer::enable();\n\n\tLedOrange::setOutput(xpcc::Gpio::High);\n\tLedGreen::setOutput(xpcc::Gpio::Low);\n\tLedRed::setOutput(xpcc::Gpio::High);\n\tLedBlue::setOutput(xpcc::Gpio::High);\n\n\tGpioOutputA2::connect(Usart2::Tx);\n\tUsart2::initialize(10);\n\n\tGpioB7::connect(MyI2cMaster::Sda);\n\tGpioB8::connect(MyI2cMaster::Scl);\n\tGpioB7::configure(Gpio::InputType::PullUp);\n\tGpioB8::configure(Gpio::InputType::PullUp);\n\n\tstream << \"\\n\\nRESTART\\n\\n\";\n\n\twhile (1)\n\t{\n\t\tone.update();\n\t\ttwo.update();\n\t\tLedOrange::toggle();\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"\/*\r\n * Copyright (c) 2007 Digital Bazaar, Inc. All rights reserved.\r\n *\/\r\n#include \r\n\r\n#include \"Base64Coder.h\"\r\n#include \"Object.h\"\r\n#include \"Runnable.h\"\r\n#include \"Thread.h\"\r\n#include \"System.h\"\r\n#include \"TcpSocket.h\"\r\n#include \"InternetAddress.h\"\r\n\r\nusing namespace std;\r\nusing namespace db::net;\r\nusing namespace db::rt;\r\nusing namespace db::util;\r\n\r\nvoid runBase64Test()\r\n{\r\n\tcout << \"Running Base64 Test\" << endl << endl;\r\n\t\r\n\tchar data[] = {'a', 'b', 'c', 'd'};\r\n\tstring encoded = Base64Coder::encode(data, 0, 4);\r\n\tcout << \"encoded=\" << encoded << endl;\r\n\t\r\n\tchar* decoded = Base64Coder::decode(encoded);\r\n int length = sizeof(decoded);\r\n\t\r\n\tcout << \"decoded bytes=\" << length << endl;\r\n for(int i = 0; i < length; i++)\r\n {\r\n cout << \"decoded[\" << i << \"]=\" << decoded[i] << endl;\r\n }\r\n\t\r\n\tstring encoded2 = Base64Coder::encode(decoded, 0, 4);\r\n\tcout << \"encoded again=\" << encoded2 << endl;\r\n\t\r\n if(decoded != NULL)\r\n {\r\n\t delete [] decoded;\r\n }\r\n}\r\n\r\nvoid runTimeTest()\r\n{\r\n cout << \"Running Time Test\" << endl << endl;\r\n \r\n unsigned long long start = System::getCurrentMilliseconds();\r\n \r\n cout << \"Time start=\" << start << endl;\r\n \r\n unsigned long long end = System::getCurrentMilliseconds();\r\n \r\n cout << \"Time end=\" << end << endl;\r\n}\r\n\r\nclass TestRunnable : public virtual Object, public Runnable\r\n{\r\n virtual void run()\r\n {\r\n string name = Thread::currentThread()->getName();\r\n cout << name << \": This is a TestRunnable thread.\" << endl;\r\n \r\n if(name == \"Thread 1\")\r\n {\r\n cout << \"Thread 1 Waiting for Thread 5...\" << endl;\r\n \r\n lock();\r\n {\r\n lock();\r\n lock();\r\n lock();\r\n wait();\r\n }\r\n unlock();\r\n \r\n cout << \"Thread 1 Finished.\" << endl;\r\n }\r\n else if(name == \"Thread 3\")\r\n {\r\n cout << \"Thread 3 Waiting for Thread 5...\" << endl;\r\n \r\n lock();\r\n lock();\r\n lock();\r\n lock();\r\n {\r\n wait();\r\n }\r\n unlock();\r\n \r\n cout << \"Thread 3 Finished.\" << endl;\r\n }\r\n else if(name == \"Thread 5\")\r\n {\r\n cout << \"Thread 5 waking up threads...\" << endl;\r\n \r\n lock();\r\n lock();\r\n lock();\r\n lock();\r\n {\r\n notifyAll();\r\n }\r\n unlock();\r\n }\r\n }\r\n};\r\n\r\nvoid runThreadTest()\r\n{\r\n cout << \"Running Thread Test\" << endl << endl;\r\n \r\n TestRunnable r1;\r\n Thread t1(&r1, \"Thread 1\");\r\n \r\n \/\/TestRunnable r2;\r\n Thread t2(&r1, \"Thread 2\");\r\n \r\n \/\/TestRunnable r3;\r\n Thread t3(&r1, \"Thread 3\");\r\n \r\n \/\/TestRunnable r4;\r\n Thread t4(&r1, \"Thread 4\");\r\n \r\n \/\/TestRunnable r5;\r\n Thread t5(&r1, \"Thread 5\");\r\n \r\n t1.start();\r\n t2.start();\r\n t3.start();\r\n t4.start();\r\n t5.start();\r\n \r\n t1.join();\r\n t2.join();\r\n t3.join();\r\n t4.join();\r\n t5.join();\r\n}\r\n\r\nvoid runWindowsSocketTest()\r\n{\r\n \/\/ initialize winsock\r\n#ifdef WIN32\r\n WSADATA wsaData;\r\n if(WSAStartup(MAKEWORD(2, 0), &wsaData) < 0)\r\n {\r\n cout << \"ERROR!!!\" << endl;\r\n }\r\n#endif\r\n \r\n \/\/ create tcp socket\r\n TcpSocket socket;\r\n \r\n \/\/ create address\r\n \/\/ \"www.google.com\"\r\n InternetAddress address(\"64.233.161.99\", 80);\r\n \r\n \/\/ connect\r\n socket.connect(&address);\r\n \r\n \/\/ close\r\n socket.close();\r\n \r\n cout << \"DONE!\" << endl;\r\n \r\n \/\/ cleanup winsock\r\n#ifdef WIN32\r\n WSACleanup();\r\n#endif\r\n}\r\n\r\nvoid runLinuxSocketTest()\r\n{\r\n \/\/ create tcp socket\r\n TcpSocket socket;\r\n \r\n \/\/ create address\r\n \/\/ \"www.google.com\"\r\n \/\/InternetAddress address(\"64.233.161.99\", 80);\r\n InternetAddress address(\"127.0.0.1\", 80);\r\n cout << address.getAddress() << endl;\r\n \r\n \/\/ connect\r\n socket.connect(&address);\r\n \r\n char request[] = \"GET \/ HTTP\/1.0\\r\\nContent-Length: 0\\r\\n\\r\\n\";\r\n socket.send(request, 0, sizeof(request));\r\n \r\n char response[2048];\r\n int numBytes = socket.receive(response, 0, 2048);\r\n \r\n cout << \"numBytes received: \" << numBytes << endl;\r\n \r\n \/\/ close\r\n socket.close();\r\n \r\n cout << \"DONE!\" << endl;\r\n}\r\n\r\n\r\nint main()\r\n{\r\n cout << \"Tests starting...\" << endl << endl;\r\n \r\n try\r\n {\r\n \/\/runBase64Test();\r\n \/\/runTimeTest();\r\n \/\/runThreadTest();\r\n \/\/runWindowsSocketTest();\r\n runLinuxSocketTest();\r\n }\r\n catch(SocketException& e)\r\n {\r\n cout << \"SocketException caught!\" << endl;\r\n cout << \"message: \" << e.getMessage() << endl;\r\n cout << \"code: \" << e.getCode() << endl;\r\n }\r\n catch(...)\r\n {\r\n cout << \"Exception caught!\" << endl;\r\n }\r\n \r\n cout << endl << \"Tests finished.\" << endl;\r\n}\r\nUpdated socket test.\/*\r\n * Copyright (c) 2007 Digital Bazaar, Inc. All rights reserved.\r\n *\/\r\n#include \r\n\r\n#include \"Base64Coder.h\"\r\n#include \"Object.h\"\r\n#include \"Runnable.h\"\r\n#include \"Thread.h\"\r\n#include \"System.h\"\r\n#include \"TcpSocket.h\"\r\n#include \"InternetAddress.h\"\r\n\r\nusing namespace std;\r\nusing namespace db::net;\r\nusing namespace db::rt;\r\nusing namespace db::util;\r\n\r\nvoid runBase64Test()\r\n{\r\n\tcout << \"Running Base64 Test\" << endl << endl;\r\n\t\r\n\tchar data[] = {'a', 'b', 'c', 'd'};\r\n\tstring encoded = Base64Coder::encode(data, 0, 4);\r\n\tcout << \"encoded=\" << encoded << endl;\r\n\t\r\n\tchar* decoded = Base64Coder::decode(encoded);\r\n int length = sizeof(decoded);\r\n\t\r\n\tcout << \"decoded bytes=\" << length << endl;\r\n for(int i = 0; i < length; i++)\r\n {\r\n cout << \"decoded[\" << i << \"]=\" << decoded[i] << endl;\r\n }\r\n\t\r\n\tstring encoded2 = Base64Coder::encode(decoded, 0, 4);\r\n\tcout << \"encoded again=\" << encoded2 << endl;\r\n\t\r\n if(decoded != NULL)\r\n {\r\n\t delete [] decoded;\r\n }\r\n}\r\n\r\nvoid runTimeTest()\r\n{\r\n cout << \"Running Time Test\" << endl << endl;\r\n \r\n unsigned long long start = System::getCurrentMilliseconds();\r\n \r\n cout << \"Time start=\" << start << endl;\r\n \r\n unsigned long long end = System::getCurrentMilliseconds();\r\n \r\n cout << \"Time end=\" << end << endl;\r\n}\r\n\r\nclass TestRunnable : public virtual Object, public Runnable\r\n{\r\n virtual void run()\r\n {\r\n string name = Thread::currentThread()->getName();\r\n cout << name << \": This is a TestRunnable thread.\" << endl;\r\n \r\n if(name == \"Thread 1\")\r\n {\r\n cout << \"Thread 1 Waiting for Thread 5...\" << endl;\r\n \r\n lock();\r\n {\r\n lock();\r\n lock();\r\n lock();\r\n wait();\r\n }\r\n unlock();\r\n \r\n cout << \"Thread 1 Finished.\" << endl;\r\n }\r\n else if(name == \"Thread 3\")\r\n {\r\n cout << \"Thread 3 Waiting for Thread 5...\" << endl;\r\n \r\n lock();\r\n lock();\r\n lock();\r\n lock();\r\n {\r\n wait();\r\n }\r\n unlock();\r\n \r\n cout << \"Thread 3 Finished.\" << endl;\r\n }\r\n else if(name == \"Thread 5\")\r\n {\r\n cout << \"Thread 5 waking up threads...\" << endl;\r\n \r\n lock();\r\n lock();\r\n lock();\r\n lock();\r\n {\r\n notifyAll();\r\n }\r\n unlock();\r\n }\r\n }\r\n};\r\n\r\nvoid runThreadTest()\r\n{\r\n cout << \"Running Thread Test\" << endl << endl;\r\n \r\n TestRunnable r1;\r\n Thread t1(&r1, \"Thread 1\");\r\n \r\n \/\/TestRunnable r2;\r\n Thread t2(&r1, \"Thread 2\");\r\n \r\n \/\/TestRunnable r3;\r\n Thread t3(&r1, \"Thread 3\");\r\n \r\n \/\/TestRunnable r4;\r\n Thread t4(&r1, \"Thread 4\");\r\n \r\n \/\/TestRunnable r5;\r\n Thread t5(&r1, \"Thread 5\");\r\n \r\n t1.start();\r\n t2.start();\r\n t3.start();\r\n t4.start();\r\n t5.start();\r\n \r\n t1.join();\r\n t2.join();\r\n t3.join();\r\n t4.join();\r\n t5.join();\r\n}\r\n\r\nvoid runWindowsSocketTest()\r\n{\r\n \/\/ initialize winsock\r\n#ifdef WIN32\r\n WSADATA wsaData;\r\n if(WSAStartup(MAKEWORD(2, 0), &wsaData) < 0)\r\n {\r\n cout << \"ERROR!!!\" << endl;\r\n }\r\n#endif\r\n \r\n \/\/ create tcp socket\r\n TcpSocket socket;\r\n \r\n \/\/ create address\r\n \/\/ \"www.google.com\"\r\n InternetAddress address(\"64.233.161.99\", 80);\r\n \r\n \/\/ connect\r\n socket.connect(&address);\r\n \r\n \/\/ close\r\n socket.close();\r\n \r\n cout << \"DONE!\" << endl;\r\n \r\n \/\/ cleanup winsock\r\n#ifdef WIN32\r\n WSACleanup();\r\n#endif\r\n}\r\n\r\nvoid runLinuxSocketTest()\r\n{\r\n \/\/ create tcp socket\r\n TcpSocket socket;\r\n \r\n \/\/ create address\r\n \/\/ \"www.google.com\"\r\n \/\/InternetAddress address(\"64.233.161.99\", 80);\r\n InternetAddress address(\"127.0.0.1\", 80);\r\n cout << address.getAddress() << endl;\r\n \r\n \/\/ connect\r\n socket.connect(&address);\r\n \r\n char request[] =\r\n \"GET \/ HTTP\/1.0\\r\\nContent-Length: 0\\r\\nConnection: close\\r\\n\\r\\n\";\r\n socket.send(request, 0, sizeof(request));\r\n \r\n char response[2048];\r\n int numBytes = 0;\r\n string str = \"\";\r\n while((numBytes = socket.receive(response, 0, 2048)) != -1)\r\n {\r\n cout << \"numBytes received: \" << numBytes << endl;\r\n str.append(response, numBytes);\r\n }\r\n \r\n \/\/ close\r\n socket.close();\r\n \r\n cout << \"Socket connection closed.\" << endl;\r\n cout << \"Response:\" << endl << str << endl;\r\n \r\n cout << endl << \"Socket test complete.\" << endl;\r\n}\r\n\r\nint main()\r\n{\r\n cout << \"Tests starting...\" << endl << endl;\r\n \r\n try\r\n {\r\n \/\/runBase64Test();\r\n \/\/runTimeTest();\r\n \/\/runThreadTest();\r\n \/\/runWindowsSocketTest();\r\n runLinuxSocketTest();\r\n }\r\n catch(SocketException& e)\r\n {\r\n cout << \"SocketException caught!\" << endl;\r\n cout << \"message: \" << e.getMessage() << endl;\r\n cout << \"code: \" << e.getCode() << endl;\r\n }\r\n catch(...)\r\n {\r\n cout << \"Exception caught!\" << endl;\r\n }\r\n \r\n cout << endl << \"Tests finished.\" << endl;\r\n}\r\n<|endoftext|>"} {"text":"\/**********************************************************************************\n * NAN - Native Abstractions for Node.js\n *\n * Copyright (c) 2014 NAN contributors\n *\n * MIT +no-false-attribs License \n **********************************************************************************\/\n\n#include \n#include \n\nstatic int magic = 1337;\n\nNAN_METHOD(NewNumber) {\n NanScope();\n NanReturnValue(NanNew(0.5));\n}\n\nNAN_METHOD(NewNegativeInteger) {\n NanScope();\n NanReturnValue(NanNew(-1));\n}\n\nNAN_METHOD(NewPositiveInteger) {\n NanScope();\n NanReturnValue(NanNew(1));\n}\n\nNAN_METHOD(NewInt32FromPositive) {\n NanScope();\n NanReturnValue(NanNew(0xFFFFFFFF));\n}\n\nNAN_METHOD(NewInt32FromNegative) {\n NanScope();\n NanReturnValue(NanNew(-1));\n}\n\nNAN_METHOD(NewUint32FromPositive) {\n NanScope();\n NanReturnValue(NanNew(0xFFFFFFFF));\n}\n\nNAN_METHOD(NewUint32FromNegative) {\n NanScope();\n NanReturnValue(NanNew(-1));\n}\n\nNAN_METHOD(NewUtf8String) {\n NanScope();\n const char s[] = \"strïng\";\n NanReturnValue(NanNew(s));\n}\n\nNAN_METHOD(NewLatin1String) {\n NanScope();\n const uint8_t s[] = \"str\\xefng\";\n NanReturnValue(NanNew(s));\n}\n\nNAN_METHOD(NewUcs2String) {\n NanScope();\n const uint16_t s[] = {'s', 't', 'r', 0xef, 'n', 'g', '\\0'};\n NanReturnValue(NanNew(s));\n}\n\nNAN_METHOD(NewStdString) {\n NanScope();\n const std::string s = \"strïng\";\n NanReturnValue(NanNew(s));\n}\n\nNAN_METHOD(NewRegExp) {\n NanScope();\n NanReturnValue(NanNew(NanNew(\"foo\"), v8::RegExp::kNone));\n}\n\nNAN_METHOD(NewStringObject) {\n NanScope();\n NanReturnValue(NanNew(NanNew(\"foo\")));\n}\n\nNAN_METHOD(NewNumberObject) {\n NanScope();\n NanReturnValue(NanNew(0.5));\n}\n\nNAN_METHOD(NewBooleanObject) {\n NanScope();\n NanReturnValue(NanNew(true));\n}\n\nNAN_METHOD(NewExternal) {\n NanScope();\n v8::Local ext = NanNew(&magic);\n assert(*static_cast(ext->Value()) == 1337);\n NanReturnValue(NanNew(\"passed\"));\n}\n\nNAN_METHOD(NewSignature) {\n NanScope();\n v8::Local tmpl =\n NanNew(NewSignature);\n v8::Local sig = NanNew(tmpl, 1, &tmpl);\n tmpl = NanNew(\n NewSignature, v8::Handle(), sig);\n NanReturnValue(NanNew(\"string\"));\n}\n\nNAN_METHOD(NewScript) {\n NanScope();\n v8::Local script = NanNew(NanNew(\"2+4\"));\n NanReturnValue(NanRunScript(script)->ToInt32());\n}\n\nNAN_METHOD(NewScript2) {\n NanScope();\n v8::ScriptOrigin origin(NanNew(\"x\"));\n v8::Local script =\n NanNew(NanNew(\"2+4\"), origin);\n NanReturnValue(NanRunScript(script)->ToInt32());\n}\n\nNAN_METHOD(CompileScript) {\n NanScope();\n v8::Local script = NanCompileScript(NanNew(\"2+4\"));\n NanReturnValue(NanRunScript(script)->ToInt32());\n}\n\nNAN_METHOD(CompileScript2) {\n NanScope();\n v8::ScriptOrigin origin(NanNew(\"x\"));\n v8::Local script = NanCompileScript(NanNew(\"2+4\"), origin);\n NanReturnValue(NanRunScript(script)->ToInt32());\n}\n\nNAN_METHOD(NewDate) {\n NanScope();\n NanReturnValue(NanNew(1337));\n}\n\nNAN_METHOD(NewArray) {\n NanScope();\n NanReturnValue(NanNew());\n}\n\nvoid Init(v8::Handle target) {\n target->Set(\n NanNew(\"newNumber\")\n , NanNew(NewNumber)->GetFunction()\n );\n target->Set(\n NanNew(\"newNegativeInteger\")\n , NanNew(NewNegativeInteger)->GetFunction()\n );\n target->Set(\n NanNew(\"newPositiveInteger\")\n , NanNew(NewPositiveInteger)->GetFunction()\n );\n target->Set(\n NanNew(\"newInt32FromPositive\")\n , NanNew(NewInt32FromPositive)->GetFunction()\n );\n target->Set(\n NanNew(\"newInt32FromNegative\")\n , NanNew(NewInt32FromNegative)->GetFunction()\n );\n target->Set(\n NanNew(\"newUint32FromPositive\")\n , NanNew(NewUint32FromPositive)->GetFunction()\n );\n target->Set(\n NanNew(\"newUint32FromNegative\")\n , NanNew(NewUint32FromNegative)->GetFunction()\n );\n target->Set(\n NanNew(\"newUtf8String\")\n , NanNew(NewUtf8String)->GetFunction()\n );\n target->Set(\n NanNew(\"newLatin1String\")\n , NanNew(NewLatin1String)->GetFunction()\n );\n target->Set(\n NanNew(\"newUcs2String\")\n , NanNew(NewUcs2String)->GetFunction()\n );\n target->Set(\n NanNew(\"newStdString\")\n , NanNew(NewUcs2String)->GetFunction()\n );\n target->Set(\n NanNew(\"newRegExp\")\n , NanNew(NewRegExp)->GetFunction()\n );\n target->Set(\n NanNew(\"newStringObject\")\n , NanNew(NewStringObject)->GetFunction()\n );\n target->Set(\n NanNew(\"newNumberObject\")\n , NanNew(NewNumberObject)->GetFunction()\n );\n target->Set(\n NanNew(\"newBooleanObject\")\n , NanNew(NewBooleanObject)->GetFunction()\n );\n target->Set(\n NanNew(\"newExternal\")\n , NanNew(NewExternal)->GetFunction()\n );\n target->Set(\n NanNew(\"newSignature\")\n , NanNew(NewSignature)->GetFunction()\n );\n target->Set(\n NanNew(\"newScript\")\n , NanNew(NewScript)->GetFunction()\n );\n target->Set(\n NanNew(\"newScript2\")\n , NanNew(NewScript2)->GetFunction()\n );\n target->Set(\n NanNew(\"compileScript\")\n , NanNew(CompileScript)->GetFunction()\n );\n target->Set(\n NanNew(\"compileScript2\")\n , NanNew(CompileScript2)->GetFunction()\n );\n target->Set(\n NanNew(\"newDate\")\n , NanNew(NewDate)->GetFunction()\n );\n target->Set(\n NanNew(\"newArray\")\n , NanNew(NewArray)->GetFunction()\n );\n}\n\nNODE_MODULE(news, Init)\nFix std::string test\/**********************************************************************************\n * NAN - Native Abstractions for Node.js\n *\n * Copyright (c) 2014 NAN contributors\n *\n * MIT +no-false-attribs License \n **********************************************************************************\/\n\n#include \n#include \n\nstatic int magic = 1337;\n\nNAN_METHOD(NewNumber) {\n NanScope();\n NanReturnValue(NanNew(0.5));\n}\n\nNAN_METHOD(NewNegativeInteger) {\n NanScope();\n NanReturnValue(NanNew(-1));\n}\n\nNAN_METHOD(NewPositiveInteger) {\n NanScope();\n NanReturnValue(NanNew(1));\n}\n\nNAN_METHOD(NewInt32FromPositive) {\n NanScope();\n NanReturnValue(NanNew(0xFFFFFFFF));\n}\n\nNAN_METHOD(NewInt32FromNegative) {\n NanScope();\n NanReturnValue(NanNew(-1));\n}\n\nNAN_METHOD(NewUint32FromPositive) {\n NanScope();\n NanReturnValue(NanNew(0xFFFFFFFF));\n}\n\nNAN_METHOD(NewUint32FromNegative) {\n NanScope();\n NanReturnValue(NanNew(-1));\n}\n\nNAN_METHOD(NewUtf8String) {\n NanScope();\n const char s[] = \"strïng\";\n NanReturnValue(NanNew(s));\n}\n\nNAN_METHOD(NewLatin1String) {\n NanScope();\n const uint8_t s[] = \"str\\xefng\";\n NanReturnValue(NanNew(s));\n}\n\nNAN_METHOD(NewUcs2String) {\n NanScope();\n const uint16_t s[] = {'s', 't', 'r', 0xef, 'n', 'g', '\\0'};\n NanReturnValue(NanNew(s));\n}\n\nNAN_METHOD(NewStdString) {\n NanScope();\n const std::string s = \"strïng\";\n NanReturnValue(NanNew(s));\n}\n\nNAN_METHOD(NewRegExp) {\n NanScope();\n NanReturnValue(NanNew(NanNew(\"foo\"), v8::RegExp::kNone));\n}\n\nNAN_METHOD(NewStringObject) {\n NanScope();\n NanReturnValue(NanNew(NanNew(\"foo\")));\n}\n\nNAN_METHOD(NewNumberObject) {\n NanScope();\n NanReturnValue(NanNew(0.5));\n}\n\nNAN_METHOD(NewBooleanObject) {\n NanScope();\n NanReturnValue(NanNew(true));\n}\n\nNAN_METHOD(NewExternal) {\n NanScope();\n v8::Local ext = NanNew(&magic);\n assert(*static_cast(ext->Value()) == 1337);\n NanReturnValue(NanNew(\"passed\"));\n}\n\nNAN_METHOD(NewSignature) {\n NanScope();\n v8::Local tmpl =\n NanNew(NewSignature);\n v8::Local sig = NanNew(tmpl, 1, &tmpl);\n tmpl = NanNew(\n NewSignature, v8::Handle(), sig);\n NanReturnValue(NanNew(\"string\"));\n}\n\nNAN_METHOD(NewScript) {\n NanScope();\n v8::Local script = NanNew(NanNew(\"2+4\"));\n NanReturnValue(NanRunScript(script)->ToInt32());\n}\n\nNAN_METHOD(NewScript2) {\n NanScope();\n v8::ScriptOrigin origin(NanNew(\"x\"));\n v8::Local script =\n NanNew(NanNew(\"2+4\"), origin);\n NanReturnValue(NanRunScript(script)->ToInt32());\n}\n\nNAN_METHOD(CompileScript) {\n NanScope();\n v8::Local script = NanCompileScript(NanNew(\"2+4\"));\n NanReturnValue(NanRunScript(script)->ToInt32());\n}\n\nNAN_METHOD(CompileScript2) {\n NanScope();\n v8::ScriptOrigin origin(NanNew(\"x\"));\n v8::Local script = NanCompileScript(NanNew(\"2+4\"), origin);\n NanReturnValue(NanRunScript(script)->ToInt32());\n}\n\nNAN_METHOD(NewDate) {\n NanScope();\n NanReturnValue(NanNew(1337));\n}\n\nNAN_METHOD(NewArray) {\n NanScope();\n NanReturnValue(NanNew());\n}\n\nvoid Init(v8::Handle target) {\n target->Set(\n NanNew(\"newNumber\")\n , NanNew(NewNumber)->GetFunction()\n );\n target->Set(\n NanNew(\"newNegativeInteger\")\n , NanNew(NewNegativeInteger)->GetFunction()\n );\n target->Set(\n NanNew(\"newPositiveInteger\")\n , NanNew(NewPositiveInteger)->GetFunction()\n );\n target->Set(\n NanNew(\"newInt32FromPositive\")\n , NanNew(NewInt32FromPositive)->GetFunction()\n );\n target->Set(\n NanNew(\"newInt32FromNegative\")\n , NanNew(NewInt32FromNegative)->GetFunction()\n );\n target->Set(\n NanNew(\"newUint32FromPositive\")\n , NanNew(NewUint32FromPositive)->GetFunction()\n );\n target->Set(\n NanNew(\"newUint32FromNegative\")\n , NanNew(NewUint32FromNegative)->GetFunction()\n );\n target->Set(\n NanNew(\"newUtf8String\")\n , NanNew(NewUtf8String)->GetFunction()\n );\n target->Set(\n NanNew(\"newLatin1String\")\n , NanNew(NewLatin1String)->GetFunction()\n );\n target->Set(\n NanNew(\"newUcs2String\")\n , NanNew(NewUcs2String)->GetFunction()\n );\n target->Set(\n NanNew(\"newStdString\")\n , NanNew(NewStdString)->GetFunction()\n );\n target->Set(\n NanNew(\"newRegExp\")\n , NanNew(NewRegExp)->GetFunction()\n );\n target->Set(\n NanNew(\"newStringObject\")\n , NanNew(NewStringObject)->GetFunction()\n );\n target->Set(\n NanNew(\"newNumberObject\")\n , NanNew(NewNumberObject)->GetFunction()\n );\n target->Set(\n NanNew(\"newBooleanObject\")\n , NanNew(NewBooleanObject)->GetFunction()\n );\n target->Set(\n NanNew(\"newExternal\")\n , NanNew(NewExternal)->GetFunction()\n );\n target->Set(\n NanNew(\"newSignature\")\n , NanNew(NewSignature)->GetFunction()\n );\n target->Set(\n NanNew(\"newScript\")\n , NanNew(NewScript)->GetFunction()\n );\n target->Set(\n NanNew(\"newScript2\")\n , NanNew(NewScript2)->GetFunction()\n );\n target->Set(\n NanNew(\"compileScript\")\n , NanNew(CompileScript)->GetFunction()\n );\n target->Set(\n NanNew(\"compileScript2\")\n , NanNew(CompileScript2)->GetFunction()\n );\n target->Set(\n NanNew(\"newDate\")\n , NanNew(NewDate)->GetFunction()\n );\n target->Set(\n NanNew(\"newArray\")\n , NanNew(NewArray)->GetFunction()\n );\n}\n\nNODE_MODULE(news, Init)\n<|endoftext|>"} {"text":"#include \"download.h\"\n\n#include \"test-helpers.h\"\n\nusing namespace podboat;\n\nTEST_CASE(\"Require-view-update callback gets called when download progress or status changes\", \"[Download]\")\n{\n\tGIVEN(\"A Download object\") {\n\t\tbool got_called = false;\n\t\tstd::function callback = [&got_called]() {\n\t\t\tgot_called = true;\n\t\t};\n\n\t\tDownload d(callback);\n\n\t\tREQUIRE(d.status() == DlStatus::QUEUED);\n\n\t\tWHEN(\"its progress is updated (increased)\") {\n\t\t\tgot_called = false;\n\t\t\td.set_progress(1.0, 1.0);\n\n\t\t\tTHEN(\"the require-view-update callback gets called\") {\n\t\t\t\tREQUIRE(got_called);\n\t\t\t}\n\t\t}\n\n\t\tWHEN(\"its progress has not changed\") {\n\t\t\tgot_called = false;\n\t\t\td.set_progress(0.0, 1.0);\n\n\t\t\tTHEN(\"the require-view-update callback does not get called\") {\n\t\t\t\tREQUIRE_FALSE(got_called);\n\t\t\t}\n\t\t}\n\n\t\tWHEN(\"its status is changed\") {\n\t\t\tgot_called = false;\n\t\t\td.set_status(DlStatus::DOWNLOADING);\n\n\t\t\tTHEN(\"the require-view-update callback gets called\") {\n\t\t\t\tREQUIRE(got_called);\n\t\t\t}\n\t\t}\n\n\t\tWHEN(\"when its status is not changed\") {\n\t\t\tgot_called = false;\n\t\t\td.set_status(DlStatus::QUEUED);\n\n\t\t\tTHEN(\"the require-view-update callback does not get called\") {\n\t\t\t\tREQUIRE_FALSE(got_called);\n\t\t\t}\n\t\t}\n\t}\n}\nAdd test for Download::filename#include \"download.h\"\n\n#include \"test-helpers.h\"\n\nusing namespace podboat;\n\nTEST_CASE(\"Require-view-update callback gets called when download progress or status changes\", \"[Download]\")\n{\n\tGIVEN(\"A Download object\") {\n\t\tbool got_called = false;\n\t\tstd::function callback = [&got_called]() {\n\t\t\tgot_called = true;\n\t\t};\n\n\t\tDownload d(callback);\n\n\t\tREQUIRE(d.status() == DlStatus::QUEUED);\n\n\t\tWHEN(\"its progress is updated (increased)\") {\n\t\t\tgot_called = false;\n\t\t\td.set_progress(1.0, 1.0);\n\n\t\t\tTHEN(\"the require-view-update callback gets called\") {\n\t\t\t\tREQUIRE(got_called);\n\t\t\t}\n\t\t}\n\n\t\tWHEN(\"its progress has not changed\") {\n\t\t\tgot_called = false;\n\t\t\td.set_progress(0.0, 1.0);\n\n\t\t\tTHEN(\"the require-view-update callback does not get called\") {\n\t\t\t\tREQUIRE_FALSE(got_called);\n\t\t\t}\n\t\t}\n\n\t\tWHEN(\"its status is changed\") {\n\t\t\tgot_called = false;\n\t\t\td.set_status(DlStatus::DOWNLOADING);\n\n\t\t\tTHEN(\"the require-view-update callback gets called\") {\n\t\t\t\tREQUIRE(got_called);\n\t\t\t}\n\t\t}\n\n\t\tWHEN(\"when its status is not changed\") {\n\t\t\tgot_called = false;\n\t\t\td.set_status(DlStatus::QUEUED);\n\n\t\t\tTHEN(\"the require-view-update callback does not get called\") {\n\t\t\t\tREQUIRE_FALSE(got_called);\n\t\t\t}\n\t\t}\n\t}\n}\n\nTEST_CASE(\"Filename returns configured filename\", \"[Download]\")\n{\n\tauto emptyCallback = [](){};\n\n\tDownload d(emptyCallback);\n\n\tSECTION(\"filename returns empty string by default\") {\n\t\tREQUIRE(d.filename() == \"\");\n\t}\n\n\n\tSECTION(\"filename returns same string which is set via set_filename\") {\n\t\td.set_filename(\"abc\");\n\t\tREQUIRE(d.filename() == \"abc\");\n\t}\n\n\tSECTION(\"filename will return the latest configured filename\") {\n\t\td.set_filename(\"abc\");\n\t\td.set_filename(\"def\");\n\n\t\tREQUIRE(d.filename() == \"def\");\n\t}\n}\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2014 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"basetexteditmodifier.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace QmlDesigner;\n\nBaseTextEditModifier::BaseTextEditModifier(TextEditor::BaseTextEditorWidget *textEdit):\n PlainTextEditModifier(textEdit)\n{\n}\n\nvoid BaseTextEditModifier::indent(int offset, int length)\n{\n if (length == 0 || offset < 0 || offset + length >= text().length())\n return;\n\n if (TextEditor::BaseTextEditorWidget *bte = qobject_cast(plainTextEdit())) {\n TextEditor::BaseTextDocument *btd = bte->baseTextDocument();\n \/\/ find the applicable block:\n QTextDocument *doc = btd->document();\n QTextCursor tc(doc);\n tc.beginEditBlock();\n tc.setPosition(offset);\n tc.setPosition(offset + length, QTextCursor::KeepAnchor);\n btd->autoIndent(tc);\n tc.endEditBlock();\n }\n}\n\nint BaseTextEditModifier::indentDepth() const\n{\n if (TextEditor::BaseTextEditorWidget *bte = qobject_cast(plainTextEdit()))\n return bte->baseTextDocument()->tabSettings().m_indentSize;\n else\n return 0;\n}\n\nbool BaseTextEditModifier::renameId(const QString &oldId, const QString &newId)\n{\n if (QmlJSEditor::QmlJSTextEditorWidget *qmljse = qobject_cast(plainTextEdit())) {\n Utils::ChangeSet changeSet;\n foreach (const QmlJS::AST::SourceLocation &loc,\n qmljse->qmlJsEditorDocument()->semanticInfo().idLocations.value(oldId)) {\n changeSet.replace(loc.begin(), loc.end(), newId);\n }\n QTextCursor tc = qmljse->textCursor();\n changeSet.apply(&tc);\n return true;\n } else {\n return false;\n }\n}\n\nQmlJS::Snapshot BaseTextEditModifier::getSnapshot() const\n{\n QmlJS::ModelManagerInterface *modelManager = QmlJS::ModelManagerInterface::instance();\n if (modelManager)\n return modelManager->snapshot();\n else\n return QmlJS::Snapshot();\n}\n\nQStringList BaseTextEditModifier::importPaths() const\n{\n QmlJS::ModelManagerInterface *modelManager = QmlJS::ModelManagerInterface::instance();\n if (modelManager)\n return modelManager->importPaths();\n else\n return QStringList();\n}\nQmlDesigner: Use QmlJSEditorDocument instead of widget\/****************************************************************************\n**\n** Copyright (C) 2014 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"basetexteditmodifier.h\"\n\n#include \n#include \n#include \n#include \n\nusing namespace QmlDesigner;\n\nBaseTextEditModifier::BaseTextEditModifier(TextEditor::BaseTextEditorWidget *textEdit):\n PlainTextEditModifier(textEdit)\n{\n}\n\nvoid BaseTextEditModifier::indent(int offset, int length)\n{\n if (length == 0 || offset < 0 || offset + length >= text().length())\n return;\n\n if (TextEditor::BaseTextEditorWidget *bte = qobject_cast(plainTextEdit())) {\n TextEditor::BaseTextDocument *btd = bte->baseTextDocument();\n \/\/ find the applicable block:\n QTextDocument *doc = btd->document();\n QTextCursor tc(doc);\n tc.beginEditBlock();\n tc.setPosition(offset);\n tc.setPosition(offset + length, QTextCursor::KeepAnchor);\n btd->autoIndent(tc);\n tc.endEditBlock();\n }\n}\n\nint BaseTextEditModifier::indentDepth() const\n{\n if (TextEditor::BaseTextEditorWidget *bte = qobject_cast(plainTextEdit()))\n return bte->baseTextDocument()->tabSettings().m_indentSize;\n else\n return 0;\n}\n\nbool BaseTextEditModifier::renameId(const QString &oldId, const QString &newId)\n{\n if (TextEditor::BaseTextEditorWidget *bte = qobject_cast(plainTextEdit())) {\n if (QmlJSEditor::QmlJSEditorDocument *document\n = qobject_cast(bte->baseTextDocument())) {\n Utils::ChangeSet changeSet;\n foreach (const QmlJS::AST::SourceLocation &loc,\n document->semanticInfo().idLocations.value(oldId)) {\n changeSet.replace(loc.begin(), loc.end(), newId);\n }\n QTextCursor tc = bte->textCursor();\n changeSet.apply(&tc);\n return true;\n }\n }\n return false;\n}\n\nQmlJS::Snapshot BaseTextEditModifier::getSnapshot() const\n{\n QmlJS::ModelManagerInterface *modelManager = QmlJS::ModelManagerInterface::instance();\n if (modelManager)\n return modelManager->snapshot();\n else\n return QmlJS::Snapshot();\n}\n\nQStringList BaseTextEditModifier::importPaths() const\n{\n QmlJS::ModelManagerInterface *modelManager = QmlJS::ModelManagerInterface::instance();\n if (modelManager)\n return modelManager->importPaths();\n else\n return QStringList();\n}\n<|endoftext|>"} {"text":"\n#pragma once\n\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n\nnamespace glbinding\n{\n\n\ntemplate \nstruct BasicCallHelper\n{\n inline static ReturnType call(const glbinding::Function * function, Arguments&&... arguments)\n {\n return reinterpret_cast::Signature>(function->address())(std::forward(arguments)...);\n }\n};\n\n\n\/\/ Special case for booleans because of MSVC differing behavior\n\ntemplate \nstruct BasicCallHelper\n{\n inline static glbinding::Boolean8 call(const glbinding::Function * function, Arguments&&... arguments)\n {\n return reinterpret_cast::Signature>(function->address())(std::forward(arguments)...);\n }\n};\n\n\ntemplate \nstruct FunctionHelper\n{\n inline static ReturnType call(const glbinding::Function * function, Arguments&&... arguments)\n {\n glbinding::FunctionCall functionCall(function);\n\n if (function->isAnyEnabled(glbinding::CallbackMask::Parameters))\n {\n functionCall.parameters = glbinding::createValues(std::forward(arguments)...);\n }\n\n if (function->isEnabled(glbinding::CallbackMask::Before))\n {\n AbstractFunction::before(functionCall);\n\n if (function->beforeCallback())\n {\n function->beforeCallback()(std::forward(arguments)...);\n }\n }\n\n auto value = BasicCallHelper::call(function, std::forward(arguments)...);\n\n if (function->isAnyEnabled(glbinding::CallbackMask::ReturnValue))\n {\n functionCall.returnValue = glbinding::createValue(value);\n }\n\n if (function->isEnabled(glbinding::CallbackMask::After))\n {\n AbstractFunction::after(functionCall);\n\n if (function->afterCallback())\n {\n function->afterCallback()(value, std::forward(arguments)...);\n }\n }\n\n if (function->isEnabled(glbinding::CallbackMask::Logging))\n {\n AbstractFunction::log(std::move(functionCall));\n }\n\n return value;\n }\n};\n\n\ntemplate \nstruct FunctionHelper\n{\n inline static void call(const glbinding::Function * function, Arguments&&... arguments)\n {\n glbinding::FunctionCall functionCall(function);\n\n if (function->isAnyEnabled(glbinding::CallbackMask::Parameters))\n {\n functionCall.parameters = glbinding::createValues(std::forward(arguments)...);\n }\n\n if (function->isEnabled(glbinding::CallbackMask::Before))\n {\n AbstractFunction::before(functionCall);\n\n if (function->beforeCallback())\n {\n function->beforeCallback()(std::forward(arguments)...);\n }\n }\n\n BasicCallHelper::call(function, std::forward(arguments)...);\n\n if (function->isEnabled(glbinding::CallbackMask::After))\n {\n AbstractFunction::after(functionCall);\n\n if (function->afterCallback())\n {\n function->afterCallback()(std::forward(arguments)...);\n }\n }\n\n if (function->isEnabled(glbinding::CallbackMask::Logging))\n {\n AbstractFunction::log(std::move(functionCall));\n }\n }\n};\n\n\ntemplate \nFunction::Function(const char * _name)\n: AbstractFunction{_name}\n, m_beforeCallback{nullptr}\n, m_afterCallback{nullptr}\n{\n}\n\ntemplate \nReturnType Function::operator()(Arguments&... arguments) const\n{\n return call(arguments...);\n}\n\ntemplate \nReturnType Function::call(Arguments&... arguments) const\n{\n const auto myAddress = address();\n\n if (myAddress == nullptr)\n {\n if (isEnabled(CallbackMask::Unresolved))\n {\n AbstractFunction::unresolved(this);\n }\n\n return ReturnType();\n }\n\n if (isAnyEnabled(CallbackMask::Before | CallbackMask::After | CallbackMask::Logging))\n {\n return FunctionHelper::call(this, std::forward(arguments)...);\n }\n else\n {\n return BasicCallHelper::call(this, std::forward(arguments)...);\n }\n}\n\ntemplate \nReturnType Function::directCall(Arguments... arguments) const\n{\n if (address() == nullptr)\n {\n return ReturnType();\n }\n\n return BasicCallHelper::call(this, std::forward(arguments)...);\n}\n\ntemplate \nvoid Function::setBeforeCallback(BeforeCallback callback)\n{\n m_beforeCallback = std::move(callback);\n}\n\ntemplate \nvoid Function::clearBeforeCallback()\n{\n m_beforeCallback = nullptr;\n}\n\ntemplate \nvoid Function::setAfterCallback(AfterCallback callback)\n{\n m_afterCallback = std::move(callback);\n}\n\ntemplate \nvoid Function::clearAfterCallback()\n{\n m_afterCallback = nullptr;\n}\n\ntemplate \ntypename Function::BeforeCallback Function::beforeCallback() const\n{\n return m_beforeCallback;\n}\n\ntemplate \ntypename Function::AfterCallback Function::afterCallback() const\n{\n return m_afterCallback;\n}\n\ntemplate \nbool Function::hasState() const\n{\n return hasState(AbstractFunction::currentPos());\n}\n\ntemplate \nbool Function::hasState(const int pos) const\n{\n return pos > -1 && AbstractFunction::maxPos() <= pos;\n}\n\ntemplate \nAbstractState & Function::state() const\n{\n return state(AbstractFunction::currentPos());\n}\n\ntemplate \nAbstractState & Function::state(const int pos) const\n{\n assert(AbstractFunction::maxPos() >= pos);\n assert(pos > -1);\n\n return m_states.at(pos);\n}\n\ntemplate \nvoid Function::resizeStates(int count)\n{\n m_states.resize(static_cast(count));\n}\n\n\n} \/\/ namespace glbinding\nAssert valid function pointer instead of silent failure (closes #262)\n#pragma once\n\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n\nnamespace glbinding\n{\n\n\ntemplate \nstruct BasicCallHelper\n{\n inline static ReturnType call(const glbinding::Function * function, Arguments&&... arguments)\n {\n return reinterpret_cast::Signature>(function->address())(std::forward(arguments)...);\n }\n};\n\n\n\/\/ Special case for booleans because of MSVC differing behavior\n\ntemplate \nstruct BasicCallHelper\n{\n inline static glbinding::Boolean8 call(const glbinding::Function * function, Arguments&&... arguments)\n {\n return reinterpret_cast::Signature>(function->address())(std::forward(arguments)...);\n }\n};\n\n\ntemplate \nstruct FunctionHelper\n{\n inline static ReturnType call(const glbinding::Function * function, Arguments&&... arguments)\n {\n glbinding::FunctionCall functionCall(function);\n\n if (function->isAnyEnabled(glbinding::CallbackMask::Parameters))\n {\n functionCall.parameters = glbinding::createValues(std::forward(arguments)...);\n }\n\n if (function->isEnabled(glbinding::CallbackMask::Before))\n {\n AbstractFunction::before(functionCall);\n\n if (function->beforeCallback())\n {\n function->beforeCallback()(std::forward(arguments)...);\n }\n }\n\n auto value = BasicCallHelper::call(function, std::forward(arguments)...);\n\n if (function->isAnyEnabled(glbinding::CallbackMask::ReturnValue))\n {\n functionCall.returnValue = glbinding::createValue(value);\n }\n\n if (function->isEnabled(glbinding::CallbackMask::After))\n {\n AbstractFunction::after(functionCall);\n\n if (function->afterCallback())\n {\n function->afterCallback()(value, std::forward(arguments)...);\n }\n }\n\n if (function->isEnabled(glbinding::CallbackMask::Logging))\n {\n AbstractFunction::log(std::move(functionCall));\n }\n\n return value;\n }\n};\n\n\ntemplate \nstruct FunctionHelper\n{\n inline static void call(const glbinding::Function * function, Arguments&&... arguments)\n {\n glbinding::FunctionCall functionCall(function);\n\n if (function->isAnyEnabled(glbinding::CallbackMask::Parameters))\n {\n functionCall.parameters = glbinding::createValues(std::forward(arguments)...);\n }\n\n if (function->isEnabled(glbinding::CallbackMask::Before))\n {\n AbstractFunction::before(functionCall);\n\n if (function->beforeCallback())\n {\n function->beforeCallback()(std::forward(arguments)...);\n }\n }\n\n BasicCallHelper::call(function, std::forward(arguments)...);\n\n if (function->isEnabled(glbinding::CallbackMask::After))\n {\n AbstractFunction::after(functionCall);\n\n if (function->afterCallback())\n {\n function->afterCallback()(std::forward(arguments)...);\n }\n }\n\n if (function->isEnabled(glbinding::CallbackMask::Logging))\n {\n AbstractFunction::log(std::move(functionCall));\n }\n }\n};\n\n\ntemplate \nFunction::Function(const char * _name)\n: AbstractFunction{_name}\n, m_beforeCallback{nullptr}\n, m_afterCallback{nullptr}\n{\n}\n\ntemplate \nReturnType Function::operator()(Arguments&... arguments) const\n{\n return call(arguments...);\n}\n\ntemplate \nReturnType Function::call(Arguments&... arguments) const\n{\n const auto myAddress = address();\n\n if (myAddress == nullptr)\n {\n if (isEnabled(CallbackMask::Unresolved))\n {\n AbstractFunction::unresolved(this);\n }\n else\n {\n \/\/ Trying to call a function without check if it is resolvable is considered a programming error.\n \/\/ You may try to call AbstractFunction::resolve first and check the address for validity (a pointer\n \/\/ unequal to nullptr is considered valid) or check the exposition of associated extensions.\n assert(false);\n }\n\n return ReturnType();\n }\n\n if (isAnyEnabled(CallbackMask::Before | CallbackMask::After | CallbackMask::Logging))\n {\n return FunctionHelper::call(this, std::forward(arguments)...);\n }\n else\n {\n return BasicCallHelper::call(this, std::forward(arguments)...);\n }\n}\n\ntemplate \nReturnType Function::directCall(Arguments... arguments) const\n{\n if (address() == nullptr)\n {\n return ReturnType();\n }\n\n return BasicCallHelper::call(this, std::forward(arguments)...);\n}\n\ntemplate \nvoid Function::setBeforeCallback(BeforeCallback callback)\n{\n m_beforeCallback = std::move(callback);\n}\n\ntemplate \nvoid Function::clearBeforeCallback()\n{\n m_beforeCallback = nullptr;\n}\n\ntemplate \nvoid Function::setAfterCallback(AfterCallback callback)\n{\n m_afterCallback = std::move(callback);\n}\n\ntemplate \nvoid Function::clearAfterCallback()\n{\n m_afterCallback = nullptr;\n}\n\ntemplate \ntypename Function::BeforeCallback Function::beforeCallback() const\n{\n return m_beforeCallback;\n}\n\ntemplate \ntypename Function::AfterCallback Function::afterCallback() const\n{\n return m_afterCallback;\n}\n\ntemplate \nbool Function::hasState() const\n{\n return hasState(AbstractFunction::currentPos());\n}\n\ntemplate \nbool Function::hasState(const int pos) const\n{\n return pos > -1 && AbstractFunction::maxPos() <= pos;\n}\n\ntemplate \nAbstractState & Function::state() const\n{\n return state(AbstractFunction::currentPos());\n}\n\ntemplate \nAbstractState & Function::state(const int pos) const\n{\n assert(AbstractFunction::maxPos() >= pos);\n assert(pos > -1);\n\n return m_states.at(pos);\n}\n\ntemplate \nvoid Function::resizeStates(int count)\n{\n m_states.resize(static_cast(count));\n}\n\n\n} \/\/ namespace glbinding\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2010 Google Inc. All rights reserved.\n * Copyright (C) 2013 Samsung Electronics. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * 3. Neither the name of Apple Computer, Inc. (\"Apple\") nor the names of\n * its contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS \"AS IS\" AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n#include \"modules\/storage\/InspectorDOMStorageAgent.h\"\n\n#include \"bindings\/core\/v8\/ExceptionState.h\"\n#include \"core\/InspectorFrontend.h\"\n#include \"core\/dom\/DOMException.h\"\n#include \"core\/dom\/Document.h\"\n#include \"core\/dom\/ExceptionCode.h\"\n#include \"core\/frame\/LocalDOMWindow.h\"\n#include \"core\/frame\/LocalFrame.h\"\n#include \"core\/inspector\/InspectorState.h\"\n#include \"core\/page\/Page.h\"\n#include \"modules\/storage\/Storage.h\"\n#include \"modules\/storage\/StorageNamespace.h\"\n#include \"modules\/storage\/StorageNamespaceController.h\"\n#include \"platform\/JSONValues.h\"\n#include \"platform\/weborigin\/SecurityOrigin.h\"\n\nnamespace blink {\n\n#ifdef MINIBLINK_NOT_IMPLEMENTED\n\nnamespace DOMStorageAgentState {\nstatic const char domStorageAgentEnabled[] = \"domStorageAgentEnabled\";\n};\n\nstatic bool hadException(ExceptionState& exceptionState, ErrorString* errorString)\n{\n if (!exceptionState.hadException())\n return false;\n\n switch (exceptionState.code()) {\n case SecurityError:\n *errorString = \"Security error\";\n return true;\n default:\n *errorString = \"Unknown DOM storage error\";\n return true;\n }\n}\n\nInspectorDOMStorageAgent::InspectorDOMStorageAgent(Page* page)\n : InspectorBaseAgent(\"DOMStorage\")\n , m_page(page)\n , m_isEnabled(false)\n{\n}\n\nInspectorDOMStorageAgent::~InspectorDOMStorageAgent()\n{\n}\n\nDEFINE_TRACE(InspectorDOMStorageAgent)\n{\n visitor->trace(m_page);\n InspectorBaseAgent::trace(visitor);\n}\n\nvoid InspectorDOMStorageAgent::restore()\n{\n if (m_state->getBoolean(DOMStorageAgentState::domStorageAgentEnabled))\n enable(0);\n}\n\nvoid InspectorDOMStorageAgent::enable(ErrorString*)\n{\n if (m_isEnabled)\n return;\n m_isEnabled = true;\n m_state->setBoolean(DOMStorageAgentState::domStorageAgentEnabled, true);\n if (StorageNamespaceController* controller = StorageNamespaceController::from(m_page))\n controller->setInspectorAgent(this);\n}\n\nvoid InspectorDOMStorageAgent::disable(ErrorString*)\n{\n if (!m_isEnabled)\n return;\n m_isEnabled = false;\n m_state->setBoolean(DOMStorageAgentState::domStorageAgentEnabled, false);\n if (StorageNamespaceController* controller = StorageNamespaceController::from(m_page))\n controller->setInspectorAgent(nullptr);\n}\n\nvoid InspectorDOMStorageAgent::getDOMStorageItems(ErrorString* errorString, const RefPtr& storageId, RefPtr>>& items)\n{\n LocalFrame* frame;\n StorageArea* storageArea = findStorageArea(errorString, storageId, frame);\n if (!storageArea)\n return;\n\n RefPtr>> storageItems = TypeBuilder::Array>::create();\n\n TrackExceptionState exceptionState;\n for (unsigned i = 0; i < storageArea->length(exceptionState, frame); ++i) {\n String name(storageArea->key(i, exceptionState, frame));\n if (hadException(exceptionState, errorString))\n return;\n String value(storageArea->getItem(name, exceptionState, frame));\n if (hadException(exceptionState, errorString))\n return;\n RefPtr> entry = TypeBuilder::Array::create();\n entry->addItem(name);\n entry->addItem(value);\n storageItems->addItem(entry);\n }\n items = storageItems.release();\n}\n\nstatic String toErrorString(ExceptionState& exceptionState)\n{\n if (exceptionState.hadException())\n return DOMException::getErrorName(exceptionState.code());\n return \"\";\n}\n\nvoid InspectorDOMStorageAgent::setDOMStorageItem(ErrorString* errorString, const RefPtr& storageId, const String& key, const String& value)\n{\n LocalFrame* frame;\n StorageArea* storageArea = findStorageArea(0, storageId, frame);\n if (!storageArea) {\n *errorString = \"Storage not found\";\n return;\n }\n\n TrackExceptionState exceptionState;\n storageArea->setItem(key, value, exceptionState, frame);\n *errorString = toErrorString(exceptionState);\n}\n\nvoid InspectorDOMStorageAgent::removeDOMStorageItem(ErrorString* errorString, const RefPtr& storageId, const String& key)\n{\n LocalFrame* frame;\n StorageArea* storageArea = findStorageArea(0, storageId, frame);\n if (!storageArea) {\n *errorString = \"Storage not found\";\n return;\n }\n\n TrackExceptionState exceptionState;\n storageArea->removeItem(key, exceptionState, frame);\n *errorString = toErrorString(exceptionState);\n}\n\nPassRefPtr InspectorDOMStorageAgent::storageId(SecurityOrigin* securityOrigin, bool isLocalStorage)\n{\n return TypeBuilder::DOMStorage::StorageId::create()\n .setSecurityOrigin(securityOrigin->toRawString())\n .setIsLocalStorage(isLocalStorage).release();\n}\n\nvoid InspectorDOMStorageAgent::didDispatchDOMStorageEvent(const String& key, const String& oldValue, const String& newValue, StorageType storageType, SecurityOrigin* securityOrigin)\n{\n if (!frontend())\n return;\n\n RefPtr id = storageId(securityOrigin, storageType == LocalStorage);\n\n if (key.isNull())\n frontend()->domStorageItemsCleared(id);\n else if (newValue.isNull())\n frontend()->domStorageItemRemoved(id, key);\n else if (oldValue.isNull())\n frontend()->domStorageItemAdded(id, key, newValue);\n else\n frontend()->domStorageItemUpdated(id, key, oldValue, newValue);\n}\n\nstatic LocalFrame* findFrameWithSecurityOrigin(LocalFrame* inspectedFrame, const String& originRawString)\n{\n for (Frame* frame = inspectedFrame; frame; frame = frame->tree().traverseNext(inspectedFrame)) {\n if (!frame->isLocalFrame())\n continue;\n RefPtr documentOrigin = toLocalFrame(frame)->document()->securityOrigin();\n if (documentOrigin->toRawString() == originRawString)\n return toLocalFrame(frame);\n }\n return nullptr;\n}\n\nStorageArea* InspectorDOMStorageAgent::findStorageArea(ErrorString* errorString, const RefPtr& storageId, LocalFrame*& targetFrame)\n{\n String securityOrigin;\n bool isLocalStorage = false;\n bool success = storageId->getString(\"securityOrigin\", &securityOrigin);\n if (success)\n success = storageId->getBoolean(\"isLocalStorage\", &isLocalStorage);\n if (!success) {\n if (errorString)\n *errorString = \"Invalid storageId format\";\n return nullptr;\n }\n\n if (!m_page->mainFrame()->isLocalFrame())\n return nullptr;\n\n LocalFrame* frame = findFrameWithSecurityOrigin(m_page->deprecatedLocalMainFrame(), securityOrigin);\n if (!frame) {\n if (errorString)\n *errorString = \"LocalFrame not found for the given security origin\";\n return nullptr;\n }\n targetFrame = frame;\n\n if (isLocalStorage)\n return StorageNamespace::localStorageArea(frame->document()->securityOrigin());\n return StorageNamespaceController::from(m_page)->sessionStorage()->storageArea(frame->document()->securityOrigin());\n}\n\n#else\n\nvoid InspectorDOMStorageAgent::didDispatchDOMStorageEvent(const String& key, const String& oldValue, const String& newValue, StorageType storageType, SecurityOrigin* securityOrigin)\n{\n ;\n}\n\nDEFINE_TRACE(InspectorDOMStorageAgent)\n{\n\/\/ visitor->trace(m_page);\n\/\/ InspectorBaseAgent::trace(visitor);\n DebugBreak();\n}\n\n#endif \/\/ MINIBLINK_NOT_IMPLEMENTED\n\n} \/\/ namespace blink\n* 打开devtools的storage\/*\n * Copyright (C) 2010 Google Inc. All rights reserved.\n * Copyright (C) 2013 Samsung Electronics. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * 3. Neither the name of Apple Computer, Inc. (\"Apple\") nor the names of\n * its contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS \"AS IS\" AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n#include \"modules\/storage\/InspectorDOMStorageAgent.h\"\n\n#include \"bindings\/core\/v8\/ExceptionState.h\"\n#include \"core\/InspectorFrontend.h\"\n#include \"core\/dom\/DOMException.h\"\n#include \"core\/dom\/Document.h\"\n#include \"core\/dom\/ExceptionCode.h\"\n#include \"core\/frame\/LocalDOMWindow.h\"\n#include \"core\/frame\/LocalFrame.h\"\n#include \"core\/inspector\/InspectorState.h\"\n#include \"core\/page\/Page.h\"\n#include \"modules\/storage\/Storage.h\"\n#include \"modules\/storage\/StorageNamespace.h\"\n#include \"modules\/storage\/StorageNamespaceController.h\"\n#include \"platform\/JSONValues.h\"\n#include \"platform\/weborigin\/SecurityOrigin.h\"\n\nnamespace blink {\n\n#if 1 \/\/ def MINIBLINK_NOT_IMPLEMENTED\n\nnamespace DOMStorageAgentState {\nstatic const char domStorageAgentEnabled[] = \"domStorageAgentEnabled\";\n};\n\nstatic bool hadException(ExceptionState& exceptionState, ErrorString* errorString)\n{\n if (!exceptionState.hadException())\n return false;\n\n switch (exceptionState.code()) {\n case SecurityError:\n *errorString = \"Security error\";\n return true;\n default:\n *errorString = \"Unknown DOM storage error\";\n return true;\n }\n}\n\nInspectorDOMStorageAgent::InspectorDOMStorageAgent(Page* page)\n : InspectorBaseAgent(\"DOMStorage\")\n , m_page(page)\n , m_isEnabled(false)\n{\n}\n\nInspectorDOMStorageAgent::~InspectorDOMStorageAgent()\n{\n}\n\nDEFINE_TRACE(InspectorDOMStorageAgent)\n{\n visitor->trace(m_page);\n InspectorBaseAgent::trace(visitor);\n}\n\nvoid InspectorDOMStorageAgent::restore()\n{\n if (m_state->getBoolean(DOMStorageAgentState::domStorageAgentEnabled))\n enable(0);\n}\n\nvoid InspectorDOMStorageAgent::enable(ErrorString*)\n{\n if (m_isEnabled)\n return;\n m_isEnabled = true;\n m_state->setBoolean(DOMStorageAgentState::domStorageAgentEnabled, true);\n if (StorageNamespaceController* controller = StorageNamespaceController::from(m_page))\n controller->setInspectorAgent(this);\n}\n\nvoid InspectorDOMStorageAgent::disable(ErrorString*)\n{\n if (!m_isEnabled)\n return;\n m_isEnabled = false;\n m_state->setBoolean(DOMStorageAgentState::domStorageAgentEnabled, false);\n if (StorageNamespaceController* controller = StorageNamespaceController::from(m_page))\n controller->setInspectorAgent(nullptr);\n}\n\nvoid InspectorDOMStorageAgent::getDOMStorageItems(ErrorString* errorString, const RefPtr& storageId, RefPtr>>& items)\n{\n LocalFrame* frame;\n StorageArea* storageArea = findStorageArea(errorString, storageId, frame);\n if (!storageArea)\n return;\n\n RefPtr>> storageItems = TypeBuilder::Array>::create();\n\n TrackExceptionState exceptionState;\n for (unsigned i = 0; i < storageArea->length(exceptionState, frame); ++i) {\n String name(storageArea->key(i, exceptionState, frame));\n if (hadException(exceptionState, errorString))\n return;\n String value(storageArea->getItem(name, exceptionState, frame));\n if (hadException(exceptionState, errorString))\n return;\n RefPtr> entry = TypeBuilder::Array::create();\n entry->addItem(name);\n entry->addItem(value);\n storageItems->addItem(entry);\n }\n items = storageItems.release();\n}\n\nstatic String toErrorString(ExceptionState& exceptionState)\n{\n if (exceptionState.hadException())\n return DOMException::getErrorName(exceptionState.code());\n return \"\";\n}\n\nvoid InspectorDOMStorageAgent::setDOMStorageItem(ErrorString* errorString, const RefPtr& storageId, const String& key, const String& value)\n{\n LocalFrame* frame;\n StorageArea* storageArea = findStorageArea(0, storageId, frame);\n if (!storageArea) {\n *errorString = \"Storage not found\";\n return;\n }\n\n TrackExceptionState exceptionState;\n storageArea->setItem(key, value, exceptionState, frame);\n *errorString = toErrorString(exceptionState);\n}\n\nvoid InspectorDOMStorageAgent::removeDOMStorageItem(ErrorString* errorString, const RefPtr& storageId, const String& key)\n{\n LocalFrame* frame;\n StorageArea* storageArea = findStorageArea(0, storageId, frame);\n if (!storageArea) {\n *errorString = \"Storage not found\";\n return;\n }\n\n TrackExceptionState exceptionState;\n storageArea->removeItem(key, exceptionState, frame);\n *errorString = toErrorString(exceptionState);\n}\n\nPassRefPtr InspectorDOMStorageAgent::storageId(SecurityOrigin* securityOrigin, bool isLocalStorage)\n{\n return TypeBuilder::DOMStorage::StorageId::create()\n .setSecurityOrigin(securityOrigin->toRawString())\n .setIsLocalStorage(isLocalStorage).release();\n}\n\nvoid InspectorDOMStorageAgent::didDispatchDOMStorageEvent(const String& key, const String& oldValue, const String& newValue, StorageType storageType, SecurityOrigin* securityOrigin)\n{\n if (!frontend())\n return;\n\n RefPtr id = storageId(securityOrigin, storageType == LocalStorage);\n\n if (key.isNull())\n frontend()->domStorageItemsCleared(id);\n else if (newValue.isNull())\n frontend()->domStorageItemRemoved(id, key);\n else if (oldValue.isNull())\n frontend()->domStorageItemAdded(id, key, newValue);\n else\n frontend()->domStorageItemUpdated(id, key, oldValue, newValue);\n}\n\nstatic LocalFrame* findFrameWithSecurityOrigin(LocalFrame* inspectedFrame, const String& originRawString)\n{\n for (Frame* frame = inspectedFrame; frame; frame = frame->tree().traverseNext(inspectedFrame)) {\n if (!frame->isLocalFrame())\n continue;\n RefPtr documentOrigin = toLocalFrame(frame)->document()->securityOrigin();\n if (documentOrigin->toRawString() == originRawString)\n return toLocalFrame(frame);\n }\n return nullptr;\n}\n\nStorageArea* InspectorDOMStorageAgent::findStorageArea(ErrorString* errorString, const RefPtr& storageId, LocalFrame*& targetFrame)\n{\n String securityOrigin;\n bool isLocalStorage = false;\n bool success = storageId->getString(\"securityOrigin\", &securityOrigin);\n if (success)\n success = storageId->getBoolean(\"isLocalStorage\", &isLocalStorage);\n if (!success) {\n if (errorString)\n *errorString = \"Invalid storageId format\";\n return nullptr;\n }\n\n if (!m_page->mainFrame()->isLocalFrame())\n return nullptr;\n\n LocalFrame* frame = findFrameWithSecurityOrigin(m_page->deprecatedLocalMainFrame(), securityOrigin);\n if (!frame) {\n if (errorString)\n *errorString = \"LocalFrame not found for the given security origin\";\n return nullptr;\n }\n targetFrame = frame;\n\n if (isLocalStorage)\n return StorageNamespace::localStorageArea(frame->document()->securityOrigin());\n return StorageNamespaceController::from(m_page)->sessionStorage()->storageArea(frame->document()->securityOrigin());\n}\n\n#else\n\nvoid InspectorDOMStorageAgent::didDispatchDOMStorageEvent(const String& key, const String& oldValue, const String& newValue, StorageType storageType, SecurityOrigin* securityOrigin)\n{\n ;\n}\n\nDEFINE_TRACE(InspectorDOMStorageAgent)\n{\n\/\/ visitor->trace(m_page);\n\/\/ InspectorBaseAgent::trace(visitor);\n DebugBreak();\n}\n\n#endif \/\/ MINIBLINK_NOT_IMPLEMENTED\n\n} \/\/ namespace blink\n<|endoftext|>"} {"text":"\/\/ Copyright 2014 BVLC and contributors.\n\n#include \n\n#include \"cuda_runtime.h\"\n#include \"gtest\/gtest.h\"\n#include \"caffe\/blob.hpp\"\n#include \"caffe\/common.hpp\"\n#include \"caffe\/filler.hpp\"\n#include \"caffe\/vision_layers.hpp\"\n#include \"caffe\/test\/test_gradient_check_util.hpp\"\n\n#include \"caffe\/test\/test_caffe_main.hpp\"\n\nnamespace caffe {\n\nextern cudaDeviceProp CAFFE_TEST_CUDA_PROP;\n\ntemplate \nclass ArgMaxLayerTest : public ::testing::Test {\n protected:\n ArgMaxLayerTest()\n : blob_bottom_(new Blob(20, 10, 1, 1)),\n blob_top_(new Blob()) {\n Caffe::set_random_seed(this->seed_);\n \/\/ fill the values\n FillerParameter filler_param;\n GaussianFiller filler(filler_param);\n filler.Fill(this->blob_bottom_);\n blob_bottom_vec_.push_back(blob_bottom_);\n blob_top_vec_.push_back(blob_top_);\n }\n virtual ~ArgMaxLayerTest() { delete blob_bottom_; delete blob_top_; }\n Blob* const blob_bottom_;\n Blob* const blob_top_;\n vector*> blob_bottom_vec_;\n vector*> blob_top_vec_;\n};\n\ntypedef ::testing::Types Dtypes;\nTYPED_TEST_CASE(ArgMaxLayerTest, Dtypes);\n\n\nTYPED_TEST(ArgMaxLayerTest, TestSetup) {\n LayerParameter layer_param;\n ArgMaxLayer layer(layer_param);\n layer.SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_));\n EXPECT_EQ(this->blob_top_->num(), this->blob_bottom_->num());\n EXPECT_EQ(this->blob_top_->channels(), 1);\n}\n\nTYPED_TEST(ArgMaxLayerTest, TestSetupMaxVal) {\n LayerParameter layer_param;\n ArgMaxParameter* argmax_param = layer_param.mutable_argmax_param();\n argmax_param->set_out_max_val(true);\n ArgMaxLayer layer(layer_param);\n layer.SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_));\n EXPECT_EQ(this->blob_top_->num(), this->blob_bottom_->num());\n EXPECT_EQ(this->blob_top_->channels(), 2);\n}\n\nTYPED_TEST(ArgMaxLayerTest, TestCPU) {\n LayerParameter layer_param;\n Caffe::set_mode(Caffe::CPU);\n ArgMaxLayer layer(layer_param);\n layer.SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_));\n layer.Forward(this->blob_bottom_vec_, &(this->blob_top_vec_));\n \/\/ Now, check values\n const TypeParam* bottom_data = this->blob_bottom_->cpu_data();\n const TypeParam* top_data = this->blob_top_->cpu_data();\n int max_ind;\n TypeParam max_val;\n int num = this->blob_bottom_->num();\n int dim = this->blob_bottom_->count() \/ num;\n for (int i = 0; i < num; ++i) {\n EXPECT_GE(top_data[i], 0);\n EXPECT_LE(top_data[i], dim);\n max_ind = top_data[i];\n max_val = bottom_data[i * dim + max_ind];\n for (int j = 0; j < dim; ++j) {\n EXPECT_LE(bottom_data[i * dim + j], max_val);\n }\n }\n}\n\nTYPED_TEST(ArgMaxLayerTest, TestCPUMaxVal) {\n LayerParameter layer_param;\n Caffe::set_mode(Caffe::CPU);\n ArgMaxParameter* argmax_param = layer_param.mutable_argmax_param();\n argmax_param->set_out_max_val(true);\n ArgMaxLayer layer(layer_param);\n layer.SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_));\n layer.Forward(this->blob_bottom_vec_, &(this->blob_top_vec_));\n \/\/ Now, check values\n const TypeParam* bottom_data = this->blob_bottom_->cpu_data();\n const TypeParam* top_data = this->blob_top_->cpu_data();\n int max_ind;\n TypeParam max_val;\n int num = this->blob_bottom_->num();\n int dim = this->blob_bottom_->count() \/ num;\n for (int i = 0; i < num; ++i) {\n EXPECT_GE(top_data[i], 0);\n EXPECT_LE(top_data[i], dim);\n max_ind = top_data[i * 2];\n max_val = top_data[i * 2 + 1];\n EXPECT_EQ(bottom_data[i * dim + max_ind], max_val);\n for (int j = 0; j < dim; ++j) {\n EXPECT_LE(bottom_data[i * dim + j], max_val);\n }\n }\n}\n\n} \/\/ namespace caffe\nRevert \"setting canonical random seed\"\/\/ Copyright 2014 BVLC and contributors.\n\n#include \n\n#include \"cuda_runtime.h\"\n#include \"gtest\/gtest.h\"\n#include \"caffe\/blob.hpp\"\n#include \"caffe\/common.hpp\"\n#include \"caffe\/filler.hpp\"\n#include \"caffe\/vision_layers.hpp\"\n#include \"caffe\/test\/test_gradient_check_util.hpp\"\n\n#include \"caffe\/test\/test_caffe_main.hpp\"\n\nnamespace caffe {\n\nextern cudaDeviceProp CAFFE_TEST_CUDA_PROP;\n\ntemplate \nclass ArgMaxLayerTest : public ::testing::Test {\n protected:\n ArgMaxLayerTest()\n : blob_bottom_(new Blob(20, 10, 1, 1)),\n blob_top_(new Blob()) {\n Caffe::set_random_seed(1701);\n \/\/ fill the values\n FillerParameter filler_param;\n GaussianFiller filler(filler_param);\n filler.Fill(this->blob_bottom_);\n blob_bottom_vec_.push_back(blob_bottom_);\n blob_top_vec_.push_back(blob_top_);\n }\n virtual ~ArgMaxLayerTest() { delete blob_bottom_; delete blob_top_; }\n Blob* const blob_bottom_;\n Blob* const blob_top_;\n vector*> blob_bottom_vec_;\n vector*> blob_top_vec_;\n};\n\ntypedef ::testing::Types Dtypes;\nTYPED_TEST_CASE(ArgMaxLayerTest, Dtypes);\n\n\nTYPED_TEST(ArgMaxLayerTest, TestSetup) {\n LayerParameter layer_param;\n ArgMaxLayer layer(layer_param);\n layer.SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_));\n EXPECT_EQ(this->blob_top_->num(), this->blob_bottom_->num());\n EXPECT_EQ(this->blob_top_->channels(), 1);\n}\n\nTYPED_TEST(ArgMaxLayerTest, TestSetupMaxVal) {\n LayerParameter layer_param;\n ArgMaxParameter* argmax_param = layer_param.mutable_argmax_param();\n argmax_param->set_out_max_val(true);\n ArgMaxLayer layer(layer_param);\n layer.SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_));\n EXPECT_EQ(this->blob_top_->num(), this->blob_bottom_->num());\n EXPECT_EQ(this->blob_top_->channels(), 2);\n}\n\nTYPED_TEST(ArgMaxLayerTest, TestCPU) {\n LayerParameter layer_param;\n Caffe::set_mode(Caffe::CPU);\n ArgMaxLayer layer(layer_param);\n layer.SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_));\n layer.Forward(this->blob_bottom_vec_, &(this->blob_top_vec_));\n \/\/ Now, check values\n const TypeParam* bottom_data = this->blob_bottom_->cpu_data();\n const TypeParam* top_data = this->blob_top_->cpu_data();\n int max_ind;\n TypeParam max_val;\n int num = this->blob_bottom_->num();\n int dim = this->blob_bottom_->count() \/ num;\n for (int i = 0; i < num; ++i) {\n EXPECT_GE(top_data[i], 0);\n EXPECT_LE(top_data[i], dim);\n max_ind = top_data[i];\n max_val = bottom_data[i * dim + max_ind];\n for (int j = 0; j < dim; ++j) {\n EXPECT_LE(bottom_data[i * dim + j], max_val);\n }\n }\n}\n\nTYPED_TEST(ArgMaxLayerTest, TestCPUMaxVal) {\n LayerParameter layer_param;\n Caffe::set_mode(Caffe::CPU);\n ArgMaxParameter* argmax_param = layer_param.mutable_argmax_param();\n argmax_param->set_out_max_val(true);\n ArgMaxLayer layer(layer_param);\n layer.SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_));\n layer.Forward(this->blob_bottom_vec_, &(this->blob_top_vec_));\n \/\/ Now, check values\n const TypeParam* bottom_data = this->blob_bottom_->cpu_data();\n const TypeParam* top_data = this->blob_top_->cpu_data();\n int max_ind;\n TypeParam max_val;\n int num = this->blob_bottom_->num();\n int dim = this->blob_bottom_->count() \/ num;\n for (int i = 0; i < num; ++i) {\n EXPECT_GE(top_data[i], 0);\n EXPECT_LE(top_data[i], dim);\n max_ind = top_data[i * 2];\n max_val = top_data[i * 2 + 1];\n EXPECT_EQ(bottom_data[i * dim + max_ind], max_val);\n for (int j = 0; j < dim; ++j) {\n EXPECT_LE(bottom_data[i * dim + j], max_val);\n }\n }\n}\n\n} \/\/ namespace caffe\n<|endoftext|>"} {"text":"#include \"mbed.h\"\n#include \"test_env.h\"\n\n#if !DEVICE_CAN\n#error [NOT_SUPPORTED] CAN not supported\n#endif\n\n#if defined(TARGET_LPC1549)\n#define CAN_RD D9\n#define CAN_TD D8\n#elif defined(TARGET_LPC1768) || defined(TARGET_LPC4088)\n#define CAN_RD p9\n#define CAN_TD p10\n#elif defined(TARGET_B96B_F446VE)\n#define CAN_RD PD_0\n#define CAN_TD PD_1\n#elif defined(TARGET_VK_RZ_A1H)\n#define CAN_RD P5_9\n#define CAN_TD P5_10\n#elif defined(TARGET_NUCLEO_F042K6) || \\\n defined(TARGET_NUCLEO_F072RB) || \\\n defined(TARGET_NUCLEO_F091RC) || \\\n defined(TARGET_NUCLEO_F302R8) || \\\n defined(TARGET_NUCLEO_F303RE) || \\\n defined(TARGET_NUCLEO_F303K8) || \\\n defined(TARGET_NUCLEO_F334R8) || \\\n defined(TARGET_NUCLEO_F412ZG) || \\\n defined(TARGET_DISCO_F429ZI) || \\\n defined(TARGET_NUCLEO_F446RE) || \\\n defined(TARGET_NUCLEO_F746ZG) || \\\n defined(TARGET_NUCLEO_L432KC) || \\\n defined(TARGET_DISCO_L476VG) || \\\n defined(TARGET_NUCLEO_L476RG)\n#define CAN_RD PA_11\n#define CAN_TD PA_12\n#elif defined(TARGET_NUCLEO_F103RB) || \\\n defined(TARGET_NUCLEO_F207ZG) || \\\n defined(TARGET_DISCO_F303VC) || \\\n defined(TARGET_NUCLEO_F303ZE) || \\\n defined(TARGET_NUCLEO_F412ZG) || \\\n defined(TARGET_NUCLEO_F429ZI) || \\\n defined(TARGET_NUCLEO_F439ZI) || \\\n defined(TARGET_NUCLEO_F446ZE) || \\\n defined(TARGET_DISCO_F469NI) || \\\n defined(TARGET_DISCO_F746NG) || \\\n defined(TARGET_NUCLEO_F756ZG) || \\\n defined(TARGET_NUCLEO_F767ZI) || \\\n defined(TARGET_DISCO_F769NI) || \\\n defined(TARGET_NUCLEO_L486RG)\n#define CAN_RD PB_8\n#define CAN_TD PB_9\n#endif\n\nint result = true;\n\nvoid Check_CAN_Frequency(int CanFrequency)\n{\n printf(\"Init CAN at %d Hz\\n\", CanFrequency);\n\n CAN can_object(CAN_RD, CAN_TD, CanFrequency);\n\n#if !defined(TARGET_VK_RZ_A1H)\n can_object.mode(CAN::Reset);\n#endif\n\n if (!can_object.mode(CAN::LocalTest)) {\n printf(\"CAN MODE_TEST_LOCAL failed\\n\");\n result = false;\n }\n}\n\nint main()\n{\n MBED_HOSTTEST_TIMEOUT(20);\n MBED_HOSTTEST_SELECT(dev_null);\n MBED_HOSTTEST_DESCRIPTION(CAN API at different frequency);\n MBED_HOSTTEST_START(\"MBED_A30\");\n\n const int frequency_table[] = {10000, 50000, 100000, 500000, 1000000};\n for (uint32_t i = 0; i < sizeof(frequency_table)\/sizeof(int); i++) {\n Check_CAN_Frequency(frequency_table[i]);\n }\n\n MBED_HOSTTEST_RESULT(result);\n}\nAdd header to the test main.cpp\/* mbed Microcontroller Library\n * Copyright (c) 2017 ARM Limited\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"mbed.h\"\n#include \"test_env.h\"\n\n#if !DEVICE_CAN\n#error [NOT_SUPPORTED] CAN not supported\n#endif\n\n#if defined(TARGET_LPC1549)\n#define CAN_RD D9\n#define CAN_TD D8\n#elif defined(TARGET_LPC1768) || defined(TARGET_LPC4088)\n#define CAN_RD p9\n#define CAN_TD p10\n#elif defined(TARGET_B96B_F446VE)\n#define CAN_RD PD_0\n#define CAN_TD PD_1\n#elif defined(TARGET_VK_RZ_A1H)\n#define CAN_RD P5_9\n#define CAN_TD P5_10\n#elif defined(TARGET_NUCLEO_F042K6) || \\\n defined(TARGET_NUCLEO_F072RB) || \\\n defined(TARGET_NUCLEO_F091RC) || \\\n defined(TARGET_NUCLEO_F302R8) || \\\n defined(TARGET_NUCLEO_F303RE) || \\\n defined(TARGET_NUCLEO_F303K8) || \\\n defined(TARGET_NUCLEO_F334R8) || \\\n defined(TARGET_NUCLEO_F412ZG) || \\\n defined(TARGET_DISCO_F429ZI) || \\\n defined(TARGET_NUCLEO_F446RE) || \\\n defined(TARGET_NUCLEO_F746ZG) || \\\n defined(TARGET_NUCLEO_L432KC) || \\\n defined(TARGET_DISCO_L476VG) || \\\n defined(TARGET_NUCLEO_L476RG)\n#define CAN_RD PA_11\n#define CAN_TD PA_12\n#elif defined(TARGET_NUCLEO_F103RB) || \\\n defined(TARGET_NUCLEO_F207ZG) || \\\n defined(TARGET_DISCO_F303VC) || \\\n defined(TARGET_NUCLEO_F303ZE) || \\\n defined(TARGET_NUCLEO_F412ZG) || \\\n defined(TARGET_NUCLEO_F429ZI) || \\\n defined(TARGET_NUCLEO_F439ZI) || \\\n defined(TARGET_NUCLEO_F446ZE) || \\\n defined(TARGET_DISCO_F469NI) || \\\n defined(TARGET_DISCO_F746NG) || \\\n defined(TARGET_NUCLEO_F756ZG) || \\\n defined(TARGET_NUCLEO_F767ZI) || \\\n defined(TARGET_DISCO_F769NI) || \\\n defined(TARGET_NUCLEO_L486RG)\n#define CAN_RD PB_8\n#define CAN_TD PB_9\n#endif\n\nint result = true;\n\nvoid Check_CAN_Frequency(int CanFrequency)\n{\n printf(\"Init CAN at %d Hz\\n\", CanFrequency);\n\n CAN can_object(CAN_RD, CAN_TD, CanFrequency);\n\n#if !defined(TARGET_VK_RZ_A1H)\n can_object.mode(CAN::Reset);\n#endif\n\n if (!can_object.mode(CAN::LocalTest)) {\n printf(\"CAN MODE_TEST_LOCAL failed\\n\");\n result = false;\n }\n}\n\nint main()\n{\n MBED_HOSTTEST_TIMEOUT(20);\n MBED_HOSTTEST_SELECT(dev_null);\n MBED_HOSTTEST_DESCRIPTION(CAN API at different frequency);\n MBED_HOSTTEST_START(\"MBED_A30\");\n\n const int frequency_table[] = {10000, 50000, 100000, 500000, 1000000};\n for (uint32_t i = 0; i < sizeof(frequency_table)\/sizeof(int); i++) {\n Check_CAN_Frequency(frequency_table[i]);\n }\n\n MBED_HOSTTEST_RESULT(result);\n}\n<|endoftext|>"} {"text":"#include \"Board.h\"\n\n#include \"Communication.h\"\n\n#include \"chprintf.h\"\n\nbool Communication::handleSerialRequest(const snd_proto_SerialRequest& _req)\n{\n bool ret{true};\n \/\/ Process the action\n switch(_req.which_type)\n {\n case snd_proto_SerialRequest_setMotorsSpeed_tag: setMotorsSpeed(_req); break;\n case snd_proto_SerialRequest_setPidSpeedLeft_tag: setPidSpeedLeft(_req); break;\n case snd_proto_SerialRequest_setPidSpeedRight_tag:\n setPidSpeedRight(_req);\n break;\n case snd_proto_SerialRequest_getStatus_tag: getStatus(_req); break;\n default: chprintf(dbg, \"message type not handled\\n\"); return false;\n }\n return ret;\n}\n\nvoid Communication::getStatus(const snd_proto_SerialRequest& _req)\n{\n (void)_req;\n snd_proto_SerialResponse resp = snd_proto_SerialResponse_init_zero;\n resp.which_type = snd_proto_SerialResponse_status_tag;\n resp.type.status.speed.left = 8.16f;\n resp.type.status.speed.right = 16.32f;\n resp.type.status.starter = gBoard.starter.read();\n resp.type.status.estop = gBoard.starter.read();\n resp.type.status.colorSwitch = gBoard.colorSwitch.read()\n ? snd_proto_eTeamColor_BLUE\n : snd_proto_eTeamColor_YELLOW;\n resp.type.status.ir.left = false;\n resp.type.status.ir.center = true;\n resp.type.status.ir.right = true;\n int32_t left, right;\n gBoard.qei.getValues(&left, &right);\n resp.type.status.encoders.left = left;\n resp.type.status.encoders.right = right;\n gBoard.serial.encodeAndSendMsg(resp);\n}\n\nvoid Communication::setMotorsSpeed(const snd_proto_SerialRequest& _req)\n{\n chprintf(dbg, \"SetMotorsSpeed request received \");\n chprintf(dbg,\n \"left: %f right: %f\\n\",\n _req.type.setMotorsSpeed.left,\n _req.type.setMotorsSpeed.right);\n const int16_t leftPercent = static_cast(\n _req.type.setMotorsSpeed.left * 0.75f * gBoard.leftMotor.kPwmPeriod \/ 1.47f);\n const int16_t rightPercent = static_cast(\n _req.type.setMotorsSpeed.right * 0.75f * gBoard.rightMotor.kPwmPeriod \/ 1.47f);\n gBoard.motors.pwm(leftPercent, rightPercent);\n}\n\nvoid Communication::setPidSpeedLeft(const snd_proto_SerialRequest& _req)\n{\n chprintf(dbg,\n \"SetPidSpeedLeft request received: P: %.4f I: %.4f D: %.4f\\n\",\n _req.type.setPidSpeedLeft.p,\n _req.type.setPidSpeedLeft.i,\n _req.type.setPidSpeedLeft.d);\n}\n\nvoid Communication::setPidSpeedRight(const snd_proto_SerialRequest& _req)\n{\n chprintf(dbg,\n \"SetPidSpeedRight request received: P: %.4f I: %.4f D: %.4f\\n\",\n _req.type.setPidSpeedRight.p,\n _req.type.setPidSpeedRight.i,\n _req.type.setPidSpeedRight.d);\n}\nFixed the speed debug print and comment the PWM part.#include \"Board.h\"\n\n#include \"Communication.h\"\n\n#include \"chprintf.h\"\n\nbool Communication::handleSerialRequest(const snd_proto_SerialRequest& _req)\n{\n bool ret{true};\n \/\/ Process the action\n switch(_req.which_type)\n {\n case snd_proto_SerialRequest_setMotorsSpeed_tag: setMotorsSpeed(_req); break;\n case snd_proto_SerialRequest_setPidSpeedLeft_tag: setPidSpeedLeft(_req); break;\n case snd_proto_SerialRequest_setPidSpeedRight_tag:\n setPidSpeedRight(_req);\n break;\n case snd_proto_SerialRequest_getStatus_tag: getStatus(_req); break;\n default: chprintf(dbg, \"message type not handled\\n\"); return false;\n }\n return ret;\n}\n\nvoid Communication::getStatus(const snd_proto_SerialRequest& _req)\n{\n (void)_req;\n snd_proto_SerialResponse resp = snd_proto_SerialResponse_init_zero;\n resp.which_type = snd_proto_SerialResponse_status_tag;\n resp.type.status.speed.left = 8.16f;\n resp.type.status.speed.right = 16.32f;\n resp.type.status.starter = gBoard.starter.read();\n resp.type.status.estop = gBoard.starter.read();\n resp.type.status.colorSwitch = gBoard.colorSwitch.read()\n ? snd_proto_eTeamColor_BLUE\n : snd_proto_eTeamColor_YELLOW;\n resp.type.status.ir.left = false;\n resp.type.status.ir.center = true;\n resp.type.status.ir.right = true;\n int32_t left, right;\n gBoard.qei.getValues(&left, &right);\n resp.type.status.encoders.left = left;\n resp.type.status.encoders.right = right;\n gBoard.serial.encodeAndSendMsg(resp);\n}\n\nvoid Communication::setMotorsSpeed(const snd_proto_SerialRequest& _req)\n{\n chprintf(dbg, \"SetMotorsSpeed request received \");\n chprintf(dbg,\n \"left: %d right: %d\\n\",\n _req.type.setMotorsSpeed.left,\n _req.type.setMotorsSpeed.right);\n \/*\n const int16_t leftPercent = static_cast(\n _req.type.setMotorsSpeed.left * 0.75f * gBoard.leftMotor.kPwmPeriod \/ 1.47f);\n const int16_t rightPercent = static_cast(\n _req.type.setMotorsSpeed.right * 0.75f * gBoard.rightMotor.kPwmPeriod \/ 1.47f);\n gBoard.motors.pwm(leftPercent, rightPercent);\n *\/\n}\n\nvoid Communication::setPidSpeedLeft(const snd_proto_SerialRequest& _req)\n{\n chprintf(dbg,\n \"SetPidSpeedLeft request received: P: %.4f I: %.4f D: %.4f\\n\",\n _req.type.setPidSpeedLeft.p,\n _req.type.setPidSpeedLeft.i,\n _req.type.setPidSpeedLeft.d);\n}\n\nvoid Communication::setPidSpeedRight(const snd_proto_SerialRequest& _req)\n{\n chprintf(dbg,\n \"SetPidSpeedRight request received: P: %.4f I: %.4f D: %.4f\\n\",\n _req.type.setPidSpeedRight.p,\n _req.type.setPidSpeedRight.i,\n _req.type.setPidSpeedRight.d);\n}\n<|endoftext|>"} {"text":"\/\/* This file is part of the MOOSE framework\n\/\/* https:\/\/www.mooseframework.org\n\/\/*\n\/\/* All rights reserved, see COPYRIGHT for full restrictions\n\/\/* https:\/\/github.com\/idaholab\/moose\/blob\/master\/COPYRIGHT\n\/\/*\n\/\/* Licensed under LGPL 2.1, please see LICENSE for details\n\/\/* https:\/\/www.gnu.org\/licenses\/lgpl-2.1.html\n\n#include \"FVAnisotropicDiffusion.h\"\n#include \"RelationshipManager.h\"\n\nregisterMooseObject(\"MooseApp\", FVAnisotropicDiffusion);\n\nInputParameters\nFVAnisotropicDiffusion::validParams()\n{\n InputParameters params = FVFluxKernel::validParams();\n params.addClassDescription(\n \"Computes residual for anisotropic diffusion operator for finite volume method.\");\n params.addRequiredParam(\"coeff\", \"diffusion coefficient\");\n params.set(\"ghost_layers\") = 2;\n return params;\n}\n\nFVAnisotropicDiffusion::FVAnisotropicDiffusion(const InputParameters & params)\n : FVFluxKernel(params), _coeff(getFunctor(\"coeff\"))\n{\n#ifndef MOOSE_GLOBAL_AD_INDEXING\n mooseError(\"FVAnisotropicDiffusion is not supported by local AD indexing. In order to use this \"\n \"object, please run \"\n \"the configure script in the root MOOSE directory with the configure option \"\n \"'--with-ad-indexing-type=global'. Note that global indexing is now the default \"\n \"configuration for AD indexing type.\");\n#endif\n\n if ((_var.faceInterpolationMethod() == Moose::FV::InterpMethod::SkewCorrectedAverage) &&\n (_tid == 0))\n {\n auto & factory = _app.getFactory();\n\n auto rm_params = factory.getValidParams(\"ElementSideNeighborLayers\");\n\n rm_params.set(\"for_whom\") = name();\n rm_params.set(\"mesh\") = &const_cast(_mesh);\n rm_params.set(\"rm_type\") =\n Moose::RelationshipManagerType::GEOMETRIC | Moose::RelationshipManagerType::ALGEBRAIC |\n Moose::RelationshipManagerType::COUPLING;\n FVKernel::setRMParams(\n _pars, rm_params, std::max((unsigned short)(3), _pars.get(\"ghost_layers\")));\n mooseAssert(rm_params.areAllRequiredParamsValid(),\n \"All relationship manager parameters should be valid.\");\n\n auto rm_obj = factory.create(\n \"ElementSideNeighborLayers\", name() + \"_skew_correction\", rm_params);\n\n \/\/ Delete the resources created on behalf of the RM if it ends up not being added to the\n \/\/ App.\n if (!_app.addRelationshipManager(rm_obj))\n factory.releaseSharedObjects(*rm_obj);\n }\n}\n\nADReal\nFVAnisotropicDiffusion::computeQpResidual()\n{\n ADReal r = 0;\n const auto face_elem = elemFromFace();\n const auto face_neighbor = neighborFromFace();\n const auto & grad_T = _var.adGradSln(*_face_info, _var.faceInterpolationMethod() == Moose::FV::InterpMethod::SkewCorrectedAverage);\n for (std::size_t i = 0; i < LIBMESH_DIM; i++)\n {\n ADReal k_face_inv;\n Moose::FV::interpolate(Moose::FV::InterpMethod::Average,\n k_face_inv,\n 1.0 \/ _coeff(face_elem)(i),\n 1.0 \/ _coeff(face_neighbor)(i),\n *_face_info,\n true);\n r += _normal(i) * grad_T(i) \/ k_face_inv;\n }\n return -r;\n}\nUpdate framework\/src\/fvkernels\/FVAnisotropicDiffusion.C\/\/* This file is part of the MOOSE framework\n\/\/* https:\/\/www.mooseframework.org\n\/\/*\n\/\/* All rights reserved, see COPYRIGHT for full restrictions\n\/\/* https:\/\/github.com\/idaholab\/moose\/blob\/master\/COPYRIGHT\n\/\/*\n\/\/* Licensed under LGPL 2.1, please see LICENSE for details\n\/\/* https:\/\/www.gnu.org\/licenses\/lgpl-2.1.html\n\n#include \"FVAnisotropicDiffusion.h\"\n#include \"RelationshipManager.h\"\n\nregisterMooseObject(\"MooseApp\", FVAnisotropicDiffusion);\n\nInputParameters\nFVAnisotropicDiffusion::validParams()\n{\n InputParameters params = FVFluxKernel::validParams();\n params.addClassDescription(\n \"Computes residual for anisotropic diffusion operator for finite volume method.\");\n params.addRequiredParam(\"coeff\", \"diffusion coefficient\");\n params.set(\"ghost_layers\") = 2;\n return params;\n}\n\nFVAnisotropicDiffusion::FVAnisotropicDiffusion(const InputParameters & params)\n : FVFluxKernel(params), _coeff(getFunctor(\"coeff\"))\n{\n#ifndef MOOSE_GLOBAL_AD_INDEXING\n mooseError(\"FVAnisotropicDiffusion is not supported by local AD indexing. In order to use this \"\n \"object, please run \"\n \"the configure script in the root MOOSE directory with the configure option \"\n \"'--with-ad-indexing-type=global'. Note that global indexing is now the default \"\n \"configuration for AD indexing type.\");\n#endif\n\n if ((_var.faceInterpolationMethod() == Moose::FV::InterpMethod::SkewCorrectedAverage) &&\n (_tid == 0))\n {\n auto & factory = _app.getFactory();\n\n auto rm_params = factory.getValidParams(\"ElementSideNeighborLayers\");\n\n rm_params.set(\"for_whom\") = name();\n rm_params.set(\"mesh\") = &const_cast(_mesh);\n rm_params.set(\"rm_type\") =\n Moose::RelationshipManagerType::GEOMETRIC | Moose::RelationshipManagerType::ALGEBRAIC |\n Moose::RelationshipManagerType::COUPLING;\n FVKernel::setRMParams(\n _pars, rm_params, std::max((unsigned short)(3), _pars.get(\"ghost_layers\")));\n mooseAssert(rm_params.areAllRequiredParamsValid(),\n \"All relationship manager parameters should be valid.\");\n\n auto rm_obj = factory.create(\n \"ElementSideNeighborLayers\", name() + \"_skew_correction\", rm_params);\n\n \/\/ Delete the resources created on behalf of the RM if it ends up not being added to the\n \/\/ App.\n if (!_app.addRelationshipManager(rm_obj))\n factory.releaseSharedObjects(*rm_obj);\n }\n}\n\nADReal\nFVAnisotropicDiffusion::computeQpResidual()\n{\n ADReal r = 0;\n const auto face_elem = elemFromFace();\n const auto face_neighbor = neighborFromFace();\n const auto & grad_T = _var.adGradSln(*_face_info, _var.faceInterpolationMethod() == Moose::FV::InterpMethod::SkewCorrectedAverage);\n for (const auto i : make_range(Moose::dim))\n {\n ADReal k_face_inv;\n Moose::FV::interpolate(Moose::FV::InterpMethod::Average,\n k_face_inv,\n 1.0 \/ _coeff(face_elem)(i),\n 1.0 \/ _coeff(face_neighbor)(i),\n *_face_info,\n true);\n r += _normal(i) * grad_T(i) \/ k_face_inv;\n }\n return -r;\n}\n<|endoftext|>"} {"text":"\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/usr\/isteps\/istep08\/call_proc_check_slave_sbe_seeprom_complete.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2017 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/**\n * @file call_proc_check_slave_sbe_seeprom_complete.C\n *\n * Support file for IStep: slave_sbe\n * Slave SBE\n *\n * HWP_IGNORE_VERSION_CHECK\n *\/\n\n\/******************************************************************************\/\n\/\/ Includes\n\/******************************************************************************\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ targeting support\n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \"sbe_extract_rc_handler.H\"\n\nusing namespace ISTEP;\nusing namespace ISTEP_ERROR;\nusing namespace ERRORLOG;\nusing namespace TARGETING;\nusing namespace fapi2;\n\nconst uint64_t MS_TO_WAIT_FIRST = 2500; \/\/(2.5 s)\nconst uint64_t MS_TO_WAIT_OTHERS= 100; \/\/(100 ms)\nnamespace ISTEP_08\n{\n\n\/\/******************************************************************************\n\/\/ call_proc_check_slave_sbe_seeprom_complete function\n\/\/******************************************************************************\nvoid* call_proc_check_slave_sbe_seeprom_complete( void *io_pArgs )\n{\n errlHndl_t l_errl = NULL;\n IStepError l_stepError;\n\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,\n \"call_proc_check_slave_sbe_seeprom_complete entry\" );\n\n \/\/\n \/\/ get the master Proc target, we want to IGNORE this one.\n \/\/\n TARGETING::Target* l_pMasterProcTarget = NULL;\n TARGETING::targetService().masterProcChipTargetHandle(l_pMasterProcTarget);\n\n \/\/\n \/\/ get a list of all the procs in the system\n \/\/\n TARGETING::TargetHandleList l_cpuTargetList;\n getAllChips(l_cpuTargetList, TYPE_PROC);\n\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,\n \"proc_check_slave_sbe_seeprom_complete: %d procs in the system.\",\n l_cpuTargetList.size() );\n\n \/\/ loop thru all the cpu's\n for (const auto & l_cpu_target: l_cpuTargetList)\n {\n if ( l_cpu_target == l_pMasterProcTarget )\n {\n \/\/ we are just checking the Slave SBE's, skip the master\n continue;\n }\n\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n \"Processor target HUID %.8X\",\n TARGETING::get_huid(l_cpu_target));\n\n const fapi2::Target l_fapi2ProcTarget(\n const_cast (l_cpu_target));\n\n sbeMsgReg_t l_sbeReg;\n\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,\n \"Running p9_get_sbe_msg_register HWP\"\n \" on processor target %.8X\",\n TARGETING::get_huid(l_cpu_target));\n\n SBE_REG_RETURN l_ret = SBE_REG_RETURN::SBE_FAILED_TO_BOOT;\n\n l_errl = sbe_timeout_handler(&l_sbeReg,l_cpu_target,&l_ret);\n\n if((!l_errl) && (l_sbeReg.currState != SBE_STATE_RUNTIME))\n {\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,\n \"SBE 0x%.8X never started, l_sbeReg=0x%.8X\",\n TARGETING::get_huid(l_cpu_target),l_sbeReg.reg );\n \/*@\n * @errortype\n * @reasoncode RC_SBE_SLAVE_TIMEOUT\n * @severity ERRORLOG::ERRL_SEV_INFORMATIONAL\n * @moduleid MOD_CHECK_SLAVE_SBE_SEEPROM_COMPLETE\n * @userdata1 HUID of proc which had SBE timeout\n * @userdata2 SBE MSG Register\n *\n * @devdesc Slave SBE did not get to ready state within\n * allotted time\n *\n * @custdesc A processor in the system has failed to initialize\n *\/\n l_errl = new ErrlEntry(\n ERRL_SEV_INFORMATIONAL,\n MOD_CHECK_SLAVE_SBE_SEEPROM_COMPLETE,\n RC_SBE_SLAVE_TIMEOUT,\n TARGETING::get_huid(l_cpu_target),\n l_sbeReg.reg);\n\n l_errl->collectTrace( \"ISTEPS_TRACE\", 256);\n\n \/\/ Commit error and continue, this is not terminating since\n \/\/ we can still at least boot with master proc\n errlCommit(l_errl,ISTEP_COMP_ID);\n\n \/\/@fixme - RTC:177921\n \/\/ Do not call p9_extract_sbe_rc because it corrupts\n \/\/ live debug of fails. Need to make some other\n \/\/ changes before turning this back on.\n#if 1 \/\/ get rid of this\n \/\/ Create IStep error log and cross reference to error\n l_stepError.addErrorDetails( l_errl );\n \n \/\/ Commit error log\n errlCommit( l_errl, HWPF_COMP_ID );\n#else\n\n \/\/ Setup for the HWP\n P9_EXTRACT_SBE_RC::RETURN_ACTION l_rcAction =\n P9_EXTRACT_SBE_RC::REIPL_UPD_SEEPROM;\n FAPI_INVOKE_HWP(l_errl, p9_extract_sbe_rc,\n l_fapi2ProcTarget, l_rcAction);\n\n if(l_errl)\n {\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n \"ERROR : proc_check_slave_sbe_seeprom_complete \"\n \"failed, p9_extract_sbe_rc HWP returning errorlog \"\n \"PLID=0x%x\",l_errl->plid());\n\n \/\/ capture the target data in the elog\n ErrlUserDetailsTarget(l_cpu_target).addToLog( l_errl );\n\n \/\/ Create IStep error log and cross reference to error\n l_stepError.addErrorDetails( l_errl );\n\n \/\/ Commit error log\n errlCommit( l_errl, HWPF_COMP_ID );\n\n }\n else if(l_rcAction != P9_EXTRACT_SBE_RC::ERROR_RECOVERED)\n {\n\n if(INITSERVICE::spBaseServicesEnabled())\n {\n \/\/ When we are on an FSP machine, we want to fail out of\n \/\/ hostboot and give control back to the FSP. They have\n \/\/ better diagnostics for this type of error.\n INITSERVICE::doShutdownWithError(RC_HWSV_COLLECT_SBE_RC,\n TARGETING::get_huid(l_cpu_target));\n }\n\n \/\/ Pull out previous rc error for threshold\n uint8_t l_prevError = 0;\n\n \/\/ Save the current rc error\n (l_cpu_target)->setAttr<\n TARGETING::ATTR_PREVIOUS_SBE_ERROR>(l_rcAction);\n#ifdef CONFIG_BMC_IPMI\n \/\/ This could potentially take awhile, reset watchdog\n l_errl = IPMIWATCHDOG::resetWatchDogTimer();\n if(l_errl)\n {\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n \"call_proc_check_slave_sbe_seeprom_complete \"\n \"Resetting watchdog before sbe_handler\");\n l_errl->collectTrace(\"ISTEPS_TRACE\",256);\n errlCommit(l_errl,ISTEP_COMP_ID);\n }\n#endif\n proc_extract_sbe_handler( l_cpu_target,\n l_prevError, l_rcAction);\n }\n#endif \/\/@fixme - RTC:177921\n\n }\n else if (l_errl)\n {\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n \"ERROR : call p9_check_slave_sbe_seeprom_complete, \"\n \"PLID=0x%x\", l_errl->plid() );\n\n \/\/ capture the target data in the elog\n ErrlUserDetailsTarget(l_cpu_target).addToLog( l_errl );\n\n \/\/ Create IStep error log and cross reference to error that occurred\n l_stepError.addErrorDetails( l_errl );\n\n \/\/ Commit error log\n errlCommit( l_errl, HWPF_COMP_ID );\n }\n \/\/ No error and still functional\n else if(l_cpu_target->getAttr().functional)\n {\n \/\/ Set attribute indicating that SBE is started\n l_cpu_target->setAttr(1);\n\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n \"SUCCESS : proc_check_slave_sbe_seeprom_complete\"\n \" completed ok for proc 0x%.8X\",\n TARGETING::get_huid(l_cpu_target));\n }\n\n\/* @TODO-RTC:100963 This should only be called when the SBE has completely\n crashed. There is a path in OpenPower where HB may get an\n attention and need to call it. For now, though, just associate\n with this story for tracking.\n\n \/\/ Not a way to pass in -soft_err, assuming that is default behavior\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,\n \"Running p9_extract_sbe_rc HWP\"\n \" on processor target %.8X\",\n TARGETING::get_huid(l_cpu_target) );\n\n \/\/@TODO-RTC:100963-Do something with the RETURN_ACTION\n P9_EXTRACT_SBE_RC::RETURN_ACTION l_rcAction\n = P9_EXTRACT_SBE_RC::RE_IPL;\n FAPI_INVOKE_HWP(l_errl, p9_extract_sbe_rc,\n l_fapi2ProcTarget,\n l_rcAction);\n if (l_errl)\n {\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n \"ERROR : proc_check_slave_sbe_seeprom_complete \"\n \"failed, p9_extract_sbe_rc HWP returning errorlog PLID=0x%x\",\n l_errl->plid());\n\n \/\/ capture the target data in the elog\n ErrlUserDetailsTarget(l_cpu_target).addToLog( l_errl );\n\n \/\/ Create IStep error log and cross reference to error that occurred\n l_stepError.addErrorDetails( l_errl );\n\n \/\/ Commit error log\n errlCommit( l_errl, HWPF_COMP_ID );\n }\n**\/\n } \/\/ end of going through all processors\n\n\n \/\/ Once the sbe's are up correctly, fetch all the proc ECIDs and\n \/\/ store them in an attribute.\n for (const auto & l_cpu_target: l_cpuTargetList)\n {\n const fapi2::Target l_fapi2ProcTarget(\n const_cast (l_cpu_target));\n\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,\n \"Running p9_getecid HWP\"\n \" on processor target %.8X\",\n TARGETING::get_huid(l_cpu_target) );\n\n \/\/ p9_getecid should set the fuse string to 112 bytes long.\n fapi2::variable_buffer l_fuseString(112);\n\n \/\/ Invoke the HWP\n FAPI_INVOKE_HWP(l_errl,\n p9_getecid,\n l_fapi2ProcTarget,\n l_fuseString );\n\n if (l_errl)\n {\n if (l_cpu_target->getAttr().functional)\n {\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n \"ERROR : p9_getecid\",\n \" failed, returning errorlog\" );\n\n \/\/ capture the target data in the elog\n ErrlUserDetailsTarget(l_cpu_target).addToLog( l_errl );\n\n \/\/ Create IStep error log and cross reference error that\n \/\/ occurred\n l_stepError.addErrorDetails( l_errl );\n\n \/\/ Commit error log\n errlCommit( l_errl, HWPF_COMP_ID );\n }\n else \/\/ Not functional, proc deconfigured, don't report error\n {\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n \"ERROR : p9_getecid\"\n \" failed, proc target deconfigured\" );\n delete l_errl;\n l_errl = NULL;\n }\n }\n else\n {\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n \"SUCCESS : proc_getecid\"\n \" completed ok\");\n\n \/\/ Update HDAT_EC to account for anything lower than the minor EC\n auto l_miniEC = l_cpu_target->getAttr();\n if( l_miniEC != 0 )\n {\n auto l_hdatEC = l_cpu_target->getAttr();\n auto l_EC = l_cpu_target->getAttr();\n auto l_newHdatEC = l_EC + l_miniEC;\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,\n \"MINI_EC=%d, HDAT_EC changing from %d->%d\",\n l_miniEC, l_hdatEC, l_newHdatEC );\n l_cpu_target->setAttr(l_newHdatEC);\n }\n }\n\n } \/\/ end of going through all processors\n\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n \"call_proc_check_slave_sbe_seeprom_complete exit\");\n\n \/\/ end task, returning any errorlogs to IStepDisp\n return l_stepError.getErrorHandle();\n}\n\n};\nFix double-commit in failed SBE path\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/usr\/isteps\/istep08\/call_proc_check_slave_sbe_seeprom_complete.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2017 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/**\n * @file call_proc_check_slave_sbe_seeprom_complete.C\n *\n * Support file for IStep: slave_sbe\n * Slave SBE\n *\n * HWP_IGNORE_VERSION_CHECK\n *\/\n\n\/******************************************************************************\/\n\/\/ Includes\n\/******************************************************************************\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ targeting support\n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \"sbe_extract_rc_handler.H\"\n\nusing namespace ISTEP;\nusing namespace ISTEP_ERROR;\nusing namespace ERRORLOG;\nusing namespace TARGETING;\nusing namespace fapi2;\n\nconst uint64_t MS_TO_WAIT_FIRST = 2500; \/\/(2.5 s)\nconst uint64_t MS_TO_WAIT_OTHERS= 100; \/\/(100 ms)\nnamespace ISTEP_08\n{\n\n\/\/******************************************************************************\n\/\/ call_proc_check_slave_sbe_seeprom_complete function\n\/\/******************************************************************************\nvoid* call_proc_check_slave_sbe_seeprom_complete( void *io_pArgs )\n{\n errlHndl_t l_errl = NULL;\n IStepError l_stepError;\n\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,\n \"call_proc_check_slave_sbe_seeprom_complete entry\" );\n\n \/\/\n \/\/ get the master Proc target, we want to IGNORE this one.\n \/\/\n TARGETING::Target* l_pMasterProcTarget = NULL;\n TARGETING::targetService().masterProcChipTargetHandle(l_pMasterProcTarget);\n\n \/\/\n \/\/ get a list of all the procs in the system\n \/\/\n TARGETING::TargetHandleList l_cpuTargetList;\n getAllChips(l_cpuTargetList, TYPE_PROC);\n\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,\n \"proc_check_slave_sbe_seeprom_complete: %d procs in the system.\",\n l_cpuTargetList.size() );\n\n \/\/ loop thru all the cpu's\n for (const auto & l_cpu_target: l_cpuTargetList)\n {\n if ( l_cpu_target == l_pMasterProcTarget )\n {\n \/\/ we are just checking the Slave SBE's, skip the master\n continue;\n }\n\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n \"Processor target HUID %.8X\",\n TARGETING::get_huid(l_cpu_target));\n\n const fapi2::Target l_fapi2ProcTarget(\n const_cast (l_cpu_target));\n\n sbeMsgReg_t l_sbeReg;\n\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,\n \"Running p9_get_sbe_msg_register HWP\"\n \" on processor target %.8X\",\n TARGETING::get_huid(l_cpu_target));\n\n SBE_REG_RETURN l_ret = SBE_REG_RETURN::SBE_FAILED_TO_BOOT;\n\n l_errl = sbe_timeout_handler(&l_sbeReg,l_cpu_target,&l_ret);\n\n if((!l_errl) && (l_sbeReg.currState != SBE_STATE_RUNTIME))\n {\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,\n \"SBE 0x%.8X never started, l_sbeReg=0x%.8X\",\n TARGETING::get_huid(l_cpu_target),l_sbeReg.reg );\n \/*@\n * @errortype\n * @reasoncode RC_SBE_SLAVE_TIMEOUT\n * @severity ERRORLOG::ERRL_SEV_INFORMATIONAL\n * @moduleid MOD_CHECK_SLAVE_SBE_SEEPROM_COMPLETE\n * @userdata1 HUID of proc which had SBE timeout\n * @userdata2 SBE MSG Register\n *\n * @devdesc Slave SBE did not get to ready state within\n * allotted time\n *\n * @custdesc A processor in the system has failed to initialize\n *\/\n l_errl = new ErrlEntry(\n ERRL_SEV_INFORMATIONAL,\n MOD_CHECK_SLAVE_SBE_SEEPROM_COMPLETE,\n RC_SBE_SLAVE_TIMEOUT,\n TARGETING::get_huid(l_cpu_target),\n l_sbeReg.reg);\n\n l_errl->collectTrace( \"ISTEPS_TRACE\", 256);\n\n \/\/@fixme - RTC:177921\n \/\/ Do not call p9_extract_sbe_rc because it corrupts\n \/\/ live debug of fails. Need to make some other\n \/\/ changes before turning this back on.\n#if 1 \/\/ get rid of this\n \/\/ Create IStep error log and cross reference to error\n l_stepError.addErrorDetails( l_errl );\n \n \/\/ Commit error log\n errlCommit( l_errl, HWPF_COMP_ID );\n#else\n\n \/\/ Commit error and continue, this is not terminating since\n \/\/ we can still at least boot with master proc\n errlCommit(l_errl,ISTEP_COMP_ID);\n\n \/\/ Setup for the HWP\n P9_EXTRACT_SBE_RC::RETURN_ACTION l_rcAction =\n P9_EXTRACT_SBE_RC::REIPL_UPD_SEEPROM;\n FAPI_INVOKE_HWP(l_errl, p9_extract_sbe_rc,\n l_fapi2ProcTarget, l_rcAction);\n\n if(l_errl)\n {\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n \"ERROR : proc_check_slave_sbe_seeprom_complete \"\n \"failed, p9_extract_sbe_rc HWP returning errorlog \"\n \"PLID=0x%x\",l_errl->plid());\n\n \/\/ capture the target data in the elog\n ErrlUserDetailsTarget(l_cpu_target).addToLog( l_errl );\n\n \/\/ Create IStep error log and cross reference to error\n l_stepError.addErrorDetails( l_errl );\n\n \/\/ Commit error log\n errlCommit( l_errl, HWPF_COMP_ID );\n\n }\n else if(l_rcAction != P9_EXTRACT_SBE_RC::ERROR_RECOVERED)\n {\n\n if(INITSERVICE::spBaseServicesEnabled())\n {\n \/\/ When we are on an FSP machine, we want to fail out of\n \/\/ hostboot and give control back to the FSP. They have\n \/\/ better diagnostics for this type of error.\n INITSERVICE::doShutdownWithError(RC_HWSV_COLLECT_SBE_RC,\n TARGETING::get_huid(l_cpu_target));\n }\n\n \/\/ Pull out previous rc error for threshold\n uint8_t l_prevError = 0;\n\n \/\/ Save the current rc error\n (l_cpu_target)->setAttr<\n TARGETING::ATTR_PREVIOUS_SBE_ERROR>(l_rcAction);\n#ifdef CONFIG_BMC_IPMI\n \/\/ This could potentially take awhile, reset watchdog\n l_errl = IPMIWATCHDOG::resetWatchDogTimer();\n if(l_errl)\n {\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n \"call_proc_check_slave_sbe_seeprom_complete \"\n \"Resetting watchdog before sbe_handler\");\n l_errl->collectTrace(\"ISTEPS_TRACE\",256);\n errlCommit(l_errl,ISTEP_COMP_ID);\n }\n#endif\n proc_extract_sbe_handler( l_cpu_target,\n l_prevError, l_rcAction);\n }\n#endif \/\/@fixme - RTC:177921\n\n }\n else if (l_errl)\n {\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n \"ERROR : call p9_check_slave_sbe_seeprom_complete, \"\n \"PLID=0x%x\", l_errl->plid() );\n\n \/\/ capture the target data in the elog\n ErrlUserDetailsTarget(l_cpu_target).addToLog( l_errl );\n\n \/\/ Create IStep error log and cross reference to error that occurred\n l_stepError.addErrorDetails( l_errl );\n\n \/\/ Commit error log\n errlCommit( l_errl, HWPF_COMP_ID );\n }\n \/\/ No error and still functional\n else if(l_cpu_target->getAttr().functional)\n {\n \/\/ Set attribute indicating that SBE is started\n l_cpu_target->setAttr(1);\n\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n \"SUCCESS : proc_check_slave_sbe_seeprom_complete\"\n \" completed ok for proc 0x%.8X\",\n TARGETING::get_huid(l_cpu_target));\n }\n\n\/* @TODO-RTC:100963 This should only be called when the SBE has completely\n crashed. There is a path in OpenPower where HB may get an\n attention and need to call it. For now, though, just associate\n with this story for tracking.\n\n \/\/ Not a way to pass in -soft_err, assuming that is default behavior\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,\n \"Running p9_extract_sbe_rc HWP\"\n \" on processor target %.8X\",\n TARGETING::get_huid(l_cpu_target) );\n\n \/\/@TODO-RTC:100963-Do something with the RETURN_ACTION\n P9_EXTRACT_SBE_RC::RETURN_ACTION l_rcAction\n = P9_EXTRACT_SBE_RC::RE_IPL;\n FAPI_INVOKE_HWP(l_errl, p9_extract_sbe_rc,\n l_fapi2ProcTarget,\n l_rcAction);\n if (l_errl)\n {\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n \"ERROR : proc_check_slave_sbe_seeprom_complete \"\n \"failed, p9_extract_sbe_rc HWP returning errorlog PLID=0x%x\",\n l_errl->plid());\n\n \/\/ capture the target data in the elog\n ErrlUserDetailsTarget(l_cpu_target).addToLog( l_errl );\n\n \/\/ Create IStep error log and cross reference to error that occurred\n l_stepError.addErrorDetails( l_errl );\n\n \/\/ Commit error log\n errlCommit( l_errl, HWPF_COMP_ID );\n }\n**\/\n } \/\/ end of going through all processors\n\n\n \/\/ Once the sbe's are up correctly, fetch all the proc ECIDs and\n \/\/ store them in an attribute.\n for (const auto & l_cpu_target: l_cpuTargetList)\n {\n const fapi2::Target l_fapi2ProcTarget(\n const_cast (l_cpu_target));\n\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,\n \"Running p9_getecid HWP\"\n \" on processor target %.8X\",\n TARGETING::get_huid(l_cpu_target) );\n\n \/\/ p9_getecid should set the fuse string to 112 bytes long.\n fapi2::variable_buffer l_fuseString(112);\n\n \/\/ Invoke the HWP\n FAPI_INVOKE_HWP(l_errl,\n p9_getecid,\n l_fapi2ProcTarget,\n l_fuseString );\n\n if (l_errl)\n {\n if (l_cpu_target->getAttr().functional)\n {\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n \"ERROR : p9_getecid\",\n \" failed, returning errorlog\" );\n\n \/\/ capture the target data in the elog\n ErrlUserDetailsTarget(l_cpu_target).addToLog( l_errl );\n\n \/\/ Create IStep error log and cross reference error that\n \/\/ occurred\n l_stepError.addErrorDetails( l_errl );\n\n \/\/ Commit error log\n errlCommit( l_errl, HWPF_COMP_ID );\n }\n else \/\/ Not functional, proc deconfigured, don't report error\n {\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n \"ERROR : p9_getecid\"\n \" failed, proc target deconfigured\" );\n delete l_errl;\n l_errl = NULL;\n }\n }\n else\n {\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n \"SUCCESS : proc_getecid\"\n \" completed ok\");\n\n \/\/ Update HDAT_EC to account for anything lower than the minor EC\n auto l_miniEC = l_cpu_target->getAttr();\n if( l_miniEC != 0 )\n {\n auto l_hdatEC = l_cpu_target->getAttr();\n auto l_EC = l_cpu_target->getAttr();\n auto l_newHdatEC = l_EC + l_miniEC;\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,\n \"MINI_EC=%d, HDAT_EC changing from %d->%d\",\n l_miniEC, l_hdatEC, l_newHdatEC );\n l_cpu_target->setAttr(l_newHdatEC);\n }\n }\n\n } \/\/ end of going through all processors\n\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n \"call_proc_check_slave_sbe_seeprom_complete exit\");\n\n \/\/ end task, returning any errorlogs to IStepDisp\n return l_stepError.getErrorHandle();\n}\n\n};\n<|endoftext|>"} {"text":"#define PUT(x) std::cout << #x \"=\" << (x) << std::endl;\n#include \n#include \n#include \n#include \n#include \n\nstruct FpTag;\ntypedef mcl::FpT Fp;\n\nvoid put(const char *msg, const void *buf, size_t bufSize)\n{\n\tprintf(\"%s:\", msg);\n\tconst unsigned char* p = (const unsigned char*)buf;\n\tfor (size_t i = 0; i < bufSize; i++) {\n\t\tprintf(\"%02x\", p[i]);\n\t}\n\tprintf(\"\\n\");\n}\n\ntemplate\ninline size_t getBinary2(uint8_t *bin, size_t maxBinN, const T *x, size_t xN, size_t w)\n{\n\tif (w == 0 || w >= 8) return 0;\n\tsize_t binN = 0;\n\tsize_t zeroNum = 0;\n\n\tmcl::fp::BitIterator iter(x, xN);\n\twhile (iter.hasNext()) {\n\t\tdo {\n\t\t\tif (iter.peekBit()) break;\n\t\t\tzeroNum++;\n\t\t\titer.skipBit();\n\t\t} while (iter.hasNext());\n\t\tfor (size_t i = 0; i < zeroNum; i++) {\n\t\t\tif (binN == maxBinN) return 0;\n\t\t\tbin[binN++] = 0;\n\t\t}\n\t\tuint32_t v = iter.getNext(w);\n\t\tif (binN == maxBinN) return 0;\n\t\tbin[binN++] = v;\n\t\tzeroNum = w - 1;\n\t}\n\twhile (binN > 0 && bin[binN - 1] == 0) {\n\t\tbinN--;\n\t}\n\treturn binN;\n}\n\ninline size_t getBinary(uint8_t *bin, size_t maxBinN, mpz_class x, size_t w)\n{\n\treturn getBinary2(bin, maxBinN, mcl::gmp::getUnit(x), mcl::gmp::getUnitSize(x), w);\n}\n\ntemplate\nvoid pow3(F& z, const F& x, const T *y, size_t yN)\n{\n\tassert(yN >= 0);\n\tassert(w > 0);\n\tif (y == 0) {\n\t\tz = 1;\n\t\treturn;\n\t}\n\tconst size_t tblSize = 1 << (w - 1);\n\tuint8_t bin[sizeof(F) * 8 + 1];\n\tF tbl[tblSize];\n\tsize_t binN = getBinary2(bin, sizeof(bin), y, yN, w);\n\tassert(binN > 0);\n\n\tF x2;\n\tF::sqr(x2, x);\n\ttbl[0] = x;\n\tfor (size_t i = 1; i < tblSize; i++) {\n\t\tF::mul(tbl[i], tbl[i - 1], x2);\n\t}\n\tz = 1;\n\tfor (size_t i = 0; i < binN; i++) {\n\t\tconst size_t bit = binN - 1 - i;\n\t\tF::sqr(z, z);\n\t\tuint8_t n = bin[bit];\n\t\tif (n > 0) {\n\t\t\tz *= tbl[(n - 1) >> 1];\n\t\t}\n\t}\n}\n\ntemplate\nvoid pow3(T& z, const T& x, const mpz_class& y)\n{\n\tpow3(z, x, mcl::gmp::getUnit(y), mcl::gmp::getUnitSize(y));\n}\n\ntemplate\nvoid pow3(T& z, const T& x, const F& y)\n{\n\tpow3(z, x, y.getMpz());\n}\n\nvoid bench(const char *name, const char *pStr)\n{\n\tputs(\"------------------\");\n\tprintf(\"bench name=%s\\n\", name);\n\tFp::init(pStr);\n\tconst int C = 10000;\n\tcybozu::XorShift rg;\n\tFp x, y, x0;\n\tfor (int i = 0; i < 100; i++) {\n\t\tx.setByCSPRNG(rg);\n\t\ty.setByCSPRNG(rg);\n\t\tFp t1, t2;\n\t\tFp::pow(t1, x, y.getMpz());\n\t\tpow3(t2, x, y.getMpz());\n\t\tCYBOZU_TEST_EQUAL(t1, t2);\n\t}\n\tCYBOZU_BENCH_C(\"Fp::add\", C, Fp::add, x, x, y);\n\tCYBOZU_BENCH_C(\"Fp::sub\", C, Fp::sub, x, x, y);\n\tCYBOZU_BENCH_C(\"Fp::mul\", C, Fp::mul, x, x, y);\n\tCYBOZU_BENCH_C(\"Fp::sqr\", C, Fp::sqr, x, x);\n\tCYBOZU_BENCH_C(\"Fp::inv\", C, Fp::inv, x, x);\n\tCYBOZU_BENCH_C(\"Fp::pow\", C, Fp::pow, x, x, x);\n\tCYBOZU_BENCH_C(\"pow3 \", C, pow3, x, x, x);\n\tCYBOZU_BENCH_C(\"getMpz\", C, x.getMpz);\n\tuint8_t bin[sizeof(Fp) * 8 + 1];\n\tmpz_class mx = x.getMpz();\n\tCYBOZU_BENCH_C(\"getBinary:4\", C, getBinary, bin, sizeof(bin), mx, 4);\n\tCYBOZU_BENCH_C(\"getBinary:5\", C, getBinary, bin, sizeof(bin), mx, 5);\n}\n\nCYBOZU_TEST_AUTO(main)\n{\n\tconst struct {\n\t\tconst char *name;\n\t\tconst char *pStr;\n\t} tbl[] = {\n\t\t{ \"secp256k1p\", mcl::ecparam::secp256k1.p },\n\t\t{ \"secp256k1r\", mcl::ecparam::secp256k1.n },\n\t\t{ \"bn254r\", \"0x2523648240000001ba344d8000000007ff9f800000000010a10000000000000d\" },\n\t\t{ \"bn254p\", \"0x2523648240000001ba344d80000000086121000000000013a700000000000013\" },\n\t\t{ \"bls12_381p\", \"0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001\" },\n\t\t{ \"bls12_381r\", \"0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab\" },\n\t};\n\tfor (size_t i = 0; i < CYBOZU_NUM_OF_ARRAY(tbl); i++) {\n\t\tbench(tbl[i].name, tbl[i].pStr);\n\t}\n}\n\nremove warning#define PUT(x) std::cout << #x \"=\" << (x) << std::endl;\n#include \n#include \n#include \n#include \n#include \n\nstruct FpTag;\ntypedef mcl::FpT Fp;\n\nvoid put(const char *msg, const void *buf, size_t bufSize)\n{\n\tprintf(\"%s:\", msg);\n\tconst unsigned char* p = (const unsigned char*)buf;\n\tfor (size_t i = 0; i < bufSize; i++) {\n\t\tprintf(\"%02x\", p[i]);\n\t}\n\tprintf(\"\\n\");\n}\n\ntemplate\ninline size_t getBinary2(uint8_t *bin, size_t maxBinN, const T *x, size_t xN, size_t w)\n{\n\tif (w == 0 || w >= 8) return 0;\n\tsize_t binN = 0;\n\tsize_t zeroNum = 0;\n\n\tmcl::fp::BitIterator iter(x, xN);\n\twhile (iter.hasNext()) {\n\t\tdo {\n\t\t\tif (iter.peekBit()) break;\n\t\t\tzeroNum++;\n\t\t\titer.skipBit();\n\t\t} while (iter.hasNext());\n\t\tfor (size_t i = 0; i < zeroNum; i++) {\n\t\t\tif (binN == maxBinN) return 0;\n\t\t\tbin[binN++] = 0;\n\t\t}\n\t\tuint32_t v = iter.getNext(w);\n\t\tif (binN == maxBinN) return 0;\n\t\tbin[binN++] = v;\n\t\tzeroNum = w - 1;\n\t}\n\twhile (binN > 0 && bin[binN - 1] == 0) {\n\t\tbinN--;\n\t}\n\treturn binN;\n}\n\ninline size_t getBinary(uint8_t *bin, size_t maxBinN, mpz_class x, size_t w)\n{\n\treturn getBinary2(bin, maxBinN, mcl::gmp::getUnit(x), mcl::gmp::getUnitSize(x), w);\n}\n\ntemplate\nvoid pow3(F& z, const F& x, const T *y, size_t yN)\n{\n\tassert(w > 0);\n\tif (y == 0) {\n\t\tz = 1;\n\t\treturn;\n\t}\n\tconst size_t tblSize = 1 << (w - 1);\n\tuint8_t bin[sizeof(F) * 8 + 1];\n\tF tbl[tblSize];\n\tsize_t binN = getBinary2(bin, sizeof(bin), y, yN, w);\n\tassert(binN > 0);\n\n\tF x2;\n\tF::sqr(x2, x);\n\ttbl[0] = x;\n\tfor (size_t i = 1; i < tblSize; i++) {\n\t\tF::mul(tbl[i], tbl[i - 1], x2);\n\t}\n\tz = 1;\n\tfor (size_t i = 0; i < binN; i++) {\n\t\tconst size_t bit = binN - 1 - i;\n\t\tF::sqr(z, z);\n\t\tuint8_t n = bin[bit];\n\t\tif (n > 0) {\n\t\t\tz *= tbl[(n - 1) >> 1];\n\t\t}\n\t}\n}\n\ntemplate\nvoid pow3(T& z, const T& x, const mpz_class& y)\n{\n\tpow3(z, x, mcl::gmp::getUnit(y), mcl::gmp::getUnitSize(y));\n}\n\ntemplate\nvoid pow3(T& z, const T& x, const F& y)\n{\n\tpow3(z, x, y.getMpz());\n}\n\nvoid bench(const char *name, const char *pStr)\n{\n\tputs(\"------------------\");\n\tprintf(\"bench name=%s\\n\", name);\n\tFp::init(pStr);\n\tconst int C = 10000;\n\tcybozu::XorShift rg;\n\tFp x, y, x0;\n\tfor (int i = 0; i < 100; i++) {\n\t\tx.setByCSPRNG(rg);\n\t\ty.setByCSPRNG(rg);\n\t\tFp t1, t2;\n\t\tFp::pow(t1, x, y.getMpz());\n\t\tpow3(t2, x, y.getMpz());\n\t\tCYBOZU_TEST_EQUAL(t1, t2);\n\t}\n\tCYBOZU_BENCH_C(\"Fp::add\", C, Fp::add, x, x, y);\n\tCYBOZU_BENCH_C(\"Fp::sub\", C, Fp::sub, x, x, y);\n\tCYBOZU_BENCH_C(\"Fp::mul\", C, Fp::mul, x, x, y);\n\tCYBOZU_BENCH_C(\"Fp::sqr\", C, Fp::sqr, x, x);\n\tCYBOZU_BENCH_C(\"Fp::inv\", C, Fp::inv, x, x);\n\tCYBOZU_BENCH_C(\"Fp::pow\", C, Fp::pow, x, x, x);\n\tCYBOZU_BENCH_C(\"pow3 \", C, pow3, x, x, x);\n\tCYBOZU_BENCH_C(\"getMpz\", C, x.getMpz);\n\tuint8_t bin[sizeof(Fp) * 8 + 1];\n\tmpz_class mx = x.getMpz();\n\tCYBOZU_BENCH_C(\"getBinary:4\", C, getBinary, bin, sizeof(bin), mx, 4);\n\tCYBOZU_BENCH_C(\"getBinary:5\", C, getBinary, bin, sizeof(bin), mx, 5);\n}\n\nCYBOZU_TEST_AUTO(main)\n{\n\tconst struct {\n\t\tconst char *name;\n\t\tconst char *pStr;\n\t} tbl[] = {\n\t\t{ \"secp256k1p\", mcl::ecparam::secp256k1.p },\n\t\t{ \"secp256k1r\", mcl::ecparam::secp256k1.n },\n\t\t{ \"bn254r\", \"0x2523648240000001ba344d8000000007ff9f800000000010a10000000000000d\" },\n\t\t{ \"bn254p\", \"0x2523648240000001ba344d80000000086121000000000013a700000000000013\" },\n\t\t{ \"bls12_381p\", \"0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001\" },\n\t\t{ \"bls12_381r\", \"0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab\" },\n\t};\n\tfor (size_t i = 0; i < CYBOZU_NUM_OF_ARRAY(tbl); i++) {\n\t\tbench(tbl[i].name, tbl[i].pStr);\n\t}\n}\n\n<|endoftext|>"} {"text":"#ifndef LOCKWRAPPER_HPP\n#define LOCKWRAPPER_HPP\n\n#include \"base.hpp\"\n\nnamespace org_pqrs_KeyRemap4MacBook {\n class IOLockWrapper {\n public:\n static IOLock* alloc(void) {\n IOLock* lock = IOLockAlloc();\n if (! lock) {\n IOLog(\"[KeyRemap4MacBook ERROR] IOLockAlloc failed.\\n\");\n }\n return lock;\n }\n static void free(IOLock*& lock) {\n if (! lock) {\n IOLog(\"[KeyRemap4MacBook ERROR] IOLockAlloc failed.\\n\");\n return;\n }\n\n IOLockLock(lock);\n IOLock* tmplock = lock;\n lock = NULL;\n IOLockUnlock(tmplock);\n IOLockFree(tmplock);\n }\n\n class ScopedLock {\n public:\n \/\/ ------------------------------------------------------------\n ScopedLock(IOLock* lock) : lock_(lock) {\n if (lock_) {\n IOLockLock(lock_);\n }\n }\n ~ScopedLock(void) {\n if (lock_) {\n IOLockUnlock(lock_);\n }\n }\n\n private:\n IOLock* lock_;\n };\n\n class ScopedTryLock {\n public:\n ScopedTryLock(IOLock* lock) : lock_(lock) {\n if (lock_) {\n if (! IOLockTryLock(lock_)) {\n \/\/ lock failed.\n lock_ = NULL;\n }\n }\n }\n ~ScopedTryLock(void) {\n if (lock_) {\n IOLockUnlock(lock_);\n }\n }\n bool locked(void) const { return lock_ != NULL; }\n\n private:\n IOLock* lock_;\n };\n };\n}\n\n#endif\nupdate IOLockWrapper to use IOLOG_*#ifndef LOCKWRAPPER_HPP\n#define LOCKWRAPPER_HPP\n\n#include \"base.hpp\"\n\nnamespace org_pqrs_KeyRemap4MacBook {\n class IOLockWrapper {\n public:\n static IOLock* alloc(void) {\n IOLock* lock = IOLockAlloc();\n if (! lock) {\n IOLOG_ERROR(\"IOLockAlloc failed.\\n\");\n }\n return lock;\n }\n static void free(IOLock*& lock) {\n if (! lock) {\n IOLOG_ERROR(\"IOLockAlloc failed.\\n\");\n return;\n }\n\n IOLockLock(lock);\n IOLock* tmplock = lock;\n lock = NULL;\n IOLockUnlock(tmplock);\n IOLockFree(tmplock);\n }\n\n class ScopedLock {\n public:\n \/\/ ------------------------------------------------------------\n ScopedLock(IOLock* lock) : lock_(lock) {\n if (lock_) {\n IOLockLock(lock_);\n }\n }\n ~ScopedLock(void) {\n if (lock_) {\n IOLockUnlock(lock_);\n }\n }\n\n private:\n IOLock* lock_;\n };\n\n class ScopedTryLock {\n public:\n ScopedTryLock(IOLock* lock) : lock_(lock) {\n if (lock_) {\n if (! IOLockTryLock(lock_)) {\n \/\/ lock failed.\n lock_ = NULL;\n }\n }\n }\n ~ScopedTryLock(void) {\n if (lock_) {\n IOLockUnlock(lock_);\n }\n }\n bool locked(void) const { return lock_ != NULL; }\n\n private:\n IOLock* lock_;\n };\n };\n}\n\n#endif\n<|endoftext|>"} {"text":"\/\/\n\/\/ Created by dar on 11\/28\/15.\n\/\/\n\n#include \"EntityPlayer.h\"\n#include \"core\/map\/Map.h\"\n#include \"EntityToy.h\"\n\nEntityPlayer::EntityPlayer(Map *map) : EntityMoving(map, 0.55, 0.55) {\n b2CircleShape shape;\n shape.m_p.Set(0, 0);\n shape.m_radius = 1.5; \/\/ A bit more than our size because it is only a sensor\n b2FixtureDef fixDef;\n fixDef.shape = &shape;\n fixDef.isSensor = true;\n fixDef.density = 2.0f;\n fixDef.friction = 0.1f;\n this->body->CreateFixture(&fixDef);\n}\n\nvoid EntityPlayer::update(double deltaTime) {\n EntityMoving::update(deltaTime);\n\n this->ejectTimer *= pow(0.75, deltaTime);\n if (std::abs(this->ejectTimer) < 0.05) {\n if (this->ejectTimer < 0.0) {\n this->setToy(true);\n }\n this->ejectTimer = 0.0;\n } else {\n if (this->ejectTimer > 0) {\n this->applyForce(3 * this->ejectTimer, 3 * this->ejectTimer);\n } else if (this->getToyToMerge() != nullptr) {\n this->applyForce((this->getToyToMerge()->getX() - this->getX()) * 2.0, (this->getToyToMerge()->getY() - this->getY()) * 2.0);\n }\n }\n\n if (this->getToy() == nullptr) {\n double speed_x = this->getBody()->GetLinearVelocity().x;\n double speed_y = this->getBody()->GetLinearVelocity().y;\n double speed = speed_x * speed_x + speed_y * speed_y;\n this->increaseTailAnimation((0.5 + speed * 0.9) * 0.3 * deltaTime);\n }\n\n if (this->getToy() != nullptr) {\n this->setX(this->getToy()->getX());\n this->setY(this->getToy()->getY());\n }\n\n if (this->getToy() != nullptr) {\n this->colorfulness += 0.04 * deltaTime;\n if (this->colorfulness > 2.0) this->colorfulness = 2.0;\n } else {\n this->colorfulness -= 0.025 * deltaTime;\n if (this->colorfulness < 0.0) this->colorfulness = 0.0;\n }\n\n if (std::abs(this->velX) > 0.01 || std::abs(this->velY) > 0.01) {\n this->applyForce(this->velX, this->velY);\n }\n\n double deltaPow = std::pow(0.9, deltaTime);\n this->velX *= deltaPow;\n this->velY *= deltaPow;\n}\n\nvoid EntityPlayer::onCollision(IPositionable *object, char state) {\n if (object != nullptr) if (EntityToy *toy = dynamic_cast(object)) {\n if (state == 0 && this->toy == nullptr) {\n this->toysToMerge++;\n this->toyToMerge = toy;\n } else if (state == 1 && this->toy == nullptr) {\n this->toysToMerge--;\n if (this->toysToMerge <= 0) {\n this->toyToMerge = nullptr;\n }\n }\n }\n}\n\nvoid EntityPlayer::eject() {\n if (this->toy != nullptr) {\n this->setX(this->toy->getX());\n this->setY(this->toy->getY());\n toy->setHost(nullptr);\n this->toyToMerge = toy;\n this->toy = nullptr;\n this->toysToMerge = 0;\n this->ejectTimer = 1.0;\n }\n}\n\nvoid EntityPlayer::applyImpulse(double x, double y) {\n if (this->toy != nullptr) {\n this->toy->applyImpulse(x, y);\n } else {\n EntityMoving::applyImpulse(x, y);\n }\n}\n\nvoid EntityPlayer::applyForce(double x, double y) {\n if (this->toy != nullptr) {\n this->toy->applyForce(x, y);\n } else {\n EntityMoving::applyForce(x, y);\n }\n}\n\nbool EntityPlayer::doesCollide(IPositionable *obj) {\n return true;\n}\n\nvoid EntityPlayer::setToy(bool force) {\n if (!force) {\n if (this->toyToMerge != nullptr) {\n EntityToy *t = this->map->getEntityAt(this->getX(), this->getY());\n if (t != nullptr) {\n this->toyToMerge = t;\n }\n }\n if (this->toyToMerge != nullptr) {\n this->ejectTimer = -1.0;\n }\n } else {\n if (this->toyToMerge != nullptr) {\n this->setDamagedToy(nullptr);\n this->toy = this->toyToMerge;\n this->toy->setHost(this);\n this->toyToMerge = nullptr;\n this->ejectTimer = 1.0;\n }\n }\n}\n\nvoid EntityPlayer::move(double x, double y, double deltaTime) {\n double power = std::sqrt(x * x + y * y);\n EntityToy *toy = this->getToy();\n if (toy != nullptr) {\n double da = atan2(y, x) - toy->getAngle();\n double dx = atan2(-sin(da), cos(da));\n if (dx < M_PI * 0.75 && dx > -M_PI * 0.75) {\n x = power * -sin(this->toy->getAngle() - M_PI_2);\n y = power * cos(this->toy->getAngle() - M_PI_2);\n } else {\n x = power * -sin(this->toy->getAngle() + M_PI_2);\n y = power * cos(this->toy->getAngle() + M_PI_2);\n if (dx >= M_PI * 0.75) {\n dx -= M_PI;\n } else {\n dx += M_PI;\n }\n }\n toy->setAngle(toy->getAngle() - dx * this->toy->getControllability() * deltaTime);\n } else {\n this->setAngle(atan2(y, x));\n }\n\n double powMod = std::pow(0.08, deltaTime);\n this->setVelocity(this->velX + x * powMod, this->velY + y * powMod);\n\n}\n\nvoid EntityPlayer::setVelocity(double velX, double velY) {\n this->velX = velX;\n this->velY = velY;\n}Made player's movement speed acceleration linear instead of exponential.\/\/\n\/\/ Created by dar on 11\/28\/15.\n\/\/\n\n#include \"EntityPlayer.h\"\n#include \"core\/map\/Map.h\"\n#include \"EntityToy.h\"\n\nEntityPlayer::EntityPlayer(Map *map) : EntityMoving(map, 0.55, 0.55) {\n b2CircleShape shape;\n shape.m_p.Set(0, 0);\n shape.m_radius = 1.5; \/\/ A bit more than our size because it is only a sensor\n b2FixtureDef fixDef;\n fixDef.shape = &shape;\n fixDef.isSensor = true;\n fixDef.density = 2.0f;\n fixDef.friction = 0.1f;\n this->body->CreateFixture(&fixDef);\n}\n\nvoid EntityPlayer::update(double deltaTime) {\n EntityMoving::update(deltaTime);\n\n this->ejectTimer *= pow(0.75, deltaTime);\n if (std::abs(this->ejectTimer) < 0.05) {\n if (this->ejectTimer < 0.0) {\n this->setToy(true);\n }\n this->ejectTimer = 0.0;\n } else {\n if (this->ejectTimer > 0) {\n this->applyForce(3 * this->ejectTimer, 3 * this->ejectTimer);\n } else if (this->getToyToMerge() != nullptr) {\n this->applyForce((this->getToyToMerge()->getX() - this->getX()) * 2.0, (this->getToyToMerge()->getY() - this->getY()) * 2.0);\n }\n }\n\n if (this->getToy() == nullptr) {\n double speed_x = this->getBody()->GetLinearVelocity().x;\n double speed_y = this->getBody()->GetLinearVelocity().y;\n double speed = speed_x * speed_x + speed_y * speed_y;\n this->increaseTailAnimation((0.5 + speed * 0.9) * 0.3 * deltaTime);\n }\n\n if (this->getToy() != nullptr) {\n this->setX(this->getToy()->getX());\n this->setY(this->getToy()->getY());\n }\n\n if (this->getToy() != nullptr) {\n this->colorfulness += 0.04 * deltaTime;\n if (this->colorfulness > 2.0) this->colorfulness = 2.0;\n } else {\n this->colorfulness -= 0.025 * deltaTime;\n if (this->colorfulness < 0.0) this->colorfulness = 0.0;\n }\n\n if (std::abs(this->velX) > 0.01 || std::abs(this->velY) > 0.01) {\n this->applyForce(this->velX, this->velY);\n }\n\n double deltaPow = std::pow(0.9, deltaTime);\n this->velX *= deltaPow;\n this->velY *= deltaPow;\n}\n\nvoid EntityPlayer::onCollision(IPositionable *object, char state) {\n if (object != nullptr) if (EntityToy *toy = dynamic_cast(object)) {\n if (state == 0 && this->toy == nullptr) {\n this->toysToMerge++;\n this->toyToMerge = toy;\n } else if (state == 1 && this->toy == nullptr) {\n this->toysToMerge--;\n if (this->toysToMerge <= 0) {\n this->toyToMerge = nullptr;\n }\n }\n }\n}\n\nvoid EntityPlayer::eject() {\n if (this->toy != nullptr) {\n this->setX(this->toy->getX());\n this->setY(this->toy->getY());\n toy->setHost(nullptr);\n this->toyToMerge = toy;\n this->toy = nullptr;\n this->toysToMerge = 0;\n this->ejectTimer = 1.0;\n }\n}\n\nvoid EntityPlayer::applyImpulse(double x, double y) {\n if (this->toy != nullptr) {\n this->toy->applyImpulse(x, y);\n } else {\n EntityMoving::applyImpulse(x, y);\n }\n}\n\nvoid EntityPlayer::applyForce(double x, double y) {\n if (this->toy != nullptr) {\n this->toy->applyForce(x, y);\n } else {\n EntityMoving::applyForce(x, y);\n }\n}\n\nbool EntityPlayer::doesCollide(IPositionable *obj) {\n return true;\n}\n\nvoid EntityPlayer::setToy(bool force) {\n if (!force) {\n if (this->toyToMerge != nullptr) {\n EntityToy *t = this->map->getEntityAt(this->getX(), this->getY());\n if (t != nullptr) {\n this->toyToMerge = t;\n }\n }\n if (this->toyToMerge != nullptr) {\n this->ejectTimer = -1.0;\n }\n } else {\n if (this->toyToMerge != nullptr) {\n this->setDamagedToy(nullptr);\n this->toy = this->toyToMerge;\n this->toy->setHost(this);\n this->toyToMerge = nullptr;\n this->ejectTimer = 1.0;\n }\n }\n}\n\nvoid EntityPlayer::move(double x, double y, double deltaTime) {\n double power = std::sqrt(x * x + y * y);\n EntityToy *toy = this->getToy();\n if (toy != nullptr) {\n double da = atan2(y, x) - toy->getAngle();\n double dx = atan2(-sin(da), cos(da));\n if (dx < M_PI * 0.75 && dx > -M_PI * 0.75) {\n x = power * -sin(this->toy->getAngle() - M_PI_2);\n y = power * cos(this->toy->getAngle() - M_PI_2);\n } else {\n x = power * -sin(this->toy->getAngle() + M_PI_2);\n y = power * cos(this->toy->getAngle() + M_PI_2);\n if (dx >= M_PI * 0.75) {\n dx -= M_PI;\n } else {\n dx += M_PI;\n }\n }\n toy->setAngle(toy->getAngle() - dx * this->toy->getControllability() * deltaTime);\n } else {\n this->setAngle(atan2(y, x));\n }\n\n double powMod = 0.08 * deltaTime;\n this->setVelocity(this->velX + x * powMod, this->velY + y * powMod);\n\n}\n\nvoid EntityPlayer::setVelocity(double velX, double velY) {\n this->velX = velX;\n this->velY = velY;\n}<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \"WiFiManager.h\"\n#include \"webserver.h\"\n#include \"gear.h\"\n#include \"range.h\"\n#include \"Adafruit_NeoPixel.h\"\n\nconst char* ssid = _SSID_;\nconst char* password = _WIFI_PASSWORD_;\n\nMDNSResponder mdns;\n\nWebServer &server = WebServer::instance();\nGear gear(5, 0, 4, 2);\nRange range(14, 12);\n\/\/ Adafruit_NeoPixel pixels = Adafruit_NeoPixel(8, 10, NEO_GRB + NEO_KHZ800);\nAdafruit_NeoPixel pixels(8, 10, NEO_GRB + NEO_KHZ800);\n\n\nvoid setup(void) {\n\n Serial.begin(115200);\n\n#if 0\n WiFi.begin(ssid, password);\n Serial.println(\"\");\n\n \/\/ Wait for connection\n while (WiFi.status() != WL_CONNECTED) {\n delay(500);\n Serial.print(\".\");\n }\n\n Serial.println(\"\");\n Serial.print(\"Connected to \");\n Serial.println(ssid);\n Serial.print(\"IP address: \");\n Serial.println(WiFi.localIP());\n\n#endif\n\n\tWiFiManager wifiManager;\n\t\/\/ wifiManager.autoConnect(\"edubot\", \"edubotpass\");\n\twifiManager.autoConnect();\n\n if (mdns.begin(_MDNS_NAME_, WiFi.localIP())) {\n Serial.println(\"MDNS responder started\");\n }\n\n server.begin();\n Serial.println(\"HTTP server started\");\n\n\tpixels.begin();\n}\n\nvoid loop(void) {\n\n server.handleClient();\n\trange.update();\n}\n\nConfigure WiFi depending on the state of a yet to define pin.#include \n#include \n#include \n\n#include \"WiFiManager.h\"\n#include \"webserver.h\"\n#include \"gear.h\"\n#include \"range.h\"\n#include \"Adafruit_NeoPixel.h\"\n\nconst char* ssid = _SSID_;\nconst char* password = _WIFI_PASSWORD_;\n\nMDNSResponder mdns;\n\nWebServer &server = WebServer::instance();\nGear gear(5, 0, 4, 2);\nRange range(14, 12);\n\/\/ Adafruit_NeoPixel pixels = Adafruit_NeoPixel(8, 10, NEO_GRB + NEO_KHZ800);\nAdafruit_NeoPixel pixels(8, 10, NEO_GRB + NEO_KHZ800);\n\n#define WIFI_MODE_PIN 99\n\nvoid setup(void) {\n\n Serial.begin(115200);\n\n\tpinMode(WIFI_MODE_PIN, INPUT);\n\n\tif(digitalRead(WIFI_MODE_PIN) == HIGH) {\n\t\t\/\/ use WiFi-Manager for network connection to STA\n\t\tSerial.println(\"Using WiFi-Manager\");\n\n\t\tWiFiManager wifiManager;\n\t\twifiManager.autoConnect(_SSID_, _WIFI_PASSWORD_);\n\t}\n\telse {\n\t\t\/\/ create own AP\n\t\tSerial.println(\"Using own AP\");\n\n\t\tWiFi.mode(WIFI_AP);\n\t\tWiFi.softAP(_SSID_, _WIFI_PASSWORD_);\t\n\t}\n\n if (mdns.begin(_MDNS_NAME_, WiFi.localIP())) {\n Serial.println(\"MDNS responder started\");\n }\n\n server.begin();\n Serial.println(\"HTTP server started\");\n\n\tpixels.begin();\n}\n\nvoid loop(void) {\n\n server.handleClient();\n\trange.update();\n}\n\n<|endoftext|>"} {"text":"\/*\nCopyright 2013-present Barefoot Networks, Inc.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n#include \n#include \n\n#include \"ir\/ir.h\"\n#include \"..\/common\/options.h\"\n#include \"lib\/nullstream.h\"\n#include \"lib\/path.h\"\n#include \"frontend.h\"\n\n#include \"frontends\/p4\/typeMap.h\"\n#include \"frontends\/p4\/typeChecking\/bindVariables.h\"\n#include \"frontends\/common\/resolveReferences\/resolveReferences.h\"\n#include \"frontends\/p4\/fromv1.0\/v1model.h\"\n\/\/ Passes\n#include \"actionsInlining.h\"\n#include \"checkConstants.h\"\n#include \"checkCoreMethods.h\"\n#include \"checkNamedArgs.h\"\n#include \"createBuiltins.h\"\n#include \"defaultArguments.h\"\n#include \"deprecated.h\"\n#include \"directCalls.h\"\n#include \"dontcareArgs.h\"\n#include \"evaluator\/evaluator.h\"\n#include \"frontends\/common\/constantFolding.h\"\n#include \"functionsInlining.h\"\n#include \"hierarchicalNames.h\"\n#include \"inlining.h\"\n#include \"localizeActions.h\"\n#include \"moveConstructors.h\"\n#include \"moveDeclarations.h\"\n#include \"parseAnnotations.h\"\n#include \"parserControlFlow.h\"\n#include \"reassociation.h\"\n#include \"redundantParsers.h\"\n#include \"removeParameters.h\"\n#include \"removeReturns.h\"\n#include \"resetHeaders.h\"\n#include \"setHeaders.h\"\n#include \"sideEffects.h\"\n#include \"simplify.h\"\n#include \"simplifyDefUse.h\"\n#include \"simplifyParsers.h\"\n#include \"simplifySwitch.h\"\n#include \"specialize.h\"\n#include \"specializeGenericFunctions.h\"\n#include \"specializeGenericTypes.h\"\n#include \"strengthReduction.h\"\n#include \"structInitializers.h\"\n#include \"switchAddDefault.h\"\n#include \"tableKeyNames.h\"\n#include \"toP4\/toP4.h\"\n#include \"typeChecking\/typeChecker.h\"\n#include \"uniqueNames.h\"\n#include \"unusedDeclarations.h\"\n#include \"uselessCasts.h\"\n#include \"validateMatchAnnotations.h\"\n#include \"validateParsedProgram.h\"\n\nnamespace P4 {\n\nnamespace {\n\n\/* Base class for inspectors that do not really visit the program. *\/\nclass NoVisit : public Inspector {\n \/\/ prune visit\n bool preorder(const IR::P4Program*) override { return false; }\n};\n\n\/**\nThis pass outputs the program as a P4 source file.\n*\/\nclass PrettyPrint : public Inspector {\n \/\/\/ output file\n cstring ppfile;\n \/\/\/ The file that is being compiled. This used\n cstring inputfile;\n public:\n explicit PrettyPrint(const CompilerOptions& options) {\n setName(\"PrettyPrint\");\n ppfile = options.prettyPrintFile;\n inputfile = options.file;\n }\n bool preorder(const IR::P4Program* program) override {\n if (!ppfile.isNullOrEmpty()) {\n Util::PathName path(ppfile);\n std::ostream *ppStream = openFile(path.toString(), true);\n P4::ToP4 top4(ppStream, false, inputfile);\n (void)program->apply(top4);\n }\n return false; \/\/ prune\n }\n};\n\n\/**\n * This pass is a no-op whose purpose is to mark the end of the\n * front-end, which is useful for debugging. It is implemented as an\n * empty @ref PassManager (instead of a @ref Visitor) for efficiency.\n *\/\nclass FrontEndLast : public NoVisit {\n public:\n FrontEndLast() { setName(\"FrontEndLast\"); }\n};\n\n\/**\n * This pass is a no-op whose purpose is to mark a point in the\n * front-end, used for testing.\n *\/\nclass FrontEndDump : public NoVisit {\n public:\n FrontEndDump() { setName(\"FrontEndDump\"); }\n};\n\n\/** Changes the value of strictStruct in the typeMap *\/\nclass SetStrictStruct : public NoVisit {\n TypeMap* typeMap;\n bool strictStruct;\n public:\n SetStrictStruct(TypeMap* typeMap, bool strict):\n typeMap(typeMap), strictStruct(strict) {}\n Visitor::profile_t init_apply(const IR::Node* node) override {\n typeMap->setStrictStruct(strictStruct);\n return Inspector::init_apply(node);\n }\n};\n\n} \/\/ namespace\n\n\/\/ TODO: remove skipSideEffectOrdering flag\nconst IR::P4Program *FrontEnd::run(const CompilerOptions &options, const IR::P4Program* program,\n bool skipSideEffectOrdering, std::ostream* outStream) {\n if (program == nullptr && options.listFrontendPasses == 0)\n return nullptr;\n\n bool isv1 = options.isv1();\n ReferenceMap refMap;\n TypeMap typeMap;\n refMap.setIsV1(isv1);\n\n auto evaluator = new P4::EvaluatorPass(&refMap, &typeMap);\n PassManager passes({\n new P4V1::getV1ModelVersion,\n \/\/ Parse annotations\n new ParseAnnotationBodies(&parseAnnotations, &typeMap),\n new PrettyPrint(options),\n \/\/ Simple checks on parsed program\n new ValidateParsedProgram(),\n \/\/ Synthesize some built-in constructs\n new CreateBuiltins(),\n new ResolveReferences(&refMap, true), \/\/ check shadowing\n \/\/ First pass of constant folding, before types are known --\n \/\/ may be needed to compute types.\n new ConstantFolding(&refMap, nullptr),\n \/\/ Desugars direct parser and control applications\n \/\/ into instantiations followed by application\n new InstantiateDirectCalls(&refMap),\n new ResolveReferences(&refMap), \/\/ check shadowing\n new Deprecated(&refMap),\n new CheckNamedArgs(),\n \/\/ Type checking and type inference. Also inserts\n \/\/ explicit casts where implicit casts exist.\n new SetStrictStruct(&typeMap, true), \/\/ Next pass uses strict struct checking\n new TypeInference(&refMap, &typeMap, false, false), \/\/ insert casts, dont' check arrays\n new SetStrictStruct(&typeMap, false),\n new ValidateMatchAnnotations(&typeMap),\n new BindTypeVariables(&refMap, &typeMap),\n new SpecializeGenericTypes(&refMap, &typeMap),\n new DefaultArguments(&refMap, &typeMap), \/\/ add default argument values to parameters\n new ResolveReferences(&refMap),\n new SetStrictStruct(&typeMap, true), \/\/ Next pass uses strict struct checking\n new TypeInference(&refMap, &typeMap, false), \/\/ more casts may be needed\n new SetStrictStruct(&typeMap, false),\n new CheckCoreMethods(&refMap, &typeMap),\n new RemoveParserIfs(&refMap, &typeMap),\n new StructInitializers(&refMap, &typeMap),\n new SpecializeGenericFunctions(&refMap, &typeMap),\n new TableKeyNames(&refMap, &typeMap),\n PassRepeated({\n new ConstantFolding(&refMap, &typeMap),\n new StrengthReduction(&refMap, &typeMap),\n new Reassociation(),\n new UselessCasts(&refMap, &typeMap)\n }),\n new SimplifyControlFlow(&refMap, &typeMap),\n new SwitchAddDefault,\n new FrontEndDump(), \/\/ used for testing the program at this point\n new RemoveAllUnusedDeclarations(&refMap, true),\n new SimplifyParsers(&refMap),\n new ResetHeaders(&refMap, &typeMap),\n new UniqueNames(&refMap), \/\/ Give each local declaration a unique internal name\n new MoveDeclarations(), \/\/ Move all local declarations to the beginning\n new MoveInitializers(&refMap),\n new SideEffectOrdering(&refMap, &typeMap, skipSideEffectOrdering),\n new SimplifyControlFlow(&refMap, &typeMap),\n new SimplifySwitch(&refMap, &typeMap),\n new MoveDeclarations(), \/\/ Move all local declarations to the beginning\n new SimplifyDefUse(&refMap, &typeMap),\n new UniqueParameters(&refMap, &typeMap),\n new SimplifyControlFlow(&refMap, &typeMap),\n new SpecializeAll(&refMap, &typeMap),\n new RemoveParserControlFlow(&refMap, &typeMap),\n new RemoveReturns(&refMap),\n new RemoveDontcareArgs(&refMap, &typeMap),\n new MoveConstructors(&refMap),\n new RemoveAllUnusedDeclarations(&refMap),\n new RemoveRedundantParsers(&refMap, &typeMap),\n new ClearTypeMap(&typeMap),\n evaluator,\n new Inline(&refMap, &typeMap, evaluator, options.optimizeParserInlining),\n new InlineActions(&refMap, &typeMap),\n new LocalizeAllActions(&refMap),\n new UniqueNames(&refMap),\n new UniqueParameters(&refMap, &typeMap),\n \/\/ Must be done before inlining functions, to allow\n \/\/ function calls used as action arguments to be inlined\n \/\/ in the proper place.\n new RemoveActionParameters(&refMap, &typeMap),\n new InlineFunctions(&refMap, &typeMap),\n new SetHeaders(&refMap, &typeMap),\n \/\/ Check for constants only after inlining\n new CheckConstants(&refMap, &typeMap),\n new SimplifyControlFlow(&refMap, &typeMap),\n new RemoveParserControlFlow(&refMap, &typeMap), \/\/ more ifs may have been added to parsers\n new UniqueNames(&refMap), \/\/ needed again after inlining\n new MoveDeclarations(), \/\/ needed again after inlining\n new SimplifyControlFlow(&refMap, &typeMap),\n new HierarchicalNames(),\n new FrontEndLast(),\n });\n if (options.listFrontendPasses) {\n passes.listPasses(*outStream, \"\\n\");\n *outStream << std::endl;\n return nullptr;\n }\n\n if (options.excludeFrontendPasses) {\n passes.removePasses(options.passesToExcludeFrontend);\n }\n\n passes.setName(\"FrontEnd\");\n passes.setStopOnError(true);\n passes.addDebugHooks(hooks, true);\n const IR::P4Program* result = program->apply(passes);\n return result;\n}\n\n} \/\/ namespace P4\nRemove undefined behaviour in pass manager initialization (#3468)\/*\nCopyright 2013-present Barefoot Networks, Inc.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n#include \n#include \n\n#include \"ir\/ir.h\"\n#include \"..\/common\/options.h\"\n#include \"lib\/nullstream.h\"\n#include \"lib\/path.h\"\n#include \"frontend.h\"\n\n#include \"frontends\/p4\/typeMap.h\"\n#include \"frontends\/p4\/typeChecking\/bindVariables.h\"\n#include \"frontends\/common\/resolveReferences\/resolveReferences.h\"\n#include \"frontends\/p4\/fromv1.0\/v1model.h\"\n\/\/ Passes\n#include \"actionsInlining.h\"\n#include \"checkConstants.h\"\n#include \"checkCoreMethods.h\"\n#include \"checkNamedArgs.h\"\n#include \"createBuiltins.h\"\n#include \"defaultArguments.h\"\n#include \"deprecated.h\"\n#include \"directCalls.h\"\n#include \"dontcareArgs.h\"\n#include \"evaluator\/evaluator.h\"\n#include \"frontends\/common\/constantFolding.h\"\n#include \"functionsInlining.h\"\n#include \"hierarchicalNames.h\"\n#include \"inlining.h\"\n#include \"localizeActions.h\"\n#include \"moveConstructors.h\"\n#include \"moveDeclarations.h\"\n#include \"parseAnnotations.h\"\n#include \"parserControlFlow.h\"\n#include \"reassociation.h\"\n#include \"redundantParsers.h\"\n#include \"removeParameters.h\"\n#include \"removeReturns.h\"\n#include \"resetHeaders.h\"\n#include \"setHeaders.h\"\n#include \"sideEffects.h\"\n#include \"simplify.h\"\n#include \"simplifyDefUse.h\"\n#include \"simplifyParsers.h\"\n#include \"simplifySwitch.h\"\n#include \"specialize.h\"\n#include \"specializeGenericFunctions.h\"\n#include \"specializeGenericTypes.h\"\n#include \"strengthReduction.h\"\n#include \"structInitializers.h\"\n#include \"switchAddDefault.h\"\n#include \"tableKeyNames.h\"\n#include \"toP4\/toP4.h\"\n#include \"typeChecking\/typeChecker.h\"\n#include \"uniqueNames.h\"\n#include \"unusedDeclarations.h\"\n#include \"uselessCasts.h\"\n#include \"validateMatchAnnotations.h\"\n#include \"validateParsedProgram.h\"\n\nnamespace P4 {\n\nnamespace {\n\n\/* Base class for inspectors that do not really visit the program. *\/\nclass NoVisit : public Inspector {\n \/\/ prune visit\n bool preorder(const IR::P4Program*) override { return false; }\n};\n\n\/**\nThis pass outputs the program as a P4 source file.\n*\/\nclass PrettyPrint : public Inspector {\n \/\/\/ output file\n cstring ppfile;\n \/\/\/ The file that is being compiled. This used\n cstring inputfile;\n public:\n explicit PrettyPrint(const CompilerOptions& options) {\n setName(\"PrettyPrint\");\n ppfile = options.prettyPrintFile;\n inputfile = options.file;\n }\n bool preorder(const IR::P4Program* program) override {\n if (!ppfile.isNullOrEmpty()) {\n Util::PathName path(ppfile);\n std::ostream *ppStream = openFile(path.toString(), true);\n P4::ToP4 top4(ppStream, false, inputfile);\n (void)program->apply(top4);\n }\n return false; \/\/ prune\n }\n};\n\n\/**\n * This pass is a no-op whose purpose is to mark the end of the\n * front-end, which is useful for debugging. It is implemented as an\n * empty @ref PassManager (instead of a @ref Visitor) for efficiency.\n *\/\nclass FrontEndLast : public NoVisit {\n public:\n FrontEndLast() { setName(\"FrontEndLast\"); }\n};\n\n\/**\n * This pass is a no-op whose purpose is to mark a point in the\n * front-end, used for testing.\n *\/\nclass FrontEndDump : public NoVisit {\n public:\n FrontEndDump() { setName(\"FrontEndDump\"); }\n};\n\n\/** Changes the value of strictStruct in the typeMap *\/\nclass SetStrictStruct : public NoVisit {\n TypeMap* typeMap;\n bool strictStruct;\n public:\n SetStrictStruct(TypeMap* typeMap, bool strict):\n typeMap(typeMap), strictStruct(strict) {}\n Visitor::profile_t init_apply(const IR::Node* node) override {\n typeMap->setStrictStruct(strictStruct);\n return Inspector::init_apply(node);\n }\n};\n\n} \/\/ namespace\n\n\/\/ TODO: remove skipSideEffectOrdering flag\nconst IR::P4Program *FrontEnd::run(const CompilerOptions &options, const IR::P4Program* program,\n bool skipSideEffectOrdering, std::ostream* outStream) {\n if (program == nullptr && options.listFrontendPasses == 0)\n return nullptr;\n\n bool isv1 = options.isv1();\n ReferenceMap refMap;\n TypeMap typeMap;\n refMap.setIsV1(isv1);\n\n auto evaluator = new P4::EvaluatorPass(&refMap, &typeMap);\n PassManager passes({\n new P4V1::getV1ModelVersion,\n \/\/ Parse annotations\n new ParseAnnotationBodies(&parseAnnotations, &typeMap),\n new PrettyPrint(options),\n \/\/ Simple checks on parsed program\n new ValidateParsedProgram(),\n \/\/ Synthesize some built-in constructs\n new CreateBuiltins(),\n new ResolveReferences(&refMap, true), \/\/ check shadowing\n \/\/ First pass of constant folding, before types are known --\n \/\/ may be needed to compute types.\n new ConstantFolding(&refMap, nullptr),\n \/\/ Desugars direct parser and control applications\n \/\/ into instantiations followed by application\n new InstantiateDirectCalls(&refMap),\n new ResolveReferences(&refMap), \/\/ check shadowing\n new Deprecated(&refMap),\n new CheckNamedArgs(),\n \/\/ Type checking and type inference. Also inserts\n \/\/ explicit casts where implicit casts exist.\n new SetStrictStruct(&typeMap, true), \/\/ Next pass uses strict struct checking\n new TypeInference(&refMap, &typeMap, false, false), \/\/ insert casts, dont' check arrays\n new SetStrictStruct(&typeMap, false),\n new ValidateMatchAnnotations(&typeMap),\n new BindTypeVariables(&refMap, &typeMap),\n new SpecializeGenericTypes(&refMap, &typeMap),\n new DefaultArguments(&refMap, &typeMap), \/\/ add default argument values to parameters\n new ResolveReferences(&refMap),\n new SetStrictStruct(&typeMap, true), \/\/ Next pass uses strict struct checking\n new TypeInference(&refMap, &typeMap, false), \/\/ more casts may be needed\n new SetStrictStruct(&typeMap, false),\n new CheckCoreMethods(&refMap, &typeMap),\n new RemoveParserIfs(&refMap, &typeMap),\n new StructInitializers(&refMap, &typeMap),\n new SpecializeGenericFunctions(&refMap, &typeMap),\n new TableKeyNames(&refMap, &typeMap),\n new PassRepeated({\n new ConstantFolding(&refMap, &typeMap),\n new StrengthReduction(&refMap, &typeMap),\n new Reassociation(),\n new UselessCasts(&refMap, &typeMap)\n }),\n new SimplifyControlFlow(&refMap, &typeMap),\n new SwitchAddDefault,\n new FrontEndDump(), \/\/ used for testing the program at this point\n new RemoveAllUnusedDeclarations(&refMap, true),\n new SimplifyParsers(&refMap),\n new ResetHeaders(&refMap, &typeMap),\n new UniqueNames(&refMap), \/\/ Give each local declaration a unique internal name\n new MoveDeclarations(), \/\/ Move all local declarations to the beginning\n new MoveInitializers(&refMap),\n new SideEffectOrdering(&refMap, &typeMap, skipSideEffectOrdering),\n new SimplifyControlFlow(&refMap, &typeMap),\n new SimplifySwitch(&refMap, &typeMap),\n new MoveDeclarations(), \/\/ Move all local declarations to the beginning\n new SimplifyDefUse(&refMap, &typeMap),\n new UniqueParameters(&refMap, &typeMap),\n new SimplifyControlFlow(&refMap, &typeMap),\n new SpecializeAll(&refMap, &typeMap),\n new RemoveParserControlFlow(&refMap, &typeMap),\n new RemoveReturns(&refMap),\n new RemoveDontcareArgs(&refMap, &typeMap),\n new MoveConstructors(&refMap),\n new RemoveAllUnusedDeclarations(&refMap),\n new RemoveRedundantParsers(&refMap, &typeMap),\n new ClearTypeMap(&typeMap),\n evaluator,\n new Inline(&refMap, &typeMap, evaluator, options.optimizeParserInlining),\n new InlineActions(&refMap, &typeMap),\n new LocalizeAllActions(&refMap),\n new UniqueNames(&refMap),\n new UniqueParameters(&refMap, &typeMap),\n \/\/ Must be done before inlining functions, to allow\n \/\/ function calls used as action arguments to be inlined\n \/\/ in the proper place.\n new RemoveActionParameters(&refMap, &typeMap),\n new InlineFunctions(&refMap, &typeMap),\n new SetHeaders(&refMap, &typeMap),\n \/\/ Check for constants only after inlining\n new CheckConstants(&refMap, &typeMap),\n new SimplifyControlFlow(&refMap, &typeMap),\n new RemoveParserControlFlow(&refMap, &typeMap), \/\/ more ifs may have been added to parsers\n new UniqueNames(&refMap), \/\/ needed again after inlining\n new MoveDeclarations(), \/\/ needed again after inlining\n new SimplifyControlFlow(&refMap, &typeMap),\n new HierarchicalNames(),\n new FrontEndLast(),\n });\n if (options.listFrontendPasses) {\n passes.listPasses(*outStream, \"\\n\");\n *outStream << std::endl;\n return nullptr;\n }\n\n if (options.excludeFrontendPasses) {\n passes.removePasses(options.passesToExcludeFrontend);\n }\n\n passes.setName(\"FrontEnd\");\n passes.setStopOnError(true);\n passes.addDebugHooks(hooks, true);\n const IR::P4Program* result = program->apply(passes);\n return result;\n}\n\n} \/\/ namespace P4\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"webrtc\/base\/format_macros.h\"\n#include \"webrtc\/modules\/audio_coding\/codecs\/opus\/audio_encoder_opus.h\"\n#include \"webrtc\/modules\/audio_coding\/neteq\/tools\/audio_loop.h\"\n#include \"webrtc\/test\/gtest.h\"\n#include \"webrtc\/test\/testsupport\/fileutils.h\"\n#include \"webrtc\/test\/testsupport\/perf_test.h\"\n#include \"webrtc\/system_wrappers\/include\/clock.h\"\n\nnamespace webrtc {\n\nnamespace {\nint64_t RunComplexityTest(const AudioEncoderOpus::Config& config) {\n \/\/ Create encoder.\n AudioEncoderOpus encoder(config);\n \/\/ Open speech file.\n const std::string kInputFileName =\n webrtc::test::ResourcePath(\"audio_coding\/speech_mono_32_48kHz\", \"pcm\");\n test::AudioLoop audio_loop;\n constexpr int kSampleRateHz = 48000;\n EXPECT_EQ(kSampleRateHz, encoder.SampleRateHz());\n constexpr size_t kMaxLoopLengthSamples =\n kSampleRateHz * 10; \/\/ 10 second loop.\n constexpr size_t kInputBlockSizeSamples =\n 10 * kSampleRateHz \/ 1000; \/\/ 60 ms.\n EXPECT_TRUE(audio_loop.Init(kInputFileName, kMaxLoopLengthSamples,\n kInputBlockSizeSamples));\n \/\/ Encode.\n webrtc::Clock* clock = webrtc::Clock::GetRealTimeClock();\n const int64_t start_time_ms = clock->TimeInMilliseconds();\n AudioEncoder::EncodedInfo info;\n rtc::Buffer encoded(500);\n uint32_t rtp_timestamp = 0u;\n for (size_t i = 0; i < 10000; ++i) {\n encoded.Clear();\n info = encoder.Encode(rtp_timestamp, audio_loop.GetNextBlock(), &encoded);\n rtp_timestamp += kInputBlockSizeSamples;\n }\n return clock->TimeInMilliseconds() - start_time_ms;\n}\n} \/\/ namespace\n\n#if defined(WEBRTC_ANDROID)\n#define MAYBE_AudioEncoderOpusComplexityAdaptationTest \\\n DISABLED_AudioEncoderOpusComplexityAdaptationTest\n#else\n#define MAYBE_AudioEncoderOpusComplexityAdaptationTest \\\n AudioEncoderOpusComplexityAdaptationTest\n#endif\n\n\/\/ This test encodes an audio file using Opus twice with different bitrates\n\/\/ (12.5 kbps and 15.5 kbps). The runtime for each is measured, and the ratio\n\/\/ between the two is calculated and tracked. This test explicitly sets the\n\/\/ low_rate_complexity to 9. When running on desktop platforms, this is the same\n\/\/ as the regular complexity, and the expectation is that the resulting ratio\n\/\/ should be less than 100% (since the encoder runs faster at lower bitrates,\n\/\/ given a fixed complexity setting). On the other hand, when running on\n\/\/ mobiles, the regular complexity is 5, and we expect the resulting ratio to\n\/\/ be higher, since we have explicitly asked for a higher complexity setting at\n\/\/ the lower rate.\nTEST(AudioEncoderOpusComplexityAdaptationTest, AdaptationOn) {\n \/\/ Create config.\n AudioEncoderOpus::Config config;\n config.bitrate_bps = rtc::Optional(12500);\n config.low_rate_complexity = 9;\n int64_t runtime_12500bps = RunComplexityTest(config);\n\n config.bitrate_bps = rtc::Optional(15500);\n int64_t runtime_15500bps = RunComplexityTest(config);\n\n test::PrintResult(\"opus_encoding_complexity_ratio\", \"\", \"adaptation_on\",\n 100.0 * runtime_12500bps \/ runtime_15500bps, \"percent\",\n true);\n}\n\n\/\/ This test is identical to the one above, but without the complexity\n\/\/ adaptation enabled (neither on desktop, nor on mobile). The expectation is\n\/\/ that the resulting ratio is less than 100% at all times.\nTEST(AudioEncoderOpusComplexityAdaptationTest, AdaptationOff) {\n \/\/ Create config.\n AudioEncoderOpus::Config config;\n config.bitrate_bps = rtc::Optional(12500);\n int64_t runtime_12500bps = RunComplexityTest(config);\n\n config.bitrate_bps = rtc::Optional(15500);\n int64_t runtime_15500bps = RunComplexityTest(config);\n\n test::PrintResult(\"opus_encoding_complexity_ratio\", \"\", \"adaptation_off\",\n 100.0 * runtime_12500bps \/ runtime_15500bps, \"\", true);\n}\n} \/\/ namespace webrtc\nReally disable Opus complexity tests on Android\/*\n * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"webrtc\/base\/format_macros.h\"\n#include \"webrtc\/modules\/audio_coding\/codecs\/opus\/audio_encoder_opus.h\"\n#include \"webrtc\/modules\/audio_coding\/neteq\/tools\/audio_loop.h\"\n#include \"webrtc\/test\/gtest.h\"\n#include \"webrtc\/test\/testsupport\/fileutils.h\"\n#include \"webrtc\/test\/testsupport\/perf_test.h\"\n#include \"webrtc\/system_wrappers\/include\/clock.h\"\n\nnamespace webrtc {\n\nnamespace {\nint64_t RunComplexityTest(const AudioEncoderOpus::Config& config) {\n \/\/ Create encoder.\n AudioEncoderOpus encoder(config);\n \/\/ Open speech file.\n const std::string kInputFileName =\n webrtc::test::ResourcePath(\"audio_coding\/speech_mono_32_48kHz\", \"pcm\");\n test::AudioLoop audio_loop;\n constexpr int kSampleRateHz = 48000;\n EXPECT_EQ(kSampleRateHz, encoder.SampleRateHz());\n constexpr size_t kMaxLoopLengthSamples =\n kSampleRateHz * 10; \/\/ 10 second loop.\n constexpr size_t kInputBlockSizeSamples =\n 10 * kSampleRateHz \/ 1000; \/\/ 60 ms.\n EXPECT_TRUE(audio_loop.Init(kInputFileName, kMaxLoopLengthSamples,\n kInputBlockSizeSamples));\n \/\/ Encode.\n webrtc::Clock* clock = webrtc::Clock::GetRealTimeClock();\n const int64_t start_time_ms = clock->TimeInMilliseconds();\n AudioEncoder::EncodedInfo info;\n rtc::Buffer encoded(500);\n uint32_t rtp_timestamp = 0u;\n for (size_t i = 0; i < 10000; ++i) {\n encoded.Clear();\n info = encoder.Encode(rtp_timestamp, audio_loop.GetNextBlock(), &encoded);\n rtp_timestamp += kInputBlockSizeSamples;\n }\n return clock->TimeInMilliseconds() - start_time_ms;\n}\n} \/\/ namespace\n\n#if defined(WEBRTC_ANDROID)\n#define MAYBE_AudioEncoderOpusComplexityAdaptationTest \\\n DISABLED_AudioEncoderOpusComplexityAdaptationTest\n#else\n#define MAYBE_AudioEncoderOpusComplexityAdaptationTest \\\n AudioEncoderOpusComplexityAdaptationTest\n#endif\n\n\/\/ This test encodes an audio file using Opus twice with different bitrates\n\/\/ (12.5 kbps and 15.5 kbps). The runtime for each is measured, and the ratio\n\/\/ between the two is calculated and tracked. This test explicitly sets the\n\/\/ low_rate_complexity to 9. When running on desktop platforms, this is the same\n\/\/ as the regular complexity, and the expectation is that the resulting ratio\n\/\/ should be less than 100% (since the encoder runs faster at lower bitrates,\n\/\/ given a fixed complexity setting). On the other hand, when running on\n\/\/ mobiles, the regular complexity is 5, and we expect the resulting ratio to\n\/\/ be higher, since we have explicitly asked for a higher complexity setting at\n\/\/ the lower rate.\nTEST(MAYBE_AudioEncoderOpusComplexityAdaptationTest, AdaptationOn) {\n \/\/ Create config.\n AudioEncoderOpus::Config config;\n config.bitrate_bps = rtc::Optional(12500);\n config.low_rate_complexity = 9;\n int64_t runtime_12500bps = RunComplexityTest(config);\n\n config.bitrate_bps = rtc::Optional(15500);\n int64_t runtime_15500bps = RunComplexityTest(config);\n\n test::PrintResult(\"opus_encoding_complexity_ratio\", \"\", \"adaptation_on\",\n 100.0 * runtime_12500bps \/ runtime_15500bps, \"percent\",\n true);\n}\n\n\/\/ This test is identical to the one above, but without the complexity\n\/\/ adaptation enabled (neither on desktop, nor on mobile). The expectation is\n\/\/ that the resulting ratio is less than 100% at all times.\nTEST(MAYBE_AudioEncoderOpusComplexityAdaptationTest, AdaptationOff) {\n \/\/ Create config.\n AudioEncoderOpus::Config config;\n config.bitrate_bps = rtc::Optional(12500);\n int64_t runtime_12500bps = RunComplexityTest(config);\n\n config.bitrate_bps = rtc::Optional(15500);\n int64_t runtime_15500bps = RunComplexityTest(config);\n\n test::PrintResult(\"opus_encoding_complexity_ratio\", \"\", \"adaptation_off\",\n 100.0 * runtime_12500bps \/ runtime_15500bps, \"\", true);\n}\n} \/\/ namespace webrtc\n<|endoftext|>"} {"text":"\/*\n * Copyright 2012 Open Source Robotics Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n*\/\n\/* Desc: Specification of a contact\n * Author: Nate Koenig\n * Date: 10 Nov 2009\n *\/\n\n#include \"gazebo\/physics\/physics.hh\"\n#include \"gazebo\/physics\/Collision.hh\"\n#include \"gazebo\/physics\/Contact.hh\"\n\nusing namespace gazebo;\nusing namespace physics;\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nContact::Contact()\n{\n this->count = 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nContact::Contact(const Contact &_c)\n{\n *this = _c;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nContact::~Contact()\n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nContact &Contact::operator =(const Contact &_contact)\n{\n this->world = _contact.world;\n this->collision1 = _contact.collision1;\n this->collision2 = _contact.collision2;\n this->collisionPtr1 = _contact.collisionPtr1;\n this->collisionPtr2 = _contact.collisionPtr2;\n\n this->count = _contact.count;\n for (int i = 0; i < MAX_CONTACT_JOINTS; i++)\n {\n this->wrench[i] = _contact.wrench[i];\n this->positions[i] = _contact.positions[i];\n this->normals[i] = _contact.normals[i];\n this->depths[i] = _contact.depths[i];\n }\n\n this->time = _contact.time;\n\n return *this;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nContact &Contact::operator =(const msgs::Contact &_contact)\n{\n this->count = 0;\n\n this->world = physics::get_world(_contact.world());\n this->collision1 = _contact.collision1();\n this->collision2 = _contact.collision2();\n\n if (world)\n {\n this->collisionPtr1 = boost::dynamic_pointer_cast(\n this->world->GetEntity(this->collision1)).get();\n this->collisionPtr2 = boost::dynamic_pointer_cast(\n this->world->GetEntity(this->collision2)).get();\n }\n else\n {\n gzwarn << \"World: \" << _contact.world() << \" not found,\"\n << \"contact collision pointers will be NULL\";\n }\n\n for (int j = 0; j < _contact.position_size(); ++j)\n {\n this->positions[j] = msgs::Convert(_contact.position(j));\n\n this->normals[j] = msgs::Convert(_contact.normal(j));\n\n this->depths[j] = _contact.depth(j);\n\n this->wrench[j].body1Force =\n msgs::Convert(_contact.wrench(j).body_1_force());\n\n this->wrench[j].body2Force =\n msgs::Convert(_contact.wrench(j).body_2_force());\n\n this->wrench[j].body1Torque =\n msgs::Convert(_contact.wrench(j).body_1_torque());\n\n this->wrench[j].body2Torque =\n msgs::Convert(_contact.wrench(j).body_2_torque());\n\n this->count++;\n }\n\n this->time = msgs::Convert(_contact.time());\n\n return *this;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid Contact::Reset()\n{\n this->count = 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstd::string Contact::DebugString() const\n{\n std::ostringstream stream;\n\n stream << \"World [\" << this->world->GetName() << \"]\\n\"\n << \"Collision 1[\" << this->collision1 << \"]\\n\"\n << \"Collision 2[\" << this->collision2 << \"]\\n\"\n << \"Time[\" << this->time << \"]\\n\"\n << \"Contact Count[\" << this->count << \"]\\n\";\n\n for (int i = 0; i < this->count; ++i)\n {\n stream << \"--- Contact[\" << i << \"]\\n\";\n stream << \" Depth[\" << this->depths[i] << \"]\\n\"\n << \" Position[\" << this->positions[i] << \"]\\n\"\n << \" Normal[\" << this->normals[i] << \"]\\n\"\n << \" Force1[\" << this->wrench[i].body1Force << \"]\\n\"\n << \" Force2[\" << this->wrench[i].body2Force << \"]\\n\"\n << \" Torque1[\" << this->wrench[i].body1Torque << \"]\\n\"\n << \" Torque2[\" << this->wrench[i].body2Torque << \"]\\n\";\n }\n\n return stream.str();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid Contact::FillMsg(msgs::Contact &_msg) const\n{\n _msg.set_world(this->world->GetName());\n _msg.set_collision1(this->collision1);\n _msg.set_collision2(this->collision2);\n msgs::Set(_msg.mutable_time(), this->time);\n\n for (int j = 0; j < this->count; ++j)\n {\n _msg.add_depth(this->depths[j]);\n\n msgs::Set(_msg.add_position(), this->positions[j]);\n msgs::Set(_msg.add_normal(), this->normals[j]);\n\n msgs::JointWrench *jntWrench = _msg.add_wrench();\n jntWrench->set_body_1_name(this->collision1);\n jntWrench->set_body_2_name(this->collision2);\n msgs::Set(jntWrench->mutable_body_1_force(), this->wrench[j].body1Force);\n msgs::Set(jntWrench->mutable_body_2_force(), this->wrench[j].body2Force);\n msgs::Set(jntWrench->mutable_body_1_torque(), this->wrench[j].body1Torque);\n msgs::Set(jntWrench->mutable_body_2_torque(), this->wrench[j].body2Torque);\n }\n}\nadded includes for forward depend\/*\n * Copyright 2012 Open Source Robotics Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n*\/\n\/* Desc: Specification of a contact\n * Author: Nate Koenig\n * Date: 10 Nov 2009\n *\/\n\n#include \"gazebo\/physics\/Physics.hh\"\n#include \"gazebo\/physics\/Collision.hh\"\n#include \"gazebo\/physics\/Contact.hh\"\n#include \"gazebo\/physics\/PhysicsTypes.hh\"\n\nusing namespace gazebo;\nusing namespace physics;\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nContact::Contact()\n{\n this->count = 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nContact::Contact(const Contact &_c)\n{\n *this = _c;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nContact::~Contact()\n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nContact &Contact::operator =(const Contact &_contact)\n{\n this->world = _contact.world;\n this->collision1 = _contact.collision1;\n this->collision2 = _contact.collision2;\n this->collisionPtr1 = _contact.collisionPtr1;\n this->collisionPtr2 = _contact.collisionPtr2;\n\n this->count = _contact.count;\n for (int i = 0; i < MAX_CONTACT_JOINTS; i++)\n {\n this->wrench[i] = _contact.wrench[i];\n this->positions[i] = _contact.positions[i];\n this->normals[i] = _contact.normals[i];\n this->depths[i] = _contact.depths[i];\n }\n\n this->time = _contact.time;\n\n return *this;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nContact &Contact::operator =(const msgs::Contact &_contact)\n{\n this->count = 0;\n\n this->world = physics::get_world(_contact.world());\n this->collision1 = _contact.collision1();\n this->collision2 = _contact.collision2();\n\n if (world)\n {\n this->collisionPtr1 = boost::dynamic_pointer_cast(\n this->world->GetEntity(this->collision1)).get();\n this->collisionPtr2 = boost::dynamic_pointer_cast(\n this->world->GetEntity(this->collision2)).get();\n }\n else\n {\n gzwarn << \"World: \" << _contact.world() << \" not found,\"\n << \"contact collision pointers will be NULL\";\n }\n\n for (int j = 0; j < _contact.position_size(); ++j)\n {\n this->positions[j] = msgs::Convert(_contact.position(j));\n\n this->normals[j] = msgs::Convert(_contact.normal(j));\n\n this->depths[j] = _contact.depth(j);\n\n this->wrench[j].body1Force =\n msgs::Convert(_contact.wrench(j).body_1_force());\n\n this->wrench[j].body2Force =\n msgs::Convert(_contact.wrench(j).body_2_force());\n\n this->wrench[j].body1Torque =\n msgs::Convert(_contact.wrench(j).body_1_torque());\n\n this->wrench[j].body2Torque =\n msgs::Convert(_contact.wrench(j).body_2_torque());\n\n this->count++;\n }\n\n this->time = msgs::Convert(_contact.time());\n\n return *this;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid Contact::Reset()\n{\n this->count = 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstd::string Contact::DebugString() const\n{\n std::ostringstream stream;\n\n stream << \"World [\" << this->world->GetName() << \"]\\n\"\n << \"Collision 1[\" << this->collision1 << \"]\\n\"\n << \"Collision 2[\" << this->collision2 << \"]\\n\"\n << \"Time[\" << this->time << \"]\\n\"\n << \"Contact Count[\" << this->count << \"]\\n\";\n\n for (int i = 0; i < this->count; ++i)\n {\n stream << \"--- Contact[\" << i << \"]\\n\";\n stream << \" Depth[\" << this->depths[i] << \"]\\n\"\n << \" Position[\" << this->positions[i] << \"]\\n\"\n << \" Normal[\" << this->normals[i] << \"]\\n\"\n << \" Force1[\" << this->wrench[i].body1Force << \"]\\n\"\n << \" Force2[\" << this->wrench[i].body2Force << \"]\\n\"\n << \" Torque1[\" << this->wrench[i].body1Torque << \"]\\n\"\n << \" Torque2[\" << this->wrench[i].body2Torque << \"]\\n\";\n }\n\n return stream.str();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid Contact::FillMsg(msgs::Contact &_msg) const\n{\n _msg.set_world(this->world->GetName());\n _msg.set_collision1(this->collision1);\n _msg.set_collision2(this->collision2);\n msgs::Set(_msg.mutable_time(), this->time);\n\n for (int j = 0; j < this->count; ++j)\n {\n _msg.add_depth(this->depths[j]);\n\n msgs::Set(_msg.add_position(), this->positions[j]);\n msgs::Set(_msg.add_normal(), this->normals[j]);\n\n msgs::JointWrench *jntWrench = _msg.add_wrench();\n jntWrench->set_body_1_name(this->collision1);\n jntWrench->set_body_2_name(this->collision2);\n msgs::Set(jntWrench->mutable_body_1_force(), this->wrench[j].body1Force);\n msgs::Set(jntWrench->mutable_body_2_force(), this->wrench[j].body2Force);\n msgs::Set(jntWrench->mutable_body_1_torque(), this->wrench[j].body1Torque);\n msgs::Set(jntWrench->mutable_body_2_torque(), this->wrench[j].body2Torque);\n }\n}\n<|endoftext|>"} {"text":"#include \n\n#define UNICODE\n#include \n\n#include \"core.hpp\"\n\n#define WGL_CONTEXT_PROFILE_MASK 0x9126\n#define WGL_CONTEXT_CORE_PROFILE_BIT 0x0001\n#define WGL_CONTEXT_MAJOR_VERSION 0x2091\n#define WGL_CONTEXT_MINOR_VERSION 0x2092\n\ntypedef HGLRC (WINAPI * PFNWGLCREATECONTEXTATTRIBSARBPROC)(HDC hDC, HGLRC hShareContext, const int * attribList);\ntypedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC)(int interval);\n\nHINSTANCE hinst;\n\nstruct MyWindow {\n CRITICAL_SECTION lock;\n HANDLE ready;\n\n HWND hwnd;\n HDC hdc;\n HGLRC hrc;\n\n bool key_down[110];\n wchar_t text_input[100];\n int text_input_size;\n int mouse_wheel;\n\n long long freq;\n long long start;\n bool alive;\n};\n\nMyWindow window;\n\nPIXELFORMATDESCRIPTOR pfd = {sizeof(PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_GENERIC_ACCELERATED | PFD_DOUBLEBUFFER, 0, 24};\n\nint keyid(int code) {\n if ('A' <= code && code <= 'Z') {\n return 27 + code - 'A';\n }\n if ('0' <= code && code <= '9') {\n return 53 + code - '0';\n }\n if (VK_F1 <= code && code <= VK_F12) {\n return 63 + code - VK_F1;\n }\n switch (code) {\n case VK_CONTROL: return 1;\n case VK_MENU: return 2;\n case VK_SHIFT: return 3;\n case VK_RETURN: return 4;\n case VK_SPACE: return 5;\n case VK_ESCAPE: return 6;\n case VK_TAB: return 7;\n case VK_BACK: return 8;\n case VK_UP: return 9;\n case VK_DOWN: return 10;\n case VK_LEFT: return 11;\n case VK_RIGHT: return 12;\n case VK_OEM_PLUS: return 13;\n case VK_OEM_MINUS: return 14;\n case VK_OEM_2: return 15;\n case VK_OEM_5: return 16;\n case VK_OEM_PERIOD: return 17;\n case VK_OEM_COMMA: return 18;\n case VK_OEM_3: return 19;\n case VK_INSERT: return 20;\n case VK_DELETE: return 21;\n case VK_HOME: return 22;\n case VK_END: return 23;\n case VK_PRIOR: return 24;\n case VK_NEXT: return 25;\n case VK_CAPITAL: return 26;\n default: return 0;\n }\n}\n\nLRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {\n switch (uMsg) {\n case WM_CLOSE: {\n DestroyWindow(hWnd);\n return 0;\n }\n case WM_DESTROY: {\n EnterCriticalSection(&window.lock);\n window.alive = false;\n LeaveCriticalSection(&window.lock);\n PostQuitMessage(0);\n return 0;\n }\n case WM_LBUTTONDOWN: {\n EnterCriticalSection(&window.lock);\n window.key_down[101] = true;\n LeaveCriticalSection(&window.lock);\n break;\n }\n case WM_LBUTTONUP: {\n EnterCriticalSection(&window.lock);\n window.key_down[101] = false;\n LeaveCriticalSection(&window.lock);\n break;\n }\n case WM_RBUTTONDOWN: {\n EnterCriticalSection(&window.lock);\n window.key_down[102] = true;\n LeaveCriticalSection(&window.lock);\n break;\n }\n case WM_RBUTTONUP: {\n EnterCriticalSection(&window.lock);\n window.key_down[102] = false;\n LeaveCriticalSection(&window.lock);\n break;\n }\n case WM_MBUTTONDOWN: {\n EnterCriticalSection(&window.lock);\n window.key_down[103] = true;\n LeaveCriticalSection(&window.lock);\n break;\n }\n case WM_MBUTTONUP: {\n EnterCriticalSection(&window.lock);\n window.key_down[103] = false;\n LeaveCriticalSection(&window.lock);\n break;\n }\n case WM_MOUSEWHEEL: {\n EnterCriticalSection(&window.lock);\n window.mouse_wheel += GET_WHEEL_DELTA_WPARAM(wParam);\n LeaveCriticalSection(&window.lock);\n break;\n }\n case WM_KEYDOWN: {\n EnterCriticalSection(&window.lock);\n window.key_down[keyid((int)wParam)] = true;\n LeaveCriticalSection(&window.lock);\n break;\n }\n case WM_KEYUP: {\n EnterCriticalSection(&window.lock);\n window.key_down[keyid((int)wParam)] = false;\n LeaveCriticalSection(&window.lock);\n break;\n }\n case WM_CHAR: {\n EnterCriticalSection(&window.lock);\n if (window.text_input_size < 100) {\n window.text_input[window.text_input_size++] = (wchar_t)wParam;\n }\n LeaveCriticalSection(&window.lock);\n break;\n }\n case WM_SYSKEYDOWN:\n case WM_SYSKEYUP: {\n EnterCriticalSection(&window.lock);\n static bool sys_alt = false;\n if (wParam == VK_MENU) {\n sys_alt = (uMsg == WM_SYSKEYDOWN);\n } else if (sys_alt && uMsg == WM_SYSKEYDOWN && wParam == VK_F4) {\n DestroyWindow(hWnd);\n }\n LeaveCriticalSection(&window.lock);\n return 0;\n }\n case WM_USER: {\n ShowCursor(!wParam);\n return 0;\n }\n }\n return DefWindowProc(hWnd, uMsg, wParam, lParam);\n}\n\nvoid window_thread(void * arg) {\n RawData * data = (RawData *)arg;\n data->window = &window;\n\n if (!hinst) {\n return;\n }\n\n HCURSOR hcursor = (HCURSOR)LoadCursor(NULL, IDC_ARROW);\n HCURSOR hicon1 = (HICON)LoadIcon(hinst, MAKEINTRESOURCE(10001));\n HCURSOR hicon2 = (HICON)LoadIcon(hinst, MAKEINTRESOURCE(10002));\n\n WNDCLASSEXW wnd_class = {sizeof(WNDCLASSEXW), CS_OWNDC, WindowProc, 0, 0, hinst, hicon1, hcursor, NULL, NULL, L\"glwindow\", hicon2};\n\n if (!RegisterClassEx(&wnd_class)) {\n return;\n }\n\n int style = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU;\n int sw = GetSystemMetrics(SM_CXSCREEN);\n int sh = GetSystemMetrics(SM_CYSCREEN);\n\n RECT rect = {};\n rect.right = data->width;\n rect.bottom = data->height;\n\n AdjustWindowRect(&rect, style, false);\n\n int adjusted_width = rect.right - rect.left;\n int adjusted_height = rect.bottom - rect.top;\n\n int x = (sw - adjusted_width) \/ 2;\n int y = (sh - adjusted_height) \/ 2;\n\n window.hwnd = CreateWindowEx(WS_EX_APPWINDOW, L\"glwindow\", (LPCWSTR)data->title, style, x, y, data->width, data->height, NULL, NULL, hinst, data);\n\n if (!window.hwnd) {\n return;\n }\n\n window.hdc = GetDC(window.hwnd);\n\n if (!window.hdc) {\n return;\n }\n\n int pixelformat = ChoosePixelFormat(window.hdc, &pfd);\n if (!pixelformat) {\n return;\n }\n\n if (!SetPixelFormat(window.hdc, pixelformat, &pfd)) {\n return;\n }\n\n window.hrc = wglCreateContext(window.hdc);\n if (!window.hrc) {\n return;\n }\n\n if (data->glversion) {\n if (!wglMakeCurrent(window.hdc, window.hrc)) {\n return;\n }\n\n PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress(\"wglCreateContextAttribsARB\");\n if (!wglCreateContextAttribsARB) {\n return;\n }\n\n if (!wglMakeCurrent(NULL, NULL)) {\n return;\n }\n\n if (!wglDeleteContext(window.hrc)) {\n return;\n }\n\n int attribs[] = {\n WGL_CONTEXT_PROFILE_MASK, WGL_CONTEXT_CORE_PROFILE_BIT,\n WGL_CONTEXT_MAJOR_VERSION, data->glversion \/ 100 % 10,\n WGL_CONTEXT_MINOR_VERSION, data->glversion \/ 10 % 10,\n 0, 0,\n };\n\n window.hrc = wglCreateContextAttribsARB(window.hdc, NULL, attribs);\n }\n\n if (!window.hrc) {\n return;\n }\n\n SetEvent(window.ready);\n\n MSG msg;\n\twhile (GetMessage(&msg, NULL, 0, 0)) {\n\t\tTranslateMessage(&msg);\n\t\tDispatchMessage(&msg);\n\t}\n}\n\n\nbool create_window(void * arg) {\n window.ready = CreateEvent(NULL, true, false, NULL);\n InitializeCriticalSection(&window.lock);\n window.alive = true;\n\n HANDLE thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)window_thread, arg, 0, NULL);\n\n HANDLE objects[2] = {\n window.ready,\n thread,\n };\n\n WaitForMultipleObjects(2, objects, false, INFINITE);\n\n if (WaitForSingleObject(window.ready, 0)) {\n PyErr_BadInternalCall();\n return false;\n }\n\n if (!wglMakeCurrent(window.hdc, window.hrc)) {\n PyErr_BadInternalCall();\n return false;\n }\n\n PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC)wglGetProcAddress(\"wglSwapIntervalEXT\");\n if (!wglSwapIntervalEXT) {\n PyErr_BadInternalCall();\n return false;\n }\n\n wglSwapIntervalEXT(1);\n\n QueryPerformanceFrequency((LARGE_INTEGER *)&window.freq);\n QueryPerformanceCounter((LARGE_INTEGER *)&window.start);\n\n ShowWindow(window.hwnd, SW_SHOW);\n\tSetForegroundWindow(window.hwnd);\n\tSetActiveWindow(window.hwnd);\n\tSetFocus(window.hwnd);\n return true;\n}\n\nbool update_window(void * arg) {\n RawData * data = (RawData *)arg;\n\n EnterCriticalSection(&window.lock);\n\n if (!window.alive) {\n LeaveCriticalSection(&window.lock);\n return false;\n }\n\n SwapBuffers(window.hdc);\n\n RECT rect;\n GetWindowRect(window.hwnd, &rect);\n\n if (data->grab != data->old_grab) {\n if (data->grab) {\n POINT point;\n GetCursorPos(&point);\n data->mx = point.x;\n data->my = point.y;\n SetCursorPos((rect.left + rect.right) \/ 2, (rect.top + rect.bottom) \/ 2);\n } else {\n SetCursorPos(data->mx, data->my);\n }\n }\n\n memcpy(data->key_down, window.key_down, 110);\n memcpy(data->text_input, window.text_input, window.text_input_size * 2);\n data->text_input_size = window.text_input_size;\n data->mw = window.mouse_wheel;\n\n LeaveCriticalSection(&window.lock);\n\n if (data->grab != data->old_grab) {\n SendMessage(window.hwnd, WM_USER, data->grab, 0);\n }\n\n POINT point;\n GetCursorPos(&point);\n\n if (data->grab) {\n SetCursorPos((rect.left + rect.right) \/ 2, (rect.top + rect.bottom) \/ 2);\n data->dmx = point.x - (rect.left + rect.right) \/ 2;\n data->dmy = point.y - (rect.top + rect.bottom) \/ 2;\n } else {\n data->mx = point.x - rect.left;\n data->my = point.y - rect.top;\n }\n\n long long now;\n QueryPerformanceCounter((LARGE_INTEGER *)&now);\n data->time = (double)(now - window.start) \/ window.freq;\n return true;\n}\n\nBOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) {\n if (fdwReason == DLL_PROCESS_ATTACH) {\n hinst = hinstDLL;\n }\n return true;\n}\norganize code#include \n\n#define UNICODE\n#include \n\n#include \"core.hpp\"\n\n#define WGL_CONTEXT_PROFILE_MASK 0x9126\n#define WGL_CONTEXT_CORE_PROFILE_BIT 0x0001\n#define WGL_CONTEXT_MAJOR_VERSION 0x2091\n#define WGL_CONTEXT_MINOR_VERSION 0x2092\n\ntypedef HGLRC (WINAPI * PFNWGLCREATECONTEXTATTRIBSARBPROC)(HDC hDC, HGLRC hShareContext, const int * attribList);\ntypedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC)(int interval);\n\nHINSTANCE hinst;\n\nstruct StaticWindow {\n CRITICAL_SECTION lock;\n HANDLE ready;\n\n HANDLE thread;\n HWND hwnd;\n HDC hdc;\n HGLRC hrc;\n\n const char * error;\n\n bool key_down[110];\n wchar_t text_input[100];\n int text_input_size;\n int mouse_wheel;\n\n long long freq;\n long long start;\n bool alive;\n} window;\n\nint keyid(int code) {\n if ('A' <= code && code <= 'Z') {\n return 27 + code - 'A';\n }\n if ('0' <= code && code <= '9') {\n return 53 + code - '0';\n }\n if (VK_F1 <= code && code <= VK_F12) {\n return 63 + code - VK_F1;\n }\n switch (code) {\n case VK_CONTROL: return 1;\n case VK_MENU: return 2;\n case VK_SHIFT: return 3;\n case VK_RETURN: return 4;\n case VK_SPACE: return 5;\n case VK_ESCAPE: return 6;\n case VK_TAB: return 7;\n case VK_BACK: return 8;\n case VK_UP: return 9;\n case VK_DOWN: return 10;\n case VK_LEFT: return 11;\n case VK_RIGHT: return 12;\n case VK_OEM_PLUS: return 13;\n case VK_OEM_MINUS: return 14;\n case VK_OEM_2: return 15;\n case VK_OEM_5: return 16;\n case VK_OEM_PERIOD: return 17;\n case VK_OEM_COMMA: return 18;\n case VK_OEM_3: return 19;\n case VK_INSERT: return 20;\n case VK_DELETE: return 21;\n case VK_HOME: return 22;\n case VK_END: return 23;\n case VK_PRIOR: return 24;\n case VK_NEXT: return 25;\n case VK_CAPITAL: return 26;\n default: return 0;\n }\n}\n\nLRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {\n switch (uMsg) {\n case WM_CLOSE: {\n DestroyWindow(hWnd);\n return 0;\n }\n case WM_DESTROY: {\n EnterCriticalSection(&window.lock);\n window.alive = false;\n LeaveCriticalSection(&window.lock);\n PostQuitMessage(0);\n return 0;\n }\n case WM_LBUTTONDOWN: {\n EnterCriticalSection(&window.lock);\n window.key_down[101] = true;\n LeaveCriticalSection(&window.lock);\n break;\n }\n case WM_LBUTTONUP: {\n EnterCriticalSection(&window.lock);\n window.key_down[101] = false;\n LeaveCriticalSection(&window.lock);\n break;\n }\n case WM_RBUTTONDOWN: {\n EnterCriticalSection(&window.lock);\n window.key_down[102] = true;\n LeaveCriticalSection(&window.lock);\n break;\n }\n case WM_RBUTTONUP: {\n EnterCriticalSection(&window.lock);\n window.key_down[102] = false;\n LeaveCriticalSection(&window.lock);\n break;\n }\n case WM_MBUTTONDOWN: {\n EnterCriticalSection(&window.lock);\n window.key_down[103] = true;\n LeaveCriticalSection(&window.lock);\n break;\n }\n case WM_MBUTTONUP: {\n EnterCriticalSection(&window.lock);\n window.key_down[103] = false;\n LeaveCriticalSection(&window.lock);\n break;\n }\n case WM_MOUSEWHEEL: {\n EnterCriticalSection(&window.lock);\n window.mouse_wheel += GET_WHEEL_DELTA_WPARAM(wParam);\n LeaveCriticalSection(&window.lock);\n break;\n }\n case WM_KEYDOWN: {\n EnterCriticalSection(&window.lock);\n window.key_down[keyid((int)wParam)] = true;\n LeaveCriticalSection(&window.lock);\n break;\n }\n case WM_KEYUP: {\n EnterCriticalSection(&window.lock);\n window.key_down[keyid((int)wParam)] = false;\n LeaveCriticalSection(&window.lock);\n break;\n }\n case WM_CHAR: {\n EnterCriticalSection(&window.lock);\n if (window.text_input_size < 100) {\n window.text_input[window.text_input_size++] = (wchar_t)wParam;\n }\n LeaveCriticalSection(&window.lock);\n break;\n }\n case WM_SYSKEYDOWN:\n case WM_SYSKEYUP: {\n EnterCriticalSection(&window.lock);\n static bool sys_alt = false;\n if (wParam == VK_MENU) {\n sys_alt = (uMsg == WM_SYSKEYDOWN);\n } else if (sys_alt && uMsg == WM_SYSKEYDOWN && wParam == VK_F4) {\n DestroyWindow(hWnd);\n }\n LeaveCriticalSection(&window.lock);\n return 0;\n }\n case WM_USER: {\n ShowCursor(!wParam);\n return 0;\n }\n }\n return DefWindowProc(hWnd, uMsg, wParam, lParam);\n}\n\nvoid window_thread(void * arg) {\n RawData * data = (RawData *)arg;\n data->window = &window;\n\n if (!hinst) {\n window.error = \"hinstance is NULL\";\n SetEvent(window.ready);\n return;\n }\n\n HCURSOR hcursor = (HCURSOR)LoadCursor(NULL, IDC_ARROW);\n HCURSOR hicon1 = (HICON)LoadIcon(hinst, MAKEINTRESOURCE(10001));\n HCURSOR hicon2 = (HICON)LoadIcon(hinst, MAKEINTRESOURCE(10002));\n\n WNDCLASSEXW wnd_class = {\n sizeof(WNDCLASSEXW), CS_OWNDC, WindowProc, 0, 0, hinst, hicon1, hcursor, NULL, NULL, L\"glwindow\", hicon2,\n };\n\n if (!RegisterClassEx(&wnd_class)) {\n window.error = \"RegisterClassEx failed\";\n SetEvent(window.ready);\n return;\n }\n\n int style = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU;\n int sw = GetSystemMetrics(SM_CXSCREEN);\n int sh = GetSystemMetrics(SM_CYSCREEN);\n\n RECT rect = {};\n rect.right = data->width;\n rect.bottom = data->height;\n\n AdjustWindowRect(&rect, style, false);\n\n int width = rect.right - rect.left;\n int height = rect.bottom - rect.top;\n\n int x = (sw - width) \/ 2;\n int y = (sh - height) \/ 2;\n\n window.hwnd = CreateWindowEx(\n WS_EX_APPWINDOW, L\"glwindow\", (LPCWSTR)data->title, style, x, y, width, height, NULL, NULL, hinst, data\n );\n\n if (!window.hwnd) {\n window.error = \"CreateWindowEx failed\";\n SetEvent(window.ready);\n return;\n }\n\n window.hdc = GetDC(window.hwnd);\n if (!window.hdc) {\n window.error = \"GetDC failed\";\n SetEvent(window.ready);\n return;\n }\n\n PIXELFORMATDESCRIPTOR pfd = {\n sizeof(PIXELFORMATDESCRIPTOR),\n 1,\n PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_GENERIC_ACCELERATED | PFD_DOUBLEBUFFER,\n 0,\n 24,\n };\n\n int pixelformat = ChoosePixelFormat(window.hdc, &pfd);\n if (!pixelformat) {\n window.error = \"ChoosePixelFormat failed\";\n SetEvent(window.ready);\n return;\n }\n\n if (!SetPixelFormat(window.hdc, pixelformat, &pfd)) {\n window.error = \"SetPixelFormat failed\";\n SetEvent(window.ready);\n return;\n }\n\n window.hrc = wglCreateContext(window.hdc);\n if (!window.hrc) {\n window.error = \"wglCreateContext failed\";\n SetEvent(window.ready);\n return;\n }\n\n if (data->glversion) {\n if (!wglMakeCurrent(window.hdc, window.hrc)) {\n window.error = \"wglMakeCurrent failed\";\n SetEvent(window.ready);\n return;\n }\n\n FARPROC proc = wglGetProcAddress(\"wglCreateContextAttribsARB\");\n PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)proc;\n if (!wglCreateContextAttribsARB) {\n window.error = \"wglCreateContextAttribsARB is missing\";\n SetEvent(window.ready);\n return;\n }\n\n if (!wglMakeCurrent(NULL, NULL)) {\n window.error = \"wglMakeCurrent failed\";\n SetEvent(window.ready);\n return;\n }\n\n if (!wglDeleteContext(window.hrc)) {\n window.error = \"wglDeleteContext failed\";\n SetEvent(window.ready);\n return;\n }\n\n int attribs[] = {\n WGL_CONTEXT_PROFILE_MASK, WGL_CONTEXT_CORE_PROFILE_BIT,\n WGL_CONTEXT_MAJOR_VERSION, data->glversion \/ 100 % 10,\n WGL_CONTEXT_MINOR_VERSION, data->glversion \/ 10 % 10,\n 0, 0,\n };\n\n window.hrc = wglCreateContextAttribsARB(window.hdc, NULL, attribs);\n if (!window.hrc) {\n window.error = \"wglCreateContextAttribsARB failed\";\n SetEvent(window.ready);\n return;\n }\n }\n\n SetEvent(window.ready);\n\n MSG msg;\n while (GetMessage(&msg, NULL, 0, 0)) {\n TranslateMessage(&msg);\n DispatchMessage(&msg);\n }\n}\n\n\nbool create_window(void * arg) {\n window.ready = CreateEvent(NULL, true, false, NULL);\n InitializeCriticalSection(&window.lock);\n window.alive = true;\n\n window.thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)window_thread, arg, 0, NULL);\n WaitForSingleObject(window.ready, INFINITE);\n\n if (window.error) {\n PyErr_Format(PyExc_Exception, window.error);\n return false;\n }\n\n if (!wglMakeCurrent(window.hdc, window.hrc)) {\n PyErr_BadInternalCall();\n return false;\n }\n\n PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC)wglGetProcAddress(\"wglSwapIntervalEXT\");\n if (!wglSwapIntervalEXT) {\n PyErr_BadInternalCall();\n return false;\n }\n\n wglSwapIntervalEXT(1);\n\n QueryPerformanceFrequency((LARGE_INTEGER *)&window.freq);\n QueryPerformanceCounter((LARGE_INTEGER *)&window.start);\n\n ShowWindow(window.hwnd, SW_SHOW);\n SetForegroundWindow(window.hwnd);\n SetActiveWindow(window.hwnd);\n SetFocus(window.hwnd);\n return true;\n}\n\nbool update_window(void * arg) {\n RawData * data = (RawData *)arg;\n\n EnterCriticalSection(&window.lock);\n\n if (!window.alive) {\n LeaveCriticalSection(&window.lock);\n return false;\n }\n\n SwapBuffers(window.hdc);\n\n RECT rect;\n GetWindowRect(window.hwnd, &rect);\n\n if (data->grab != data->old_grab) {\n if (data->grab) {\n POINT point;\n GetCursorPos(&point);\n data->mx = point.x;\n data->my = point.y;\n SetCursorPos((rect.left + rect.right) \/ 2, (rect.top + rect.bottom) \/ 2);\n } else {\n SetCursorPos(data->mx, data->my);\n }\n }\n\n memcpy(data->key_down, window.key_down, 110);\n memcpy(data->text_input, window.text_input, window.text_input_size * 2);\n data->text_input_size = window.text_input_size;\n data->mw = window.mouse_wheel;\n\n LeaveCriticalSection(&window.lock);\n\n if (data->grab != data->old_grab) {\n SendMessage(window.hwnd, WM_USER, data->grab, 0);\n }\n\n POINT point;\n GetCursorPos(&point);\n\n if (data->grab) {\n SetCursorPos((rect.left + rect.right) \/ 2, (rect.top + rect.bottom) \/ 2);\n data->dmx = point.x - (rect.left + rect.right) \/ 2;\n data->dmy = point.y - (rect.top + rect.bottom) \/ 2;\n } else {\n data->mx = point.x - rect.left;\n data->my = point.y - rect.top;\n }\n\n long long now;\n QueryPerformanceCounter((LARGE_INTEGER *)&now);\n data->time = (double)(now - window.start) \/ window.freq;\n return true;\n}\n\nBOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) {\n if (fdwReason == DLL_PROCESS_ATTACH) {\n hinst = hinstDLL;\n }\n return true;\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ ftDrawForces.cpp\n\/\/ ofxFlowToolsExample\n\/\/\n\/\/ Created by Ties East on 18\/6\/15.\n\/\/\n\/\/\n\n#include \"ftDrawInputForces.h\"\n\n\nnamespace flowTools {\n\t\n\tftDrawInputForces::ftDrawInputForces() {\n\t\tofAddListener(ofEvents().mouseMoved, this, &ftDrawInputForces::mouseMoved);\n\t\tofAddListener(ofEvents().mouseDragged, this, &ftDrawInputForces::mouseDragged);\n\t\tofAddListener( ofEvents().touchMoved, this, &ftDrawInputForces::touchMoved );\n\t\tofAddListener( ofEvents().touchDown, this, &ftDrawInputForces::touchDown );\n\t}\n \n ftDrawInputForces::~ftDrawInputForces() {\n ofRemoveListener(ofEvents().mouseMoved, this, &ftDrawInputForces::mouseMoved);\n ofRemoveListener(ofEvents().mouseDragged, this, &ftDrawInputForces::mouseDragged);\n\t\tofRemoveListener( ofEvents().touchMoved, this, &ftDrawInputForces::touchMoved );\n\t\tofRemoveListener( ofEvents().touchDown, this, &ftDrawInputForces::touchDown );\n }\n\t\n\tvoid ftDrawInputForces::setup(int _simulationWidth, int _simulationHeight, int _densityWidth, int _densityHeight) {\n\t\tsimulationWidth = _simulationWidth;\n\t\tsimulationHeight = _simulationHeight;\n\t\tdensityWidth = (!_densityWidth)? simulationWidth : _densityWidth;\n\t\tdensityHeight = (!_densityHeight)? simulationHeight: _densityHeight;\n\t\t\n\t\tnumDrawForces = 12;\n\t\tdrawForces = new ftDrawForce[numDrawForces];\n\t\tdrawForces[0].setup(densityWidth, densityHeight, FT_DENSITY, true);\n\t\tdrawForces[0].setName(\"draw full res\");\n\t\tdrawForces[1].setup(simulationWidth, simulationHeight, FT_VELOCITY, true);\n\t\tdrawForces[1].setName(\"draw flow res 1\");\n\t\tdrawForces[2].setup(simulationWidth, simulationHeight, FT_TEMPERATURE, true);\n\t\tdrawForces[2].setName(\"draw flow res 2\");\n\t\tdrawForces[3].setup(densityWidth, densityHeight, FT_DENSITY, false);\n\t\tdrawForces[3].setName(\"draw full res\");\n\t\tdrawForces[4].setup(simulationWidth, simulationHeight, FT_VELOCITY, false);\n\t\tdrawForces[4].setName(\"draw flow res 1\");\n\t\tdrawForces[5].setup(simulationWidth, simulationHeight, FT_TEMPERATURE, false);\n\t\tdrawForces[5].setName(\"draw flow res 2\");\n\t\tdrawForces[6].setup(densityWidth, densityHeight, FT_DENSITY, true);\n\t\tdrawForces[6].setName(\"draw full res\");\n\t\tdrawForces[7].setup(simulationWidth, simulationHeight, FT_VELOCITY, true);\n\t\tdrawForces[7].setName(\"draw flow res 1\");\n\t\tdrawForces[8].setup(simulationWidth, simulationHeight, FT_TEMPERATURE, true);\n\t\tdrawForces[8].setName(\"draw flow res 2\");\n\t\tdrawForces[ 9 ].setup( densityWidth, densityHeight, FT_DENSITY, true );\n\t\tdrawForces[ 9 ].setName( \"draw full res\" );\n\t\tdrawForces[ 10 ].setup( simulationWidth, simulationHeight, FT_VELOCITY, true );\n\t\tdrawForces[ 10 ].setName( \"draw flow res 1\" );\n\t\tdrawForces[ 11 ].setup( simulationWidth, simulationHeight, FT_TEMPERATURE, true );\n\t\tdrawForces[ 11 ].setName( \"draw flow res 2\" );\n\t\t\n\t\tleftButtonParameters.setName(\"mouse left button\");\n\t\tleftButtonParameters.add(doResetDrawForces.set(\"reset\", false));\n\t\trightButtonParameters.setName(\"mouse right button\");\n\t\trightButtonParameters.add(doResetDrawForces.set(\"reset\", false));\n\t\tmiddleButtonParameters.setName(\"mouse middle button\");\n\t\tmiddleButtonParameters.add(doResetDrawForces.set(\"reset\", false));\n\t\tsingleTouchParameters.setName( \"single touch\" );\n\t\tsingleTouchParameters.add( doResetDrawForces.set( \"reset\", false ) );\n\t\tdoResetDrawForces.addListener(this, &ftDrawInputForces::resetDrawForcesListner);\n\t\tfor (int i=0; i<3; i++) {\n\t\t\tleftButtonParameters.add(drawForces[i].parameters);\n\t\t\trightButtonParameters.add(drawForces[i+3].parameters);\n\t\t\tmiddleButtonParameters.add(drawForces[i+6].parameters);\n\t\t\tsingleTouchParameters.add( drawForces[ i + 9 ].parameters );\n\t\t}\n\t}\n\t\n\tvoid ftDrawInputForces::update(float _deltaTime) {\n\t\tdeltaTime = _deltaTime;\n\t\t\n\t\tfor (int i=0; i= numDrawForces) {\n\t\t\tofLogWarning(\"ftDrawInputForces::getDrawForceType: index out of range\");\n\t\t\treturn false;\n\t\t}\n\t\telse\n\t\t\treturn drawForces[_index].didChange();\n\t}\n\t\n\t\/\/--------------------------------------------------------------\n\tftDrawForceType ftDrawInputForces::getType(int _index) {\n\t\tif (_index < 0 || _index >= numDrawForces) {\n\t\t\tofLogWarning(\"ftDrawInputForces::getDrawForceType: index out of range\");\n\t\t\treturn FT_NONE;\n\t\t}\n\t\telse\n\t\t\treturn drawForces[_index].getType();\n\t}\n\t\n\t\/\/--------------------------------------------------------------\n\tofTexture& ftDrawInputForces::getTextureReference(int _index) {\n\t\tif (_index < 0 || _index >= numDrawForces) {\n\t\t\tofLogError(\"ftDrawInputForces::getTexture: index out of range\");\n\t\t}\n\t\telse\n\t\t\treturn drawForces[_index].getTexture();\n\t\t\n\t}\n\t\n\t\/\/--------------------------------------------------------------\n\tfloat ftDrawInputForces::getStrength(int _index) {\n\t\tif (_index < 0 || _index >= numDrawForces) {\n\t\t\tofLogWarning(\"ftDrawInputForces::getStrength: index out of range\");\n\t\t\treturn 0;\n\t\t}\n\t\telse {\n\t\t\tif (drawForces[_index].getIsTemporary()) {\n\t\t\t\treturn drawForces[_index].getStrength();\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn drawForces[_index].getStrength() * deltaTime;;\n\t\t\t}\n\t\t}\n\t}\n\t\n\t\/\/--------------------------------------------------------------\n\tvoid ftDrawInputForces::mouseDragged( ofMouseEventArgs& mouse ) {\n\t\tofVec2f normalizedMouse;\n\t\t\n\t\tnormalizedMouse.set(mouse.x \/ (float)ofGetWindowWidth(), mouse.y \/ (float)ofGetWindowHeight());\n\t\t\n\t\tofVec2f velocity = normalizedMouse - lastNormalizedMouse;\n\t\t\/\/velocity.normalize();\n\t\t\n\t\tif (mouse.button == 0) {\n\t\t\t\n\t\t\tfor (int i=0; i<3; i++) {\n\t\t\t\tif (drawForces[i].getType() == FT_VELOCITY)\n\t\t\t\t\tdrawForces[i].setForce(velocity);\n\t\t\t\tdrawForces[i].applyForce(normalizedMouse);\n\t\t\t}\n\t\t}\n\t\telse if(mouse.button == 2)\n\t\t{\n\t\t\t\n\t\t\tfor (int i=3; i<6; i++) {\n\t\t\t\tif (drawForces[i].getType() == FT_VELOCITY)\n\t\t\t\t\tdrawForces[i].setForce(velocity);\n\t\t\t\tdrawForces[i].applyForce(normalizedMouse);\n\t\t\t}\n\t\t}\n\t\telse if (mouse.button == 1)\n\t\t{\n\t\t\tfor (int i = 6; iotw - Fixed bug with middle mouse button creating white\/black ink.\/\/\n\/\/ ftDrawForces.cpp\n\/\/ ofxFlowToolsExample\n\/\/\n\/\/ Created by Ties East on 18\/6\/15.\n\/\/\n\/\/\n\n#include \"ftDrawInputForces.h\"\n\n\nnamespace flowTools {\n\t\n\tftDrawInputForces::ftDrawInputForces() {\n\t\tofAddListener(ofEvents().mouseMoved, this, &ftDrawInputForces::mouseMoved);\n\t\tofAddListener(ofEvents().mouseDragged, this, &ftDrawInputForces::mouseDragged);\n\t\tofAddListener( ofEvents().touchMoved, this, &ftDrawInputForces::touchMoved );\n\t\tofAddListener( ofEvents().touchDown, this, &ftDrawInputForces::touchDown );\n\t}\n \n ftDrawInputForces::~ftDrawInputForces() {\n ofRemoveListener(ofEvents().mouseMoved, this, &ftDrawInputForces::mouseMoved);\n ofRemoveListener(ofEvents().mouseDragged, this, &ftDrawInputForces::mouseDragged);\n\t\tofRemoveListener( ofEvents().touchMoved, this, &ftDrawInputForces::touchMoved );\n\t\tofRemoveListener( ofEvents().touchDown, this, &ftDrawInputForces::touchDown );\n }\n\t\n\tvoid ftDrawInputForces::setup(int _simulationWidth, int _simulationHeight, int _densityWidth, int _densityHeight) {\n\t\tsimulationWidth = _simulationWidth;\n\t\tsimulationHeight = _simulationHeight;\n\t\tdensityWidth = (!_densityWidth)? simulationWidth : _densityWidth;\n\t\tdensityHeight = (!_densityHeight)? simulationHeight: _densityHeight;\n\t\t\n\t\tnumDrawForces = 12;\n\t\tdrawForces = new ftDrawForce[numDrawForces];\n\t\tdrawForces[0].setup(densityWidth, densityHeight, FT_DENSITY, true);\n\t\tdrawForces[0].setName(\"draw full res\");\n\t\tdrawForces[1].setup(simulationWidth, simulationHeight, FT_VELOCITY, true);\n\t\tdrawForces[1].setName(\"draw flow res 1\");\n\t\tdrawForces[2].setup(simulationWidth, simulationHeight, FT_TEMPERATURE, true);\n\t\tdrawForces[2].setName(\"draw flow res 2\");\n\t\tdrawForces[3].setup(densityWidth, densityHeight, FT_DENSITY, false);\n\t\tdrawForces[3].setName(\"draw full res\");\n\t\tdrawForces[4].setup(simulationWidth, simulationHeight, FT_VELOCITY, false);\n\t\tdrawForces[4].setName(\"draw flow res 1\");\n\t\tdrawForces[5].setup(simulationWidth, simulationHeight, FT_TEMPERATURE, false);\n\t\tdrawForces[5].setName(\"draw flow res 2\");\n\t\tdrawForces[6].setup(densityWidth, densityHeight, FT_DENSITY, true);\n\t\tdrawForces[6].setName(\"draw full res\");\n\t\tdrawForces[7].setup(simulationWidth, simulationHeight, FT_VELOCITY, true);\n\t\tdrawForces[7].setName(\"draw flow res 1\");\n\t\tdrawForces[8].setup(simulationWidth, simulationHeight, FT_TEMPERATURE, true);\n\t\tdrawForces[8].setName(\"draw flow res 2\");\n\t\tdrawForces[ 9 ].setup( densityWidth, densityHeight, FT_DENSITY, true );\n\t\tdrawForces[ 9 ].setName( \"draw full res\" );\n\t\tdrawForces[ 10 ].setup( simulationWidth, simulationHeight, FT_VELOCITY, true );\n\t\tdrawForces[ 10 ].setName( \"draw flow res 1\" );\n\t\tdrawForces[ 11 ].setup( simulationWidth, simulationHeight, FT_TEMPERATURE, true );\n\t\tdrawForces[ 11 ].setName( \"draw flow res 2\" );\n\t\t\n\t\tleftButtonParameters.setName(\"mouse left button\");\n\t\tleftButtonParameters.add(doResetDrawForces.set(\"reset\", false));\n\t\trightButtonParameters.setName(\"mouse right button\");\n\t\trightButtonParameters.add(doResetDrawForces.set(\"reset\", false));\n\t\tmiddleButtonParameters.setName(\"mouse middle button\");\n\t\tmiddleButtonParameters.add(doResetDrawForces.set(\"reset\", false));\n\t\tsingleTouchParameters.setName( \"single touch\" );\n\t\tsingleTouchParameters.add( doResetDrawForces.set( \"reset\", false ) );\n\t\tdoResetDrawForces.addListener(this, &ftDrawInputForces::resetDrawForcesListner);\n\t\tfor (int i=0; i<3; i++) {\n\t\t\tleftButtonParameters.add(drawForces[i].parameters);\n\t\t\trightButtonParameters.add(drawForces[i+3].parameters);\n\t\t\tmiddleButtonParameters.add(drawForces[i+6].parameters);\n\t\t\tsingleTouchParameters.add( drawForces[ i + 9 ].parameters );\n\t\t}\n\t}\n\t\n\tvoid ftDrawInputForces::update(float _deltaTime) {\n\t\tdeltaTime = _deltaTime;\n\t\t\n\t\tfor (int i=0; i= numDrawForces) {\n\t\t\tofLogWarning(\"ftDrawInputForces::getDrawForceType: index out of range\");\n\t\t\treturn false;\n\t\t}\n\t\telse\n\t\t\treturn drawForces[_index].didChange();\n\t}\n\t\n\t\/\/--------------------------------------------------------------\n\tftDrawForceType ftDrawInputForces::getType(int _index) {\n\t\tif (_index < 0 || _index >= numDrawForces) {\n\t\t\tofLogWarning(\"ftDrawInputForces::getDrawForceType: index out of range\");\n\t\t\treturn FT_NONE;\n\t\t}\n\t\telse\n\t\t\treturn drawForces[_index].getType();\n\t}\n\t\n\t\/\/--------------------------------------------------------------\n\tofTexture& ftDrawInputForces::getTextureReference(int _index) {\n\t\tif (_index < 0 || _index >= numDrawForces) {\n\t\t\tofLogError(\"ftDrawInputForces::getTexture: index out of range\");\n\t\t}\n\t\telse\n\t\t\treturn drawForces[_index].getTexture();\n\t\t\n\t}\n\t\n\t\/\/--------------------------------------------------------------\n\tfloat ftDrawInputForces::getStrength(int _index) {\n\t\tif (_index < 0 || _index >= numDrawForces) {\n\t\t\tofLogWarning(\"ftDrawInputForces::getStrength: index out of range\");\n\t\t\treturn 0;\n\t\t}\n\t\telse {\n\t\t\tif (drawForces[_index].getIsTemporary()) {\n\t\t\t\treturn drawForces[_index].getStrength();\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn drawForces[_index].getStrength() * deltaTime;;\n\t\t\t}\n\t\t}\n\t}\n\t\n\t\/\/--------------------------------------------------------------\n\tvoid ftDrawInputForces::mouseDragged( ofMouseEventArgs& mouse ) {\n\t\tofVec2f normalizedMouse;\n\t\t\n\t\tnormalizedMouse.set(mouse.x \/ (float)ofGetWindowWidth(), mouse.y \/ (float)ofGetWindowHeight());\n\t\t\n\t\tofVec2f velocity = normalizedMouse - lastNormalizedMouse;\n\t\t\/\/velocity.normalize();\n\t\t\n\t\tif (mouse.button == 0) {\n\t\t\t\n\t\t\tfor (int i=0; i<3; i++) {\n\t\t\t\tif (drawForces[i].getType() == FT_VELOCITY)\n\t\t\t\t\tdrawForces[i].setForce(velocity);\n\t\t\t\tdrawForces[i].applyForce(normalizedMouse);\n\t\t\t}\n\t\t}\n\t\telse if(mouse.button == 2)\n\t\t{\n\t\t\t\n\t\t\tfor (int i=3; i<6; i++) {\n\t\t\t\tif (drawForces[i].getType() == FT_VELOCITY)\n\t\t\t\t\tdrawForces[i].setForce(velocity);\n\t\t\t\tdrawForces[i].applyForce(normalizedMouse);\n\t\t\t}\n\t\t}\n\t\telse if (mouse.button == 1)\n\t\t{\n\t\t\tfor (int i = 6; i<9; i++) {\n\t\t\t\tif (drawForces[i].getType() == FT_VELOCITY)\n\t\t\t\t\tdrawForces[i].setForce(velocity);\n\t\t\t\tdrawForces[i].applyForce(normalizedMouse);\n\t\t\t}\n\t\t}\n\t\tlastNormalizedMouse.set(normalizedMouse);\n\t\t\n\t}\n\t\n\t\/\/---------------------------------------------------------------------------------------------\n\tvoid ftDrawInputForces::mouseMoved( ofMouseEventArgs& mouse ){\n\t\tofVec2f normalizedMouse;\n\n\t\tnormalizedMouse.set ( mouse.x \/ (float)ofGetWindowWidth()\n\t\t\t\t\t\t\t, mouse.y \/ (float)ofGetWindowHeight()\n\t\t\t\t\t\t\t);\n\n\t\tlastNormalizedMouse.set(normalizedMouse);\n\t}\n\n\t\/\/---------------------------------------------------------------------------------------------\n\tvoid ftDrawInputForces::touchDown( ofTouchEventArgs& touch)\n\t{\n\t\tofVec2f normalizedTouch;\n\t\tnormalizedTouch.set ( touch.x \/ (float)ofGetWindowWidth()\n\t\t\t\t\t\t\t , touch.y \/ (float)ofGetWindowHeight()\n\t\t\t\t\t\t\t);\n\t\tlastNormalizedTouch.set( normalizedTouch );\n\t}\n\n\t\/\/---------------------------------------------------------------------------------------------\n\tvoid ftDrawInputForces::touchMoved( ofTouchEventArgs& touch)\n\t{\n\t\tofVec2f normalizedTouch;\n\t\tnormalizedTouch.set( touch.x \/ (float)ofGetWindowWidth()\n\t\t\t\t\t\t\t , touch.y \/ (float)ofGetWindowHeight()\n\t\t);\n\n\t\tofVec2f normalizedTouchSpeed;\n\t\tnormalizedTouchSpeed.set( touch.xspeed \/ (float)ofGetWindowWidth()\n\t\t\t\t\t\t\t , touch.yspeed \/ (float)ofGetWindowHeight()\n\t\t);\n\n\t\tofVec2f normalizedTouchAccel;\n\t\tnormalizedTouchAccel.set( touch.xaccel \/ (float)ofGetWindowWidth()\n\t\t\t\t\t\t\t , touch.yaccel \/ (float)ofGetWindowHeight()\n\t\t);\n\n\t\tofVec2f velocity = normalizedTouch - lastNormalizedTouch;\n\t\t\/\/ofVec2f velocity = normalizedTouchSpeed;\n\t\tofVec2f acceleration = normalizedTouchAccel;\n\n\t\tfor( int i = 0; i<3; i++ )\n\t\t{\n\t\t\tif( drawForces[ i ].getType() == FT_VELOCITY )\n\t\t\t\tdrawForces[ i ].setForce( velocity );\n\t\t\tdrawForces[ i ].applyForce( normalizedTouch );\n\t\t}\n\n\t\tlastNormalizedTouch.set( normalizedTouch );\n\t}\n\t\n}<|endoftext|>"} {"text":"\/**************************************************************************\n\n The MIT License (MIT)\n\n Copyright (c) 2015 Dmitry Sovetov\n\n https:\/\/github.com\/dmsovetov\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n\n **************************************************************************\/\n\n#include \"Entity.h\"\n\nDC_BEGIN_DREEMCHEST\n\nnamespace Ecs {\n\n\/\/ ** Entity::Entity\nEntity::Entity( void ) : m_flags( 0 )\n{\n\n}\n\n\/\/ ** Entity::setEcs\nvoid Entity::setEcs( EcsWPtr value )\n{\n\tm_ecs = value;\n}\n\n\/\/ ** Entity::ecs\nEcsWPtr Entity::ecs( void ) const\n{\n\treturn m_ecs;\n}\n\n\/\/ ** Entity::setId\nvoid Entity::setId( const EntityId& value )\n{\n\tm_id = value;\n}\n\n\/\/ ** Entity::id\nconst EntityId& Entity::id( void ) const\n{\n\treturn m_id;\n}\n\n\/\/ ** Entity::clear\nvoid Entity::clear( void )\n{\n m_components.clear();\n}\n\n\/\/ ** Entity::isSerializable\nbool Entity::isSerializable( void ) const\n{\n return m_flags.is( Serializable );\n}\n\n\/\/ ** Entity::setSerializable\nvoid Entity::setSerializable( bool value )\n{\n m_flags.set( Serializable, value );\n}\n\n\/\/ ** Entity::mask\nconst Bitset& Entity::mask( void ) const\n{\n\treturn m_mask;\n}\n\n\/\/ ** Entity::components\nconst Entity::Components& Entity::components( void ) const\n{\n\treturn m_components;\n}\n\n\/\/ ** Entity::components\nEntity::Components& Entity::components( void )\n{\n\treturn m_components;\n}\n\n\/\/ ** Entity::queueRemoval\nvoid Entity::queueRemoval( void )\n{\n\tm_ecs->removeEntity( m_id );\n}\n\n\/\/ ** Entity::markAsRemoved\nvoid Entity::markAsRemoved( void )\n{\n\tm_flags.on( Removed );\n}\n\n\/\/ ** Entity::flags\nu8 Entity::flags( void ) const\n{\n\treturn m_flags;\n}\n\n\/\/ ** Entity::setFlags\nvoid Entity::setFlags( u8 value )\n{\n\tm_flags = value;\n}\n\n\/\/ ** Entity::updateComponentBit\nvoid Entity::updateComponentBit( u32 bit, bool value )\n{\n\tif( value ) {\n\t\tm_mask.set( bit );\n\t} else {\n\t\tm_mask.clear( bit );\n\t}\n\t\n\tif( m_ecs.valid() ) {\n\t\tm_ecs->notifyEntityChanged( m_id );\n\t}\n}\n\n\/\/ ** Entity::detachById\nvoid Entity::detachById( TypeIdx id )\n{\n\tDC_BREAK_IF( m_flags.is( Removed ) );\n\n\tComponents::iterator i = m_components.find( id );\n\tDC_BREAK_IF( i == m_components.end() );\n\tupdateComponentBit( i->second->typeIndex(), false );\n i->second->setParentEntity( NULL );\n\tm_components.erase( i );\n}\n\n#if DC_ECS_ENTITY_CLONING\n\n\/\/ ** Entity::deepCopy\nEntityPtr Entity::deepCopy( const EntityId& id ) const\n{\n \/\/ Create entity instance\n Ecs* ecs = const_cast( m_ecs.get() );\n EntityPtr entity = id.isNull() ? ecs->createEntity() : ecs->createEntity( id );\n\n \/\/ Now clone components\n for( Components::const_iterator i = m_components.begin(), end = m_components.end(); i != end; ++i ) {\n entity->attachComponent( i->second->deepCopy().get() );\n }\n\n return entity;\n}\n\n#endif \/* DC_ECS_ENTITY_CLONING *\/\n\n#ifndef DC_ECS_NO_SERIALIZATION\n\n\/\/ ** Entity::read\nvoid Entity::read( const Io::Storage* storage )\n{\n\tIo::KeyValue ar;\n ar.read( storage );\n\n SerializationContext ctx( ecs() );\n deserialize( ctx, ar );\n}\n\n\/\/ ** Entity::write\nvoid Entity::write( Io::Storage* storage ) const\n{\n SerializationContext ctx( ecs() );\n Io::KeyValue ar;\n\n serialize( ctx, ar );\n\tar.write( storage );\n}\n\n\/\/ ** Entity::serialize\nvoid Entity::serialize( SerializationContext& ctx, Io::KeyValue& ar ) const\n{\n\tar = Io::KeyValue::object();\n\n\tar[\"Type\"] = typeName();\n\tar[\"_id\"] = id()\/*.toString()*\/;\n ar[\"flags\"] = static_cast( m_flags );\n\n\tconst Components& items = components();\n\n\tfor( Components::const_iterator i = items.begin(), end = items.end(); i != end; ++i ) {\n\t\tCString key = i->second->typeName();\n\t\tIo::KeyValue component;\n\n i->second->serialize( ctx, component );\n\n\t\tif( component.isNull() ) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tar[key] = component;\n\t}\n}\n\n\/\/ ** Entity::deserialize\nvoid Entity::deserialize( SerializationContext& ctx, const Io::KeyValue& ar )\n{\n\tDC_BREAK_IF( ar.get( \"Type\", \"\" ).asString() != typeName() );\n\n\tComponents& items = components();\n\n \/\/ Set flags\n m_flags = ar[\"flags\"].asUByte();\n\n\t\/\/ Load all attached components\n\tfor( Components::iterator i = items.begin(), end = items.end(); i != end; ++i ) {\n\t\tCString key = i->second->typeName();\n const Io::KeyValue& kv = ar.get( key );\n\n if( kv.isNull() ) {\n log::verbose( \"Entity::deserialize : no data for component '%s'\\n\", key );\n continue;\n }\n\n i->second->deserialize( ctx, kv );\n\t}\n\t\n\t\/\/ Create components from key-value archive\n\tconst Io::KeyValue::Properties& kv = ar.properties();\n\n\tfor( Io::KeyValue::Properties::const_iterator i = kv.begin(); i != kv.end(); ++i ) {\n\t\tif( i->first == \"Type\" || i->first == \"_id\" || i->first == \"flags\" ) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tbool hasComponent = false;\n\n\t\tfor( Components::iterator j = items.begin(); j != items.end(); ++j ) {\n\t\t\tif( j->second->typeName() == i->first ) {\n\t\t\t\thasComponent = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif( hasComponent ) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif( i->second.isNull() ) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tComponentPtr component = ctx.createComponent( i->first );\n component->deserialize( ctx, i->second );\n\t\tattachComponent( component.get() );\n\t}\n}\n\n#endif \/* !DC_ECS_NO_SERIALIZATION *\/\n\n} \/\/ namespace Ecs\n\nDC_END_DREEMCHESTRemoved: deprecated debug break macro\/**************************************************************************\n\n The MIT License (MIT)\n\n Copyright (c) 2015 Dmitry Sovetov\n\n https:\/\/github.com\/dmsovetov\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n\n **************************************************************************\/\n\n#include \"Entity.h\"\n\nDC_BEGIN_DREEMCHEST\n\nnamespace Ecs {\n\n\/\/ ** Entity::Entity\nEntity::Entity( void ) : m_flags( 0 )\n{\n\n}\n\n\/\/ ** Entity::setEcs\nvoid Entity::setEcs( EcsWPtr value )\n{\n\tm_ecs = value;\n}\n\n\/\/ ** Entity::ecs\nEcsWPtr Entity::ecs( void ) const\n{\n\treturn m_ecs;\n}\n\n\/\/ ** Entity::setId\nvoid Entity::setId( const EntityId& value )\n{\n\tm_id = value;\n}\n\n\/\/ ** Entity::id\nconst EntityId& Entity::id( void ) const\n{\n\treturn m_id;\n}\n\n\/\/ ** Entity::clear\nvoid Entity::clear( void )\n{\n m_components.clear();\n}\n\n\/\/ ** Entity::isSerializable\nbool Entity::isSerializable( void ) const\n{\n return m_flags.is( Serializable );\n}\n\n\/\/ ** Entity::setSerializable\nvoid Entity::setSerializable( bool value )\n{\n m_flags.set( Serializable, value );\n}\n\n\/\/ ** Entity::mask\nconst Bitset& Entity::mask( void ) const\n{\n\treturn m_mask;\n}\n\n\/\/ ** Entity::components\nconst Entity::Components& Entity::components( void ) const\n{\n\treturn m_components;\n}\n\n\/\/ ** Entity::components\nEntity::Components& Entity::components( void )\n{\n\treturn m_components;\n}\n\n\/\/ ** Entity::queueRemoval\nvoid Entity::queueRemoval( void )\n{\n\tm_ecs->removeEntity( m_id );\n}\n\n\/\/ ** Entity::markAsRemoved\nvoid Entity::markAsRemoved( void )\n{\n\tm_flags.on( Removed );\n}\n\n\/\/ ** Entity::flags\nu8 Entity::flags( void ) const\n{\n\treturn m_flags;\n}\n\n\/\/ ** Entity::setFlags\nvoid Entity::setFlags( u8 value )\n{\n\tm_flags = value;\n}\n\n\/\/ ** Entity::updateComponentBit\nvoid Entity::updateComponentBit( u32 bit, bool value )\n{\n\tif( value ) {\n\t\tm_mask.set( bit );\n\t} else {\n\t\tm_mask.clear( bit );\n\t}\n\t\n\tif( m_ecs.valid() ) {\n\t\tm_ecs->notifyEntityChanged( m_id );\n\t}\n}\n\n\/\/ ** Entity::detachById\nvoid Entity::detachById( TypeIdx id )\n{\n\tDC_BREAK_IF( m_flags.is( Removed ) );\n\n\tComponents::iterator i = m_components.find( id );\n\tDC_BREAK_IF( i == m_components.end() );\n\tupdateComponentBit( i->second->typeIndex(), false );\n i->second->setParentEntity( NULL );\n\tm_components.erase( i );\n}\n\n#if DC_ECS_ENTITY_CLONING\n\n\/\/ ** Entity::deepCopy\nEntityPtr Entity::deepCopy( const EntityId& id ) const\n{\n \/\/ Create entity instance\n Ecs* ecs = const_cast( m_ecs.get() );\n EntityPtr entity = id.isNull() ? ecs->createEntity() : ecs->createEntity( id );\n\n \/\/ Now clone components\n for( Components::const_iterator i = m_components.begin(), end = m_components.end(); i != end; ++i ) {\n entity->attachComponent( i->second->deepCopy().get() );\n }\n\n return entity;\n}\n\n#endif \/* DC_ECS_ENTITY_CLONING *\/\n\n#ifndef DC_ECS_NO_SERIALIZATION\n\n\/\/ ** Entity::read\nvoid Entity::read( const Io::Storage* storage )\n{\n\tIo::KeyValue ar;\n ar.read( storage );\n\n SerializationContext ctx( ecs() );\n deserialize( ctx, ar );\n}\n\n\/\/ ** Entity::write\nvoid Entity::write( Io::Storage* storage ) const\n{\n SerializationContext ctx( ecs() );\n Io::KeyValue ar;\n\n serialize( ctx, ar );\n\tar.write( storage );\n}\n\n\/\/ ** Entity::serialize\nvoid Entity::serialize( SerializationContext& ctx, Io::KeyValue& ar ) const\n{\n\tar = Io::KeyValue::object();\n\n\tar[\"Type\"] = typeName();\n\tar[\"_id\"] = id()\/*.toString()*\/;\n ar[\"flags\"] = static_cast( m_flags );\n\n\tconst Components& items = components();\n\n\tfor( Components::const_iterator i = items.begin(), end = items.end(); i != end; ++i ) {\n\t\tCString key = i->second->typeName();\n\t\tIo::KeyValue component;\n\n i->second->serialize( ctx, component );\n\n\t\tif( component.isNull() ) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tar[key] = component;\n\t}\n}\n\n\/\/ ** Entity::deserialize\nvoid Entity::deserialize( SerializationContext& ctx, const Io::KeyValue& ar )\n{\n\/\/\tDC_BREAK_IF( ar.get( \"Type\", \"\" ).asString() != typeName() );\n\n\tComponents& items = components();\n\n \/\/ Set flags\n m_flags = ar[\"flags\"].asUByte();\n\n\t\/\/ Load all attached components\n\tfor( Components::iterator i = items.begin(), end = items.end(); i != end; ++i ) {\n\t\tCString key = i->second->typeName();\n const Io::KeyValue& kv = ar.get( key );\n\n if( kv.isNull() ) {\n log::verbose( \"Entity::deserialize : no data for component '%s'\\n\", key );\n continue;\n }\n\n i->second->deserialize( ctx, kv );\n\t}\n\t\n\t\/\/ Create components from key-value archive\n\tconst Io::KeyValue::Properties& kv = ar.properties();\n\n\tfor( Io::KeyValue::Properties::const_iterator i = kv.begin(); i != kv.end(); ++i ) {\n\t\tif( i->first == \"Type\" || i->first == \"_id\" || i->first == \"flags\" ) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tbool hasComponent = false;\n\n\t\tfor( Components::iterator j = items.begin(); j != items.end(); ++j ) {\n\t\t\tif( j->second->typeName() == i->first ) {\n\t\t\t\thasComponent = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif( hasComponent ) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif( i->second.isNull() ) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tComponentPtr component = ctx.createComponent( i->first );\n component->deserialize( ctx, i->second );\n\t\tattachComponent( component.get() );\n\t}\n}\n\n#endif \/* !DC_ECS_NO_SERIALIZATION *\/\n\n} \/\/ namespace Ecs\n\nDC_END_DREEMCHEST<|endoftext|>"} {"text":"#include \"movepicker.h\"\n#include \"eval.h\"\n#include \"defs.h\"\n\n\/\/ Indexed by [victimValue][attackerValue]\nint MovePicker::_mvvLvaTable[5][6];\n\nvoid MovePicker::init() {\n int currScore = 0;\n PieceType victimsLoToHi[] = {PAWN, KNIGHT, BISHOP, ROOK, QUEEN};\n PieceType attackersHiToLo[] = {KING, QUEEN, ROOK, BISHOP, KNIGHT, PAWN};\n\n \/\/ Iterate over victims (low to high)\n for (auto victim : victimsLoToHi) {\n \/\/ Iterate over attackers (high to low)\n for (auto attacker : attackersHiToLo) {\n _mvvLvaTable[victim][attacker] = currScore;\n currScore ++;\n }\n }\n}\n\nMovePicker::MovePicker(const OrderingInfo* orderingInfo, const Board* board, MoveList* moveList) {\n _orderingInfo = orderingInfo;\n _moves = moveList;\n _board = board;\n _currHead = 0; \n _scoreMoves();\n}\n\nvoid MovePicker::_scoreMoves() {\n const TranspTableEntry* ttEntry = _orderingInfo->getTt()->getEntry(_board->getZKey());\n Move pvMove;\n if (ttEntry) {\n pvMove = ttEntry->getBestMove();\n }\n\n for (auto &move : *_moves) {\n Board tempBoard = *_board;\n tempBoard.doMove(move);\n\n if (move == pvMove) {\n move.setValue(INF);\n } else if (move.getFlags() & Move::CAPTURE) {\n move.setValue(CAPTURE_BONUS + _mvvLvaTable[move.getCapturedPieceType()][move.getPieceType()]);\n } else if (move.getFlags() & Move::PROMOTION) {\n move.setValue(PROMOTION_BONUS + Eval::getMaterialValue(move.getPromotionPieceType()));\n } else if (move == _orderingInfo->getKiller1(_orderingInfo->getPly())) {\n move.setValue(KILLER1_BONUS);\n } else if (move == _orderingInfo->getKiller2(_orderingInfo->getPly())) {\n move.setValue(KILLER2_BONUS);\n } else { \/\/ Quiet\n move.setValue(QUIET_BONUS + _orderingInfo->getHistory(_board->getActivePlayer(), move.getFrom(), move.getTo()));\n }\n }\n}\n\nbool MovePicker::hasNext() const {\n return _currHead < _moves->size();\n}\n\nMove MovePicker::getNext() {\n size_t bestIndex;\n int bestScore = -INF;\n\n for (size_t i=_currHead;i<_moves->size();i++) {\n if (_moves->at(i).getValue() > bestScore) {\n bestScore = _moves->at(i).getValue();\n bestIndex = i;\n }\n }\n\n std::swap(_moves->at(_currHead), _moves->at(bestIndex));\n _currHead ++;\n return _moves->at(_currHead-1);\n}Inline ++ operators in movepicker.cc#include \"movepicker.h\"\n#include \"eval.h\"\n#include \"defs.h\"\n\n\/\/ Indexed by [victimValue][attackerValue]\nint MovePicker::_mvvLvaTable[5][6];\n\nvoid MovePicker::init() {\n int currScore = 0;\n PieceType victimsLoToHi[] = {PAWN, KNIGHT, BISHOP, ROOK, QUEEN};\n PieceType attackersHiToLo[] = {KING, QUEEN, ROOK, BISHOP, KNIGHT, PAWN};\n\n \/\/ Iterate over victims (low to high)\n for (auto victim : victimsLoToHi) {\n \/\/ Iterate over attackers (high to low)\n for (auto attacker : attackersHiToLo) {\n _mvvLvaTable[victim][attacker] = currScore++;\n }\n }\n}\n\nMovePicker::MovePicker(const OrderingInfo* orderingInfo, const Board* board, MoveList* moveList) {\n _orderingInfo = orderingInfo;\n _moves = moveList;\n _board = board;\n _currHead = 0; \n _scoreMoves();\n}\n\nvoid MovePicker::_scoreMoves() {\n const TranspTableEntry* ttEntry = _orderingInfo->getTt()->getEntry(_board->getZKey());\n Move pvMove;\n if (ttEntry) {\n pvMove = ttEntry->getBestMove();\n }\n\n for (auto &move : *_moves) {\n Board tempBoard = *_board;\n tempBoard.doMove(move);\n\n if (move == pvMove) {\n move.setValue(INF);\n } else if (move.getFlags() & Move::CAPTURE) {\n move.setValue(CAPTURE_BONUS + _mvvLvaTable[move.getCapturedPieceType()][move.getPieceType()]);\n } else if (move.getFlags() & Move::PROMOTION) {\n move.setValue(PROMOTION_BONUS + Eval::getMaterialValue(move.getPromotionPieceType()));\n } else if (move == _orderingInfo->getKiller1(_orderingInfo->getPly())) {\n move.setValue(KILLER1_BONUS);\n } else if (move == _orderingInfo->getKiller2(_orderingInfo->getPly())) {\n move.setValue(KILLER2_BONUS);\n } else { \/\/ Quiet\n move.setValue(QUIET_BONUS + _orderingInfo->getHistory(_board->getActivePlayer(), move.getFrom(), move.getTo()));\n }\n }\n}\n\nbool MovePicker::hasNext() const {\n return _currHead < _moves->size();\n}\n\nMove MovePicker::getNext() {\n size_t bestIndex;\n int bestScore = -INF;\n\n for (size_t i=_currHead;i<_moves->size();i++) {\n if (_moves->at(i).getValue() > bestScore) {\n bestScore = _moves->at(i).getValue();\n bestIndex = i;\n }\n }\n\n std::swap(_moves->at(_currHead), _moves->at(bestIndex));\n return _moves->at(_currHead++);\n}<|endoftext|>"} {"text":"\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2013-2016.\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/www.opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#include \n#include \n\n#include \n#include \n\n#include \"test.hpp\"\n\nnamespace {\n\nvoid test_base(){\n std::list a{1, 0, 0, 2, 3, 4};\n\n check(a.size() == 6, \"Invalid list:size\");\n check(a.front()== 1, \"Invalid list:[]\");\n check(a.back() == 4, \"Invalid list:[]\");\n\n check(*a.begin() == 1);\n}\n\ntemplate\nIterator advance(Iterator it, size_t n){\n for(size_t i = 0; i < n; ++i){\n ++it;\n }\n\n return it;\n}\n\nvoid test_erase(){\n std::list a{1, 0, 0, 2, 3, 4};\n\n a.erase(advance(a.begin(), 2));\n\n check(a.size() == 5, \"Invalid list:size\");\n check(a.front() == 1, \"Invalid list:front()\");\n check(a.back() == 4, \"Invalid list:back()\");\n\n check(*a.begin() == 1, \"erase: Invalid element 0\");\n check(*advance(a.begin(),1) == 0, \"erase: Invalid element 1\");\n check(*advance(a.begin(),2) == 2, \"erase: Invalid element 2\");\n check(*advance(a.begin(),3) == 3, \"erase: Invalid element 3\");\n check(*advance(a.begin(),4) == 4, \"erase: Invalid element 4\");\n\n a.erase(a.begin());\n\n check(a.size() == 4, \"erase: Invalid list:size\");\n check(a.front() == 0, \"erase: Invalid list:front()\");\n check(a.back() == 4, \"erase: Invalid list:back()\");\n\n check(*a.begin() == 0, \"erase: Invalid element 0 \");\n check(*advance(a.begin(),1) == 2, \"erase: Invalid element 1\");\n check(*advance(a.begin(),2) == 3, \"erase: Invalid element 2\");\n check(*advance(a.begin(),3) == 4, \"erase: Invalid element 3\");\n}\n\nvoid test_erase_range(){\n std::list a{1, 0, 0, 2, 3, 4};\n\n a.erase(advance(a.begin(), 1), advance(a.begin(), 4));\n\n check(a.size() == 3, \"erase_range: Invalid list:size\");\n check(a.front() == 1, \"erase_range: Invalid list:[]\");\n check(a.back() == 4, \"erase_range: Invalid list:[]\");\n\n check(*a.begin() == 1);\n}\n\nvoid test_erase_remove(){\n std::list a{1, 0, 0, 2, 3, 4};\n\n a.erase(std::remove(a.begin(), a.end(), 0), a.end());\n\n check(a.size() == 4, \"erase_remove: Invalid list:size\");\n check(a.front() == 1, \"erase_remove: Invalid list:front()\");\n check(a.back() == 4, \"erase_remove: Invalid list:back()\");\n\n check(*a.begin() == 1, \"erase_remove: Invalid begin()\");\n}\n\nvoid test_erase_remove_if(){\n std::list a{1, 0, 0, 2, 3, 4};\n\n a.erase(std::remove_if(a.begin(), a.end(), [](int value){\n return value == 1 || value == 3;\n }), a.end());\n\n check(a.size() == 4, \"erase_remove_if: Invalid list:size\");\n check(a.front() == 0, \"erase_remove_if: Invalid list:front()\");\n check(a.back() == 4, \"erase_remove_if: Invalid list:back()\");\n\n check(*a.begin() == 0);\n}\n\nvoid test_push_front(){\n std::list a{1, 0, 0, 2, 3, 4};\n\n a.push_front(99);\n\n check(a.size() == 7, \"Invalid list:size\");\n check(a.front() == 99, \"Invalid list:[]\");\n check(a.back() == 4, \"Invalid list:[]\");\n\n check(*a.begin() == 99);\n}\n\nvoid test_iterator(){\n std::list a{1, 0, 0, 2, 3, 4};\n\n auto it = a.begin();\n auto end = a.end();\n\n check(it != end, \"Invalid iterator\");\n check(*it == 1, \"Invalid iterator\");\n\n ++it;\n check(it != end, \"Invalid iterator\");\n check(*it == 0, \"Invalid iterator\");\n\n ++it;\n check(it != end, \"Invalid iterator\");\n check(*it == 0, \"Invalid iterator\");\n\n ++it;\n check(it != end, \"Invalid iterator\");\n check(*it == 2, \"Invalid iterator\");\n\n ++it;\n check(it != end, \"Invalid iterator\");\n check(*it == 3, \"Invalid iterator\");\n\n ++it;\n check(it != end, \"Invalid iterator\");\n check(*it == 4, \"Invalid iterator\");\n\n ++it;\n check(it == end, \"Invalid iterator\");\n}\n\nvoid test_reverse_iterator(){\n std::list a{1, 0, 0, 2, 3, 4};\n\n auto it = a.rbegin();\n auto end = a.rend();\n\n check(it != end, \"Invalid reverse iterator\");\n check(*it == 4, \"Invalid reverse iterator\");\n\n ++it;\n check(it != end, \"Invalid reverse iterator\");\n check(*it == 3, \"Invalid reverse iterator\");\n\n ++it;\n check(it != end, \"Invalid reverse iterator\");\n check(*it == 2, \"Invalid reverse iterator\");\n\n ++it;\n check(it != end, \"Invalid reverse iterator\");\n check(*it == 0, \"Invalid reverse iterator\");\n\n ++it;\n check(it != end, \"Invalid reverse iterator\");\n check(*it == 0, \"Invalid reverse iterator\");\n\n ++it;\n check(it != end, \"Invalid reverse iterator\");\n check(*it == 1, \"Invalid reverse iterator\");\n\n ++it;\n check(it == end, \"Invalid reverse iterator\");\n}\n\n} \/\/end of anonymous namespace\n\nvoid list_tests(){\n test_base();\n test_erase();\n test_erase_range();\n test_erase_remove();\n test_erase_remove_if();\n test_push_front();\n test_iterator();\n test_reverse_iterator();\n}\nMore tests for std::list\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2013-2016.\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/www.opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#include \n#include \n\n#include \n#include \n\n#include \"test.hpp\"\n\nnamespace {\n\nvoid test_base(){\n std::list a{1, 0, 0, 2, 3, 4};\n\n check(a.size() == 6, \"Invalid list:size\");\n check(a.front()== 1, \"Invalid list:[]\");\n check(a.back() == 4, \"Invalid list:[]\");\n\n check(*a.begin() == 1);\n}\n\ntemplate\nIterator advance(Iterator it, size_t n){\n for(size_t i = 0; i < n; ++i){\n ++it;\n }\n\n return it;\n}\n\nvoid test_erase(){\n std::list a{1, 0, 0, 2, 3, 4};\n\n a.erase(advance(a.begin(), 2));\n\n check(a.size() == 5, \"Invalid list:size\");\n check(a.front() == 1, \"Invalid list:front()\");\n check(a.back() == 4, \"Invalid list:back()\");\n\n check(*a.begin() == 1, \"erase: Invalid element 0\");\n check(*advance(a.begin(),1) == 0, \"erase: Invalid element 1\");\n check(*advance(a.begin(),2) == 2, \"erase: Invalid element 2\");\n check(*advance(a.begin(),3) == 3, \"erase: Invalid element 3\");\n check(*advance(a.begin(),4) == 4, \"erase: Invalid element 4\");\n\n a.erase(a.begin());\n\n check(a.size() == 4, \"erase: Invalid list:size\");\n check(a.front() == 0, \"erase: Invalid list:front()\");\n check(a.back() == 4, \"erase: Invalid list:back()\");\n\n check(*a.begin() == 0, \"erase: Invalid element 0 \");\n check(*advance(a.begin(),1) == 2, \"erase: Invalid element 1\");\n check(*advance(a.begin(),2) == 3, \"erase: Invalid element 2\");\n check(*advance(a.begin(),3) == 4, \"erase: Invalid element 3\");\n}\n\nvoid test_erase_range(){\n std::list a{1, 0, 0, 2, 3, 4};\n\n a.erase(advance(a.begin(), 1), advance(a.begin(), 4));\n\n check(a.size() == 3, \"erase_range: Invalid list:size\");\n check(a.front() == 1, \"erase_range: Invalid list:[]\");\n check(a.back() == 4, \"erase_range: Invalid list:[]\");\n\n check(*a.begin() == 1);\n}\n\nvoid test_erase_remove(){\n std::list a{1, 0, 0, 2, 3, 4};\n\n a.erase(std::remove(a.begin(), a.end(), 0), a.end());\n\n check(a.size() == 4, \"erase_remove: Invalid list:size\");\n check(a.front() == 1, \"erase_remove: Invalid list:front()\");\n check(a.back() == 4, \"erase_remove: Invalid list:back()\");\n\n check(*a.begin() == 1, \"erase_remove: Invalid begin()\");\n}\n\nvoid test_erase_remove_if(){\n std::list a{1, 0, 0, 2, 3, 4};\n\n a.erase(std::remove_if(a.begin(), a.end(), [](int value){\n return value == 1 || value == 3;\n }), a.end());\n\n check(a.size() == 4, \"erase_remove_if: Invalid list:size\");\n check(a.front() == 0, \"erase_remove_if: Invalid list:front()\");\n check(a.back() == 4, \"erase_remove_if: Invalid list:back()\");\n\n check(*a.begin() == 0);\n}\n\nvoid test_push_front(){\n std::list a{1, 0, 0, 2, 3, 4};\n\n a.push_front(99);\n\n check(a.size() == 7, \"Invalid list:size\");\n check(a.front() == 99, \"Invalid list:[]\");\n check(a.back() == 4, \"Invalid list:[]\");\n\n check(*a.begin() == 99);\n}\n\nvoid test_push_back(){\n std::list a{1, 0, 0, 2, 3, 4};\n\n a.push_back(99);\n\n check(a.size() == 7, \"Invalid list:size\");\n check(a.front() == 1, \"Invalid list:[]\");\n check(a.back() == 99, \"Invalid list:[]\");\n\n check(*a.begin() == 1);\n}\n\nvoid test_iterator(){\n std::list a{1, 0, 0, 2, 3, 4};\n\n auto it = a.begin();\n auto end = a.end();\n\n check(it != end, \"Invalid iterator\");\n check(*it == 1, \"Invalid iterator\");\n\n ++it;\n check(it != end, \"Invalid iterator\");\n check(*it == 0, \"Invalid iterator\");\n\n ++it;\n check(it != end, \"Invalid iterator\");\n check(*it == 0, \"Invalid iterator\");\n\n ++it;\n check(it != end, \"Invalid iterator\");\n check(*it == 2, \"Invalid iterator\");\n\n ++it;\n check(it != end, \"Invalid iterator\");\n check(*it == 3, \"Invalid iterator\");\n\n ++it;\n check(it != end, \"Invalid iterator\");\n check(*it == 4, \"Invalid iterator\");\n\n ++it;\n check(it == end, \"Invalid iterator\");\n}\n\nvoid test_reverse_iterator(){\n std::list a{1, 0, 0, 2, 3, 4};\n\n auto it = a.rbegin();\n auto end = a.rend();\n\n check(it != end, \"Invalid reverse iterator\");\n check(*it == 4, \"Invalid reverse iterator\");\n\n ++it;\n check(it != end, \"Invalid reverse iterator\");\n check(*it == 3, \"Invalid reverse iterator\");\n\n ++it;\n check(it != end, \"Invalid reverse iterator\");\n check(*it == 2, \"Invalid reverse iterator\");\n\n ++it;\n check(it != end, \"Invalid reverse iterator\");\n check(*it == 0, \"Invalid reverse iterator\");\n\n ++it;\n check(it != end, \"Invalid reverse iterator\");\n check(*it == 0, \"Invalid reverse iterator\");\n\n ++it;\n check(it != end, \"Invalid reverse iterator\");\n check(*it == 1, \"Invalid reverse iterator\");\n\n ++it;\n check(it == end, \"Invalid reverse iterator\");\n}\n\nvoid test_lots() {\n std::list vec;\n\n for(size_t i = 0; i < 1000; ++i){\n vec.push_back(i);\n }\n\n for(size_t i = 10000; i < 11000; ++i){\n vec.push_front(i);\n }\n\n auto it = vec.begin();\n for(size_t i = 0; i < 1000; ++i){\n check_equals(*it, 10999 - i, \"test_lots: invalid iterator\");\n ++it;\n }\n\n for(size_t i = 1000; i < 2000; ++i){\n check_equals(*it, i - 1000, \"test_lots: invalid iterator\");\n ++it;\n }\n\n check_equals(vec.size(), 2000, \"test_lots: invalid size()\");\n check_equals(vec.front(), 10999, \"test_lots: invalid front()\");\n check_equals(vec.back(), 999, \"test_lots: invalid back()\");\n\n for(size_t i = 0; i < 1000; ++i){\n vec.pop_back();\n }\n\n check_equals(vec.size(), 1000, \"test_lots: invalid size()\");\n check_equals(vec.front(), 10999, \"test_lots: invalid front()\");\n check_equals(vec.back(), 10000, \"test_lots: invalid back()\");\n\n for(size_t i = 0; i < 500; ++i){\n vec.pop_front();\n }\n\n check_equals(vec.size(), 500, \"test_lots: invalid size()\");\n check_equals(vec.front(), 10499, \"test_lots: invalid front()\");\n check_equals(vec.back(), 10000, \"test_lots: invalid back()\");\n}\n\n} \/\/end of anonymous namespace\n\nvoid list_tests(){\n test_base();\n test_erase();\n test_erase_range();\n test_erase_remove();\n test_erase_remove_if();\n test_push_front();\n test_push_back();\n test_iterator();\n test_reverse_iterator();\n test_lots();\n}\n<|endoftext|>"} {"text":"#include \".\/label_collision_force.h\"\n#include \n#include \n#include \"..\/math\/aabb2d.h\"\n#include \".\/label_state.h\"\n\nnamespace Forces\n{\nLabelCollisionForce::LabelCollisionForce() : Force(\"Label Collision\", 1.0f)\n{\n}\n\nEigen::Vector2f LabelCollisionForce::calculate(LabelState &label,\n std::vector &labels)\n{\n Eigen::Vector2f result(0, 0);\n\n for (auto &otherLabel : labels)\n {\n if (otherLabel.id == label.id)\n continue;\n\n Math::Aabb2d aabb(label.labelPosition2D, 0.5f * label.size);\n Math::Aabb2d otherAabb(otherLabel.labelPosition2D, 0.5f * otherLabel.size);\n\n if (aabb.testAabb(otherAabb))\n {\n qWarning() << \"Collision between:\" << label.text.c_str() << \"and\"\n << otherLabel.text.c_str();\n Eigen::Vector2f diff = label.labelPosition2D - otherLabel.labelPosition2D;\n result += diff.normalized();\n }\n }\n\n return result;\n}\n} \/\/ namespace Forces\nFix linting error.#include \".\/label_collision_force.h\"\n#include \n#include \n#include \"..\/math\/aabb2d.h\"\n#include \".\/label_state.h\"\n\nnamespace Forces\n{\nLabelCollisionForce::LabelCollisionForce() : Force(\"Label Collision\", 1.0f)\n{\n}\n\nEigen::Vector2f LabelCollisionForce::calculate(LabelState &label,\n std::vector &labels)\n{\n Eigen::Vector2f result(0, 0);\n\n for (auto &otherLabel : labels)\n {\n if (otherLabel.id == label.id)\n continue;\n\n Math::Aabb2d aabb(label.labelPosition2D, 0.5f * label.size);\n Math::Aabb2d otherAabb(otherLabel.labelPosition2D, 0.5f * otherLabel.size);\n\n if (aabb.testAabb(otherAabb))\n {\n qWarning() << \"Collision between:\" << label.text.c_str() << \"and\"\n << otherLabel.text.c_str();\n Eigen::Vector2f diff = label.labelPosition2D - otherLabel.labelPosition2D;\n result += diff.normalized();\n }\n }\n\n return result;\n}\n} \/\/ namespace Forces\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"lib\/RtMidi\/RtMidi.h\"\n#include \"lib\/RtMidi\/RtMidi.cpp\"\n\nclass NodeMidiOutput : public Nan::ObjectWrap\n{\nprivate:\n RtMidiOut* out;\npublic:\n static Nan::Persistent s_ct;\n static void Init(v8::Handle target)\n {\n Nan::HandleScope scope;\n\n v8::Local t = Nan::New(NodeMidiOutput::New);\n\n s_ct.Reset(t);\n t->SetClassName(Nan::New(\"NodeMidiOutput\").ToLocalChecked());\n t->InstanceTemplate()->SetInternalFieldCount(1);\n\n Nan::SetPrototypeMethod(t, \"getPortCount\", GetPortCount);\n Nan::SetPrototypeMethod(t, \"getPortName\", GetPortName);\n\n Nan::SetPrototypeMethod(t, \"openPort\", OpenPort);\n Nan::SetPrototypeMethod(t, \"openVirtualPort\", OpenVirtualPort);\n Nan::SetPrototypeMethod(t, \"closePort\", ClosePort);\n\n Nan::SetPrototypeMethod(t, \"sendMessage\", SendMessage);\n\n target->Set(Nan::New(\"output\").ToLocalChecked(), t->GetFunction());\n }\n\n NodeMidiOutput()\n {\n out = new RtMidiOut();\n }\n\n ~NodeMidiOutput()\n {\n delete out;\n }\n\n static NAN_METHOD(New)\n {\n Nan::HandleScope scope;\n\n if (!info.IsConstructCall()) {\n return Nan::ThrowTypeError(\"Use the new operator to create instances of this object.\");\n }\n\n NodeMidiOutput* output = new NodeMidiOutput();\n output->Wrap(info.This());\n\n info.GetReturnValue().Set(info.This());\n }\n\n static NAN_METHOD(GetPortCount)\n {\n Nan::HandleScope scope;\n NodeMidiOutput* output = Nan::ObjectWrap::Unwrap(info.This());\n v8::Local result = Nan::New(output->out->getPortCount());\n info.GetReturnValue().Set(result);\n }\n\n static NAN_METHOD(GetPortName)\n {\n Nan::HandleScope scope;\n NodeMidiOutput* output = Nan::ObjectWrap::Unwrap(info.This());\n if (info.Length() == 0 || !info[0]->IsUint32()) {\n return Nan::ThrowTypeError(\"First argument must be an integer\");\n }\n\n unsigned int portNumber = info[0]->Uint32Value();\n v8::Local result = Nan::New(output->out->getPortName(portNumber).c_str()).ToLocalChecked();\n info.GetReturnValue().Set(result);\n }\n\n static NAN_METHOD(OpenPort)\n {\n Nan::HandleScope scope;\n NodeMidiOutput* output = Nan::ObjectWrap::Unwrap(info.This());\n if (info.Length() == 0 || !info[0]->IsUint32()) {\n return Nan::ThrowTypeError(\"First argument must be an integer\");\n }\n unsigned int portNumber = info[0]->Uint32Value();\n if (portNumber >= output->out->getPortCount()) {\n return Nan::ThrowRangeError(\"Invalid MIDI port number\");\n }\n\n output->out->openPort(portNumber);\n return;\n }\n\n static NAN_METHOD(OpenVirtualPort)\n {\n Nan::HandleScope scope;\n NodeMidiOutput* output = Nan::ObjectWrap::Unwrap(info.This());\n if (info.Length() == 0 || !info[0]->IsString()) {\n return Nan::ThrowTypeError(\"First argument must be a string\");\n }\n\n std::string name(*v8::String::Utf8Value(info[0].As()));\n\n output->out->openVirtualPort(name);\n return;\n }\n\n static NAN_METHOD(ClosePort)\n {\n Nan::HandleScope scope;\n NodeMidiOutput* output = Nan::ObjectWrap::Unwrap(info.This());\n output->out->closePort();\n return;\n }\n\n static NAN_METHOD(SendMessage)\n {\n Nan::HandleScope scope;\n NodeMidiOutput* output = Nan::ObjectWrap::Unwrap(info.This());\n if (info.Length() == 0 || !info[0]->IsArray()) {\n return Nan::ThrowTypeError(\"First argument must be an array\");\n }\n\n v8::Local message = info[0]->ToObject();\n int32_t messageLength = message->Get(Nan::New(\"length\").ToLocalChecked())->Int32Value();\n std::vector messageOutput;\n for (int32_t i = 0; i != messageLength; ++i) {\n messageOutput.push_back(message->Get(Nan::New(i))->Int32Value());\n }\n output->out->sendMessage(&messageOutput);\n return;\n }\n};\n\nconst char* symbol_emit = \"emit\";\nconst char* symbol_message = \"message\";\n\nclass NodeMidiInput : public Nan::ObjectWrap\n{\nprivate:\n RtMidiIn* in;\n\npublic:\n uv_async_t message_async;\n uv_mutex_t message_mutex;\n\n struct MidiMessage\n {\n double deltaTime;\n std::vector message;\n };\n std::queue message_queue;\n\n static Nan::Persistent s_ct;\n static void Init(v8::Handle target)\n {\n Nan::HandleScope scope;\n\n v8::Local t = Nan::New(NodeMidiInput::New);\n\n s_ct.Reset(t);\n t->SetClassName(Nan::New(\"NodeMidiInput\").ToLocalChecked());\n t->InstanceTemplate()->SetInternalFieldCount(1);\n\n Nan::SetPrototypeMethod(t, \"getPortCount\", GetPortCount);\n Nan::SetPrototypeMethod(t, \"getPortName\", GetPortName);\n\n Nan::SetPrototypeMethod(t, \"openPort\", OpenPort);\n Nan::SetPrototypeMethod(t, \"openVirtualPort\", OpenVirtualPort);\n Nan::SetPrototypeMethod(t, \"closePort\", ClosePort);\n\n Nan::SetPrototypeMethod(t, \"ignoreTypes\", IgnoreTypes);\n\n target->Set(Nan::New(\"input\").ToLocalChecked(), t->GetFunction());\n }\n\n NodeMidiInput()\n {\n in = new RtMidiIn();\n uv_mutex_init(&message_mutex);\n }\n\n ~NodeMidiInput()\n {\n in->closePort();\n delete in;\n uv_mutex_destroy(&message_mutex);\n }\n\n static NAUV_WORK_CB(EmitMessage)\n {\n Nan::HandleScope scope;\n NodeMidiInput *input = static_cast(async->data);\n uv_mutex_lock(&input->message_mutex);\n v8::Local emitFunction = input->handle()->Get(Nan::New(symbol_emit).ToLocalChecked()).As();\n while (!input->message_queue.empty())\n {\n MidiMessage* message = input->message_queue.front();\n v8::Local info[3];\n info[0] = Nan::New(symbol_message).ToLocalChecked();\n info[1] = Nan::New(message->deltaTime);\n int32_t count = (int32_t)message->message.size();\n v8::Local data = Nan::New(count);\n for (int32_t i = 0; i < count; ++i) {\n data->Set(Nan::New(i), Nan::New(message->message[i]));\n }\n info[2] = data;\n Nan::MakeCallback(input->handle(), emitFunction, 3, info);\n input->message_queue.pop();\n delete message;\n }\n uv_mutex_unlock(&input->message_mutex);\n }\n\n static void Callback(double deltaTime, std::vector *message, void *userData)\n {\n NodeMidiInput *input = static_cast(userData);\n MidiMessage* data = new MidiMessage();\n data->deltaTime = deltaTime;\n data->message = *message;\n uv_mutex_lock(&input->message_mutex);\n input->message_queue.push(data);\n uv_mutex_unlock(&input->message_mutex);\n uv_async_send(&input->message_async);\n }\n\n static NAN_METHOD(New)\n {\n Nan::HandleScope scope;\n\n if (!info.IsConstructCall()) {\n return Nan::ThrowTypeError(\"Use the new operator to create instances of this object.\");\n }\n\n NodeMidiInput* input = new NodeMidiInput();\n input->message_async.data = input;\n uv_async_init(uv_default_loop(), &input->message_async, NodeMidiInput::EmitMessage);\n input->Wrap(info.This());\n\n info.GetReturnValue().Set(info.This());\n }\n\n static NAN_METHOD(GetPortCount)\n {\n Nan::HandleScope scope;\n NodeMidiInput* input = Nan::ObjectWrap::Unwrap(info.This());\n v8::Local result = Nan::New(input->in->getPortCount());\n info.GetReturnValue().Set(result);\n }\n\n static NAN_METHOD(GetPortName)\n {\n Nan::HandleScope scope;\n NodeMidiInput* input = Nan::ObjectWrap::Unwrap(info.This());\n if (info.Length() == 0 || !info[0]->IsUint32()) {\n return Nan::ThrowTypeError(\"First argument must be an integer\");\n }\n\n unsigned int portNumber = info[0]->Uint32Value();\n v8::Local result = Nan::New(input->in->getPortName(portNumber).c_str()).ToLocalChecked();\n info.GetReturnValue().Set(result);\n }\n\n static NAN_METHOD(OpenPort)\n {\n Nan::HandleScope scope;\n NodeMidiInput* input = Nan::ObjectWrap::Unwrap(info.This());\n if (info.Length() == 0 || !info[0]->IsUint32()) {\n return Nan::ThrowTypeError(\"First argument must be an integer\");\n }\n unsigned int portNumber = info[0]->Uint32Value();\n if (portNumber >= input->in->getPortCount()) {\n return Nan::ThrowRangeError(\"Invalid MIDI port number\");\n }\n\n input->Ref();\n input->in->setCallback(&NodeMidiInput::Callback, Nan::ObjectWrap::Unwrap(info.This()));\n input->in->openPort(portNumber);\n return;\n }\n\n static NAN_METHOD(OpenVirtualPort)\n {\n Nan::HandleScope scope;\n NodeMidiInput* input = Nan::ObjectWrap::Unwrap(info.This());\n if (info.Length() == 0 || !info[0]->IsString()) {\n return Nan::ThrowTypeError(\"First argument must be a string\");\n }\n\n std::string name(*v8::String::Utf8Value(info[0].As()));\n\n input->Ref();\n input->in->setCallback(&NodeMidiInput::Callback, Nan::ObjectWrap::Unwrap(info.This()));\n input->in->openVirtualPort(name);\n return;\n }\n\n static NAN_METHOD(ClosePort)\n {\n Nan::HandleScope scope;\n NodeMidiInput* input = Nan::ObjectWrap::Unwrap(info.This());\n if (input->in->isPortOpen()) {\n input->Unref();\n }\n input->in->cancelCallback();\n input->in->closePort();\n uv_close((uv_handle_t*)&input->message_async, NULL);\n return;\n }\n\n static NAN_METHOD(IgnoreTypes)\n {\n Nan::HandleScope scope;\n NodeMidiInput* input = Nan::ObjectWrap::Unwrap(info.This());\n if (info.Length() != 3 || !info[0]->IsBoolean() || !info[1]->IsBoolean() || !info[2]->IsBoolean()) {\n return Nan::ThrowTypeError(\"Arguments must be boolean\");\n }\n\n bool filter_sysex = info[0]->BooleanValue();\n bool filter_timing = info[1]->BooleanValue();\n bool filter_sensing = info[2]->BooleanValue();\n input->in->ignoreTypes(filter_sysex, filter_timing, filter_sensing);\n return;\n }\n};\n\nNan::Persistent NodeMidiOutput::s_ct;\nNan::Persistent NodeMidiInput::s_ct;\n\nextern \"C\" {\n void init (v8::Handle target)\n {\n NodeMidiOutput::Init(target);\n NodeMidiInput::Init(target);\n }\n NODE_MODULE(midi, init)\n}\nremove unused headers#include \n#include \n#include \n\n#include \"lib\/RtMidi\/RtMidi.h\"\n#include \"lib\/RtMidi\/RtMidi.cpp\"\n\nclass NodeMidiOutput : public Nan::ObjectWrap\n{\nprivate:\n RtMidiOut* out;\npublic:\n static Nan::Persistent s_ct;\n static void Init(v8::Handle target)\n {\n Nan::HandleScope scope;\n\n v8::Local t = Nan::New(NodeMidiOutput::New);\n\n s_ct.Reset(t);\n t->SetClassName(Nan::New(\"NodeMidiOutput\").ToLocalChecked());\n t->InstanceTemplate()->SetInternalFieldCount(1);\n\n Nan::SetPrototypeMethod(t, \"getPortCount\", GetPortCount);\n Nan::SetPrototypeMethod(t, \"getPortName\", GetPortName);\n\n Nan::SetPrototypeMethod(t, \"openPort\", OpenPort);\n Nan::SetPrototypeMethod(t, \"openVirtualPort\", OpenVirtualPort);\n Nan::SetPrototypeMethod(t, \"closePort\", ClosePort);\n\n Nan::SetPrototypeMethod(t, \"sendMessage\", SendMessage);\n\n target->Set(Nan::New(\"output\").ToLocalChecked(), t->GetFunction());\n }\n\n NodeMidiOutput()\n {\n out = new RtMidiOut();\n }\n\n ~NodeMidiOutput()\n {\n delete out;\n }\n\n static NAN_METHOD(New)\n {\n Nan::HandleScope scope;\n\n if (!info.IsConstructCall()) {\n return Nan::ThrowTypeError(\"Use the new operator to create instances of this object.\");\n }\n\n NodeMidiOutput* output = new NodeMidiOutput();\n output->Wrap(info.This());\n\n info.GetReturnValue().Set(info.This());\n }\n\n static NAN_METHOD(GetPortCount)\n {\n Nan::HandleScope scope;\n NodeMidiOutput* output = Nan::ObjectWrap::Unwrap(info.This());\n v8::Local result = Nan::New(output->out->getPortCount());\n info.GetReturnValue().Set(result);\n }\n\n static NAN_METHOD(GetPortName)\n {\n Nan::HandleScope scope;\n NodeMidiOutput* output = Nan::ObjectWrap::Unwrap(info.This());\n if (info.Length() == 0 || !info[0]->IsUint32()) {\n return Nan::ThrowTypeError(\"First argument must be an integer\");\n }\n\n unsigned int portNumber = info[0]->Uint32Value();\n v8::Local result = Nan::New(output->out->getPortName(portNumber).c_str()).ToLocalChecked();\n info.GetReturnValue().Set(result);\n }\n\n static NAN_METHOD(OpenPort)\n {\n Nan::HandleScope scope;\n NodeMidiOutput* output = Nan::ObjectWrap::Unwrap(info.This());\n if (info.Length() == 0 || !info[0]->IsUint32()) {\n return Nan::ThrowTypeError(\"First argument must be an integer\");\n }\n unsigned int portNumber = info[0]->Uint32Value();\n if (portNumber >= output->out->getPortCount()) {\n return Nan::ThrowRangeError(\"Invalid MIDI port number\");\n }\n\n output->out->openPort(portNumber);\n return;\n }\n\n static NAN_METHOD(OpenVirtualPort)\n {\n Nan::HandleScope scope;\n NodeMidiOutput* output = Nan::ObjectWrap::Unwrap(info.This());\n if (info.Length() == 0 || !info[0]->IsString()) {\n return Nan::ThrowTypeError(\"First argument must be a string\");\n }\n\n std::string name(*v8::String::Utf8Value(info[0].As()));\n\n output->out->openVirtualPort(name);\n return;\n }\n\n static NAN_METHOD(ClosePort)\n {\n Nan::HandleScope scope;\n NodeMidiOutput* output = Nan::ObjectWrap::Unwrap(info.This());\n output->out->closePort();\n return;\n }\n\n static NAN_METHOD(SendMessage)\n {\n Nan::HandleScope scope;\n NodeMidiOutput* output = Nan::ObjectWrap::Unwrap(info.This());\n if (info.Length() == 0 || !info[0]->IsArray()) {\n return Nan::ThrowTypeError(\"First argument must be an array\");\n }\n\n v8::Local message = info[0]->ToObject();\n int32_t messageLength = message->Get(Nan::New(\"length\").ToLocalChecked())->Int32Value();\n std::vector messageOutput;\n for (int32_t i = 0; i != messageLength; ++i) {\n messageOutput.push_back(message->Get(Nan::New(i))->Int32Value());\n }\n output->out->sendMessage(&messageOutput);\n return;\n }\n};\n\nconst char* symbol_emit = \"emit\";\nconst char* symbol_message = \"message\";\n\nclass NodeMidiInput : public Nan::ObjectWrap\n{\nprivate:\n RtMidiIn* in;\n\npublic:\n uv_async_t message_async;\n uv_mutex_t message_mutex;\n\n struct MidiMessage\n {\n double deltaTime;\n std::vector message;\n };\n std::queue message_queue;\n\n static Nan::Persistent s_ct;\n static void Init(v8::Handle target)\n {\n Nan::HandleScope scope;\n\n v8::Local t = Nan::New(NodeMidiInput::New);\n\n s_ct.Reset(t);\n t->SetClassName(Nan::New(\"NodeMidiInput\").ToLocalChecked());\n t->InstanceTemplate()->SetInternalFieldCount(1);\n\n Nan::SetPrototypeMethod(t, \"getPortCount\", GetPortCount);\n Nan::SetPrototypeMethod(t, \"getPortName\", GetPortName);\n\n Nan::SetPrototypeMethod(t, \"openPort\", OpenPort);\n Nan::SetPrototypeMethod(t, \"openVirtualPort\", OpenVirtualPort);\n Nan::SetPrototypeMethod(t, \"closePort\", ClosePort);\n\n Nan::SetPrototypeMethod(t, \"ignoreTypes\", IgnoreTypes);\n\n target->Set(Nan::New(\"input\").ToLocalChecked(), t->GetFunction());\n }\n\n NodeMidiInput()\n {\n in = new RtMidiIn();\n uv_mutex_init(&message_mutex);\n }\n\n ~NodeMidiInput()\n {\n in->closePort();\n delete in;\n uv_mutex_destroy(&message_mutex);\n }\n\n static NAUV_WORK_CB(EmitMessage)\n {\n Nan::HandleScope scope;\n NodeMidiInput *input = static_cast(async->data);\n uv_mutex_lock(&input->message_mutex);\n v8::Local emitFunction = input->handle()->Get(Nan::New(symbol_emit).ToLocalChecked()).As();\n while (!input->message_queue.empty())\n {\n MidiMessage* message = input->message_queue.front();\n v8::Local info[3];\n info[0] = Nan::New(symbol_message).ToLocalChecked();\n info[1] = Nan::New(message->deltaTime);\n int32_t count = (int32_t)message->message.size();\n v8::Local data = Nan::New(count);\n for (int32_t i = 0; i < count; ++i) {\n data->Set(Nan::New(i), Nan::New(message->message[i]));\n }\n info[2] = data;\n Nan::MakeCallback(input->handle(), emitFunction, 3, info);\n input->message_queue.pop();\n delete message;\n }\n uv_mutex_unlock(&input->message_mutex);\n }\n\n static void Callback(double deltaTime, std::vector *message, void *userData)\n {\n NodeMidiInput *input = static_cast(userData);\n MidiMessage* data = new MidiMessage();\n data->deltaTime = deltaTime;\n data->message = *message;\n uv_mutex_lock(&input->message_mutex);\n input->message_queue.push(data);\n uv_mutex_unlock(&input->message_mutex);\n uv_async_send(&input->message_async);\n }\n\n static NAN_METHOD(New)\n {\n Nan::HandleScope scope;\n\n if (!info.IsConstructCall()) {\n return Nan::ThrowTypeError(\"Use the new operator to create instances of this object.\");\n }\n\n NodeMidiInput* input = new NodeMidiInput();\n input->message_async.data = input;\n uv_async_init(uv_default_loop(), &input->message_async, NodeMidiInput::EmitMessage);\n input->Wrap(info.This());\n\n info.GetReturnValue().Set(info.This());\n }\n\n static NAN_METHOD(GetPortCount)\n {\n Nan::HandleScope scope;\n NodeMidiInput* input = Nan::ObjectWrap::Unwrap(info.This());\n v8::Local result = Nan::New(input->in->getPortCount());\n info.GetReturnValue().Set(result);\n }\n\n static NAN_METHOD(GetPortName)\n {\n Nan::HandleScope scope;\n NodeMidiInput* input = Nan::ObjectWrap::Unwrap(info.This());\n if (info.Length() == 0 || !info[0]->IsUint32()) {\n return Nan::ThrowTypeError(\"First argument must be an integer\");\n }\n\n unsigned int portNumber = info[0]->Uint32Value();\n v8::Local result = Nan::New(input->in->getPortName(portNumber).c_str()).ToLocalChecked();\n info.GetReturnValue().Set(result);\n }\n\n static NAN_METHOD(OpenPort)\n {\n Nan::HandleScope scope;\n NodeMidiInput* input = Nan::ObjectWrap::Unwrap(info.This());\n if (info.Length() == 0 || !info[0]->IsUint32()) {\n return Nan::ThrowTypeError(\"First argument must be an integer\");\n }\n unsigned int portNumber = info[0]->Uint32Value();\n if (portNumber >= input->in->getPortCount()) {\n return Nan::ThrowRangeError(\"Invalid MIDI port number\");\n }\n\n input->Ref();\n input->in->setCallback(&NodeMidiInput::Callback, Nan::ObjectWrap::Unwrap(info.This()));\n input->in->openPort(portNumber);\n return;\n }\n\n static NAN_METHOD(OpenVirtualPort)\n {\n Nan::HandleScope scope;\n NodeMidiInput* input = Nan::ObjectWrap::Unwrap(info.This());\n if (info.Length() == 0 || !info[0]->IsString()) {\n return Nan::ThrowTypeError(\"First argument must be a string\");\n }\n\n std::string name(*v8::String::Utf8Value(info[0].As()));\n\n input->Ref();\n input->in->setCallback(&NodeMidiInput::Callback, Nan::ObjectWrap::Unwrap(info.This()));\n input->in->openVirtualPort(name);\n return;\n }\n\n static NAN_METHOD(ClosePort)\n {\n Nan::HandleScope scope;\n NodeMidiInput* input = Nan::ObjectWrap::Unwrap(info.This());\n if (input->in->isPortOpen()) {\n input->Unref();\n }\n input->in->cancelCallback();\n input->in->closePort();\n uv_close((uv_handle_t*)&input->message_async, NULL);\n return;\n }\n\n static NAN_METHOD(IgnoreTypes)\n {\n Nan::HandleScope scope;\n NodeMidiInput* input = Nan::ObjectWrap::Unwrap(info.This());\n if (info.Length() != 3 || !info[0]->IsBoolean() || !info[1]->IsBoolean() || !info[2]->IsBoolean()) {\n return Nan::ThrowTypeError(\"Arguments must be boolean\");\n }\n\n bool filter_sysex = info[0]->BooleanValue();\n bool filter_timing = info[1]->BooleanValue();\n bool filter_sensing = info[2]->BooleanValue();\n input->in->ignoreTypes(filter_sysex, filter_timing, filter_sensing);\n return;\n }\n};\n\nNan::Persistent NodeMidiOutput::s_ct;\nNan::Persistent NodeMidiInput::s_ct;\n\nextern \"C\" {\n void init (v8::Handle target)\n {\n NodeMidiOutput::Init(target);\n NodeMidiInput::Init(target);\n }\n NODE_MODULE(midi, init)\n}\n<|endoftext|>"} {"text":"file_util: don't compile any of the deprecated functions on non-Windows<|endoftext|>"} {"text":"#include \"pch.h\"\n#include \"jnc_OperatorMgr.h\"\n#include \"jnc_Module.h\"\n\nnamespace jnc {\n\n\/\/.............................................................................\n\nvoid\nOperatorMgr::getDataRefObjHdr (\n\tconst Value& value,\n\tValue* resultValue\n\t)\n{\n\tASSERT (value.getType ()->getTypeKind () == TypeKind_DataRef);\n\tDataPtrType* ptrType = (DataPtrType*) value.getType ();\n\tDataPtrTypeKind ptrTypeKind = ptrType->getPtrTypeKind ();\n\n\tif (ptrTypeKind == DataPtrTypeKind_Lean)\n\t{\n\t\tgetLeanDataPtrObjHdr (value, resultValue);\n\t}\n\telse\n\t{\n\t\tm_module->m_llvmIrBuilder.createExtractValue (\n\t\t\tvalue,\n\t\t\t3,\n\t\t\tm_module->m_typeMgr.getStdType (StdType_ObjHdrPtr),\n\t\t\tresultValue\n\t\t\t);\n\t}\n}\n\nvoid\nOperatorMgr::checkPtr (\n\tStdFunction stdTryCheckFunction,\n\tStdFunction stdCheckFunction,\n\tconst Value* argValueArray,\n\tsize_t argCount\n\t)\n{\n\tScope* scope = m_module->m_namespaceMgr.getCurrentScope ();\n\tASSERT (scope);\n\n\tif (!(scope->getFlags () & ScopeFlag_CanThrow))\n\t{\n\t\tFunction* checkFunction = m_module->m_functionMgr.getStdFunction (stdCheckFunction);\n\n\t\tm_module->m_llvmIrBuilder.createCall (\n\t\t\tcheckFunction,\n\t\t\tcheckFunction->getType (),\n\t\t\targValueArray,\n\t\t\targCount,\n\t\t\tNULL\n\t\t\t);\n\t}\n\telse\n\t{\n\t\tFunction* checkFunction = m_module->m_functionMgr.getStdFunction (stdTryCheckFunction);\n\t\tFunctionType* checkFunctionType = checkFunction->getType ();\n\n\t\tValue returnValue;\n\t\tm_module->m_llvmIrBuilder.createCall (\n\t\t\tcheckFunction,\n\t\t\tcheckFunctionType,\n\t\t\targValueArray,\n\t\t\targCount,\n\t\t\t&returnValue\n\t\t\t);\n\n\t\tbool result = m_module->m_controlFlowMgr.throwIf (returnValue, checkFunctionType);\n\t\tASSERT (result);\n\t}\n}\n\nvoid\nOperatorMgr::checkDataPtrRange (const Value& value)\n{\n\tASSERT (value.getType ()->getTypeKind () == TypeKind_DataPtr || value.getType ()->getTypeKind () == TypeKind_DataRef);\n\tDataPtrType* type = (DataPtrType*) value.getType ();\n\n\tif (m_module->m_operatorMgr.isUnsafeRgn () || (type->getFlags () & PtrTypeFlag_Safe))\n\t\treturn;\n\n\tValue ptrValue;\n\tValue rangeBeginValue;\n\tValue rangeEndValue;\n\n\tDataPtrTypeKind ptrTypeKind = type->getPtrTypeKind ();\n\tswitch (ptrTypeKind)\n\t{\n\tcase DataPtrTypeKind_Thin:\n\t\treturn;\n\n\tcase DataPtrTypeKind_Lean:\n\t\tgetLeanDataPtrRange (value, &rangeBeginValue, &rangeEndValue);\n\t\tm_module->m_llvmIrBuilder.createBitCast (value, m_module->m_typeMgr.getStdType (StdType_BytePtr), &ptrValue);\n\t\tbreak;\n\n\tcase DataPtrTypeKind_Normal:\n\t\tm_module->m_llvmIrBuilder.createExtractValue (value, 0, NULL, &ptrValue);\n\t\tm_module->m_llvmIrBuilder.createExtractValue (value, 1, NULL, &rangeBeginValue);\n\t\tm_module->m_llvmIrBuilder.createExtractValue (value, 2, NULL, &rangeEndValue);\n\t\tbreak;\n\n\tdefault:\n\t\tASSERT (false);\n\t\treturn;\n\t}\n\n\tValue sizeValue (\n\t\ttype->getTargetType ()->getSize (), \n\t\tm_module->m_typeMgr.getPrimitiveType (TypeKind_SizeT)\n\t\t);\n\n\tValue argValueArray [] =\n\t{\n\t\tptrValue,\n\t\tsizeValue,\n\t\trangeBeginValue,\n\t\trangeEndValue,\n\t};\n\n\tcheckPtr (\n\t\tStdFunction_TryCheckDataPtrRange,\n\t\tStdFunction_CheckDataPtrRange,\n\t\targValueArray,\n\t\tcountof (argValueArray)\n\t\t);\n}\n\nbool\nOperatorMgr::checkDataPtrScopeLevel (\n\tconst Value& srcValue,\n\tconst Value& dstValue\n\t)\n{\n\tASSERT (srcValue.getType ()->getTypeKind () == TypeKind_DataPtr);\n\n\tDataPtrType* ptrType = (DataPtrType*) srcValue.getType ();\n\tDataPtrTypeKind ptrTypeKind = ptrType->getPtrTypeKind ();\n\t\t\n\tif (m_module->m_operatorMgr.isUnsafeRgn () || ptrTypeKind == DataPtrTypeKind_Thin)\n\t\treturn true;\n\n\tif (srcValue.getValueKind () == ValueKind_Variable && dstValue.getValueKind () == ValueKind_Variable)\n\t{\n\t\tif (srcValue.getVariable ()->getScopeLevel () > dstValue.getVariable ()->getScopeLevel ())\n\t\t{\n\t\t\terr::setFormatStringError (\"data pointer scope level mismatch\");\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tValue srcObjHdrValue;\n\n\tif (ptrTypeKind == DataPtrTypeKind_Lean)\n\t\tgetLeanDataPtrObjHdr (srcValue, &srcObjHdrValue);\n\telse\n\t\tm_module->m_llvmIrBuilder.createExtractValue (srcValue, 3, m_module->m_typeMgr.getStdType (StdType_ObjHdrPtr), &srcObjHdrValue);\n\n\tFunction* checkFunction;\n\tValue dstObjHdrValue;\n\n\tif (dstValue.getValueKind () == ValueKind_Variable)\n\t{\n\t\tcheckFunction = m_module->m_functionMgr.getStdFunction (StdFunction_CheckScopeLevelDirect);\n\t\tdstObjHdrValue = m_module->m_namespaceMgr.getScopeLevel (dstValue.getVariable ()->getScopeLevel ());\n\t}\n\telse\n\t{\n\t\tcheckFunction = m_module->m_functionMgr.getStdFunction (StdFunction_CheckScopeLevel);\n\t\tgetDataRefObjHdr (dstValue, &dstObjHdrValue);\n\t}\n\n\tLlvmScopeComment comment (&m_module->m_llvmIrBuilder, \"check data pointer scope level\");\n\n\tm_module->m_llvmIrBuilder.createCall2 (\n\t\tcheckFunction,\n\t\tcheckFunction->getType (),\n\t\tsrcObjHdrValue,\n\t\tdstObjHdrValue,\n\t\tNULL\n\t\t);\n\n\treturn true;\n}\n\nvoid\nOperatorMgr::checkClassPtrScopeLevel (\n\tconst Value& srcValue,\n\tconst Value& dstValue\n\t)\n{\n\tASSERT (srcValue.getType ()->getTypeKindFlags () & TypeKindFlag_ClassPtr);\n\n\tif (m_module->m_operatorMgr.isUnsafeRgn ())\n\t\treturn;\n\n\tValue dstObjHdrValue;\n\tgetDataRefObjHdr (dstValue, &dstObjHdrValue);\n\n\tLlvmScopeComment comment (&m_module->m_llvmIrBuilder, \"check class scope level\");\n\n\tValue ifaceValue;\n\tm_module->m_llvmIrBuilder.createBitCast (srcValue, m_module->m_typeMgr.getStdType (StdType_AbstractClassPtr), &ifaceValue);\n\n\tFunction* checkFunction = m_module->m_functionMgr.getStdFunction (StdFunction_CheckClassPtrScopeLevel);\n\n\tm_module->m_llvmIrBuilder.createCall2 (\n\t\tcheckFunction,\n\t\tcheckFunction->getType (),\n\t\tifaceValue,\n\t\tdstObjHdrValue,\n\t\tNULL\n\t\t);\n}\n\nvoid\nOperatorMgr::checkNullPtr (const Value& value)\n{\n\tType* type = value.getType ();\n\t\n\tif (m_module->m_operatorMgr.isUnsafeRgn () || (type->getFlags () & PtrTypeFlag_Safe))\n\t\treturn;\n\n\tTypeKind typeKind = type->getTypeKind ();\n\n\tbool isThin;\n\n\tswitch (typeKind)\n\t{\n\tcase TypeKind_ClassPtr:\n\tcase TypeKind_ClassRef:\n\t\tisThin = true;\n\t\tbreak;\n\n\tcase TypeKind_FunctionPtr:\n\tcase TypeKind_FunctionRef:\n\t\tisThin = ((FunctionPtrType*) type)->getPtrTypeKind () == FunctionPtrTypeKind_Thin;\n\t\tbreak;\n\n\tcase TypeKind_PropertyPtr:\n\tcase TypeKind_PropertyRef:\n\t\tisThin = ((PropertyPtrType*) type)->getPtrTypeKind () == PropertyPtrTypeKind_Thin;\n\t\tbreak;\n\n\tdefault:\n\t\tASSERT (false);\n\t\treturn;\n\t}\n\n\tValue ptrValue;\n\tValue typeKindValue (typeKind, m_module->m_typeMgr.getPrimitiveType (TypeKind_Int));\n\n\tif (isThin)\n\t\tm_module->m_llvmIrBuilder.createBitCast (value, m_module->m_typeMgr.getStdType (StdType_BytePtr), &ptrValue);\n\telse\n\t\tm_module->m_llvmIrBuilder.createExtractValue (value, 0, NULL, &ptrValue);\n\n\tValue argValueArray [] =\n\t{\n\t\tptrValue,\n\t\ttypeKindValue,\n\t};\n\n\tcheckPtr (\n\t\tStdFunction_TryCheckNullPtr,\n\t\tStdFunction_CheckNullPtr,\n\t\targValueArray,\n\t\tcountof (argValueArray)\n\t\t);\n\n}\n\nvoid\nOperatorMgr::checkFunctionPtrScopeLevel (\n\tconst Value& srcValue,\n\tconst Value& dstValue\n\t)\n{\n\tASSERT (srcValue.getType ()->getTypeKindFlags () & TypeKindFlag_FunctionPtr);\n\tFunctionPtrType* ptrType = (FunctionPtrType*) srcValue.getType ();\n\n\tif (m_module->m_operatorMgr.isUnsafeRgn () || !ptrType->hasClosure ())\n\t\treturn;\n\n\tValue closureValue;\n\tm_module->m_llvmIrBuilder.createExtractValue (srcValue, 1, m_module->m_typeMgr.getStdType (StdType_AbstractClassPtr), &closureValue);\n\tcheckClassPtrScopeLevel (closureValue, dstValue);\n}\n\nvoid\nOperatorMgr::checkPropertyPtrScopeLevel (\n\tconst Value& srcValue,\n\tconst Value& dstValue\n\t)\n{\n\tASSERT (srcValue.getType ()->getTypeKind () == TypeKind_PropertyPtr);\n\tPropertyPtrType* ptrType = (PropertyPtrType*) srcValue.getType ();\n\n\tif (m_module->m_operatorMgr.isUnsafeRgn () || !ptrType->hasClosure ())\n\t\treturn;\n\n\tValue closureValue;\n\tm_module->m_llvmIrBuilder.createExtractValue (srcValue, 1, m_module->m_typeMgr.getStdType (StdType_AbstractClassPtr), &closureValue);\n\tcheckClassPtrScopeLevel (closureValue, dstValue);\n}\n\nvoid\nOperatorMgr::checkVariantScopeLevel (\n\tconst Value& srcValue,\n\tconst Value& dstValue\n\t)\n{\n\tASSERT (srcValue.getType ()->getTypeKind () == TypeKind_Variant);\n\n\tif (m_module->m_operatorMgr.isUnsafeRgn ())\n\t\treturn;\n\n\tValue dstObjHdrValue;\n\tgetDataRefObjHdr (dstValue, &dstObjHdrValue);\n\n\tLlvmScopeComment comment (&m_module->m_llvmIrBuilder, \"check variant scope level\");\n\n\tFunction* checkFunction = m_module->m_functionMgr.getStdFunction (StdFunction_CheckVariantScopeLevel);\n\n\tm_module->m_llvmIrBuilder.createCall2 (\n\t\tcheckFunction,\n\t\tcheckFunction->getType (),\n\t\tsrcValue,\n\t\tdstObjHdrValue,\n\t\tNULL\n\t\t);\n}\n\n\/\/.............................................................................\n\n} \/\/ namespace jnc {\n[jancy] critical bugfix: checkVariantScopeLevel should use OperatorMgr::callOperator and not LlvmIrBuilder::createCall -- due to TypeFlag_StructRet#include \"pch.h\"\n#include \"jnc_OperatorMgr.h\"\n#include \"jnc_Module.h\"\n\nnamespace jnc {\n\n\/\/.............................................................................\n\nvoid\nOperatorMgr::getDataRefObjHdr (\n\tconst Value& value,\n\tValue* resultValue\n\t)\n{\n\tASSERT (value.getType ()->getTypeKind () == TypeKind_DataRef);\n\tDataPtrType* ptrType = (DataPtrType*) value.getType ();\n\tDataPtrTypeKind ptrTypeKind = ptrType->getPtrTypeKind ();\n\n\tif (ptrTypeKind == DataPtrTypeKind_Lean)\n\t{\n\t\tgetLeanDataPtrObjHdr (value, resultValue);\n\t}\n\telse\n\t{\n\t\tm_module->m_llvmIrBuilder.createExtractValue (\n\t\t\tvalue,\n\t\t\t3,\n\t\t\tm_module->m_typeMgr.getStdType (StdType_ObjHdrPtr),\n\t\t\tresultValue\n\t\t\t);\n\t}\n}\n\nvoid\nOperatorMgr::checkPtr (\n\tStdFunction stdTryCheckFunction,\n\tStdFunction stdCheckFunction,\n\tconst Value* argValueArray,\n\tsize_t argCount\n\t)\n{\n\tScope* scope = m_module->m_namespaceMgr.getCurrentScope ();\n\tASSERT (scope);\n\n\tif (!(scope->getFlags () & ScopeFlag_CanThrow))\n\t{\n\t\tFunction* checkFunction = m_module->m_functionMgr.getStdFunction (stdCheckFunction);\n\n\t\tm_module->m_llvmIrBuilder.createCall (\n\t\t\tcheckFunction,\n\t\t\tcheckFunction->getType (),\n\t\t\targValueArray,\n\t\t\targCount,\n\t\t\tNULL\n\t\t\t);\n\t}\n\telse\n\t{\n\t\tFunction* checkFunction = m_module->m_functionMgr.getStdFunction (stdTryCheckFunction);\n\t\tFunctionType* checkFunctionType = checkFunction->getType ();\n\n\t\tValue returnValue;\n\t\tm_module->m_llvmIrBuilder.createCall (\n\t\t\tcheckFunction,\n\t\t\tcheckFunctionType,\n\t\t\targValueArray,\n\t\t\targCount,\n\t\t\t&returnValue\n\t\t\t);\n\n\t\tbool result = m_module->m_controlFlowMgr.throwIf (returnValue, checkFunctionType);\n\t\tASSERT (result);\n\t}\n}\n\nvoid\nOperatorMgr::checkDataPtrRange (const Value& value)\n{\n\tASSERT (value.getType ()->getTypeKind () == TypeKind_DataPtr || value.getType ()->getTypeKind () == TypeKind_DataRef);\n\tDataPtrType* type = (DataPtrType*) value.getType ();\n\n\tif (m_module->m_operatorMgr.isUnsafeRgn () || (type->getFlags () & PtrTypeFlag_Safe))\n\t\treturn;\n\n\tValue ptrValue;\n\tValue rangeBeginValue;\n\tValue rangeEndValue;\n\n\tDataPtrTypeKind ptrTypeKind = type->getPtrTypeKind ();\n\tswitch (ptrTypeKind)\n\t{\n\tcase DataPtrTypeKind_Thin:\n\t\treturn;\n\n\tcase DataPtrTypeKind_Lean:\n\t\tgetLeanDataPtrRange (value, &rangeBeginValue, &rangeEndValue);\n\t\tm_module->m_llvmIrBuilder.createBitCast (value, m_module->m_typeMgr.getStdType (StdType_BytePtr), &ptrValue);\n\t\tbreak;\n\n\tcase DataPtrTypeKind_Normal:\n\t\tm_module->m_llvmIrBuilder.createExtractValue (value, 0, NULL, &ptrValue);\n\t\tm_module->m_llvmIrBuilder.createExtractValue (value, 1, NULL, &rangeBeginValue);\n\t\tm_module->m_llvmIrBuilder.createExtractValue (value, 2, NULL, &rangeEndValue);\n\t\tbreak;\n\n\tdefault:\n\t\tASSERT (false);\n\t\treturn;\n\t}\n\n\tValue sizeValue (\n\t\ttype->getTargetType ()->getSize (), \n\t\tm_module->m_typeMgr.getPrimitiveType (TypeKind_SizeT)\n\t\t);\n\n\tValue argValueArray [] =\n\t{\n\t\tptrValue,\n\t\tsizeValue,\n\t\trangeBeginValue,\n\t\trangeEndValue,\n\t};\n\n\tcheckPtr (\n\t\tStdFunction_TryCheckDataPtrRange,\n\t\tStdFunction_CheckDataPtrRange,\n\t\targValueArray,\n\t\tcountof (argValueArray)\n\t\t);\n}\n\nbool\nOperatorMgr::checkDataPtrScopeLevel (\n\tconst Value& srcValue,\n\tconst Value& dstValue\n\t)\n{\n\tASSERT (srcValue.getType ()->getTypeKind () == TypeKind_DataPtr);\n\n\tDataPtrType* ptrType = (DataPtrType*) srcValue.getType ();\n\tDataPtrTypeKind ptrTypeKind = ptrType->getPtrTypeKind ();\n\t\t\n\tif (m_module->m_operatorMgr.isUnsafeRgn () || ptrTypeKind == DataPtrTypeKind_Thin)\n\t\treturn true;\n\n\tif (srcValue.getValueKind () == ValueKind_Variable && dstValue.getValueKind () == ValueKind_Variable)\n\t{\n\t\tif (srcValue.getVariable ()->getScopeLevel () > dstValue.getVariable ()->getScopeLevel ())\n\t\t{\n\t\t\terr::setFormatStringError (\"data pointer scope level mismatch\");\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tValue srcObjHdrValue;\n\n\tif (ptrTypeKind == DataPtrTypeKind_Lean)\n\t\tgetLeanDataPtrObjHdr (srcValue, &srcObjHdrValue);\n\telse\n\t\tm_module->m_llvmIrBuilder.createExtractValue (srcValue, 3, m_module->m_typeMgr.getStdType (StdType_ObjHdrPtr), &srcObjHdrValue);\n\n\tFunction* checkFunction;\n\tValue dstObjHdrValue;\n\n\tif (dstValue.getValueKind () == ValueKind_Variable)\n\t{\n\t\tcheckFunction = m_module->m_functionMgr.getStdFunction (StdFunction_CheckScopeLevelDirect);\n\t\tdstObjHdrValue = m_module->m_namespaceMgr.getScopeLevel (dstValue.getVariable ()->getScopeLevel ());\n\t}\n\telse\n\t{\n\t\tcheckFunction = m_module->m_functionMgr.getStdFunction (StdFunction_CheckScopeLevel);\n\t\tgetDataRefObjHdr (dstValue, &dstObjHdrValue);\n\t}\n\n\tLlvmScopeComment comment (&m_module->m_llvmIrBuilder, \"check data pointer scope level\");\n\n\tm_module->m_llvmIrBuilder.createCall2 (\n\t\tcheckFunction,\n\t\tcheckFunction->getType (),\n\t\tsrcObjHdrValue,\n\t\tdstObjHdrValue,\n\t\tNULL\n\t\t);\n\n\treturn true;\n}\n\nvoid\nOperatorMgr::checkClassPtrScopeLevel (\n\tconst Value& srcValue,\n\tconst Value& dstValue\n\t)\n{\n\tASSERT (srcValue.getType ()->getTypeKindFlags () & TypeKindFlag_ClassPtr);\n\n\tif (m_module->m_operatorMgr.isUnsafeRgn ())\n\t\treturn;\n\n\tValue dstObjHdrValue;\n\tgetDataRefObjHdr (dstValue, &dstObjHdrValue);\n\n\tLlvmScopeComment comment (&m_module->m_llvmIrBuilder, \"check class scope level\");\n\n\tValue ifaceValue;\n\tm_module->m_llvmIrBuilder.createBitCast (srcValue, m_module->m_typeMgr.getStdType (StdType_AbstractClassPtr), &ifaceValue);\n\n\tFunction* checkFunction = m_module->m_functionMgr.getStdFunction (StdFunction_CheckClassPtrScopeLevel);\n\n\tm_module->m_llvmIrBuilder.createCall2 (\n\t\tcheckFunction,\n\t\tcheckFunction->getType (),\n\t\tifaceValue,\n\t\tdstObjHdrValue,\n\t\tNULL\n\t\t);\n}\n\nvoid\nOperatorMgr::checkNullPtr (const Value& value)\n{\n\tType* type = value.getType ();\n\t\n\tif (m_module->m_operatorMgr.isUnsafeRgn () || (type->getFlags () & PtrTypeFlag_Safe))\n\t\treturn;\n\n\tTypeKind typeKind = type->getTypeKind ();\n\n\tbool isThin;\n\n\tswitch (typeKind)\n\t{\n\tcase TypeKind_ClassPtr:\n\tcase TypeKind_ClassRef:\n\t\tisThin = true;\n\t\tbreak;\n\n\tcase TypeKind_FunctionPtr:\n\tcase TypeKind_FunctionRef:\n\t\tisThin = ((FunctionPtrType*) type)->getPtrTypeKind () == FunctionPtrTypeKind_Thin;\n\t\tbreak;\n\n\tcase TypeKind_PropertyPtr:\n\tcase TypeKind_PropertyRef:\n\t\tisThin = ((PropertyPtrType*) type)->getPtrTypeKind () == PropertyPtrTypeKind_Thin;\n\t\tbreak;\n\n\tdefault:\n\t\tASSERT (false);\n\t\treturn;\n\t}\n\n\tValue ptrValue;\n\tValue typeKindValue (typeKind, m_module->m_typeMgr.getPrimitiveType (TypeKind_Int));\n\n\tif (isThin)\n\t\tm_module->m_llvmIrBuilder.createBitCast (value, m_module->m_typeMgr.getStdType (StdType_BytePtr), &ptrValue);\n\telse\n\t\tm_module->m_llvmIrBuilder.createExtractValue (value, 0, NULL, &ptrValue);\n\n\tValue argValueArray [] =\n\t{\n\t\tptrValue,\n\t\ttypeKindValue,\n\t};\n\n\tcheckPtr (\n\t\tStdFunction_TryCheckNullPtr,\n\t\tStdFunction_CheckNullPtr,\n\t\targValueArray,\n\t\tcountof (argValueArray)\n\t\t);\n\n}\n\nvoid\nOperatorMgr::checkFunctionPtrScopeLevel (\n\tconst Value& srcValue,\n\tconst Value& dstValue\n\t)\n{\n\tASSERT (srcValue.getType ()->getTypeKindFlags () & TypeKindFlag_FunctionPtr);\n\tFunctionPtrType* ptrType = (FunctionPtrType*) srcValue.getType ();\n\n\tif (m_module->m_operatorMgr.isUnsafeRgn () || !ptrType->hasClosure ())\n\t\treturn;\n\n\tValue closureValue;\n\tm_module->m_llvmIrBuilder.createExtractValue (srcValue, 1, m_module->m_typeMgr.getStdType (StdType_AbstractClassPtr), &closureValue);\n\tcheckClassPtrScopeLevel (closureValue, dstValue);\n}\n\nvoid\nOperatorMgr::checkPropertyPtrScopeLevel (\n\tconst Value& srcValue,\n\tconst Value& dstValue\n\t)\n{\n\tASSERT (srcValue.getType ()->getTypeKind () == TypeKind_PropertyPtr);\n\tPropertyPtrType* ptrType = (PropertyPtrType*) srcValue.getType ();\n\n\tif (m_module->m_operatorMgr.isUnsafeRgn () || !ptrType->hasClosure ())\n\t\treturn;\n\n\tValue closureValue;\n\tm_module->m_llvmIrBuilder.createExtractValue (srcValue, 1, m_module->m_typeMgr.getStdType (StdType_AbstractClassPtr), &closureValue);\n\tcheckClassPtrScopeLevel (closureValue, dstValue);\n}\n\nvoid\nOperatorMgr::checkVariantScopeLevel (\n\tconst Value& srcValue,\n\tconst Value& dstValue\n\t)\n{\n\tASSERT (srcValue.getType ()->getTypeKind () == TypeKind_Variant);\n\n\tif (m_module->m_operatorMgr.isUnsafeRgn ())\n\t\treturn;\n\n\tValue dstObjHdrValue;\n\tgetDataRefObjHdr (dstValue, &dstObjHdrValue);\n\n\tLlvmScopeComment comment (&m_module->m_llvmIrBuilder, \"check variant scope level\");\n\n\tFunction* checkFunction = m_module->m_functionMgr.getStdFunction (StdFunction_CheckVariantScopeLevel);\n\tm_module->m_operatorMgr.callOperator (checkFunction, srcValue, dstObjHdrValue);\n}\n\n\/\/.............................................................................\n\n} \/\/ namespace jnc {\n<|endoftext|>"} {"text":"\/*\n Copyright (C) 2008 Nikolas Zimmermann \n\n This file is part of the KDE project\n\n This library is free software you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n aint with this library see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n*\/\n\n\n\/\/ Own\n#include \"GeoParser.h\"\n\n\/\/ Qt\n#include \n\n\/\/ Geodata\n#include \"GeoDocument.h\"\n#include \"GeoTagHandler.h\"\n\nnamespace Marble\n{\n\n\/\/ Set to a value greather than 0, to dump parent node chain while parsing\n#define DUMP_PARENT_STACK 0\n\nGeoParser::GeoParser( GeoDataGenericSourceType source )\n : QXmlStreamReader(),\n m_document( 0 ),\n m_source( source )\n{\n}\n\nGeoParser::~GeoParser()\n{\n}\n\n#if DUMP_PARENT_STACK > 0\nstatic void dumpParentStack( const QString& name, int size, bool close )\n{\n static int depth = 0;\n\n if ( !close )\n depth++;\n\n QString result;\n for ( int i = 0; i < depth; ++i )\n result += ' ';\n\n if ( close ) {\n depth--;\n result += \"<\/\";\n } else\n result += '<';\n\n result += name + \"> stack size \" + QString::number( size );\n fprintf( stderr, \"%s\\n\", qPrintable( result ));\n}\n#endif\n\nbool GeoParser::read( QIODevice* device )\n{\n \/\/ Assert previous document got released.\n Q_ASSERT( !m_document );\n m_document = createDocument();\n Q_ASSERT( m_document );\n\n \/\/ Set data source\n setDevice( device );\n\n \/\/ Start parsing\n while ( !atEnd() ) {\n readNext();\n\n if ( isStartElement() ) {\n if ( isValidDocumentElement() ) {\n#if DUMP_PARENT_STACK > 0\n dumpParentStack( name().toString(), m_nodeStack.size(), false );\n#endif\n \n parseDocument();\n\n if ( !m_nodeStack.isEmpty() )\n raiseError(\n QObject::tr(\"Parsing failed. Still %1 unclosed tag(s) after document end.\", \"\",\n m_nodeStack.size() ));\n } else\n raiseDocumentElementError();\n }\n }\n\n if ( error() )\n qDebug() << \"[GeoParser::read] -> Error occurred:\" << errorString();\n\n return !error();\n}\n\nbool GeoParser::isValidElement( const QString& tagName ) const\n{\n return name() == tagName;\n}\n\nGeoStackItem GeoParser::parentElement( unsigned int depth )\n{\n QStack::const_iterator it = m_nodeStack.constEnd() - 1;\n\n if ( it - depth < m_nodeStack.constBegin() )\n return GeoStackItem();\n\n return *(it - depth);\n}\n\nvoid GeoParser::parseDocument()\n{\n Q_ASSERT( isStartElement() );\n\n while ( !atEnd() ) {\n readNext();\n GeoTagHandler::QualifiedName qName( name().toString(),\n namespaceUri().toString() );\n if ( isEndElement() ) {\n if ( !isValidDocumentElement() )\n m_nodeStack.pop();\n\n#if DUMP_PARENT_STACK > 0\n dumpParentStack( name().toString(), m_nodeStack.size(), true );\n#endif\n break;\n }\n\n if ( isStartElement() ) {\n bool processChildren = true;\n GeoStackItem stackItem( qName, 0 );\n\n if ( const GeoTagHandler* handler = GeoTagHandler::recognizes( qName )) {\n stackItem.assignNode( handler->parse( *this ));\n processChildren = !isEndElement();\n }\n\n \/\/ Only add GeoStackItem to the parent chain, if the tag handler\n \/\/ for the current element possibly contains non-textual children.\n \/\/ Consider following DGML snippet \"Test<\/name>\" - the\n \/\/ DGMLNameTagHandler assumes that only contains textual\n \/\/ children, and reads the joined value of all children using\n \/\/ readElementText(). This implicates that tags like \n \/\/ don't contain any children that would need to be processed using\n \/\/ this parseDocument() function.\n if ( processChildren ) {\n m_nodeStack.push( stackItem );\n\n#if DUMP_PARENT_STACK > 0\n dumpParentStack( name().toString(), m_nodeStack.size(), false );\n#endif\n\n parseDocument();\n }\n#if DUMP_PARENT_STACK > 0\n else {\n \/\/ This is only used for debugging purposes.\n m_nodeStack.push( stackItem );\n dumpParentStack( name().toString(), m_nodeStack.size(), false );\n\n m_nodeStack.pop();\n dumpParentStack( name().toString(), m_nodeStack.size(), true );\n }\n#endif\n }\n }\n}\n\nvoid GeoParser::raiseDocumentElementError()\n{\n raiseError( QObject::tr( \"File format unrecognized\" ));\n}\n\nvoid GeoParser::raiseWarning( const QString& warning )\n{\n \/\/ TODO: Maybe introduce a strict parsing mode where we feed the warning to\n \/\/ raiseError() (which stops parsing).\n qDebug() << \"[GeoParser::raiseWarning] -> \" << warning;\n}\n\nQString GeoParser::attribute( const char* attributeName ) const\n{\n return attributes().value( QString::fromLatin1( attributeName )).toString();\n}\n\nGeoDocument* GeoParser::releaseDocument()\n{\n GeoDocument* document = m_document;\n m_document = 0;\n return document;\n}\n\n}\nReplace %1 with %n.\/*\n Copyright (C) 2008 Nikolas Zimmermann \n\n This file is part of the KDE project\n\n This library is free software you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n aint with this library see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n*\/\n\n\n\/\/ Own\n#include \"GeoParser.h\"\n\n\/\/ Qt\n#include \n\n\/\/ Geodata\n#include \"GeoDocument.h\"\n#include \"GeoTagHandler.h\"\n\nnamespace Marble\n{\n\n\/\/ Set to a value greather than 0, to dump parent node chain while parsing\n#define DUMP_PARENT_STACK 0\n\nGeoParser::GeoParser( GeoDataGenericSourceType source )\n : QXmlStreamReader(),\n m_document( 0 ),\n m_source( source )\n{\n}\n\nGeoParser::~GeoParser()\n{\n}\n\n#if DUMP_PARENT_STACK > 0\nstatic void dumpParentStack( const QString& name, int size, bool close )\n{\n static int depth = 0;\n\n if ( !close )\n depth++;\n\n QString result;\n for ( int i = 0; i < depth; ++i )\n result += ' ';\n\n if ( close ) {\n depth--;\n result += \"<\/\";\n } else\n result += '<';\n\n result += name + \"> stack size \" + QString::number( size );\n fprintf( stderr, \"%s\\n\", qPrintable( result ));\n}\n#endif\n\nbool GeoParser::read( QIODevice* device )\n{\n \/\/ Assert previous document got released.\n Q_ASSERT( !m_document );\n m_document = createDocument();\n Q_ASSERT( m_document );\n\n \/\/ Set data source\n setDevice( device );\n\n \/\/ Start parsing\n while ( !atEnd() ) {\n readNext();\n\n if ( isStartElement() ) {\n if ( isValidDocumentElement() ) {\n#if DUMP_PARENT_STACK > 0\n dumpParentStack( name().toString(), m_nodeStack.size(), false );\n#endif\n \n parseDocument();\n\n if ( !m_nodeStack.isEmpty() )\n raiseError(\n QObject::tr(\"Parsing failed. Still %n unclosed tag(s) after document end.\", \"\",\n m_nodeStack.size() ));\n } else\n raiseDocumentElementError();\n }\n }\n\n if ( error() )\n qDebug() << \"[GeoParser::read] -> Error occurred:\" << errorString();\n\n return !error();\n}\n\nbool GeoParser::isValidElement( const QString& tagName ) const\n{\n return name() == tagName;\n}\n\nGeoStackItem GeoParser::parentElement( unsigned int depth )\n{\n QStack::const_iterator it = m_nodeStack.constEnd() - 1;\n\n if ( it - depth < m_nodeStack.constBegin() )\n return GeoStackItem();\n\n return *(it - depth);\n}\n\nvoid GeoParser::parseDocument()\n{\n Q_ASSERT( isStartElement() );\n\n while ( !atEnd() ) {\n readNext();\n GeoTagHandler::QualifiedName qName( name().toString(),\n namespaceUri().toString() );\n if ( isEndElement() ) {\n if ( !isValidDocumentElement() )\n m_nodeStack.pop();\n\n#if DUMP_PARENT_STACK > 0\n dumpParentStack( name().toString(), m_nodeStack.size(), true );\n#endif\n break;\n }\n\n if ( isStartElement() ) {\n bool processChildren = true;\n GeoStackItem stackItem( qName, 0 );\n\n if ( const GeoTagHandler* handler = GeoTagHandler::recognizes( qName )) {\n stackItem.assignNode( handler->parse( *this ));\n processChildren = !isEndElement();\n }\n\n \/\/ Only add GeoStackItem to the parent chain, if the tag handler\n \/\/ for the current element possibly contains non-textual children.\n \/\/ Consider following DGML snippet \"Test<\/name>\" - the\n \/\/ DGMLNameTagHandler assumes that only contains textual\n \/\/ children, and reads the joined value of all children using\n \/\/ readElementText(). This implicates that tags like \n \/\/ don't contain any children that would need to be processed using\n \/\/ this parseDocument() function.\n if ( processChildren ) {\n m_nodeStack.push( stackItem );\n\n#if DUMP_PARENT_STACK > 0\n dumpParentStack( name().toString(), m_nodeStack.size(), false );\n#endif\n\n parseDocument();\n }\n#if DUMP_PARENT_STACK > 0\n else {\n \/\/ This is only used for debugging purposes.\n m_nodeStack.push( stackItem );\n dumpParentStack( name().toString(), m_nodeStack.size(), false );\n\n m_nodeStack.pop();\n dumpParentStack( name().toString(), m_nodeStack.size(), true );\n }\n#endif\n }\n }\n}\n\nvoid GeoParser::raiseDocumentElementError()\n{\n raiseError( QObject::tr( \"File format unrecognized\" ));\n}\n\nvoid GeoParser::raiseWarning( const QString& warning )\n{\n \/\/ TODO: Maybe introduce a strict parsing mode where we feed the warning to\n \/\/ raiseError() (which stops parsing).\n qDebug() << \"[GeoParser::raiseWarning] -> \" << warning;\n}\n\nQString GeoParser::attribute( const char* attributeName ) const\n{\n return attributes().value( QString::fromLatin1( attributeName )).toString();\n}\n\nGeoDocument* GeoParser::releaseDocument()\n{\n GeoDocument* document = m_document;\n m_document = 0;\n return document;\n}\n\n}\n<|endoftext|>"} {"text":"#include \"sqlite_add_indices.hpp\"\n\n#include \n#include \n#include \n\n#include \"operators\/print.hpp\"\n\n#include \"hyrise.hpp\"\n#include \"utils\/meta_table_manager.hpp\"\n#include \"utils\/sqlite_wrapper.hpp\"\n#include \"utils\/timer.hpp\"\n\nnamespace opossum {\n\nvoid add_indices_to_sqlite(const std::string& schema_file_path, const std::string& create_indices_file_path,\n std::shared_ptr& sqlite_wrapper) {\n Assert(sqlite_wrapper, \"sqlite_wrapper should be set\");\n\n std::cout << \"- Adding indexes to SQLite\" << std::endl;\n Timer timer;\n\n \/\/ SQLite does not support adding primary keys to non-empty tables, so we rename the table, create an empty one from\n \/\/ the provided schema and copy the data.\n for (const auto& table_name : Hyrise::get().storage_manager.table_names()) {\n \/\/ SQLite doesn't like an unescaped \"ORDER\" as a table name, thus we escape it. No need to escape the\n \/\/ \"..._unindexed\" name.\n const auto escaped_table_name = std::string{\"\\\"\"} + table_name + \"\\\"\";\n\n sqlite_wrapper->main_connection.raw_execute_query(std::string{\"ALTER TABLE \"}\n .append(escaped_table_name)\n .append(\" RENAME TO \")\n .append(table_name)\n .append(\"_unindexed\"));\n }\n\n \/\/ Recreate tables using the passed schema sql file\n std::ifstream schema_file(schema_file_path);\n std::string schema_sql((std::istreambuf_iterator(schema_file)), std::istreambuf_iterator());\n sqlite_wrapper->main_connection.raw_execute_query(schema_sql);\n\n \/\/ If indices are not part of the schema file, add them here\n if (!create_indices_file_path.empty()) {\n std::ifstream create_indices_file(create_indices_file_path);\n std::string create_indices_sql((std::istreambuf_iterator(create_indices_file)),\n std::istreambuf_iterator());\n sqlite_wrapper->main_connection.raw_execute_query(create_indices_sql);\n }\n\n \/\/ Copy over data\n for (const auto& table_name : Hyrise::get().storage_manager.table_names()) {\n Timer per_table_time;\n std::cout << \"- Adding indexes to SQLite table \" << table_name << std::flush;\n\n const auto escaped_table_name = std::string{\"\\\"\"} + table_name + \"\\\"\";\n\n sqlite_wrapper->main_connection.raw_execute_query(std::string{\"INSERT INTO \"}\n .append(escaped_table_name)\n .append(\" SELECT * FROM \")\n .append(table_name)\n .append(\"_unindexed\"));\n\n std::cout << \" (\" << per_table_time.lap_formatted() << \")\" << std::endl;\n }\n\n std::cout << \"- Added indexes to SQLite (\" << timer.lap_formatted() << \")\" << std::endl;\n}\n\n} \/\/ namespace opossum\nBetter error message for --verify (#2338)#include \"sqlite_add_indices.hpp\"\n\n#include \n#include \n#include \n\n#include \"operators\/print.hpp\"\n\n#include \"hyrise.hpp\"\n#include \"utils\/meta_table_manager.hpp\"\n#include \"utils\/sqlite_wrapper.hpp\"\n#include \"utils\/timer.hpp\"\n\nnamespace opossum {\n\nvoid add_indices_to_sqlite(const std::string& schema_file_path, const std::string& create_indices_file_path,\n std::shared_ptr& sqlite_wrapper) {\n Assert(sqlite_wrapper, \"sqlite_wrapper should be set\");\n\n std::cout << \"- Adding indexes to SQLite\" << std::endl;\n Timer timer;\n\n \/\/ SQLite does not support adding primary keys to non-empty tables, so we rename the table, create an empty one from\n \/\/ the provided schema and copy the data.\n for (const auto& table_name : Hyrise::get().storage_manager.table_names()) {\n \/\/ SQLite doesn't like an unescaped \"ORDER\" as a table name, thus we escape it. No need to escape the\n \/\/ \"..._unindexed\" name.\n const auto escaped_table_name = std::string{\"\\\"\"} + table_name + \"\\\"\";\n\n sqlite_wrapper->main_connection.raw_execute_query(std::string{\"ALTER TABLE \"}\n .append(escaped_table_name)\n .append(\" RENAME TO \")\n .append(table_name)\n .append(\"_unindexed\"));\n }\n\n \/\/ Recreate tables using the passed schema sql file\n std::ifstream schema_file(schema_file_path);\n Assert(schema_file.good(), std::string{\"Schema file \"} + schema_file_path +\n \" not found - try running the binary from the Hyrise root or the build directory\");\n std::string schema_sql((std::istreambuf_iterator(schema_file)), std::istreambuf_iterator());\n sqlite_wrapper->main_connection.raw_execute_query(schema_sql);\n\n \/\/ If indices are not part of the schema file, add them here\n if (!create_indices_file_path.empty()) {\n std::ifstream create_indices_file(create_indices_file_path);\n Assert(create_indices_file.good(),\n std::string{\"Index file \"} + create_indices_file_path +\n \" not found - try running the binary from the Hyrise root or the build directory\");\n std::string create_indices_sql((std::istreambuf_iterator(create_indices_file)),\n std::istreambuf_iterator());\n sqlite_wrapper->main_connection.raw_execute_query(create_indices_sql);\n }\n\n \/\/ Copy over data\n for (const auto& table_name : Hyrise::get().storage_manager.table_names()) {\n Timer per_table_time;\n std::cout << \"- Adding indexes to SQLite table \" << table_name << std::flush;\n\n const auto escaped_table_name = std::string{\"\\\"\"} + table_name + \"\\\"\";\n\n sqlite_wrapper->main_connection.raw_execute_query(std::string{\"INSERT INTO \"}\n .append(escaped_table_name)\n .append(\" SELECT * FROM \")\n .append(table_name)\n .append(\"_unindexed\"));\n\n std::cout << \" (\" << per_table_time.lap_formatted() << \")\" << std::endl;\n }\n\n std::cout << \"- Added indexes to SQLite (\" << timer.lap_formatted() << \")\" << std::endl;\n}\n\n} \/\/ namespace opossum\n<|endoftext|>"} {"text":"\/\/! \\file\n\/*\n** Copyright (C) - Triton\n**\n** This program is under the terms of the BSD License.\n*\/\n\n#ifndef TRITON_CALLBACKS_H\n#define TRITON_CALLBACKS_H\n\n#include \n\n#include \"ast.hpp\"\n#include \"tritonTypes.hpp\"\n\n#ifdef TRITON_PYTHON_BINDINGS\n #include \"pythonBindings.hpp\"\n#endif\n\n\n\n\/\/! The Triton namespace\nnamespace triton {\n\/*!\n * \\addtogroup triton\n * @{\n *\/\n\n \/\/! The Callbacks namespace\n namespace callbacks {\n \/*!\n * \\ingroup triton\n * \\addtogroup callbacks\n * @{\n *\/\n\n \/*! Enumerates all kinds callbacks. *\/\n enum callback_e {\n MEMORY_HIT, \/*!< Memory hits callback *\/\n SYMBOLIC_SIMPLIFICATION, \/*!< Symbolic simplification callback *\/\n };\n\n \/*! \\brief The prototype of a memory hit callback.\n *\n * \\description The callback takes as uniq argument an address which representes the memory\n * cell hit. Callbacks will be called each time that a memory cell will be hit.\n *\/\n typedef void (*memoryHitCallback)(triton::uint64 address);\n\n \/*! \\brief The prototype of a symbolic simplification callback.\n *\n * \\description The callback takes as uniq argument an AbstractNode and must return a valid AbstractNode.\n * The returned node is used as assignment. See also the page about \\ref SMT_simplification_page.\n *\/\n typedef triton::ast::AbstractNode* (*symbolicSimplificationCallback)(triton::ast::AbstractNode* node);\n\n \/\/! \\class Callbacks\n \/*! \\brief The callbacks class *\/\n class Callbacks {\n protected:\n #ifdef TRITON_PYTHON_BINDINGS\n \/\/! [python] Callbacks for all memory hits.\n std::list pyMemoryHitCallbacks;\n\n \/\/! [python] Callbacks for all symbolic simplifications.\n std::list pySymbolicSimplificationCallbacks;\n #endif\n\n \/\/! [c++] Callbacks for all memory hits.\n std::list memoryHitCallbacks;\n\n \/\/! [c++] Callbacks for all symbolic simplifications.\n std::list symbolicSimplificationCallbacks;\n\n \/\/! Returns the number of callbacks recorded.\n triton::uint32 countCallbacks(void) const;\n\n public:\n \/\/! True if there is at least one callback defined.\n bool isDefined;\n\n \/\/! Constructor.\n Callbacks();\n\n \/\/! Constructor.\n Callbacks(const Callbacks& copy);\n\n \/\/! Destructor.\n ~Callbacks();\n\n \/\/! Copies a Callbacks class\n void operator=(const Callbacks& copy);\n\n \/\/! Adds a memory hit callback.\n void addCallback(triton::callbacks::memoryHitCallback cb);\n\n \/\/! Adds a symbolic simplification callback.\n void addCallback(triton::callbacks::symbolicSimplificationCallback cb);\n\n #ifdef TRITON_PYTHON_BINDINGS\n \/\/! Adds a python callback.\n void addCallback(triton::callbacks::callback_e kind, PyObject* function);\n #endif\n\n \/\/! Deletes a memory hit callback.\n void deleteCallback(triton::callbacks::memoryHitCallback cb);\n\n \/\/! Deletes a symbolic simplification callback.\n void deleteCallback(triton::callbacks::symbolicSimplificationCallback cb);\n\n #ifdef TRITON_PYTHON_BINDINGS\n \/\/! Deletes a python callback.\n void deleteCallback(triton::callbacks::callback_e kind, PyObject* function);\n #endif\n\n \/\/! Processes callbacks according to the kind and the C++ polymorphism.\n triton::ast::AbstractNode* processCallbacks(triton::callbacks::callback_e kind, triton::ast::AbstractNode* node) const;\n\n \/\/! Processes callbacks according to the kind and the C++ polymorphism.\n void processCallbacks(triton::callbacks::callback_e kind, triton::uint64 address) const;\n };\n\n \/*! @} End of callbacks namespace *\/\n };\n\/*! @} End of triton namespace *\/\n};\n\n#endif \/* TRITON_CALLBACKS_H *\/\n#318 in progress\/\/! \\file\n\/*\n** Copyright (C) - Triton\n**\n** This program is under the terms of the BSD License.\n*\/\n\n#ifndef TRITON_CALLBACKS_H\n#define TRITON_CALLBACKS_H\n\n#include \n\n#include \"ast.hpp\"\n#include \"tritonTypes.hpp\"\n\n#ifdef TRITON_PYTHON_BINDINGS\n #include \"pythonBindings.hpp\"\n#endif\n\n\n\n\/\/! The Triton namespace\nnamespace triton {\n\/*!\n * \\addtogroup triton\n * @{\n *\/\n\n \/\/! The Callbacks namespace\n namespace callbacks {\n \/*!\n * \\ingroup triton\n * \\addtogroup callbacks\n * @{\n *\/\n\n \/*! Enumerates all kinds callbacks. *\/\n enum callback_e {\n MEMORY_HIT, \/*!< Memory hits callback *\/\n SYMBOLIC_SIMPLIFICATION, \/*!< Symbolic simplification callback *\/\n };\n\n \/*! \\brief The prototype of a memory hit callback.\n *\n * \\description The callback takes as uniq argument an address which representes the memory\n * cell hit. Callbacks will be called each time that a memory cell will be hit.\n *\/\n typedef void (*memoryHitCallback)(triton::uint64 address);\n\n \/*! \\brief The prototype of a symbolic simplification callback.\n *\n * \\description The callback takes as uniq argument an triton::ast::AbstractNode and must return a valid triton::ast::AbstractNode.\n * The returned node is used as assignment. See also the page about \\ref SMT_simplification_page.\n *\/\n typedef triton::ast::AbstractNode* (*symbolicSimplificationCallback)(triton::ast::AbstractNode* node);\n\n \/\/! \\class Callbacks\n \/*! \\brief The callbacks class *\/\n class Callbacks {\n protected:\n #ifdef TRITON_PYTHON_BINDINGS\n \/\/! [python] Callbacks for all memory hits.\n std::list pyMemoryHitCallbacks;\n\n \/\/! [python] Callbacks for all symbolic simplifications.\n std::list pySymbolicSimplificationCallbacks;\n #endif\n\n \/\/! [c++] Callbacks for all memory hits.\n std::list memoryHitCallbacks;\n\n \/\/! [c++] Callbacks for all symbolic simplifications.\n std::list symbolicSimplificationCallbacks;\n\n \/\/! Returns the number of callbacks recorded.\n triton::uint32 countCallbacks(void) const;\n\n public:\n \/\/! True if there is at least one callback defined.\n bool isDefined;\n\n \/\/! Constructor.\n Callbacks();\n\n \/\/! Constructor.\n Callbacks(const Callbacks& copy);\n\n \/\/! Destructor.\n ~Callbacks();\n\n \/\/! Copies a Callbacks class\n void operator=(const Callbacks& copy);\n\n \/\/! Adds a memory hit callback.\n void addCallback(triton::callbacks::memoryHitCallback cb);\n\n \/\/! Adds a symbolic simplification callback.\n void addCallback(triton::callbacks::symbolicSimplificationCallback cb);\n\n #ifdef TRITON_PYTHON_BINDINGS\n \/\/! Adds a python callback.\n void addCallback(triton::callbacks::callback_e kind, PyObject* function);\n #endif\n\n \/\/! Deletes a memory hit callback.\n void deleteCallback(triton::callbacks::memoryHitCallback cb);\n\n \/\/! Deletes a symbolic simplification callback.\n void deleteCallback(triton::callbacks::symbolicSimplificationCallback cb);\n\n #ifdef TRITON_PYTHON_BINDINGS\n \/\/! Deletes a python callback.\n void deleteCallback(triton::callbacks::callback_e kind, PyObject* function);\n #endif\n\n \/\/! Processes callbacks according to the kind and the C++ polymorphism.\n triton::ast::AbstractNode* processCallbacks(triton::callbacks::callback_e kind, triton::ast::AbstractNode* node) const;\n\n \/\/! Processes callbacks according to the kind and the C++ polymorphism.\n void processCallbacks(triton::callbacks::callback_e kind, triton::uint64 address) const;\n };\n\n \/*! @} End of callbacks namespace *\/\n };\n\/*! @} End of triton namespace *\/\n};\n\n#endif \/* TRITON_CALLBACKS_H *\/\n<|endoftext|>"} {"text":"\/*\n * info.cpp\n *\n * Created on: Nov 22, 2012\n * Author: partio\n *\/\n\n#include \"info.h\"\n#include \/\/ for std::numeric_limits::max();\n#include \n#include \"plugin_factory.h\"\n#include \"logger_factory.h\"\n\n#ifdef NEWBASE_INTERPOLATION\n#include \n#include \n#include \n#endif\n\n#define HIMAN_AUXILIARY_INCLUDE\n\n#include \"neons.h\"\n\n#undef HIMAN_AUXILIARY_INCLUDE\n\nusing namespace std;\nusing namespace himan;\n\ninfo::info()\n{\n Init();\n itsLogger = std::unique_ptr (logger_factory::Instance()->GetLog(\"info\"));\n\n itsDataMatrix = shared_ptr (new matrix_t());\n itsTimeIterator = shared_ptr (new time_iter());\n}\n\ninfo::~info()\n{\n}\n\nshared_ptr info::Clone() const\n{\n\n shared_ptr clone = shared_ptr (new info());\n\n clone->Projection(itsProjection);\n clone->Orientation(itsOrientation);\n\n clone->BottomLeftLatitude(itsBottomLeftLatitude);\n clone->BottomLeftLongitude(itsBottomLeftLongitude);\n clone->TopRightLatitude(itsTopRightLatitude);\n clone->TopRightLongitude(itsTopRightLongitude);\n\n clone->Data(itsDataMatrix);\n\n clone->ParamIterator(*itsParamIterator);\n clone->LevelIterator(*itsLevelIterator);\n clone->TimeIterator(*itsTimeIterator);\n\n clone->Producer(itsProducer);\n\n clone->OriginDateTime(itsOriginDateTime.String(\"%Y-%m-%d %H:%M:%S\"), \"%Y-%m-%d %H:%M:%S\");\n\n \/*\n clone->ParamIndex(itsParamIndex);\n clone->TimeIndex(itsTimeIndex);\n clone->LevelIndex(itsLevelIndex);\n *\/\n clone->LocationIndex(itsLocationIndex);\n\n return clone;\n\n}\n\nvoid info::Init()\n{\n\n itsProjection = kUnknownProjection;\n\n itsBottomLeftLatitude = kHPMissingFloat;\n itsBottomLeftLongitude = kHPMissingFloat;\n itsTopRightLatitude = kHPMissingFloat;\n itsTopRightLongitude = kHPMissingFloat;\n itsOrientation = kHPMissingFloat;\n\n itsScanningMode = kTopLeft;\n\n}\n\nstd::ostream& info::Write(std::ostream& file) const\n{\n\n file << \"<\" << ClassName() << \" \" << Version() << \">\" << endl;\n\n file << \"__itsProjection__ \" << itsProjection << endl;\n file << \"__itsBottomLeftLongitude__ \" << itsBottomLeftLongitude << endl;\n file << \"__itsBottomLeftLatitude__ \" << itsBottomLeftLatitude << endl;\n file << \"__itsTopRightLongitude__ \" << itsTopRightLongitude << endl;\n file << \"__itsTopRightLatitude__ \" << itsTopRightLatitude << endl;\n file << \"__itsOrientation__ \" << itsOrientation << endl;\n\n file << \"__itsOriginDateTime__ \" << OriginDateTime().String() << endl;\n\n file << \"__itsProducer__ \" << itsProducer << endl;\n\n file << itsParamIterator << endl;\n file << itsLevelIterator << endl;\n file << itsTimeIterator << endl;\n\n return file;\n}\n\n\nbool info::Create()\n{\n\n itsDataMatrix = shared_ptr (new matrix_t(itsTimeIterator->Size(), itsLevelIterator->Size(), itsParamIterator->Size()));\n\n Reset();\n\n while (NextTime())\n {\n ResetLevel();\n\n while (NextLevel())\n {\n ResetParam();\n\n while (NextParam())\n \/\/ Create empty placeholders\n {\n \tData(shared_ptr (new d_matrix_t(0, 0)));\n }\n }\n }\n\n return true;\n\n}\n\nHPProjectionType info::Projection() const\n{\n return itsProjection;\n}\n\nvoid info::Projection(HPProjectionType theProjection)\n{\n itsProjection = theProjection;\n}\n\ndouble info::BottomLeftLatitude() const\n{\n return itsBottomLeftLatitude;\n}\ndouble info::BottomLeftLongitude() const\n{\n return itsBottomLeftLongitude;\n}\ndouble info::TopRightLongitude() const\n{\n return itsTopRightLongitude;\n}\ndouble info::TopRightLatitude() const\n{\n return itsTopRightLatitude;\n}\n\nvoid info::BottomLeftLatitude(double theBottomLeftLatitude)\n{\n itsBottomLeftLatitude = theBottomLeftLatitude;\n}\n\nvoid info::BottomLeftLongitude(double theBottomLeftLongitude)\n{\n itsBottomLeftLongitude = theBottomLeftLongitude;\n}\nvoid info::TopRightLatitude(double theTopRightLatitude)\n{\n itsTopRightLatitude = theTopRightLatitude;\n}\nvoid info::TopRightLongitude(double theTopRightLongitude)\n{\n itsTopRightLongitude = theTopRightLongitude;\n}\n\ndouble info::Orientation() const\n{\n return itsOrientation;\n}\n\nvoid info::Orientation(double theOrientation)\n{\n itsOrientation = theOrientation;\n}\n\nconst producer& info::Producer() const\n{\n return itsProducer;\n}\n\nvoid info::Producer(long theFmiProducerId)\n{\n itsProducer = producer(theFmiProducerId);\n}\n\n\nvoid info::Producer(const producer& theProducer)\n{\n itsProducer = theProducer;\n}\n\/*\nvector > info::Params() const\n{\n\treturn itsParams;\n}\n*\/\nvoid info::ParamIterator(const param_iter& theParamIterator)\n{\n itsParamIterator = shared_ptr (new param_iter(theParamIterator));\n}\n\nvoid info::Params(const vector& theParams)\n{\n itsParamIterator = shared_ptr (new param_iter(theParams));\n}\n\/*\nvector > info::Levels() const\n{\n\treturn itsLevels;\n}\n*\/\n\nvoid info::LevelIterator(const level_iter& theLevelIterator)\n{\n itsLevelIterator = shared_ptr (new level_iter(theLevelIterator));\n}\n\nvoid info::Levels(const vector& theLevels)\n{\n \/\/itsLevels = theLevels;\n itsLevelIterator = shared_ptr (new level_iter(theLevels));\n}\n\/*\nvector > info::Times() const\n{\n\treturn itsTimes;\n}*\/\n\nvoid info::TimeIterator(const time_iter& theTimeIterator)\n{\n itsTimeIterator = shared_ptr (new time_iter(theTimeIterator));\n}\n\nvoid info::Times(const vector& theTimes)\n{\n \/\/itsTimes = theTimes;\n itsTimeIterator = shared_ptr (new time_iter(theTimes));\n}\n\nraw_time info::OriginDateTime() const\n{\n return itsOriginDateTime;\n}\n\nvoid info::OriginDateTime(const string& theOriginDateTime, const string& theTimeMask)\n{\n itsOriginDateTime = raw_time(theOriginDateTime, theTimeMask);\n}\n\nbool info::Param(const param& theRequestedParam)\n{\n return itsParamIterator->Set(theRequestedParam);\n}\n\nbool info::NextParam()\n{\n return itsParamIterator->Next();\n}\n\nvoid info::ResetParam()\n{\n itsParamIterator->Reset();\n}\n\nbool info::FirstParam()\n{\n return itsParamIterator->First();\n}\n\nsize_t info::ParamIndex() const\n{\n return itsParamIterator->Index();\n}\n\nvoid info::ParamIndex(size_t theParamIndex)\n{\n itsParamIterator->Set(theParamIndex);\n}\n\nparam& info::Param() const\n{\n return itsParamIterator->At();\n}\n\nbool info::NextLevel()\n{\n return itsLevelIterator->Next();\n}\n\nvoid info::Reset()\n{\n ResetLevel();\n ResetParam();\n ResetTime();\n ResetLocation();\n}\n\nvoid info::ResetLevel()\n{\n itsLevelIterator->Reset();\n}\n\nbool info::FirstLevel()\n{\n return itsLevelIterator->First();\n}\n\nsize_t info::LevelIndex() const\n{\n return itsLevelIterator->Index();\n}\n\nvoid info::LevelIndex(size_t theLevelIndex)\n{\n itsLevelIterator->Set(theLevelIndex);\n}\n\nbool info::Level(const level& theLevel)\n{\n return itsLevelIterator->Set(theLevel);\n}\n\nlevel& info::Level() const\n{\n return itsLevelIterator->At();\n}\n\nbool info::NextTime()\n{\n return itsTimeIterator->Next();\n}\n\nvoid info::ResetTime()\n{\n itsTimeIterator->Reset();\n}\n\nbool info::FirstTime()\n{\n return itsTimeIterator->First();\n}\n\nsize_t info::TimeIndex() const\n{\n return itsTimeIterator->Index();\n}\n\nvoid info::TimeIndex(size_t theTimeIndex)\n{\n itsTimeIterator->Set(theTimeIndex);\n}\n\nbool info::Time(const forecast_time& theTime)\n{\n return itsTimeIterator->Set(theTime);\n}\n\nforecast_time& info::Time() const\n{\n return itsTimeIterator->At();\n}\n\nbool info::NextLocation()\n{\n if (itsLocationIndex == kMAX_SIZE_T)\n {\n itsLocationIndex = 0; \/\/ ResetLocation() has been called before this function\n }\n\n else\n {\n itsLocationIndex++;\n }\n\n size_t locationSize = Data()->Size();\n\n if (itsLocationIndex >= locationSize)\n {\n itsLocationIndex = (locationSize == 0) ? 0 : locationSize - 1;\n\n return false;\n }\n\n return true;\n\n}\n\nvoid info::ResetLocation()\n{\n itsLocationIndex = kMAX_SIZE_T;\n}\n\nbool info::FirstLocation()\n{\n ResetLocation();\n\n return NextTime();\n}\n\nvoid info::LocationIndex(size_t theLocationIndex)\n{\n itsLocationIndex = theLocationIndex;\n}\n\nshared_ptr info::Data() const\n{\n return itsDataMatrix->At(TimeIndex(), LevelIndex(), ParamIndex());\n}\n\nshared_ptr info::Data(size_t timeIndex, size_t levelIndex, size_t paramIndex) const\n{\n return itsDataMatrix->At(timeIndex, levelIndex, paramIndex);\n}\n\nvoid info::Data(shared_ptr m)\n{\n itsDataMatrix = m;\n}\n\nvoid info::Data(shared_ptr d)\n{\n itsDataMatrix->At(TimeIndex(), LevelIndex(), ParamIndex()) = d;\n}\n\nbool info::Value(double theValue)\n{\n return Data()->Set(itsLocationIndex, theValue) ;\n}\n\ndouble info::Value() const\n{\n return Data()->At(itsLocationIndex);\n}\n\nsize_t info::Ni() const\n{\n return Data()->SizeX();\n}\n\nsize_t info::Nj() const\n{\n return Data()->SizeY();\n}\n\ndouble info::Di() const\n{\n return abs((itsBottomLeftLongitude - itsTopRightLongitude) \/ Ni());\n}\n\ndouble info::Dj() const\n{\n return abs((itsBottomLeftLatitude - itsTopRightLatitude) \/ Nj());\n}\n\nHPScanningMode info::ScanningMode() const\n{\n return itsScanningMode;\n}\n\nvoid info::ScanningMode(HPScanningMode theScanningMode)\n{\n itsScanningMode = theScanningMode;\n}\n\nbool info::GridAndAreaEquals(shared_ptr other) const\n{\n\n\t\/**\n\t * @todo A clever way to compare if two areas are equal. For newbase we need bottomleft\/topright coordinates\n * but grib gives us just first gridpoints.\n\t *\n\t *\/\n\n if (itsBottomLeftLatitude != other->BottomLeftLatitude())\n {\n itsLogger->Trace(\"BottomLeftLatitudes aren't the same\");\n return false;\n }\n\n if (itsBottomLeftLongitude != other->BottomLeftLongitude())\n {\n itsLogger->Trace(\"BottomLeftLongitude aren't the same\");\n return false;\n }\n\n if (itsTopRightLatitude != other->TopRightLatitude())\n {\n itsLogger->Trace(\"TopRightLatitudes aren't the same\");\n return false;\n }\n\n if (itsTopRightLongitude != other->TopRightLongitude())\n {\n cout << itsTopRightLongitude << \" != \" << other->TopRightLongitude() << endl;\n\n itsLogger->Trace(\"TopRightLongitudes aren't the same\");\n return false;\n }\n\n if (itsProjection != other->Projection())\n {\n return false;\n }\n\n if (itsOrientation != other->Orientation())\n {\n return false;\n }\n\n if (Ni() != other->Ni())\n {\n return false;\n }\n\n if (Nj() != other->Nj())\n {\n return false;\n }\n\n return true;\n\n}\n\n#ifdef NEWBASE_INTERPOLATION\n\nshared_ptr info::ToNewbaseGrid() const\n{\n\n FmiInterpolationMethod interp = kLinearly;\n FmiDirection dir = static_cast (itsScanningMode);\n\n NFmiArea* theArea = 0;\n\n \/\/ Newbase does not understand grib2 longitude coordinates\n\n double bottomLeftLongitude = itsBottomLeftLongitude;\n double topRightLongitude = itsTopRightLongitude;\n\n if (bottomLeftLongitude > 180 || topRightLongitude > 180)\n {\n bottomLeftLongitude -= 180;\n topRightLongitude -= 180;\n }\n\n switch (itsProjection)\n {\n case kLatLonProjection:\n {\n theArea = new NFmiLatLonArea(NFmiPoint(bottomLeftLongitude, itsBottomLeftLatitude),\n NFmiPoint(topRightLongitude, itsTopRightLatitude));\n\n break;\n }\n\n case kRotatedLatLonProjection:\n {\n theArea = new NFmiRotatedLatLonArea(NFmiPoint(bottomLeftLongitude, itsBottomLeftLatitude),\n NFmiPoint(topRightLongitude, itsTopRightLatitude),\n NFmiPoint(0., -30.) \/\/ south pole location\n );\n break;\n }\n\n case kStereographicProjection:\n {\n theArea = new NFmiStereographicArea(NFmiPoint(bottomLeftLongitude, itsBottomLeftLatitude),\n NFmiPoint(topRightLongitude, itsTopRightLatitude),\n itsOrientation);\n break;\n\n }\n\n default:\n throw runtime_error(ClassName() + \": No supported projection found\");\n\n break;\n }\n\n shared_ptr theGrid (new NFmiGrid(theArea, Ni(), Nj(), dir, interp));\n\n size_t dataSize = Data()->Size();\n\n if (dataSize) \/\/ Do we have data\n {\n\n NFmiDataPool thePool;\n\n float* arr = new float[dataSize];\n\n \/\/ convert double array to float\n\n for (unsigned int i = 0; i < dataSize; i++)\n {\n arr[i] = static_cast (Data()->At(i));\n }\n\n if (!thePool.Init(dataSize, arr))\n {\n throw runtime_error(\"DataPool init failed\");\n }\n\n if (!theGrid->Init(&thePool))\n {\n throw runtime_error(\"Grid data init failed\");\n }\n\n delete [] arr;\n }\n\n delete theArea;\n\n return theGrid;\n\n}\n\n#endif\n\nRename kMAX_SIZE_T, add functions for south pole coordinates and compare coordinates with kCoordinateEpsilon\/*\n * info.cpp\n *\n * Created on: Nov 22, 2012\n * Author: partio\n *\/\n\n#include \"info.h\"\n#include \/\/ for std::numeric_limits::max();\n#include \n#include \"plugin_factory.h\"\n#include \"logger_factory.h\"\n\n#ifdef NEWBASE_INTERPOLATION\n#include \n#include \n#include \n#endif\n\n#define HIMAN_AUXILIARY_INCLUDE\n\n#include \"neons.h\"\n\n#undef HIMAN_AUXILIARY_INCLUDE\n\nusing namespace std;\nusing namespace himan;\n\ninfo::info()\n{\n Init();\n itsLogger = std::unique_ptr (logger_factory::Instance()->GetLog(\"info\"));\n\n itsDataMatrix = shared_ptr (new matrix_t());\n itsTimeIterator = shared_ptr (new time_iter());\n}\n\ninfo::~info()\n{\n}\n\nshared_ptr info::Clone() const\n{\n\n shared_ptr clone = shared_ptr (new info());\n\n clone->Projection(itsProjection);\n clone->Orientation(itsOrientation);\n\n clone->BottomLeftLatitude(itsBottomLeftLatitude);\n clone->BottomLeftLongitude(itsBottomLeftLongitude);\n clone->TopRightLatitude(itsTopRightLatitude);\n clone->TopRightLongitude(itsTopRightLongitude);\n\n clone->SouthPoleLatitude(itsSouthPoleLatitude);\n clone->SouthPoleLongitude(itsSouthPoleLongitude);\n\n clone->Data(itsDataMatrix);\n\n clone->ParamIterator(*itsParamIterator);\n clone->LevelIterator(*itsLevelIterator);\n clone->TimeIterator(*itsTimeIterator);\n\n clone->Producer(itsProducer);\n\n clone->OriginDateTime(itsOriginDateTime.String(\"%Y-%m-%d %H:%M:%S\"), \"%Y-%m-%d %H:%M:%S\");\n\n \/*\n clone->ParamIndex(itsParamIndex);\n clone->TimeIndex(itsTimeIndex);\n clone->LevelIndex(itsLevelIndex);\n *\/\n clone->LocationIndex(itsLocationIndex);\n\n return clone;\n\n}\n\nvoid info::Init()\n{\n\n itsProjection = kUnknownProjection;\n\n itsBottomLeftLatitude = kHPMissingFloat;\n itsBottomLeftLongitude = kHPMissingFloat;\n itsTopRightLatitude = kHPMissingFloat;\n itsTopRightLongitude = kHPMissingFloat;\n\n itsSouthPoleLatitude = kHPMissingFloat;\n itsSouthPoleLongitude = kHPMissingFloat;\n\n itsOrientation = kHPMissingFloat;\n\n itsScanningMode = kTopLeft;\n\n}\n\nstd::ostream& info::Write(std::ostream& file) const\n{\n\n file << \"<\" << ClassName() << \" \" << Version() << \">\" << endl;\n\n file << \"__itsProjection__ \" << itsProjection << endl;\n file << \"__itsBottomLeftLongitude__ \" << itsBottomLeftLongitude << endl;\n file << \"__itsBottomLeftLatitude__ \" << itsBottomLeftLatitude << endl;\n file << \"__itsTopRightLongitude__ \" << itsTopRightLongitude << endl;\n file << \"__itsTopRightLatitude__ \" << itsTopRightLatitude << endl;\n file << \"__itsOrientation__ \" << itsOrientation << endl;\n\n file << \"__itsOriginDateTime__ \" << OriginDateTime().String() << endl;\n\n file << \"__itsProducer__ \" << itsProducer << endl;\n\n file << itsParamIterator << endl;\n file << itsLevelIterator << endl;\n file << itsTimeIterator << endl;\n\n return file;\n}\n\n\nbool info::Create()\n{\n\n itsDataMatrix = shared_ptr (new matrix_t(itsTimeIterator->Size(), itsLevelIterator->Size(), itsParamIterator->Size()));\n\n Reset();\n\n while (NextTime())\n {\n ResetLevel();\n\n while (NextLevel())\n {\n ResetParam();\n\n while (NextParam())\n \/\/ Create empty placeholders\n {\n \tData(shared_ptr (new d_matrix_t(0, 0)));\n }\n }\n }\n\n return true;\n\n}\n\nHPProjectionType info::Projection() const\n{\n return itsProjection;\n}\n\nvoid info::Projection(HPProjectionType theProjection)\n{\n itsProjection = theProjection;\n}\n\ndouble info::BottomLeftLatitude() const\n{\n return itsBottomLeftLatitude;\n}\ndouble info::BottomLeftLongitude() const\n{\n return itsBottomLeftLongitude;\n}\ndouble info::TopRightLongitude() const\n{\n return itsTopRightLongitude;\n}\ndouble info::TopRightLatitude() const\n{\n return itsTopRightLatitude;\n}\n\nvoid info::BottomLeftLatitude(double theBottomLeftLatitude)\n{\n itsBottomLeftLatitude = theBottomLeftLatitude;\n}\n\nvoid info::BottomLeftLongitude(double theBottomLeftLongitude)\n{\n itsBottomLeftLongitude = theBottomLeftLongitude;\n}\n\nvoid info::TopRightLatitude(double theTopRightLatitude)\n{\n itsTopRightLatitude = theTopRightLatitude;\n}\n\nvoid info::TopRightLongitude(double theTopRightLongitude)\n{\n itsTopRightLongitude = theTopRightLongitude;\n}\n\nvoid info::SouthPoleLatitude(double theSouthPoleLatitude)\n{\n itsSouthPoleLatitude = theSouthPoleLatitude;\n}\n\ndouble info::SouthPoleLatitude() const\n{\n return itsSouthPoleLatitude;\n}\n\nvoid info::SouthPoleLongitude(double theSouthPoleLongitude)\n{\n itsSouthPoleLongitude = theSouthPoleLongitude;\n}\n\ndouble info::SouthPoleLongitude() const\n{\n return itsSouthPoleLongitude;\n}\n\ndouble info::Orientation() const\n{\n return itsOrientation;\n}\n\nvoid info::Orientation(double theOrientation)\n{\n itsOrientation = theOrientation;\n}\n\nconst producer& info::Producer() const\n{\n return itsProducer;\n}\n\nvoid info::Producer(long theFmiProducerId)\n{\n itsProducer = producer(theFmiProducerId);\n}\n\n\nvoid info::Producer(const producer& theProducer)\n{\n itsProducer = theProducer;\n}\n\/*\nvector > info::Params() const\n{\n\treturn itsParams;\n}\n*\/\nvoid info::ParamIterator(const param_iter& theParamIterator)\n{\n itsParamIterator = shared_ptr (new param_iter(theParamIterator));\n}\n\nvoid info::Params(const vector& theParams)\n{\n itsParamIterator = shared_ptr (new param_iter(theParams));\n}\n\/*\nvector > info::Levels() const\n{\n\treturn itsLevels;\n}\n*\/\n\nvoid info::LevelIterator(const level_iter& theLevelIterator)\n{\n itsLevelIterator = shared_ptr (new level_iter(theLevelIterator));\n}\n\nvoid info::Levels(const vector& theLevels)\n{\n \/\/itsLevels = theLevels;\n itsLevelIterator = shared_ptr (new level_iter(theLevels));\n}\n\/*\nvector > info::Times() const\n{\n\treturn itsTimes;\n}*\/\n\nvoid info::TimeIterator(const time_iter& theTimeIterator)\n{\n itsTimeIterator = shared_ptr (new time_iter(theTimeIterator));\n}\n\nvoid info::Times(const vector& theTimes)\n{\n \/\/itsTimes = theTimes;\n itsTimeIterator = shared_ptr (new time_iter(theTimes));\n}\n\nraw_time info::OriginDateTime() const\n{\n return itsOriginDateTime;\n}\n\nvoid info::OriginDateTime(const string& theOriginDateTime, const string& theTimeMask)\n{\n itsOriginDateTime = raw_time(theOriginDateTime, theTimeMask);\n}\n\nbool info::Param(const param& theRequestedParam)\n{\n return itsParamIterator->Set(theRequestedParam);\n}\n\nbool info::NextParam()\n{\n return itsParamIterator->Next();\n}\n\nvoid info::ResetParam()\n{\n itsParamIterator->Reset();\n}\n\nbool info::FirstParam()\n{\n return itsParamIterator->First();\n}\n\nsize_t info::ParamIndex() const\n{\n return itsParamIterator->Index();\n}\n\nvoid info::ParamIndex(size_t theParamIndex)\n{\n itsParamIterator->Set(theParamIndex);\n}\n\nparam& info::Param() const\n{\n return itsParamIterator->At();\n}\n\nbool info::NextLevel()\n{\n return itsLevelIterator->Next();\n}\n\nvoid info::Reset()\n{\n ResetLevel();\n ResetParam();\n ResetTime();\n ResetLocation();\n}\n\nvoid info::ResetLevel()\n{\n itsLevelIterator->Reset();\n}\n\nbool info::FirstLevel()\n{\n return itsLevelIterator->First();\n}\n\nsize_t info::LevelIndex() const\n{\n return itsLevelIterator->Index();\n}\n\nvoid info::LevelIndex(size_t theLevelIndex)\n{\n itsLevelIterator->Set(theLevelIndex);\n}\n\nbool info::Level(const level& theLevel)\n{\n return itsLevelIterator->Set(theLevel);\n}\n\nlevel& info::Level() const\n{\n return itsLevelIterator->At();\n}\n\nbool info::NextTime()\n{\n return itsTimeIterator->Next();\n}\n\nvoid info::ResetTime()\n{\n itsTimeIterator->Reset();\n}\n\nbool info::FirstTime()\n{\n return itsTimeIterator->First();\n}\n\nsize_t info::TimeIndex() const\n{\n return itsTimeIterator->Index();\n}\n\nvoid info::TimeIndex(size_t theTimeIndex)\n{\n itsTimeIterator->Set(theTimeIndex);\n}\n\nbool info::Time(const forecast_time& theTime)\n{\n return itsTimeIterator->Set(theTime);\n}\n\nforecast_time& info::Time() const\n{\n return itsTimeIterator->At();\n}\n\nbool info::NextLocation()\n{\n if (itsLocationIndex == kIteratorResetValue)\n {\n itsLocationIndex = 0; \/\/ ResetLocation() has been called before this function\n }\n\n else\n {\n itsLocationIndex++;\n }\n\n size_t locationSize = Data()->Size();\n\n if (itsLocationIndex >= locationSize)\n {\n itsLocationIndex = (locationSize == 0) ? 0 : locationSize - 1;\n\n return false;\n }\n\n return true;\n\n}\n\nvoid info::ResetLocation()\n{\n itsLocationIndex = kIteratorResetValue;\n}\n\nbool info::FirstLocation()\n{\n ResetLocation();\n\n return NextTime();\n}\n\nvoid info::LocationIndex(size_t theLocationIndex)\n{\n itsLocationIndex = theLocationIndex;\n}\n\nshared_ptr info::Data() const\n{\n return itsDataMatrix->At(TimeIndex(), LevelIndex(), ParamIndex());\n}\n\nshared_ptr info::Data(size_t timeIndex, size_t levelIndex, size_t paramIndex) const\n{\n return itsDataMatrix->At(timeIndex, levelIndex, paramIndex);\n}\n\nvoid info::Data(shared_ptr m)\n{\n itsDataMatrix = m;\n}\n\nvoid info::Data(shared_ptr d)\n{\n itsDataMatrix->At(TimeIndex(), LevelIndex(), ParamIndex()) = d;\n}\n\nbool info::Value(double theValue)\n{\n return Data()->Set(itsLocationIndex, theValue) ;\n}\n\ndouble info::Value() const\n{\n return Data()->At(itsLocationIndex);\n}\n\nsize_t info::Ni() const\n{\n return Data()->SizeX();\n}\n\nsize_t info::Nj() const\n{\n return Data()->SizeY();\n}\n\ndouble info::Di() const\n{\n return abs((itsBottomLeftLongitude - itsTopRightLongitude) \/ Ni());\n}\n\ndouble info::Dj() const\n{\n return abs((itsBottomLeftLatitude - itsTopRightLatitude) \/ Nj());\n}\n\nHPScanningMode info::ScanningMode() const\n{\n return itsScanningMode;\n}\n\nvoid info::ScanningMode(HPScanningMode theScanningMode)\n{\n itsScanningMode = theScanningMode;\n}\n\nbool info::GridAndAreaEquals(shared_ptr other) const\n{\n\n\tconst float kCoordinateEpsilon = 0.00001;\n\n\t\/**\n\t * @todo A clever way to compare if two areas are equal. For newbase we need bottomleft\/topright coordinates\n * but grib gives us just first gridpoints.\n\t *\n\t *\/\n\n if (fabs(itsBottomLeftLatitude - other->BottomLeftLatitude()) > kCoordinateEpsilon)\n {\n itsLogger->Trace(\"BottomLeftLatitudes don't match: \" + boost::lexical_cast (itsBottomLeftLatitude) + \" vs \" + boost::lexical_cast (other->BottomLeftLatitude()));\n return false;\n }\n\n if (fabs(itsBottomLeftLongitude - other->BottomLeftLongitude()) > kCoordinateEpsilon)\n {\n itsLogger->Trace(\"BottomLeftLongitude don't match: \" + boost::lexical_cast (itsBottomLeftLongitude) + \" vs \" + boost::lexical_cast (other->BottomLeftLongitude()));\n return false;\n }\n\n if (fabs(itsTopRightLatitude - other->TopRightLatitude()) > kCoordinateEpsilon)\n {\n itsLogger->Trace(\"TopRightLatitudes don't match: \" + boost::lexical_cast (itsTopRightLatitude) + \" vs \" + boost::lexical_cast (other->TopRightLatitude()));\n return false;\n }\n\n if (fabs(itsTopRightLongitude - other->TopRightLongitude()) > kCoordinateEpsilon)\n {\n itsLogger->Trace(\"TopRightLongitudes don't match: \" + boost::lexical_cast (itsTopRightLongitude) + \" vs \" + boost::lexical_cast (other->TopRightLongitude()));\n return false;\n }\n\n if (itsProjection != other->Projection())\n {\n itsLogger->Trace(\"Projections don't match: \" + boost::lexical_cast (itsProjection) + \" vs \" + boost::lexical_cast (other->Projection()));\n return false;\n }\n\n if (itsProjection == kRotatedLatLonProjection)\n {\n\t\tif (fabs(itsSouthPoleLatitude - other->SouthPoleLatitude()) > kCoordinateEpsilon)\n \t{\n \titsLogger->Trace(\"SouthPoleLatitudes don't match: \" + boost::lexical_cast (itsSouthPoleLatitude) + \" vs \" + boost::lexical_cast (other->SouthPoleLatitude()));\n \treturn false;\n \t}\n\t\tif (fabs(itsSouthPoleLongitude - other->SouthPoleLongitude()) > kCoordinateEpsilon)\n \t{\n \titsLogger->Trace(\"SouthPoleLongitudes don't match: \" + boost::lexical_cast (itsSouthPoleLongitude) + \" vs \" + boost::lexical_cast (other->SouthPoleLongitude()));\n \treturn false;\n \t}\n }\n\n if (itsOrientation != other->Orientation())\n {\n \titsLogger->Trace(\"Orientations don't match: \" + boost::lexical_cast (itsOrientation) + \" vs \" + boost::lexical_cast (other->Orientation()));\n return false;\n }\n\n if (Ni() != other->Ni())\n {\n \titsLogger->Trace(\"Grid X-counts don't match: \" + boost::lexical_cast (Ni()) + \" vs \" + boost::lexical_cast (other->Ni()));\n return false;\n }\n\n if (Nj() != other->Nj())\n {\n \titsLogger->Trace(\"Grid Y-counts don't match: \" + boost::lexical_cast (Nj()) + \" vs \" + boost::lexical_cast (other->Nj()));\n return false;\n }\n\n return true;\n\n}\n\n#ifdef NEWBASE_INTERPOLATION\n\nshared_ptr info::ToNewbaseGrid() const\n{\n\n FmiInterpolationMethod interp = kLinearly;\n FmiDirection dir = static_cast (itsScanningMode);\n\n NFmiArea* theArea = 0;\n\n \/\/ Newbase does not understand grib2 longitude coordinates\n\n double bottomLeftLongitude = itsBottomLeftLongitude;\n double topRightLongitude = itsTopRightLongitude;\n\n if (bottomLeftLongitude > 180 || topRightLongitude > 180)\n {\n bottomLeftLongitude -= 180;\n topRightLongitude -= 180;\n }\n\n switch (itsProjection)\n {\n case kLatLonProjection:\n {\n theArea = new NFmiLatLonArea(NFmiPoint(bottomLeftLongitude, itsBottomLeftLatitude),\n NFmiPoint(topRightLongitude, itsTopRightLatitude));\n\n break;\n }\n\n case kRotatedLatLonProjection:\n {\n theArea = new NFmiRotatedLatLonArea(NFmiPoint(bottomLeftLongitude, itsBottomLeftLatitude),\n NFmiPoint(topRightLongitude, itsTopRightLatitude),\n NFmiPoint(0., -30.) \/\/ south pole location\n );\n break;\n }\n\n case kStereographicProjection:\n {\n theArea = new NFmiStereographicArea(NFmiPoint(bottomLeftLongitude, itsBottomLeftLatitude),\n NFmiPoint(topRightLongitude, itsTopRightLatitude),\n itsOrientation);\n break;\n\n }\n\n default:\n throw runtime_error(ClassName() + \": No supported projection found\");\n\n break;\n }\n\n shared_ptr theGrid (new NFmiGrid(theArea, Ni(), Nj(), dir, interp));\n\n size_t dataSize = Data()->Size();\n\n if (dataSize) \/\/ Do we have data\n {\n\n NFmiDataPool thePool;\n\n float* arr = new float[dataSize];\n\n \/\/ convert double array to float\n\n for (unsigned int i = 0; i < dataSize; i++)\n {\n arr[i] = static_cast (Data()->At(i));\n }\n\n if (!thePool.Init(dataSize, arr))\n {\n throw runtime_error(\"DataPool init failed\");\n }\n\n if (!theGrid->Init(&thePool))\n {\n throw runtime_error(\"Grid data init failed\");\n }\n\n delete [] arr;\n }\n\n delete theArea;\n\n return theGrid;\n\n}\n\n#endif\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/views\/tab_contents\/tab_contents_container.h\"\n\n#include \"chrome\/browser\/renderer_host\/render_view_host.h\"\n#include \"chrome\/browser\/renderer_host\/render_widget_host_view.h\"\n#include \"chrome\/browser\/tab_contents\/interstitial_page.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/browser\/ui\/view_ids.h\"\n#include \"chrome\/browser\/ui\/views\/tab_contents\/native_tab_contents_container_gtk.h\"\n#include \"chrome\/browser\/ui\/views\/tab_contents\/native_tab_contents_container.h\"\n#include \"chrome\/browser\/ui\/views\/tab_contents\/tab_contents_view_views.h\"\n#include \"chrome\/common\/notification_details.h\"\n#include \"chrome\/common\/notification_source.h\"\n#include \"views\/fill_layout.h\"\n\n\/\/ Some of this class is implemented in tab_contents_container.cc, where\n\/\/ the implementation doesn't vary between a pure views approach and a\n\/\/ native view host approach. See the header file for details.\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ TabContentsContainer, public:\n\nTabContentsContainer::TabContentsContainer()\n : tab_contents_(NULL) {\n SetID(VIEW_ID_TAB_CONTAINER);\n}\n\nvoid TabContentsContainer::SetReservedContentsRect(\n const gfx::Rect& reserved_rect) {\n cached_reserved_rect_ = reserved_rect;\n \/\/ TODO(anicolao): find out what this is supposed to be used for and ensure\n \/\/ it's OK for touch.\n}\n\nvoid TabContentsContainer::ChangeTabContents(TabContents* contents) {\n if (tab_contents_) {\n views::View *v = static_cast(tab_contents_->view());\n RemoveChildView(v);\n tab_contents_->WasHidden();\n RemoveObservers();\n }\n tab_contents_ = contents;\n \/\/ When detaching the last tab of the browser ChangeTabContents is invoked\n \/\/ with NULL. Don't attempt to do anything in that case.\n if (tab_contents_) {\n views::View *v = static_cast(contents->view());\n AddChildView(v);\n SetLayoutManager(new views::FillLayout());\n Layout();\n AddObservers();\n }\n}\n\nvoid TabContentsContainer::TabContentsFocused(TabContents* tab_contents) {\n}\n\nvoid TabContentsContainer::SetFastResize(bool fast_resize) {\n}\n\nvoid TabContentsContainer::RenderViewHostChanged(RenderViewHost* old_host,\n RenderViewHost* new_host) {\n NOTIMPLEMENTED(); \/\/ TODO(anicolao)\n}\nDo not include GTK file on Windows.\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/views\/tab_contents\/tab_contents_container.h\"\n\n#include \"chrome\/browser\/renderer_host\/render_view_host.h\"\n#include \"chrome\/browser\/renderer_host\/render_widget_host_view.h\"\n#include \"chrome\/browser\/tab_contents\/interstitial_page.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/browser\/ui\/view_ids.h\"\n#include \"chrome\/browser\/ui\/views\/tab_contents\/native_tab_contents_container.h\"\n#include \"chrome\/browser\/ui\/views\/tab_contents\/tab_contents_view_views.h\"\n#include \"chrome\/common\/notification_details.h\"\n#include \"chrome\/common\/notification_source.h\"\n#include \"views\/fill_layout.h\"\n\n#if defined(OS_LINUX)\n#include \"chrome\/browser\/ui\/views\/tab_contents\/native_tab_contents_container_gtk.h\"\n#endif\n\n\/\/ Some of this class is implemented in tab_contents_container.cc, where\n\/\/ the implementation doesn't vary between a pure views approach and a\n\/\/ native view host approach. See the header file for details.\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ TabContentsContainer, public:\n\nTabContentsContainer::TabContentsContainer()\n : tab_contents_(NULL) {\n SetID(VIEW_ID_TAB_CONTAINER);\n}\n\nvoid TabContentsContainer::SetReservedContentsRect(\n const gfx::Rect& reserved_rect) {\n cached_reserved_rect_ = reserved_rect;\n \/\/ TODO(anicolao): find out what this is supposed to be used for and ensure\n \/\/ it's OK for touch.\n}\n\nvoid TabContentsContainer::ChangeTabContents(TabContents* contents) {\n if (tab_contents_) {\n views::View *v = static_cast(tab_contents_->view());\n RemoveChildView(v);\n tab_contents_->WasHidden();\n RemoveObservers();\n }\n tab_contents_ = contents;\n \/\/ When detaching the last tab of the browser ChangeTabContents is invoked\n \/\/ with NULL. Don't attempt to do anything in that case.\n if (tab_contents_) {\n views::View *v = static_cast(contents->view());\n AddChildView(v);\n SetLayoutManager(new views::FillLayout());\n Layout();\n AddObservers();\n }\n}\n\nvoid TabContentsContainer::TabContentsFocused(TabContents* tab_contents) {\n}\n\nvoid TabContentsContainer::SetFastResize(bool fast_resize) {\n}\n\nvoid TabContentsContainer::RenderViewHostChanged(RenderViewHost* old_host,\n RenderViewHost* new_host) {\n NOTIMPLEMENTED(); \/\/ TODO(anicolao)\n}\n<|endoftext|>"} {"text":"\/*\n Copyright 2017 Barcelona Supercomputing Center (www.bsc.es)\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n#include \"persistent_cache.h\"\n\nstatic int cached_object_init(cached_object* self,\n PyObject *args, PyObject *kwds) {\n return 0;\n}\n\nstatic void cached_object_dealloc(cached_object* self) {\n Py_DECREF(self->obj);\n Py_XDECREF(self->comparison_function);\n}\n\nbool _default_comparison_function(const cached_object& a, const cached_object& b) {\n if(a.hit_count != b.hit_count) {\n return a.hit_count < b.hit_count;\n }\n if(a.last_hit_time != b.last_hit_time) {\n return a.last_hit_time < b.last_hit_time;\n }\n return a.id < b.id;\n}\n\nstatic PyObject* default_comparison_function(PyObject* self, PyObject* args) {\n PyObject* a;\n PyObject* b;\n if(!Py_BuildValue(\"OO\", &a, &b)) {\n return NULL;\n }\n cached_object* _a = (cached_object*)a;\n cached_object* _b = (cached_object*)b;\n return PyBool_FromLong(_default_comparison_function(*_a, *_b));\n}\n\nstatic PyObject*\ncached_object_new(PyTypeObject* type, PyObject* args, PyObject* kwds) {\n cached_object* self = (cached_object*)type->tp_alloc(type, 0);\n const char* object_id;\n\n if(!PyArg_ParseTuple(args, \"sOlOl\", &object_id, &self->obj, &self->object_size,\n &self->comparison_function, &self->last_hit_time)) {\n return NULL;\n }\n Py_INCREF(self->obj);\n Py_XINCREF(self->comparison_function);\n self->id = std::string(object_id);\n return (PyObject*)self;\n}\n\nstatic PyObject* cached_object_get_id(PyObject* self, PyObject* args) {\n cached_object* _self = (cached_object*)self;\n return PyString_FromStringAndSize(_self->id.c_str(), _self->id.size());\n}\n\nstatic PyObject* cached_object_get_obj(PyObject* self, PyObject* args) {\n cached_object* _self = (cached_object*)self;\n return _self->obj;\n}\n\nvoid _delete_element(Cache* c, cached_object* obj) {\n c->current_size -= obj->object_size;\n c->H->erase(obj->id);\n Py_DECREF(obj->obj);\n Py_XDECREF(obj->comparison_function);\n c->S->erase(*obj);\n}\n\nvoid _delete_first_element(Cache* c) {\n cached_object* first_element = (cached_object*)&*(c->S->begin());\n _delete_element(c, first_element);\n}\n\nstatic void Cache_dealloc(Cache* self) {\n while(!self->S->empty()) _delete_first_element(self);\n delete(self->S);\n delete(self->H);\n Py_XDECREF(self->comparator);\n}\n\nstatic int Cache_init(Cache* self, PyObject* args, PyObject* kwds) {\n return 0;\n}\n\nstatic PyObject* Cache_new(PyTypeObject* type, PyObject* args, PyObject* kwds) {\n Cache* self = (Cache*)type->tp_alloc(type, 0);\n self->S = new std::set< cached_object, cached_object_comparator >();\n self->H = new std::map< std::string, cached_object >();\n self->current_time = 0ll;\n self->size_limit = 1024*1024*1024ll;\n static char* kwlist[] = {(char*)\"size_limit\", (char*)\"comparison_function\"};\n if (!PyArg_ParseTupleAndKeywords(args, kwds, \"|lO\", kwlist, &self->size_limit,\n &self->comparator)) {\n return NULL;\n }\n Py_XINCREF(self->comparator);\n return (PyObject*)self;\n}\n\nstatic PyObject* Cache_add(PyObject* self, PyObject* args) {\n Cache* _self = (Cache*)self;\n const char* object_id;\n PyObject* obj_to_add;\n long long object_size = -1ll;\n if(!PyArg_ParseTuple(args, \"sO|l\", &object_id, &obj_to_add, &object_size)) {\n return NULL;\n }\n cached_object to_add = *(new cached_object());\n to_add.id = std::string(object_id);\n if(_self->H->count(to_add.id)) {\n std::string err_msg = \"Object with id \" + to_add.id + \" is\\\n already cached!\";\n PyErr_SetString(PyExc_KeyError, err_msg.c_str());\n return NULL;\n }\n to_add.obj = obj_to_add;\n if(object_size == -1ll) {\n \/\/ rough approximation to the object's size (only invoked when obj size is\n \/\/ not given by the user)\n object_size = sizeof(*obj_to_add);\n }\n \/\/ Delete the object with least priority until cache is empty or\n \/\/ the total used space is less than the limit\n \/\/ Note that this operation can delete the most recent object\n \/\/ depending on the comparison function\n while(!_self->S->empty() && _self->current_size >= _self->size_limit) {\n _delete_first_element(_self);\n }\n \/\/ Does this object fit on cache?\n \/\/ If yes, add it and then update the total used cache space\n if(_self->current_size + object_size <= _self->size_limit) {\n to_add.object_size = object_size;\n to_add.hit_count = 1;\n to_add.last_hit_time = _self->current_time;\n to_add.comparison_function = _self->comparator;\n Py_XINCREF(_self->comparator);\n Py_INCREF(to_add.obj);\n _self->current_size += to_add.object_size;\n std::map< std::string, cached_object >& map_ref = *_self->H;\n map_ref[to_add.id] = to_add;\n _self->S->insert(map_ref[to_add.id]);\n }\n ++_self->current_time;\n Py_RETURN_NONE;\n}\n\nbool _has_object(Cache* self, std::string id) {\n return self->H->count(id);\n}\n\nstatic PyObject* Cache_has_object(PyObject* self, PyObject* args) {\n Cache* _self = (Cache*)self;\n const char* to_query;\n if(!PyArg_ParseTuple(args, \"s\", &to_query)) {\n return NULL;\n }\n return PyBool_FromLong(_has_object(_self, std::string(to_query)));\n}\n\nstatic PyObject* Cache_hit(PyObject* self, PyObject* args) {\n Cache* _self = (Cache*) self;\n const char* to_query;\n if(!PyArg_ParseTuple(args, \"s\", &to_query)) {\n return NULL;\n }\n std::string object_id(to_query);\n if(!_has_object(_self, object_id)) {\n std::string err_msg = \"Cache does not contain object with id \" +\n object_id;\n PyErr_SetString(PyExc_KeyError, err_msg.c_str());\n return NULL;\n }\n std::map< std::string, cached_object >& map_ref = *_self->H;\n cached_object& cached_friend = map_ref[object_id];\n \/\/ As a remark: an std::set cannot know when some of its objects changes in\n \/\/ such a way that its ordering also does, so it must be removed and then\n \/\/ re-added in order to ensure that it is in a proper place inside the set\n _self->S->erase(cached_friend);\n ++cached_friend.hit_count;\n cached_friend.last_hit_time = _self->current_time;\n _self->S->insert(cached_friend);\n ++_self->current_time;\n Py_RETURN_NONE;\n}\n\nstatic PyObject* Cache_get(PyObject* self, PyObject* args) {\n Cache* _self = (Cache*)self;\n const char* to_query;\n if(!PyArg_ParseTuple(args, \"s\", &to_query)) {\n return NULL;\n }\n std::string id(to_query);\n if(!_has_object(_self, id)) {\n std::string err_msg = \"Cache does not contain object with id \" +\n id;\n PyErr_SetString(PyExc_KeyError, err_msg.c_str());\n return NULL;\n }\n std::map< std::string, cached_object >& map_ref = *_self->H;\n PyObject* ret = map_ref[id].obj;\n Py_INCREF(ret);\n return ret;\n}\n\nstatic PyObject* Cache_delete(PyObject* self, PyObject* args) {\n Cache* _self = (Cache*) self;\n const char* to_query;\n if(!PyArg_ParseTuple(args, \"s\", &to_query)) {\n return NULL;\n }\n std::string id(to_query);\n if(!_has_object(_self, id)) {\n std::string err_msg = \"Cache does not contain object with id \" +\n id;\n PyErr_SetString(PyExc_KeyError, err_msg.c_str());\n return NULL;\n }\n std::map< std::string, cached_object >& map_ref = *_self->H;\n cached_object& cached_friend = map_ref[id];\n _delete_element(_self, &cached_friend);\n Py_RETURN_NONE;\n}\n\nstatic PyObject* Cache_get_last(PyObject* self, PyObject* args) {\n Cache* _self = (Cache*)self;\n cached_object ret = *_self->S->begin();\n Py_INCREF(ret.obj);\n return ret.obj;\n}\n\nstatic PyObject* Cache_is_empty(PyObject* self, PyObject* args) {\n Cache* _self = (Cache*)self;\n return PyBool_FromLong(_self->S->empty());\n}\n\nstatic PyObject* Cache_set_object(PyObject* self, PyObject* args) {\n Cache* _self = (Cache*)self;\n const char* to_query;\n PyObject* new_obj;\n long long new_object_size = -1;\n if(!PyArg_ParseTuple(args, \"sO|l\", &to_query, &new_obj, &new_object_size)) {\n return NULL;\n }\n if(new_object_size == -1) {\n new_object_size = sizeof(*new_obj);\n }\n std::string id(to_query);\n std::map< std::string, cached_object >& map_ref = *_self->H;\n \/\/ let's get the cached_object that contains our target object\n \/\/ and remove it from the priority set\n cached_object& cached_friend = map_ref[id];\n long long old_object_size = cached_friend.object_size;\n _self->S->erase(cached_friend);\n Py_DECREF(cached_friend.obj);\n \/\/ update the data structure with the new object\n cached_friend.obj = new_obj;\n Py_INCREF(cached_friend.obj);\n cached_friend.object_size = new_object_size;\n _self->current_size -= old_object_size;\n _self->current_size += new_object_size;\n _self->S->insert(cached_friend);\n \/\/ a new object may have its size modified (for example, it we append stuff\n \/\/ to some list). Let's be sure that this modification do not violate the\n \/\/ cache invariant\n while(!_self->S->empty() && _self->current_size >= _self->size_limit) {\n _delete_first_element(_self);\n }\n Py_RETURN_NONE;\n}\n\nPyMODINIT_FUNC initpersistent_cache(void) {\n PyObject* m;\n m = Py_InitModule(\"persistent_cache\", module_methods);\n\n if (PyType_Ready(&cached_objectType) < 0)\n return;\n Py_INCREF(&cached_objectType);\n PyModule_AddObject(m, \"cached_object\", (PyObject*)&cached_objectType);\n\n if (PyType_Ready(&CacheType) < 0)\n return;\n Py_INCREF(&CacheType);\n PyModule_AddObject(m, \"Cache\", (PyObject*)&CacheType);\n}\nadd explanatory comments to the size approximation in set_object\/*\n Copyright 2017 Barcelona Supercomputing Center (www.bsc.es)\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n#include \"persistent_cache.h\"\n\nstatic int cached_object_init(cached_object* self,\n PyObject *args, PyObject *kwds) {\n return 0;\n}\n\nstatic void cached_object_dealloc(cached_object* self) {\n Py_DECREF(self->obj);\n Py_XDECREF(self->comparison_function);\n}\n\nbool _default_comparison_function(const cached_object& a, const cached_object& b) {\n if(a.hit_count != b.hit_count) {\n return a.hit_count < b.hit_count;\n }\n if(a.last_hit_time != b.last_hit_time) {\n return a.last_hit_time < b.last_hit_time;\n }\n return a.id < b.id;\n}\n\nstatic PyObject* default_comparison_function(PyObject* self, PyObject* args) {\n PyObject* a;\n PyObject* b;\n if(!Py_BuildValue(\"OO\", &a, &b)) {\n return NULL;\n }\n cached_object* _a = (cached_object*)a;\n cached_object* _b = (cached_object*)b;\n return PyBool_FromLong(_default_comparison_function(*_a, *_b));\n}\n\nstatic PyObject*\ncached_object_new(PyTypeObject* type, PyObject* args, PyObject* kwds) {\n cached_object* self = (cached_object*)type->tp_alloc(type, 0);\n const char* object_id;\n\n if(!PyArg_ParseTuple(args, \"sOlOl\", &object_id, &self->obj, &self->object_size,\n &self->comparison_function, &self->last_hit_time)) {\n return NULL;\n }\n Py_INCREF(self->obj);\n Py_XINCREF(self->comparison_function);\n self->id = std::string(object_id);\n return (PyObject*)self;\n}\n\nstatic PyObject* cached_object_get_id(PyObject* self, PyObject* args) {\n cached_object* _self = (cached_object*)self;\n return PyString_FromStringAndSize(_self->id.c_str(), _self->id.size());\n}\n\nstatic PyObject* cached_object_get_obj(PyObject* self, PyObject* args) {\n cached_object* _self = (cached_object*)self;\n return _self->obj;\n}\n\nvoid _delete_element(Cache* c, cached_object* obj) {\n c->current_size -= obj->object_size;\n c->H->erase(obj->id);\n Py_DECREF(obj->obj);\n Py_XDECREF(obj->comparison_function);\n c->S->erase(*obj);\n}\n\nvoid _delete_first_element(Cache* c) {\n cached_object* first_element = (cached_object*)&*(c->S->begin());\n _delete_element(c, first_element);\n}\n\nstatic void Cache_dealloc(Cache* self) {\n while(!self->S->empty()) _delete_first_element(self);\n delete(self->S);\n delete(self->H);\n Py_XDECREF(self->comparator);\n}\n\nstatic int Cache_init(Cache* self, PyObject* args, PyObject* kwds) {\n return 0;\n}\n\nstatic PyObject* Cache_new(PyTypeObject* type, PyObject* args, PyObject* kwds) {\n Cache* self = (Cache*)type->tp_alloc(type, 0);\n self->S = new std::set< cached_object, cached_object_comparator >();\n self->H = new std::map< std::string, cached_object >();\n self->current_time = 0ll;\n self->size_limit = 1024*1024*1024ll;\n static char* kwlist[] = {(char*)\"size_limit\", (char*)\"comparison_function\"};\n if (!PyArg_ParseTupleAndKeywords(args, kwds, \"|lO\", kwlist, &self->size_limit,\n &self->comparator)) {\n return NULL;\n }\n Py_XINCREF(self->comparator);\n return (PyObject*)self;\n}\n\nstatic PyObject* Cache_add(PyObject* self, PyObject* args) {\n Cache* _self = (Cache*)self;\n const char* object_id;\n PyObject* obj_to_add;\n long long object_size = -1ll;\n if(!PyArg_ParseTuple(args, \"sO|l\", &object_id, &obj_to_add, &object_size)) {\n return NULL;\n }\n cached_object to_add = *(new cached_object());\n to_add.id = std::string(object_id);\n if(_self->H->count(to_add.id)) {\n std::string err_msg = \"Object with id \" + to_add.id + \" is\\\n already cached!\";\n PyErr_SetString(PyExc_KeyError, err_msg.c_str());\n return NULL;\n }\n to_add.obj = obj_to_add;\n if(object_size == -1ll) {\n \/\/ rough approximation to the object's size (only invoked when obj size is\n \/\/ not given by the user)\n object_size = sizeof(*obj_to_add);\n }\n \/\/ Delete the object with least priority until cache is empty or\n \/\/ the total used space is less than the limit\n \/\/ Note that this operation can delete the most recent object\n \/\/ depending on the comparison function\n while(!_self->S->empty() && _self->current_size >= _self->size_limit) {\n _delete_first_element(_self);\n }\n \/\/ Does this object fit on cache?\n \/\/ If yes, add it and then update the total used cache space\n if(_self->current_size + object_size <= _self->size_limit) {\n to_add.object_size = object_size;\n to_add.hit_count = 1;\n to_add.last_hit_time = _self->current_time;\n to_add.comparison_function = _self->comparator;\n Py_XINCREF(_self->comparator);\n Py_INCREF(to_add.obj);\n _self->current_size += to_add.object_size;\n std::map< std::string, cached_object >& map_ref = *_self->H;\n map_ref[to_add.id] = to_add;\n _self->S->insert(map_ref[to_add.id]);\n }\n ++_self->current_time;\n Py_RETURN_NONE;\n}\n\nbool _has_object(Cache* self, std::string id) {\n return self->H->count(id);\n}\n\nstatic PyObject* Cache_has_object(PyObject* self, PyObject* args) {\n Cache* _self = (Cache*)self;\n const char* to_query;\n if(!PyArg_ParseTuple(args, \"s\", &to_query)) {\n return NULL;\n }\n return PyBool_FromLong(_has_object(_self, std::string(to_query)));\n}\n\nstatic PyObject* Cache_hit(PyObject* self, PyObject* args) {\n Cache* _self = (Cache*) self;\n const char* to_query;\n if(!PyArg_ParseTuple(args, \"s\", &to_query)) {\n return NULL;\n }\n std::string object_id(to_query);\n if(!_has_object(_self, object_id)) {\n std::string err_msg = \"Cache does not contain object with id \" +\n object_id;\n PyErr_SetString(PyExc_KeyError, err_msg.c_str());\n return NULL;\n }\n std::map< std::string, cached_object >& map_ref = *_self->H;\n cached_object& cached_friend = map_ref[object_id];\n \/\/ As a remark: an std::set cannot know when some of its objects changes in\n \/\/ such a way that its ordering also does, so it must be removed and then\n \/\/ re-added in order to ensure that it is in a proper place inside the set\n _self->S->erase(cached_friend);\n ++cached_friend.hit_count;\n cached_friend.last_hit_time = _self->current_time;\n _self->S->insert(cached_friend);\n ++_self->current_time;\n Py_RETURN_NONE;\n}\n\nstatic PyObject* Cache_get(PyObject* self, PyObject* args) {\n Cache* _self = (Cache*)self;\n const char* to_query;\n if(!PyArg_ParseTuple(args, \"s\", &to_query)) {\n return NULL;\n }\n std::string id(to_query);\n if(!_has_object(_self, id)) {\n std::string err_msg = \"Cache does not contain object with id \" +\n id;\n PyErr_SetString(PyExc_KeyError, err_msg.c_str());\n return NULL;\n }\n std::map< std::string, cached_object >& map_ref = *_self->H;\n PyObject* ret = map_ref[id].obj;\n Py_INCREF(ret);\n return ret;\n}\n\nstatic PyObject* Cache_delete(PyObject* self, PyObject* args) {\n Cache* _self = (Cache*) self;\n const char* to_query;\n if(!PyArg_ParseTuple(args, \"s\", &to_query)) {\n return NULL;\n }\n std::string id(to_query);\n if(!_has_object(_self, id)) {\n std::string err_msg = \"Cache does not contain object with id \" +\n id;\n PyErr_SetString(PyExc_KeyError, err_msg.c_str());\n return NULL;\n }\n std::map< std::string, cached_object >& map_ref = *_self->H;\n cached_object& cached_friend = map_ref[id];\n _delete_element(_self, &cached_friend);\n Py_RETURN_NONE;\n}\n\nstatic PyObject* Cache_get_last(PyObject* self, PyObject* args) {\n Cache* _self = (Cache*)self;\n cached_object ret = *_self->S->begin();\n Py_INCREF(ret.obj);\n return ret.obj;\n}\n\nstatic PyObject* Cache_is_empty(PyObject* self, PyObject* args) {\n Cache* _self = (Cache*)self;\n return PyBool_FromLong(_self->S->empty());\n}\n\nstatic PyObject* Cache_set_object(PyObject* self, PyObject* args) {\n Cache* _self = (Cache*)self;\n const char* to_query;\n PyObject* new_obj;\n long long new_object_size = -1;\n if(!PyArg_ParseTuple(args, \"sO|l\", &to_query, &new_obj, &new_object_size)) {\n return NULL;\n }\n \/\/ same as add method, this is intended to be a rough approximation\n \/\/ to the object's size and its only used if the object size is not\n \/\/ provided as a parameter\n if(new_object_size == -1) {\n new_object_size = sizeof(*new_obj);\n }\n std::string id(to_query);\n std::map< std::string, cached_object >& map_ref = *_self->H;\n \/\/ let's get the cached_object that contains our target object\n \/\/ and remove it from the priority set\n cached_object& cached_friend = map_ref[id];\n long long old_object_size = cached_friend.object_size;\n _self->S->erase(cached_friend);\n Py_DECREF(cached_friend.obj);\n \/\/ update the data structure with the new object\n cached_friend.obj = new_obj;\n Py_INCREF(cached_friend.obj);\n cached_friend.object_size = new_object_size;\n _self->current_size -= old_object_size;\n _self->current_size += new_object_size;\n _self->S->insert(cached_friend);\n \/\/ a new object may have its size modified (for example, it we append stuff\n \/\/ to some list). Let's be sure that this modification do not violate the\n \/\/ cache invariant\n while(!_self->S->empty() && _self->current_size >= _self->size_limit) {\n _delete_first_element(_self);\n }\n Py_RETURN_NONE;\n}\n\nPyMODINIT_FUNC initpersistent_cache(void) {\n PyObject* m;\n m = Py_InitModule(\"persistent_cache\", module_methods);\n\n if (PyType_Ready(&cached_objectType) < 0)\n return;\n Py_INCREF(&cached_objectType);\n PyModule_AddObject(m, \"cached_object\", (PyObject*)&cached_objectType);\n\n if (PyType_Ready(&CacheType) < 0)\n return;\n Py_INCREF(&CacheType);\n PyModule_AddObject(m, \"Cache\", (PyObject*)&CacheType);\n}\n<|endoftext|>"} {"text":"\/**\n * Problem description: Given a linked list, sort it using insertion sort.\n * Solution time complexity: O(n^2)\n * Comments: \n *\/\n\n\/**\n * Definition of ListNode\n * class ListNode {\n * public:\n * int val;\n * ListNode *next;\n * ListNode(int val) {\n * this->val = val;\n * this->next = NULL;\n * }\n * }\n *\/\nclass Solution {\npublic:\n \/**\n * @param head: The first node of linked list.\n * @return: The head of linked list.\n *\/\n ListNode *insertionSortList(ListNode *head) \n {\n auto dummy = ListNode{ 0 };\n auto node = head;\n \n while (node != nullptr) \n {\n auto next = node->next;\n auto dest = &dummy;\n \n while (dest->next != nullptr && node->val > dest->next->val) {\n dest = dest->next;\n }\n \n node->next = dest->next;\n dest->next = node;\n \n node = next;\n }\n \n return dummy.next;\n }\n};\nUpdate solution.cpp\/**\n * Problem description: Given a linked list, sort it using insertion sort.\n * Solution time complexity: O(n^2)\n * Comments: Dummy node technique is used to facilitate sorting.\n *\/\n\n\/**\n * Definition of ListNode\n * class ListNode {\n * public:\n * int val;\n * ListNode *next;\n * ListNode(int val) {\n * this->val = val;\n * this->next = NULL;\n * }\n * }\n *\/\nclass Solution {\npublic:\n \/**\n * @param head: The first node of linked list.\n * @return: The head of linked list.\n *\/\n ListNode *insertionSortList(ListNode *head) \n {\n auto dummy = ListNode{ 0 };\n auto node = head;\n \n while (node != nullptr) \n {\n auto next = node->next;\n auto dest = &dummy;\n \n while (dest->next != nullptr && node->val > dest->next->val) {\n dest = dest->next;\n }\n \n node->next = dest->next;\n dest->next = node;\n \n node = next;\n }\n \n return dummy.next;\n }\n};\n<|endoftext|>"} {"text":"\/* Copyright 2016 Samsung Electronics Co., LTD\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"daydream_renderer.h\"\n#include \"glm\/gtc\/matrix_inverse.hpp\"\n\nnamespace {\n static const uint64_t kPredictionTimeWithoutVsyncNanos = 50000000;\n static const int kDefaultFboResolution = 1024;\n\n \/\/ Use the same default clipping distances as the perspective camera\n \/\/ TODO: Change this to read the values from the gvr.xml file\n static const float kZNear = 0.1f;\n static const float kZFar = 1000.0f;\n\n static glm::mat4 MatrixToGLMMatrix(const gvr::Mat4f &matrix) {\n glm::mat4 result;\n for (int i = 0; i < 4; ++i) {\n for (int j = 0; j < 4; ++j) {\n result[i][j] = matrix.m[i][j];\n }\n }\n return result;\n }\n\n static gvr::Rectf ModulateRect(const gvr::Rectf &rect, float width,\n float height) {\n gvr::Rectf result = {rect.left * width, rect.right * width,\n rect.bottom * height, rect.top * height};\n return result;\n }\n\n static gvr::Recti CalculatePixelSpaceRect(const gvr::Sizei &texture_size,\n const gvr::Rectf &texture_rect) {\n const float width = static_cast(texture_size.width);\n const float height = static_cast(texture_size.height);\n const gvr::Rectf rect = ModulateRect(texture_rect, width, height);\n const gvr::Recti result = {\n static_cast(rect.left), static_cast(rect.right),\n static_cast(rect.bottom), static_cast(rect.top)};\n return result;\n }\n\n\n static void CheckGLError(const char *label) {\n int gl_error = glGetError();\n if (gl_error != GL_NO_ERROR) {\n LOGW(\"GL error @ %s: %d\", label, gl_error);\n \/\/ Crash immediately to make OpenGL errors obvious.\n abort();\n }\n }\n\n} \/\/ namespace\n\nDaydreamRenderer::DaydreamRenderer(JNIEnv &env, jclass clazz,\n gvr_context *gvr_context)\n : gvr_api_(gvr::GvrApi::WrapNonOwned(gvr_context)),\n scratch_viewport_(gvr_api_->CreateBufferViewport()) {\n jclass rendererClass = env.GetObjectClass(clazz);\n rendererObject_ = env.NewGlobalRef(clazz);\n onDrawEyeMethodId_ = env.GetMethodID(rendererClass, \"onDrawEye\", \"(I)V\");\n env.DeleteLocalRef(rendererClass);\n}\n\nDaydreamRenderer::~DaydreamRenderer() {\n}\n\nvoid DaydreamRenderer::InitializeGl() {\n gvr_api_->InitializeGl();\n\n \/\/@todo read gvr.xml and obtain the values from EyeBufferParams\n render_size_.height = kDefaultFboResolution;\n render_size_.width = 2*kDefaultFboResolution;\n std::vector specs;\n specs.push_back(gvr_api_->CreateBufferSpec());\n specs.push_back(gvr_api_->CreateBufferSpec());\n\n specs[0].SetColorFormat(GVR_COLOR_FORMAT_RGBA_8888);\n specs[0].SetDepthStencilFormat(GVR_DEPTH_STENCIL_FORMAT_DEPTH_24_STENCIL_8);\n specs[0].SetSize(render_size_);\n specs[0].SetSamples(2);\n\n specs[1].SetColorFormat(GVR_COLOR_FORMAT_RGBA_8888);\n specs[1].SetDepthStencilFormat(GVR_DEPTH_STENCIL_FORMAT_DEPTH_24_STENCIL_8);\n specs[1].SetSize(render_size_);\n specs[1].SetSamples(2);\n swapchain_.reset(new gvr::SwapChain(gvr_api_->CreateSwapChain(specs)));\n\n viewport_list_.reset(new gvr::BufferViewportList(\n gvr_api_->CreateEmptyBufferViewportList()));\n scratch_viewport_list_.reset(new gvr::BufferViewportList(\n gvr_api_->CreateEmptyBufferViewportList()));\n\n}\n\nvoid DaydreamRenderer::DrawFrame(JNIEnv &env) {\n \/\/ use the scratch list to get the recommended viewports\n scratch_viewport_list_->SetToRecommendedBufferViewports();\n\n \/\/ construct FBO backed viewports\n gvr::BufferViewport fbo_viewport = gvr_api_->CreateBufferViewport();\n\n scratch_viewport_list_->GetBufferViewport(0, &scratch_viewport_);\n fbo_viewport.SetSourceBufferIndex(0);\n fbo_viewport.SetSourceFov(scratch_viewport_.GetSourceFov());\n fbo_viewport.SetReprojection(scratch_viewport_.GetReprojection());\n fbo_viewport.SetSourceUv(scratch_viewport_.GetSourceUv());\n fbo_viewport.SetTargetEye(GVR_LEFT_EYE);\n viewport_list_->SetBufferViewport(0, fbo_viewport);\n\n scratch_viewport_list_->GetBufferViewport(1, &scratch_viewport_);\n fbo_viewport.SetSourceBufferIndex(1);\n fbo_viewport.SetSourceFov(scratch_viewport_.GetSourceFov());\n fbo_viewport.SetReprojection(scratch_viewport_.GetReprojection());\n fbo_viewport.SetSourceUv(scratch_viewport_.GetSourceUv());\n fbo_viewport.SetTargetEye(GVR_RIGHT_EYE);\n viewport_list_->SetBufferViewport(1, fbo_viewport);\n\n gvr::Frame frame = swapchain_->AcquireFrame();\n\n gvr::ClockTimePoint target_time = gvr::GvrApi::GetTimePointNow();\n target_time.monotonic_system_time_nanos += kPredictionTimeWithoutVsyncNanos;\n\n head_view_ = gvr_api_->GetHeadSpaceFromStartSpaceRotation(target_time);\n\n cameraRig_->getHeadTransform()->setModelMatrix(MatrixToGLMMatrix(head_view_));\n\n \/\/ Render the eye images.\n for (int eye = 0; eye < 2; eye++) {\n frame.BindBuffer(eye);\n viewport_list_->GetBufferViewport(eye, &scratch_viewport_);\n SetViewport(scratch_viewport_);\n env.CallVoidMethod(rendererObject_, onDrawEyeMethodId_, eye);\n frame.Unbind();\n }\n\n \/\/ Submit frame.\n frame.Submit(*viewport_list_, head_view_);\n\n CheckGLError(\"onDrawFrame\");\n}\n\nvoid DaydreamRenderer::OnPause() {\n gvr_api_->PauseTracking();\n}\n\nvoid DaydreamRenderer::OnResume() {\n gvr_api_->RefreshViewerProfile();\n gvr_api_->ResumeTracking();\n}\n\nvoid DaydreamRenderer::OnDestroy(JNIEnv &env) {\n env.DeleteGlobalRef(rendererObject_);\n delete cameraRig_;\n}\n\nvoid DaydreamRenderer::SetViewport(const gvr::BufferViewport &viewport) {\n const gvr::Recti pixel_rect = CalculatePixelSpaceRect(render_size_, viewport.GetSourceUv());\n\n glViewport(pixel_rect.left, pixel_rect.bottom,\n pixel_rect.right - pixel_rect.left,\n pixel_rect.top - pixel_rect.bottom);\n\n CheckGLError(\"SetViewport\");\n}\n\nvoid DaydreamRenderer::SetCameraRig(jlong native_camera) {\n cameraRig_ = reinterpret_cast(native_camera);\n scratch_viewport_list_->SetToRecommendedBufferViewports();\n\n scratch_viewport_list_->GetBufferViewport(0, &scratch_viewport_);\n SetCameraProjectionMatrix((gvr::CustomCamera *) cameraRig_->left_camera(), scratch_viewport_\n .GetSourceFov(), kZNear, kZFar);\n\n scratch_viewport_list_->GetBufferViewport(1, &scratch_viewport_);\n SetCameraProjectionMatrix((gvr::CustomCamera *) cameraRig_->right_camera(), scratch_viewport_\n .GetSourceFov(), kZNear, kZFar);\n}\n\nvoid DaydreamRenderer::SetCameraProjectionMatrix(gvr::CustomCamera *camera, const gvr::Rectf &fov,\n float z_near, float z_far) {\n float x_left = -std::tan(fov.left * M_PI \/ 180.0f) * z_near;\n float x_right = std::tan(fov.right * M_PI \/ 180.0f) * z_near;\n float y_bottom = -std::tan(fov.bottom * M_PI \/ 180.0f) * z_near;\n float y_top = std::tan(fov.top * M_PI \/ 180.0f) * z_near;\n glm::mat4 projection_matrix = glm::frustum(x_left, x_right, y_bottom, y_top, z_near, z_far);\n \/\/ set the camera projection matrix\n camera->set_projection_matrix(projection_matrix);\n}Fix the daydream default FBO and UV values.\/* Copyright 2016 Samsung Electronics Co., LTD\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"daydream_renderer.h\"\n#include \"glm\/gtc\/matrix_inverse.hpp\"\n\nnamespace {\n static const uint64_t kPredictionTimeWithoutVsyncNanos = 50000000;\n static const int kDefaultFboResolution = 1024;\n static const gvr::Rectf kDefaultUV = {0.0f, 1.0f, 0.0f, 1.0f};\n\n \/\/ Use the same default clipping distances as the perspective camera\n \/\/ TODO: Change this to read the values from the gvr.xml file\n static const float kZNear = 0.1f;\n static const float kZFar = 1000.0f;\n\n static glm::mat4 MatrixToGLMMatrix(const gvr::Mat4f &matrix) {\n glm::mat4 result;\n for (int i = 0; i < 4; ++i) {\n for (int j = 0; j < 4; ++j) {\n result[i][j] = matrix.m[i][j];\n }\n }\n return result;\n }\n\n static gvr::Rectf ModulateRect(const gvr::Rectf &rect, float width,\n float height) {\n gvr::Rectf result = {rect.left * width, rect.right * width,\n rect.bottom * height, rect.top * height};\n return result;\n }\n\n static gvr::Recti CalculatePixelSpaceRect(const gvr::Sizei &texture_size,\n const gvr::Rectf &texture_rect) {\n const float width = static_cast(texture_size.width);\n const float height = static_cast(texture_size.height);\n const gvr::Rectf rect = ModulateRect(texture_rect, width, height);\n const gvr::Recti result = {\n static_cast(rect.left), static_cast(rect.right),\n static_cast(rect.bottom), static_cast(rect.top)};\n return result;\n }\n\n\n static void CheckGLError(const char *label) {\n int gl_error = glGetError();\n if (gl_error != GL_NO_ERROR) {\n LOGW(\"GL error @ %s: %d\", label, gl_error);\n \/\/ Crash immediately to make OpenGL errors obvious.\n abort();\n }\n }\n\n} \/\/ namespace\n\nDaydreamRenderer::DaydreamRenderer(JNIEnv &env, jclass clazz,\n gvr_context *gvr_context)\n : gvr_api_(gvr::GvrApi::WrapNonOwned(gvr_context)),\n scratch_viewport_(gvr_api_->CreateBufferViewport()) {\n jclass rendererClass = env.GetObjectClass(clazz);\n rendererObject_ = env.NewGlobalRef(clazz);\n onDrawEyeMethodId_ = env.GetMethodID(rendererClass, \"onDrawEye\", \"(I)V\");\n env.DeleteLocalRef(rendererClass);\n}\n\nDaydreamRenderer::~DaydreamRenderer() {\n}\n\nvoid DaydreamRenderer::InitializeGl() {\n gvr_api_->InitializeGl();\n\n \/\/@todo read gvr.xml and obtain the values from EyeBufferParams\n render_size_.height = kDefaultFboResolution;\n render_size_.width = kDefaultFboResolution;\n std::vector specs;\n specs.push_back(gvr_api_->CreateBufferSpec());\n specs.push_back(gvr_api_->CreateBufferSpec());\n\n specs[0].SetColorFormat(GVR_COLOR_FORMAT_RGBA_8888);\n specs[0].SetDepthStencilFormat(GVR_DEPTH_STENCIL_FORMAT_DEPTH_24_STENCIL_8);\n specs[0].SetSize(render_size_);\n specs[0].SetSamples(2);\n\n specs[1].SetColorFormat(GVR_COLOR_FORMAT_RGBA_8888);\n specs[1].SetDepthStencilFormat(GVR_DEPTH_STENCIL_FORMAT_DEPTH_24_STENCIL_8);\n specs[1].SetSize(render_size_);\n specs[1].SetSamples(2);\n swapchain_.reset(new gvr::SwapChain(gvr_api_->CreateSwapChain(specs)));\n\n viewport_list_.reset(new gvr::BufferViewportList(\n gvr_api_->CreateEmptyBufferViewportList()));\n scratch_viewport_list_.reset(new gvr::BufferViewportList(\n gvr_api_->CreateEmptyBufferViewportList()));\n\n}\n\nvoid DaydreamRenderer::DrawFrame(JNIEnv &env) {\n \/\/ use the scratch list to get the recommended viewports\n scratch_viewport_list_->SetToRecommendedBufferViewports();\n\n \/\/ construct FBO backed viewports\n gvr::BufferViewport fbo_viewport = gvr_api_->CreateBufferViewport();\n\n scratch_viewport_list_->GetBufferViewport(0, &scratch_viewport_);\n fbo_viewport.SetSourceBufferIndex(0);\n fbo_viewport.SetSourceFov(scratch_viewport_.GetSourceFov());\n fbo_viewport.SetReprojection(scratch_viewport_.GetReprojection());\n fbo_viewport.SetSourceUv(kDefaultUV);\n fbo_viewport.SetTargetEye(GVR_LEFT_EYE);\n viewport_list_->SetBufferViewport(0, fbo_viewport);\n\n scratch_viewport_list_->GetBufferViewport(1, &scratch_viewport_);\n fbo_viewport.SetSourceBufferIndex(1);\n fbo_viewport.SetSourceFov(scratch_viewport_.GetSourceFov());\n fbo_viewport.SetReprojection(scratch_viewport_.GetReprojection());\n fbo_viewport.SetSourceUv(kDefaultUV);\n fbo_viewport.SetTargetEye(GVR_RIGHT_EYE);\n viewport_list_->SetBufferViewport(1, fbo_viewport);\n\n gvr::Frame frame = swapchain_->AcquireFrame();\n\n gvr::ClockTimePoint target_time = gvr::GvrApi::GetTimePointNow();\n target_time.monotonic_system_time_nanos += kPredictionTimeWithoutVsyncNanos;\n\n head_view_ = gvr_api_->GetHeadSpaceFromStartSpaceRotation(target_time);\n\n cameraRig_->getHeadTransform()->setModelMatrix(MatrixToGLMMatrix(head_view_));\n\n \/\/ Render the eye images.\n for (int eye = 0; eye < 2; eye++) {\n frame.BindBuffer(eye);\n viewport_list_->GetBufferViewport(eye, &scratch_viewport_);\n SetViewport(scratch_viewport_);\n env.CallVoidMethod(rendererObject_, onDrawEyeMethodId_, eye);\n frame.Unbind();\n }\n\n \/\/ Submit frame.\n frame.Submit(*viewport_list_, head_view_);\n\n CheckGLError(\"onDrawFrame\");\n}\n\nvoid DaydreamRenderer::OnPause() {\n gvr_api_->PauseTracking();\n}\n\nvoid DaydreamRenderer::OnResume() {\n gvr_api_->RefreshViewerProfile();\n gvr_api_->ResumeTracking();\n}\n\nvoid DaydreamRenderer::OnDestroy(JNIEnv &env) {\n env.DeleteGlobalRef(rendererObject_);\n delete cameraRig_;\n}\n\nvoid DaydreamRenderer::SetViewport(const gvr::BufferViewport &viewport) {\n const gvr::Recti pixel_rect = CalculatePixelSpaceRect(render_size_, viewport.GetSourceUv());\n\n glViewport(pixel_rect.left, pixel_rect.bottom,\n pixel_rect.right - pixel_rect.left,\n pixel_rect.top - pixel_rect.bottom);\n\n CheckGLError(\"SetViewport\");\n}\n\nvoid DaydreamRenderer::SetCameraRig(jlong native_camera) {\n cameraRig_ = reinterpret_cast(native_camera);\n scratch_viewport_list_->SetToRecommendedBufferViewports();\n\n scratch_viewport_list_->GetBufferViewport(0, &scratch_viewport_);\n SetCameraProjectionMatrix((gvr::CustomCamera *) cameraRig_->left_camera(), scratch_viewport_\n .GetSourceFov(), kZNear, kZFar);\n\n scratch_viewport_list_->GetBufferViewport(1, &scratch_viewport_);\n SetCameraProjectionMatrix((gvr::CustomCamera *) cameraRig_->right_camera(), scratch_viewport_\n .GetSourceFov(), kZNear, kZFar);\n}\n\nvoid DaydreamRenderer::SetCameraProjectionMatrix(gvr::CustomCamera *camera, const gvr::Rectf &fov,\n float z_near, float z_far) {\n float x_left = -std::tan(fov.left * M_PI \/ 180.0f) * z_near;\n float x_right = std::tan(fov.right * M_PI \/ 180.0f) * z_near;\n float y_bottom = -std::tan(fov.bottom * M_PI \/ 180.0f) * z_near;\n float y_top = std::tan(fov.top * M_PI \/ 180.0f) * z_near;\n glm::mat4 projection_matrix = glm::frustum(x_left, x_right, y_bottom, y_top, z_near, z_far);\n \/\/ set the camera projection matrix\n camera->set_projection_matrix(projection_matrix);\n}<|endoftext|>"} {"text":"#include \"Channel_AWGN_fast_LLR.hpp\"\n\n#include \n#include \n\ntemplate \nChannel_AWGN_fast_LLR\n::Channel_AWGN_fast_LLR(const R& sigma, const int seed, const R scaling_factor)\n: sigma(sigma),\n scaling_factor(scaling_factor),\n rd(),\n rd_engine(this->rd()),\n dist(std::numeric_limits::min(),1)\n{\n\trd_engine.seed(seed);\n\n\tstd::cout << \"min = \" << std::numeric_limits::min() << std::endl;\n}\n\ntemplate \nChannel_AWGN_fast_LLR\n::~Channel_AWGN_fast_LLR()\n{\n}\n\n\/\/ box muller method in the polar form\ntemplate \nvoid Channel_AWGN_fast_LLR\n::add_noise(const mipp::vector& X_N, mipp::vector& Y_N)\n{\n\tassert(X_N.size() % 2 == 0 );\n\tassert(X_N.size() == Y_N.size());\n\tassert(scaling_factor != 0 );\n\tassert(sigma != 0 );\n\tassert(X_N.size() % (2 * mipp::nElReg()) == 0 );\n\n\tconst auto loop_size = (int)Y_N.size();\n\tfor (auto i = 0; i < loop_size; i++)\n\t{\n\t\tY_N[i] = this->dist(this->rd_engine);\n\t\tif (Y_N[i] == 0)\n\t\t\tstd::cout << \"PROUTTTT\" << std::endl;\n\t}\n\n\t\/\/ const mipp::Reg sf = this->scaling_factor;\n\t\/\/ const mipp::Reg sigma = this->sigma;\n\t\/\/ const mipp::Reg twopi = 2.0 * 3.14159265358979323846;\n\t\/\/ const mipp::Reg one = 1.0;\n\t\/\/ const mipp::Reg minustwo = -2.0;\n\n\t\/\/ for (auto i = 0; i < loop_size; i += mipp::nElReg() * 2) \n\t\/\/ {\n\t\/\/ \t\/\/ const auto u1 = one - mipp::Reg(&Y_N[i ]); \/\/ [0, 1) -> (0, 1]\n\t\/\/ \tconst auto u1 = mipp::Reg(&Y_N[i ]);\n\t\/\/ \tconst auto u2 = mipp::Reg(&Y_N[i + mipp::nElReg()]);\n\n\t\/\/ \tconst auto radius = mipp::sqrt(minustwo * mipp::log(u1)) * sigma;\n\t\/\/ \tconst auto theta = twopi * u2;\n\n\t\/\/ \tmipp::Reg sintheta, costheta;\n\t\/\/ \tmipp::sincos(theta, sintheta, costheta);\n\n\t\/\/ \t\/\/ fmadd(a, b, c) = a * b + c\n\t\/\/ \tauto awgn1 = mipp::fmadd(radius, costheta, mipp::Reg(&X_N[i ])) * sf;\n\t\/\/ \tauto awgn2 = mipp::fmadd(radius, sintheta, mipp::Reg(&X_N[i + mipp::nElReg()])) * sf;\n\n\t\/\/ \tawgn1.store(&Y_N[i ]);\n\t\/\/ \tawgn2.store(&Y_N[i + mipp::nElReg()]);\n\t\/\/ }\n\n\n\tauto twopi = (R)(2.0 * 3.14159265358979323846);\n\tfor (auto i = 0; i < loop_size; i += 2)\n\t{\n\t\t\/\/ auto x = (R)sqrt(-2.0 * log((R)rand() \/ (R)2147483647));\n\t\t\/\/ auto y = (R)rand() \/ (R)2147483647;\n\t\tconst auto u1 = Y_N[i +0];\n\t\tconst auto u2 = Y_N[i +1];\n\n\t\tconst auto radius = (R)std::sqrt((R)-2.0 * std::log(u1)) * sigma;\n\t\tconst auto theta = twopi * u2;\n\n\t\tconst auto sintheta = std::sin(theta);\n\t\tconst auto costheta = std::cos(theta);\n\n\t\tY_N[i +0] = (X_N[i +0] + radius * sintheta) * scaling_factor;\n\t\tY_N[i +1] = (X_N[i +1] + radius * costheta) * scaling_factor;\n\t}\n\n\tfor (auto i = 0; i < loop_size; i++)\n\t\tif (std::isnan(Y_N[i]))\n\t\t\tstd::cout << \"NaN\" << std::endl;\n}\n\n\/\/ ==================================================================================== explicit template instantiation \n#include \"..\/..\/..\/Tools\/types.h\"\n#ifdef MULTI_PREC\ntemplate class Channel_AWGN_fast_LLR;\ntemplate class Channel_AWGN_fast_LLR;\n#else\ntemplate class Channel_AWGN_fast_LLR;\n#endif\n\/\/ ==================================================================================== explicit template instantiationTurn on SIMD code.#include \"Channel_AWGN_fast_LLR.hpp\"\n\n#include \n#include \n\ntemplate \nChannel_AWGN_fast_LLR\n::Channel_AWGN_fast_LLR(const R& sigma, const int seed, const R scaling_factor)\n: sigma(sigma),\n scaling_factor(scaling_factor),\n rd(),\n rd_engine(this->rd()),\n dist(std::numeric_limits::min(),1)\n{\n\trd_engine.seed(seed);\n\n\tstd::cout << \"min = \" << std::numeric_limits::min() << std::endl;\n}\n\ntemplate \nChannel_AWGN_fast_LLR\n::~Channel_AWGN_fast_LLR()\n{\n}\n\n\/\/ box muller method in the polar form\ntemplate \nvoid Channel_AWGN_fast_LLR\n::add_noise(const mipp::vector& X_N, mipp::vector& Y_N)\n{\n\tassert(X_N.size() % 2 == 0 );\n\tassert(X_N.size() == Y_N.size());\n\tassert(scaling_factor != 0 );\n\tassert(sigma != 0 );\n\tassert(X_N.size() % (2 * mipp::nElReg()) == 0 );\n\n\tconst auto loop_size = (int)Y_N.size();\n\tfor (auto i = 0; i < loop_size; i++)\n\t{\n\t\tY_N[i] = this->dist(this->rd_engine);\n\t\t\/\/ if (Y_N[i] == 0)\n\t\t\/\/ \tstd::cout << \"PROUTTTT\" << std::endl;\n\t}\n\n\tconst mipp::Reg sf = this->scaling_factor;\n\tconst mipp::Reg sigma = this->sigma;\n\tconst mipp::Reg twopi = 2.0 * 3.14159265358979323846;\n\tconst mipp::Reg one = 1.0;\n\tconst mipp::Reg minustwo = -2.0;\n\n\tfor (auto i = 0; i < loop_size; i += mipp::nElReg() * 2) \n\t{\n\t\t\/\/ const auto u1 = one - mipp::Reg(&Y_N[i ]); \/\/ [0, 1) -> (0, 1]\n\t\tconst auto u1 = mipp::Reg(&Y_N[i ]);\n\t\tconst auto u2 = mipp::Reg(&Y_N[i + mipp::nElReg()]);\n\n\t\tconst auto radius = mipp::sqrt(minustwo * mipp::log(u1)) * sigma;\n\t\tconst auto theta = twopi * u2;\n\n\t\tmipp::Reg sintheta, costheta;\n\t\tmipp::sincos(theta, sintheta, costheta);\n\n\t\t\/\/ fmadd(a, b, c) = a * b + c\n\t\tauto awgn1 = mipp::fmadd(radius, costheta, mipp::Reg(&X_N[i ])) * sf;\n\t\tauto awgn2 = mipp::fmadd(radius, sintheta, mipp::Reg(&X_N[i + mipp::nElReg()])) * sf;\n\n\t\tawgn1.store(&Y_N[i ]);\n\t\tawgn2.store(&Y_N[i + mipp::nElReg()]);\n\t}\n\n\t\/\/ auto twopi = (R)(2.0 * 3.14159265358979323846);\n\t\/\/ for (auto i = 0; i < loop_size; i += 2)\n\t\/\/ {\n\t\/\/ \t\/\/ auto x = (R)sqrt(-2.0 * log((R)rand() \/ (R)2147483647));\n\t\/\/ \t\/\/ auto y = (R)rand() \/ (R)2147483647;\n\t\/\/ \tconst auto u1 = Y_N[i +0];\n\t\/\/ \tconst auto u2 = Y_N[i +1];\n\n\t\/\/ \tconst auto radius = (R)std::sqrt((R)-2.0 * std::log(u1)) * sigma;\n\t\/\/ \tconst auto theta = twopi * u2;\n\n\t\/\/ \tconst auto sintheta = std::sin(theta);\n\t\/\/ \tconst auto costheta = std::cos(theta);\n\n\t\/\/ \tY_N[i +0] = (X_N[i +0] + radius * sintheta) * scaling_factor;\n\t\/\/ \tY_N[i +1] = (X_N[i +1] + radius * costheta) * scaling_factor;\n\t\/\/ }\n\n\t\/\/ for (auto i = 0; i < loop_size; i++)\n\t\/\/ \tif (std::isnan(Y_N[i]))\n\t\/\/ \t\tstd::cout << \"NaN\" << std::endl;\n}\n\n\/\/ ==================================================================================== explicit template instantiation \n#include \"..\/..\/..\/Tools\/types.h\"\n#ifdef MULTI_PREC\ntemplate class Channel_AWGN_fast_LLR;\ntemplate class Channel_AWGN_fast_LLR;\n#else\ntemplate class Channel_AWGN_fast_LLR;\n#endif\n\/\/ ==================================================================================== explicit template instantiation<|endoftext|>"} {"text":"\/**\n * Copyright (c) 2017 DeepCortex GmbH \n * Authors:\n * - Laura Schlimmer \n *\n * This program is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License (\"the license\") as\n * published by the Free Software Foundation, either version 3 of the License,\n * or any later version.\n *\n * In accordance with Section 7(e) of the license, the licensing of the Program\n * under the license does not imply a trademark license. Therefore any rights,\n * title and interest in our trademarks remain entirely with us.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the license for more details.\n *\n * You can be released from the requirements of the license by purchasing a\n * commercial license. Buying such a license is mandatory as soon as you develop\n * commercial activities involving this program without disclosing the source\n * code of your own applications\n *\/\n#include \"eventql\/eventql.h\"\n#include \"eventql\/util\/stringutil.h\"\n#include \"eventql\/util\/io\/fileutil.h\"\n#include \"eventql\/util\/csv\/CSVOutputStream.h\"\n#include \"eventql\/sql\/runtime\/defaultruntime.h\"\n#include \"eventql\/sql\/CSTableScanProvider.h\"\n#include \"eventql\/sql\/result_list.h\"\n#include \"eventql\/util\/csv\/CSVInputStream.h\"\n#include \"test_repository.h\"\n\nnamespace eventql {\nnamespace test {\nnamespace sql {\n\nenum class ResultExpectation { TABLE, CHART, ERROR };\n\nconst auto kBaseDirectoryPath = \".\/test\";\nconst auto kDirectoryPath = FileUtil::joinPaths(kBaseDirectoryPath, \"sql\");\nconst auto kTestListFile = FileUtil::joinPaths(\n kBaseDirectoryPath,\n \"sql_tests.lst\");\nconst auto kSQLPathEnding = \".sql\";\nconst auto kResultPathEnding = \".result.txt\";\nconst auto kActualResultPathEnding = \".actual.result.txt\";\nconst auto kChartColumnName = \"__chart\";\nconst auto kDefaultResultExpectation = ResultExpectation::TABLE;\n\nstd::string getResultCSV(\n csql::ResultList* result,\n const std::string& row_sep = \"\\n\") {\n std::string result_csv;\n auto is = new StringOutputStream(&result_csv);\n auto csv_is = new CSVOutputStream(\n std::unique_ptr(is),\n \";\",\n row_sep);\n\n auto columns = result->getColumns();\n csv_is->appendRow(columns);\n\n auto num_rows = result->getNumRows();\n for (size_t i = 0; i < num_rows; ++i) {\n auto row = result->getRow(i);\n csv_is->appendRow(row);\n }\n\n return result_csv;\n}\n\nStatus checkTableResult(\n csql::ResultList* result,\n const std::string& result_file_path) {\n auto csv_is = CSVInputStream::openFile(result_file_path);\n std::vector columns;\n if (!csv_is->readNextRow(&columns)) {\n return Status(eRuntimeError, \"CSV needs a header\");\n }\n\n \/* compare columns *\/\n if (result->getNumColumns() != columns.size()) {\n return Status(eRuntimeError, StringUtil::format(\n \"wrong number of columns, expected $0 to be $1\",\n result->getNumColumns(),\n columns.size()));\n }\n\n auto returned_columns = result->getColumns();\n for (size_t i = 0; i < returned_columns.size(); ++i) {\n if (returned_columns[i] != columns[i]) {\n return Status(eRuntimeError, StringUtil::format(\n \"wrong column name, expected $0 to be $1\",\n returned_columns[i],\n columns[i]));\n }\n }\n\n \/* compare rows *\/\n auto num_returned_rows = result->getNumRows();\n size_t count = 0;\n std::vector row;\n while (csv_is->readNextRow(&row)) {\n if (count >= num_returned_rows) {\n return Status(eRuntimeError, \"not enough rows returned\");\n }\n\n auto returned_row = result->getRow(count);\n if (returned_row.size() != row.size()) {\n return Status(eRuntimeError, StringUtil::format(\n \"wrong number of values, expected $0 to be $1\",\n returned_row.size(),\n row.size()));\n }\n\n for (size_t i = 0; i < row.size(); ++i) {\n if (row[i] != returned_row[i]) {\n return Status(\n eRuntimeError,\n StringUtil::format(\n \"result mismatch at row $0, column $1; expected: >$2<, got: >$3<\",\n count,\n i,\n row[i],\n returned_row[i]));\n }\n }\n\n ++count;\n }\n\n if (count < num_returned_rows) {\n return Status(eRuntimeError, StringUtil::format(\n \"too many rows, expected $0 to be $1\",\n num_returned_rows,\n count));\n }\n\n return Status::success();\n}\n\nStatus checkChartResult(\n csql::ResultList* result,\n const std::string& result_file_path) {\n auto num_returned_rows = result->getNumRows();\n if (num_returned_rows != 1) {\n return Status(eRuntimeError, StringUtil::format(\n \"wrong number of rows returned, expected $0 to be 1\",\n num_returned_rows));\n }\n\n auto is = FileInputStream::openFile(result_file_path);\n std::string expected_result;\n is->readUntilEOF(&expected_result);\n\n auto returned_result = result->getRow(0)[0];\n if (expected_result != returned_result) {\n return Status(eRuntimeError, \"result charts don't match\");\n }\n\n return Status::success();\n}\n\nStatus checkErrorResult(\n const std::string& error_message,\n csql::ResultList* result,\n const std::string& result_file_path) {\n auto is = FileInputStream::openFile(result_file_path);\n\n {\n std::string result_expectation_line;\n is->readLine(&result_expectation_line);\n }\n\n std::string expected_error;\n is->readUntilEOF(&expected_error);\n StringUtil::chomp(&expected_error);\n\n if (expected_error == error_message) {\n return Status::success();\n } else {\n if (error_message.empty()) {\n auto result_csv = getResultCSV(result, \" \");\n return Status(eRuntimeError, StringUtil::format(\n \"expected error: $0 but got result: $1\",\n expected_error,\n result_csv));\n\n } else {\n return Status(eRuntimeError, StringUtil::format(\n \"expected error: $0 but got error $1\",\n expected_error,\n error_message));\n }\n }\n}\n\nbool runTest(std::string id) {\n auto sql_file_path = FileUtil::joinPaths(\n kDirectoryPath,\n StringUtil::format(\"$0$1\", id, kSQLPathEnding));\n\n if (!FileUtil::exists(sql_file_path)) {\n RAISE(\n kIOError,\n StringUtil::format(\"File does not exist: $0\", sql_file_path));\n }\n\n auto result_file_path = FileUtil::joinPaths(\n kDirectoryPath,\n StringUtil::format(\"$0$1\", id, kResultPathEnding));\n\n if (!FileUtil::exists(result_file_path)) {\n RAISE(\n kIOError,\n StringUtil::format(\"File does not exist: $0\", result_file_path));\n }\n\n auto result_expectation = kDefaultResultExpectation;\n auto result_is = FileInputStream::openFile(result_file_path);\n std::string first_line;\n if (result_is->readLine(&first_line)) {\n StringUtil::chomp(&first_line);\n if (first_line == \"ERROR!\") {\n result_expectation = ResultExpectation::ERROR;\n }\n }\n\n \/* input table path *\/\n auto sql_is = FileInputStream::openFile(sql_file_path);\n std::string input_table_path;\n if (!sql_is->readLine(&input_table_path) ||\n !StringUtil::beginsWith(input_table_path, \"--\")) {\n RAISE(kRuntimeError, \"no input table provided\");\n }\n\n StringUtil::replaceAll(&input_table_path, \"--\");\n StringUtil::ltrim(&input_table_path);\n StringUtil::chomp(&input_table_path);\n input_table_path = FileUtil::joinPaths(\n kBaseDirectoryPath,\n input_table_path);\n\n if (!FileUtil::exists(input_table_path)) {\n RAISE(\n kRuntimeError,\n StringUtil::format(\"file does not exist: $0\", input_table_path));\n }\n\n std::string query;\n sql_is->readUntilEOF(&query);\n\n \/* execute query *\/\n auto runtime = csql::Runtime::getDefaultRuntime();\n auto txn = runtime->newTransaction();\n\n txn->setTableProvider(\n new csql::CSTableScanProvider(\"testtable\", input_table_path));\n csql::ResultList result;\n\n std::string error_message;\n try {\n auto qplan = runtime->buildQueryPlan(txn.get(), query);\n qplan->execute(0, &result);\n } catch (const std::exception& e) {\n error_message = e.what();\n\n if (result_expectation != ResultExpectation::ERROR) {\n RAISE(\n kRuntimeError,\n StringUtil::format(\"unexpected error: $0\", error_message));\n }\n }\n\n if (result.getNumColumns() == 1 &&\n result.getColumns()[0] == kChartColumnName) {\n result_expectation = ResultExpectation::CHART;\n }\n\n auto rc = Status::success();\n switch (result_expectation) {\n case ResultExpectation::TABLE:\n rc = checkTableResult(&result, result_file_path);\n break;\n\n case ResultExpectation::CHART:\n rc = checkChartResult(&result, result_file_path);\n break;\n\n case ResultExpectation::ERROR:\n rc = checkErrorResult(error_message, &result, result_file_path);\n break;\n }\n\n if (rc.isSuccess()) {\n return true;\n }\n\n \/* write file with actual result *\/\n auto acutal_result_file_path = FileUtil::joinPaths(\n kDirectoryPath,\n StringUtil::format(\"$0$1\", id, kActualResultPathEnding));\n\n const auto& csv_result = getResultCSV(&result);\n FileUtil::write(acutal_result_file_path, csv_result);\n\n RAISE(kRuntimeError, rc.message());\n}\n\nvoid setup_sql_tests(TestRepository* repo) {\n auto is = FileInputStream::openFile(kTestListFile);\n std::string test_id;\n while (is->readLine(&test_id)) {\n StringUtil::chomp(&test_id);\n\n auto test_case = eventql::test::TestCase {\n .test_id = StringUtil::format(\"SQL-$0\", test_id.substr(0, 5)),\n .description = test_id,\n .fun = std::bind(runTest, test_id),\n .suites = { TestSuite::WORLD, TestSuite::SMOKE }\n };\n\n repo->addTestBundle({ test_case });\n test_id.clear();\n }\n\n}\n\n} \/\/ namespace sql\n} \/\/ namespace test\n} \/\/ namespace eventql\n\n\nimproved sql test description\/**\n * Copyright (c) 2017 DeepCortex GmbH \n * Authors:\n * - Laura Schlimmer \n *\n * This program is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License (\"the license\") as\n * published by the Free Software Foundation, either version 3 of the License,\n * or any later version.\n *\n * In accordance with Section 7(e) of the license, the licensing of the Program\n * under the license does not imply a trademark license. Therefore any rights,\n * title and interest in our trademarks remain entirely with us.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the license for more details.\n *\n * You can be released from the requirements of the license by purchasing a\n * commercial license. Buying such a license is mandatory as soon as you develop\n * commercial activities involving this program without disclosing the source\n * code of your own applications\n *\/\n#include \"eventql\/eventql.h\"\n#include \"eventql\/util\/stringutil.h\"\n#include \"eventql\/util\/io\/fileutil.h\"\n#include \"eventql\/util\/csv\/CSVOutputStream.h\"\n#include \"eventql\/sql\/runtime\/defaultruntime.h\"\n#include \"eventql\/sql\/CSTableScanProvider.h\"\n#include \"eventql\/sql\/result_list.h\"\n#include \"eventql\/util\/csv\/CSVInputStream.h\"\n#include \"test_repository.h\"\n\nnamespace eventql {\nnamespace test {\nnamespace sql {\n\nenum class ResultExpectation { TABLE, CHART, ERROR };\n\nconst auto kBaseDirectoryPath = \".\/test\";\nconst auto kDirectoryPath = FileUtil::joinPaths(kBaseDirectoryPath, \"sql\");\nconst auto kTestListFile = FileUtil::joinPaths(\n kBaseDirectoryPath,\n \"sql_tests.lst\");\nconst auto kSQLPathEnding = \".sql\";\nconst auto kResultPathEnding = \".result.txt\";\nconst auto kActualResultPathEnding = \".actual.result.txt\";\nconst auto kChartColumnName = \"__chart\";\nconst auto kDefaultResultExpectation = ResultExpectation::TABLE;\n\nstd::string getResultCSV(\n csql::ResultList* result,\n const std::string& row_sep = \"\\n\") {\n std::string result_csv;\n auto is = new StringOutputStream(&result_csv);\n auto csv_is = new CSVOutputStream(\n std::unique_ptr(is),\n \";\",\n row_sep);\n\n auto columns = result->getColumns();\n csv_is->appendRow(columns);\n\n auto num_rows = result->getNumRows();\n for (size_t i = 0; i < num_rows; ++i) {\n auto row = result->getRow(i);\n csv_is->appendRow(row);\n }\n\n return result_csv;\n}\n\nStatus checkTableResult(\n csql::ResultList* result,\n const std::string& result_file_path) {\n auto csv_is = CSVInputStream::openFile(result_file_path);\n std::vector columns;\n if (!csv_is->readNextRow(&columns)) {\n return Status(eRuntimeError, \"CSV needs a header\");\n }\n\n \/* compare columns *\/\n if (result->getNumColumns() != columns.size()) {\n return Status(eRuntimeError, StringUtil::format(\n \"wrong number of columns, expected $0 to be $1\",\n result->getNumColumns(),\n columns.size()));\n }\n\n auto returned_columns = result->getColumns();\n for (size_t i = 0; i < returned_columns.size(); ++i) {\n if (returned_columns[i] != columns[i]) {\n return Status(eRuntimeError, StringUtil::format(\n \"wrong column name, expected $0 to be $1\",\n returned_columns[i],\n columns[i]));\n }\n }\n\n \/* compare rows *\/\n auto num_returned_rows = result->getNumRows();\n size_t count = 0;\n std::vector row;\n while (csv_is->readNextRow(&row)) {\n if (count >= num_returned_rows) {\n return Status(eRuntimeError, \"not enough rows returned\");\n }\n\n auto returned_row = result->getRow(count);\n if (returned_row.size() != row.size()) {\n return Status(eRuntimeError, StringUtil::format(\n \"wrong number of values, expected $0 to be $1\",\n returned_row.size(),\n row.size()));\n }\n\n for (size_t i = 0; i < row.size(); ++i) {\n if (row[i] != returned_row[i]) {\n return Status(\n eRuntimeError,\n StringUtil::format(\n \"result mismatch at row $0, column $1; expected: >$2<, got: >$3<\",\n count,\n i,\n row[i],\n returned_row[i]));\n }\n }\n\n ++count;\n }\n\n if (count < num_returned_rows) {\n return Status(eRuntimeError, StringUtil::format(\n \"too many rows, expected $0 to be $1\",\n num_returned_rows,\n count));\n }\n\n return Status::success();\n}\n\nStatus checkChartResult(\n csql::ResultList* result,\n const std::string& result_file_path) {\n auto num_returned_rows = result->getNumRows();\n if (num_returned_rows != 1) {\n return Status(eRuntimeError, StringUtil::format(\n \"wrong number of rows returned, expected $0 to be 1\",\n num_returned_rows));\n }\n\n auto is = FileInputStream::openFile(result_file_path);\n std::string expected_result;\n is->readUntilEOF(&expected_result);\n\n auto returned_result = result->getRow(0)[0];\n if (expected_result != returned_result) {\n return Status(eRuntimeError, \"result charts don't match\");\n }\n\n return Status::success();\n}\n\nStatus checkErrorResult(\n const std::string& error_message,\n csql::ResultList* result,\n const std::string& result_file_path) {\n auto is = FileInputStream::openFile(result_file_path);\n\n {\n std::string result_expectation_line;\n is->readLine(&result_expectation_line);\n }\n\n std::string expected_error;\n is->readUntilEOF(&expected_error);\n StringUtil::chomp(&expected_error);\n\n if (expected_error == error_message) {\n return Status::success();\n } else {\n if (error_message.empty()) {\n auto result_csv = getResultCSV(result, \" \");\n return Status(eRuntimeError, StringUtil::format(\n \"expected error: $0 but got result: $1\",\n expected_error,\n result_csv));\n\n } else {\n return Status(eRuntimeError, StringUtil::format(\n \"expected error: $0 but got error $1\",\n expected_error,\n error_message));\n }\n }\n}\n\nbool runTest(std::string id) {\n auto sql_file_path = FileUtil::joinPaths(\n kDirectoryPath,\n StringUtil::format(\"$0$1\", id, kSQLPathEnding));\n\n if (!FileUtil::exists(sql_file_path)) {\n RAISE(\n kIOError,\n StringUtil::format(\"File does not exist: $0\", sql_file_path));\n }\n\n auto result_file_path = FileUtil::joinPaths(\n kDirectoryPath,\n StringUtil::format(\"$0$1\", id, kResultPathEnding));\n\n if (!FileUtil::exists(result_file_path)) {\n RAISE(\n kIOError,\n StringUtil::format(\"File does not exist: $0\", result_file_path));\n }\n\n auto result_expectation = kDefaultResultExpectation;\n auto result_is = FileInputStream::openFile(result_file_path);\n std::string first_line;\n if (result_is->readLine(&first_line)) {\n StringUtil::chomp(&first_line);\n if (first_line == \"ERROR!\") {\n result_expectation = ResultExpectation::ERROR;\n }\n }\n\n \/* input table path *\/\n auto sql_is = FileInputStream::openFile(sql_file_path);\n std::string input_table_path;\n if (!sql_is->readLine(&input_table_path) ||\n !StringUtil::beginsWith(input_table_path, \"--\")) {\n RAISE(kRuntimeError, \"no input table provided\");\n }\n\n StringUtil::replaceAll(&input_table_path, \"--\");\n StringUtil::ltrim(&input_table_path);\n StringUtil::chomp(&input_table_path);\n input_table_path = FileUtil::joinPaths(\n kBaseDirectoryPath,\n input_table_path);\n\n if (!FileUtil::exists(input_table_path)) {\n RAISE(\n kRuntimeError,\n StringUtil::format(\"file does not exist: $0\", input_table_path));\n }\n\n std::string query;\n sql_is->readUntilEOF(&query);\n\n \/* execute query *\/\n auto runtime = csql::Runtime::getDefaultRuntime();\n auto txn = runtime->newTransaction();\n\n txn->setTableProvider(\n new csql::CSTableScanProvider(\"testtable\", input_table_path));\n csql::ResultList result;\n\n std::string error_message;\n try {\n auto qplan = runtime->buildQueryPlan(txn.get(), query);\n qplan->execute(0, &result);\n } catch (const std::exception& e) {\n error_message = e.what();\n\n if (result_expectation != ResultExpectation::ERROR) {\n RAISE(\n kRuntimeError,\n StringUtil::format(\"unexpected error: $0\", error_message));\n }\n }\n\n if (result.getNumColumns() == 1 &&\n result.getColumns()[0] == kChartColumnName) {\n result_expectation = ResultExpectation::CHART;\n }\n\n auto rc = Status::success();\n switch (result_expectation) {\n case ResultExpectation::TABLE:\n rc = checkTableResult(&result, result_file_path);\n break;\n\n case ResultExpectation::CHART:\n rc = checkChartResult(&result, result_file_path);\n break;\n\n case ResultExpectation::ERROR:\n rc = checkErrorResult(error_message, &result, result_file_path);\n break;\n }\n\n if (rc.isSuccess()) {\n return true;\n }\n\n \/* write file with actual result *\/\n auto acutal_result_file_path = FileUtil::joinPaths(\n kDirectoryPath,\n StringUtil::format(\"$0$1\", id, kActualResultPathEnding));\n\n const auto& csv_result = getResultCSV(&result);\n FileUtil::write(acutal_result_file_path, csv_result);\n\n RAISE(kRuntimeError, rc.message());\n}\n\nvoid setup_sql_tests(TestRepository* repo) {\n auto is = FileInputStream::openFile(kTestListFile);\n std::string test_id;\n while (is->readLine(&test_id)) {\n StringUtil::chomp(&test_id);\n\n auto test_case = eventql::test::TestCase {\n .test_id = StringUtil::format(\"SQL-$0\", test_id.substr(0, 5)),\n .description = test_id.substr(6),\n .fun = std::bind(runTest, test_id),\n .suites = { TestSuite::WORLD, TestSuite::SMOKE }\n };\n\n repo->addTestBundle({ test_case });\n test_id.clear();\n }\n}\n\n} \/\/ namespace sql\n} \/\/ namespace test\n} \/\/ namespace eventql\n\n\n<|endoftext|>"} {"text":"#include \"game.hpp\"\n\n\/\/\/\/\/\/\/\/\/\/\n\/\/ Code \/\/\n\nstruct PositionEvent : public clibgame::Event {\n std::string name;\n float x, y;\n float w, h;\n\n PositionEvent(std::string name,\n float x, float y,\n float w, float h) {\n this->name = name;\n\n this->x = x;\n this->y = y;\n this->w = w;\n this->h = h;\n }\n\n std::string getEventType() const { return this->name; }\n};\n\nstruct Position : public clibgame::Component {\n float x, y, w, h;\n bool alert;\n\n Position(float x, float y,\n float w, float h,\n bool alert) {\n this->x = x;\n this->y = y;\n\n this->w = w;\n this->h = h;\n\n this->alert = alert;\n }\n\n std::string getName() const { return \"position\"; }\n\n void translate(float dx, float dy) {\n this->x += dx;\n this->y += dy;\n\n if (this->alert)\n clibgame::ListenerManager::instance().alert(PositionEvent(this->getName(),\n this->x, this->y,\n this->w, this->h));\n }\n};\n\nstruct PlayerController : public clibgame::Component {\n float speed;\n\n PlayerController(float speed) {\n this->speed = speed;\n }\n\n std::string getName() const { return \"playerController\"; }\n\n void update(GLFWwindow* window, const clibgame::ECP& ecp, float dt) {\n float dx = 0,\n dy = 0;\n\n if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)\n dy += speed;\n if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)\n dy -= speed;\n if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)\n dx -= speed;\n if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)\n dx += speed;\n\n if (dx != 0 || dy != 0) {\n Position& p = dynamic_cast(this->getOwner().getComponent(\"position\"));\n p.translate(dx, dy);\n }\n }\n};\n\nstruct PlayerRender : public clibgame::Component,\n public clibgame::Listener {\n clibgame::Texture* texture;\n clibgame::Shader* shader;\n GLuint vao, ebo;\n\n GLuint vbo1, vbo2;\n bool mode;\n\n std::vector generateCoords(float x, float y,\n float w, float h) {\n std::vector vertices = {\n x , y , 0, 0,\n x + w, y , 1, 0,\n x + w, y + h, 1, 1,\n x , y + h, 0, 1\n };\n\n return vertices;\n }\n\n void updateVertices(float x, float y, float w, float h) {\n auto vVertices = generateCoords(x, y, w, h);\n\n GLfloat aVertices[vVertices.size()];\n for (int i = 0; i < vVertices.size(); i++)\n aVertices[i] = vVertices.at(i);\n\n glBindBuffer(GL_ARRAY_BUFFER, this->mode ? vbo1 : vbo2);\n glBufferData(GL_ARRAY_BUFFER, sizeof(aVertices), aVertices, GL_DYNAMIC_DRAW);\n mode = !mode;\n }\n\n PlayerRender() {\n clibgame::ListenerManager::instance().registerListener(this, \"position\");\n\n texture = nullptr;\n shader = nullptr;\n vao = 0;\n vbo1 = 0;\n vbo2 = 0;\n ebo = 0;\n }\n\n ~PlayerRender() {\n if (texture != nullptr)\n delete texture;\n if (shader != nullptr)\n delete shader;\n\n glDeleteVertexArrays(1, &this->vao);\n glDeleteBuffers(1, &this->vbo1);\n glDeleteBuffers(1, &this->vbo2);\n glDeleteBuffers(1, &this->ebo);\n }\n\n std::string getName() const { return \"playerRender\"; }\n\n void init(GLFWwindow* window, const clibgame::ECP& ecp, const clibgame::Res& res) {\n texture = new clibgame::Texture(res.getTexture(\"res\/test.png\"));\n shader = new clibgame::Shader(res.getShader(\"res\/test\"));\n\n glGenVertexArrays(1, &this->vao);\n glBindVertexArray(this->vao);\n\n glGenBuffers(1, &this->vbo1);\n glGenBuffers(1, &this->vbo2);\n this->updateVertices(0, 0, 0.1, 0.1);\n this->updateVertices(0, 0, 0.1, 0.1);\n\n glGenBuffers(1, &this->ebo);\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->ebo);\n\n GLuint order[] = {\n 0, 1, 2,\n 2, 3, 0\n };\n\n glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(order), order, GL_STATIC_DRAW);\n }\n\n void render() const {\n glBindVertexArray(this->vao);\n glBindBuffer(GL_ARRAY_BUFFER, this->mode ? vbo2 : vbo1);\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->ebo);\n\n glUseProgram(this->shader->getShaderID());\n\n \/\/ Initializing the coordinates.\n GLint coordAttrib = glGetAttribLocation(this->shader->getShaderID(), \"in_coordinates\");\n\n glEnableVertexAttribArray(coordAttrib);\n glVertexAttribPointer(coordAttrib, 4, GL_FLOAT, GL_FALSE, 0, 0);\n\n \/\/ Initializing the texture.\n glActiveTexture(GL_TEXTURE0);\n glBindTexture(GL_TEXTURE_2D, this->texture->getTextureID());\n glUniform1i(glGetUniformLocation(this->shader->getShaderID(), \"in_tex\"), 0);\n\n glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);\n }\n\n void alert(const clibgame::Event&& e) {\n if (e.getEventType() == \"position\") {\n const PositionEvent&& pe = dynamic_cast(e);\n \/\/this->updateVertices(pe.x, pe.y,\n \/\/pe.w, pe.h);\n }\n }\n};\n\n\/\/ Creating a new game.\nGame::Game() {\n this->addEntity(\"player\");\n this->getEntity(\"player\").addComponent(new Position(0, 0, 0.1, 0.1, true));\n this->getEntity(\"player\").addComponent(new PlayerController(0.5));\n this->getEntity(\"player\").addComponent(new PlayerRender());\n}\nSome stuff!#include \"game.hpp\"\n\n\/\/\/\/\/\/\/\/\/\/\n\/\/ Code \/\/\n\nstruct PositionEvent : public clibgame::Event {\n std::string name;\n float x, y;\n float w, h;\n\n PositionEvent(std::string name,\n float x, float y,\n float w, float h) {\n this->name = name;\n\n this->x = x;\n this->y = y;\n this->w = w;\n this->h = h;\n }\n\n std::string getEventType() const { return this->name; }\n};\n\nstruct Position : public clibgame::Component {\n float x, y, w, h;\n bool alert;\n\n Position(float x, float y,\n float w, float h,\n bool alert) {\n this->x = x;\n this->y = y;\n\n this->w = w;\n this->h = h;\n\n this->alert = alert;\n }\n\n std::string getName() const { return \"position\"; }\n\n void translate(float dx, float dy) {\n this->x += dx;\n this->y += dy;\n\n if (this->alert)\n clibgame::ListenerManager::instance().alert(PositionEvent(this->getName(),\n this->x, this->y,\n this->w, this->h));\n }\n};\n\nstruct PlayerController : public clibgame::Component {\n float speed;\n\n PlayerController(float speed) {\n this->speed = speed;\n }\n\n std::string getName() const { return \"playerController\"; }\n\n void update(GLFWwindow* window, const clibgame::ECP& ecp, float dt) {\n float dx = 0,\n dy = 0;\n\n if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)\n dy += speed;\n if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)\n dy -= speed;\n if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)\n dx -= speed;\n if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)\n dx += speed;\n\n if (dx != 0 || dy != 0) {\n Position& p = dynamic_cast(this->getOwner().getComponent(\"position\"));\n p.translate(dx * dt, dy * dt);\n }\n }\n};\n\nstruct PlayerRender : public clibgame::Component,\n public clibgame::Listener {\n clibgame::Texture* texture;\n clibgame::Shader* shader;\n GLuint vao, vbo, ebo;\n\n std::vector generateCoords(float x, float y,\n float w, float h) {\n std::vector vertices = {\n x , y , 0, 0,\n x + w, y , 1, 0,\n x + w, y + h, 1, 1,\n x , y + h, 0, 1\n };\n\n return vertices;\n }\n\n void updateVertices(float x, float y, float w, float h) {\n auto vVertices = generateCoords(x, y, w, h);\n\n GLfloat aVertices[vVertices.size()];\n for (int i = 0; i < vVertices.size(); i++)\n aVertices[i] = vVertices.at(i);\n\n glBindBuffer(GL_ARRAY_BUFFER, this->vbo);\n glBufferData(GL_ARRAY_BUFFER, sizeof(aVertices), aVertices, GL_DYNAMIC_DRAW);\n }\n\n PlayerRender() {\n clibgame::ListenerManager::instance().registerListener(this, \"position\");\n\n texture = nullptr;\n shader = nullptr;\n vao = 0;\n vbo = 0;\n ebo = 0;\n }\n\n ~PlayerRender() {\n if (texture != nullptr)\n delete texture;\n if (shader != nullptr)\n delete shader;\n\n glDeleteVertexArrays(1, &this->vao);\n glDeleteBuffers(1, &this->vbo);\n glDeleteBuffers(1, &this->ebo);\n }\n\n std::string getName() const { return \"playerRender\"; }\n\n void init(GLFWwindow* window, const clibgame::ECP& ecp, const clibgame::Res& res) {\n texture = new clibgame::Texture(res.getTexture(\"res\/test.png\"));\n shader = new clibgame::Shader(res.getShader(\"res\/test\"));\n\n glGenVertexArrays(1, &this->vao);\n glBindVertexArray(this->vao);\n\n glGenBuffers(1, &this->vbo);\n this->updateVertices(0, 0, 0.1, 0.1);\n\n glGenBuffers(1, &this->ebo);\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->ebo);\n\n GLuint order[] = {\n 0, 1, 2,\n 2, 3, 0\n };\n\n glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(order), order, GL_STATIC_DRAW);\n }\n\n void render() const {\n glBindVertexArray(this->vao);\n glBindBuffer(GL_ARRAY_BUFFER, this->vbo);\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->ebo);\n\n glUseProgram(this->shader->getShaderID());\n\n \/\/ Initializing the coordinates.\n GLint coordAttrib = glGetAttribLocation(this->shader->getShaderID(), \"in_coordinates\");\n\n glEnableVertexAttribArray(coordAttrib);\n glVertexAttribPointer(coordAttrib, 4, GL_FLOAT, GL_FALSE, 0, 0);\n\n \/\/ Initializing the texture.\n glActiveTexture(GL_TEXTURE0);\n glBindTexture(GL_TEXTURE_2D, this->texture->getTextureID());\n glUniform1i(glGetUniformLocation(this->shader->getShaderID(), \"in_tex\"), 0);\n\n glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);\n }\n\n void alert(const clibgame::Event&& e) {\n if (e.getEventType() == \"position\") {\n const PositionEvent&& pe = dynamic_cast(e);\n this->updateVertices(pe.x, pe.y,\n pe.w, pe.h);\n }\n }\n};\n\n\/\/ Creating a new game.\nGame::Game() {\n this->addEntity(\"player\");\n this->getEntity(\"player\").addComponent(new Position(0, 0, 0.1, 0.1, true));\n this->getEntity(\"player\").addComponent(new PlayerController(0.5));\n this->getEntity(\"player\").addComponent(new PlayerRender());\n}\n<|endoftext|>"} {"text":"\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) University College London (UCL).\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"QmitkCmdLineModuleMenuComboBox.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ -------------------------------------------------------------------------\nQmitkCmdLineModuleMenuComboBox::QmitkCmdLineModuleMenuComboBox(QWidget* parent)\n: ctkMenuComboBox(parent)\n, m_ModuleManager(NULL)\n{\n}\n\n\n\/\/ -------------------------------------------------------------------------\nQmitkCmdLineModuleMenuComboBox::~QmitkCmdLineModuleMenuComboBox()\n{\n\n}\n\n\n\/\/ -------------------------------------------------------------------------\nvoid QmitkCmdLineModuleMenuComboBox::SetManager(ctkCmdLineModuleManager* manager)\n{\n if (m_ModuleManager != NULL)\n {\n QObject::disconnect(manager, 0, this, 0);\n }\n\n m_ModuleManager = manager;\n\n connect(m_ModuleManager, SIGNAL(moduleRegistered(const ctkCmdLineModuleReference&)), this, SLOT(OnModuleRegistered(const ctkCmdLineModuleReference&)));\n connect(m_ModuleManager, SIGNAL(moduleUnregistered(const ctkCmdLineModuleReference&)), this, SLOT(OnModuleUnRegistered(const ctkCmdLineModuleReference&)));\n}\n\n\n\/\/ -------------------------------------------------------------------------\nctkCmdLineModuleManager* QmitkCmdLineModuleMenuComboBox::GetManager() const\n{\n return m_ModuleManager;\n}\n\n\n\/\/ -------------------------------------------------------------------------\nvoid QmitkCmdLineModuleMenuComboBox::OnModuleRegistered(const ctkCmdLineModuleReference& ref)\n{\n this->RebuildMenu();\n}\n\n\n\/\/ -------------------------------------------------------------------------\nvoid QmitkCmdLineModuleMenuComboBox::OnModuleUnRegistered(const ctkCmdLineModuleReference& ref)\n{\n this->RebuildMenu();\n}\n\n\n\/\/ -------------------------------------------------------------------------\nvoid QmitkCmdLineModuleMenuComboBox::AddName(\n QList< QHash* >& listOfHashMaps,\n const int& depth,\n const QString& name,\n QMenu* menu\n )\n{\n if (depth >= listOfHashMaps.size())\n {\n int need = depth - listOfHashMaps.size();\n for (int i = 0; i <= need; i++)\n {\n QHash *newHashMap = new QHash();\n listOfHashMaps.push_back(newHashMap);\n }\n }\n listOfHashMaps[depth]->insert(name, menu);\n}\n\n\n\/\/ -------------------------------------------------------------------------\nvoid QmitkCmdLineModuleMenuComboBox::RebuildMenu()\n{\n if (m_ModuleManager == NULL)\n {\n qDebug() << \"QmitkCmdLineModuleMenuComboBox::RebuildMenu(): Module Manager is NULL? Surely a bug?\";\n return;\n }\n\n \/\/ Can't see another way to get a nested menu, without rebuilding the whole thing each time.\n \/\/ :-(\n\n QMenu *menu = new QMenu();\n QStringList listOfModules;\n\n QList references = m_ModuleManager->moduleReferences();\n\n \/\/ Get full names\n for (int i = 0; i < references.size(); i++)\n {\n ctkCmdLineModuleReference reference = references[i];\n ctkCmdLineModuleDescription description = reference.description();\n QString title = description.title();\n QString category = description.category();\n QString fullName = category + \".\" + title;\n listOfModules << fullName;\n }\n\n \/\/ Sort list, so menu comes out in some sort of nice order.\n listOfModules.sort();\n\n qDebug() << \"QmitkCmdLineModuleMenuComboBox::RebuildMenu, listOfModules=\" << listOfModules;\n\n \/\/ Temporary data structure to enable connecting menus together.\n QList< QHash* > list;\n\n \/\/ Iterate through all modules.\n foreach (QString fullName, listOfModules)\n {\n \/\/ Pointer to keep track of where we are in the menu tree.\n QMenu *currentMenu = menu;\n\n \/\/ Get individual parts, as they correspond to menu levels.\n QStringList nameParts = fullName.split(\".\", QString::SkipEmptyParts);\n\n \/\/ Iterate over each part, building up either a QMenu or QAction.\n for (int i = 0; i < nameParts.size(); i++)\n {\n QString part = nameParts[i];\n\n if (i != nameParts.size() - 1)\n {\n \/\/ Need to add a menu\/submenu, not an action.\n if (list.size() <= i || list[i] == NULL || !list[i]->contains(part))\n {\n QMenu *newMenu = new QMenu(part);\n currentMenu->addMenu(newMenu);\n currentMenu = newMenu;\n\n \/\/ Add this newMenu pointer to temporary datastructure,\n \/\/ so we know we have already created it.\n this->AddName(list, i, part, newMenu);\n }\n else\n {\n currentMenu = list[i]->value(part);\n }\n }\n else\n {\n \/\/ Leaf node, just add the action.\n currentMenu->addAction(part);\n }\n }\n }\n\n \/\/ Clearup termporary data structure\n for (int i = 0; i < list.size(); i++)\n {\n delete list[i];\n }\n\n \/\/ Set the constructed menu on the base class combo box.\n this->setMenu(menu);\n}\n\nRemoved spurious debug output from QmitkCmdLineModuleMenuComboBox\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) University College London (UCL).\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"QmitkCmdLineModuleMenuComboBox.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ -------------------------------------------------------------------------\nQmitkCmdLineModuleMenuComboBox::QmitkCmdLineModuleMenuComboBox(QWidget* parent)\n: ctkMenuComboBox(parent)\n, m_ModuleManager(NULL)\n{\n}\n\n\n\/\/ -------------------------------------------------------------------------\nQmitkCmdLineModuleMenuComboBox::~QmitkCmdLineModuleMenuComboBox()\n{\n\n}\n\n\n\/\/ -------------------------------------------------------------------------\nvoid QmitkCmdLineModuleMenuComboBox::SetManager(ctkCmdLineModuleManager* manager)\n{\n if (m_ModuleManager != NULL)\n {\n QObject::disconnect(manager, 0, this, 0);\n }\n\n m_ModuleManager = manager;\n\n connect(m_ModuleManager, SIGNAL(moduleRegistered(const ctkCmdLineModuleReference&)), this, SLOT(OnModuleRegistered(const ctkCmdLineModuleReference&)));\n connect(m_ModuleManager, SIGNAL(moduleUnregistered(const ctkCmdLineModuleReference&)), this, SLOT(OnModuleUnRegistered(const ctkCmdLineModuleReference&)));\n}\n\n\n\/\/ -------------------------------------------------------------------------\nctkCmdLineModuleManager* QmitkCmdLineModuleMenuComboBox::GetManager() const\n{\n return m_ModuleManager;\n}\n\n\n\/\/ -------------------------------------------------------------------------\nvoid QmitkCmdLineModuleMenuComboBox::OnModuleRegistered(const ctkCmdLineModuleReference& ref)\n{\n this->RebuildMenu();\n}\n\n\n\/\/ -------------------------------------------------------------------------\nvoid QmitkCmdLineModuleMenuComboBox::OnModuleUnRegistered(const ctkCmdLineModuleReference& ref)\n{\n this->RebuildMenu();\n}\n\n\n\/\/ -------------------------------------------------------------------------\nvoid QmitkCmdLineModuleMenuComboBox::AddName(\n QList< QHash* >& listOfHashMaps,\n const int& depth,\n const QString& name,\n QMenu* menu\n )\n{\n if (depth >= listOfHashMaps.size())\n {\n int need = depth - listOfHashMaps.size();\n for (int i = 0; i <= need; i++)\n {\n QHash *newHashMap = new QHash();\n listOfHashMaps.push_back(newHashMap);\n }\n }\n listOfHashMaps[depth]->insert(name, menu);\n}\n\n\n\/\/ -------------------------------------------------------------------------\nvoid QmitkCmdLineModuleMenuComboBox::RebuildMenu()\n{\n if (m_ModuleManager == NULL)\n {\n qDebug() << \"QmitkCmdLineModuleMenuComboBox::RebuildMenu(): Module Manager is NULL? Surely a bug?\";\n return;\n }\n\n \/\/ Can't see another way to get a nested menu, without rebuilding the whole thing each time.\n \/\/ :-(\n\n QMenu *menu = new QMenu();\n QStringList listOfModules;\n\n QList references = m_ModuleManager->moduleReferences();\n\n \/\/ Get full names\n for (int i = 0; i < references.size(); i++)\n {\n ctkCmdLineModuleReference reference = references[i];\n ctkCmdLineModuleDescription description = reference.description();\n QString title = description.title();\n QString category = description.category();\n QString fullName = category + \".\" + title;\n listOfModules << fullName;\n }\n\n \/\/ Sort list, so menu comes out in some sort of nice order.\n listOfModules.sort();\n\n \/\/ Temporary data structure to enable connecting menus together.\n QList< QHash* > list;\n\n \/\/ Iterate through all modules.\n foreach (QString fullName, listOfModules)\n {\n \/\/ Pointer to keep track of where we are in the menu tree.\n QMenu *currentMenu = menu;\n\n \/\/ Get individual parts, as they correspond to menu levels.\n QStringList nameParts = fullName.split(\".\", QString::SkipEmptyParts);\n\n \/\/ Iterate over each part, building up either a QMenu or QAction.\n for (int i = 0; i < nameParts.size(); i++)\n {\n QString part = nameParts[i];\n\n if (i != nameParts.size() - 1)\n {\n \/\/ Need to add a menu\/submenu, not an action.\n if (list.size() <= i || list[i] == NULL || !list[i]->contains(part))\n {\n QMenu *newMenu = new QMenu(part);\n currentMenu->addMenu(newMenu);\n currentMenu = newMenu;\n\n \/\/ Add this newMenu pointer to temporary datastructure,\n \/\/ so we know we have already created it.\n this->AddName(list, i, part, newMenu);\n }\n else\n {\n currentMenu = list[i]->value(part);\n }\n }\n else\n {\n \/\/ Leaf node, just add the action.\n currentMenu->addAction(part);\n }\n }\n }\n\n \/\/ Clearup termporary data structure\n for (int i = 0; i < list.size(); i++)\n {\n delete list[i];\n }\n\n \/\/ Set the constructed menu on the base class combo box.\n this->setMenu(menu);\n}\n\n<|endoftext|>"} {"text":"#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE Math\n\n#include \"math.hpp\"\n\n#include \n#include \n#include \n#include \n\nusing namespace Math;\n\nconst quat R0{0,0,0,0}, R1{1,0,0,0}, \n\t i{0,1,0,0}, j{0,0,1,0}, k{0,0,0,1};\nconst dual E0{R0}, E1{R0, 1}, \n\t Ei = i*E1, Ej = j*E1, Ek = k*E1;\n\nBOOST_AUTO_TEST_CASE(quaternions) {\n\tBOOST_REQUIRE(i*j == k);\n\tBOOST_REQUIRE(j*i == -k);\n\tBOOST_REQUIRE(i*i == -R1);\n\tBOOST_REQUIRE(j*j == -R1);\n\tBOOST_REQUIRE(k*k == -R1);\n}\n\nBOOST_AUTO_TEST_CASE(dual_quaternions) {\n\tBOOST_REQUIRE(E1 != 0);\n\tBOOST_REQUIRE(E1*E1 == 0);\n}\nAdded a test#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE Math\n\n#include \"math.hpp\"\n\n#include \n#include \n#include \n#include \n\nusing namespace Math;\n\nconst quat R0{0,0,0,0}, R1{1,0,0,0}, \n\t i{0,1,0,0}, j{0,0,1,0}, k{0,0,0,1};\nconst dual E0{R0}, E1{R0, 1}, \n\t Ei = i*E1, Ej = j*E1, Ek = k*E1;\n\nBOOST_AUTO_TEST_CASE(quaternions) {\n\tBOOST_REQUIRE(i*j == k);\n\tBOOST_REQUIRE(j*i == -k);\n\tBOOST_REQUIRE(i*i == -R1);\n\tBOOST_REQUIRE(j*j == -R1);\n\tBOOST_REQUIRE(k*k == -R1);\n}\n\nBOOST_AUTO_TEST_CASE(dual_quaternions) {\n\tBOOST_REQUIRE(E1 != 0);\n\tBOOST_REQUIRE(E1*E1 == 0);\n\tBOOST_REQUIRE((k*E1)*i != i*(k*E1));\n}\n<|endoftext|>"} {"text":"\/\/Author: Julian Yi\r\n\/\/Date: 14 July 2017\r\n\/\/board functions\r\n\r\n#include \r\n#include \"board.h\"\r\n#include \"pieceutils.h\"\r\n\r\nboard::board() : squares()\r\n{ }\r\n\r\nvoid board::promote(coord pos, TeamColor color)\r\n{\r\n\tauto current = &squares[pos.x][pos.y];\r\n\r\n\tstd::string Command = \"\";\r\n\r\n\tstd::cout << colorToString(current->pieces.front()->team) << \" Pawn has reached a promotion area Pick a type: \";\r\n\tstd::cin >> Command;\r\n\tPieceType newType = pieceFromString(Command);\r\n\r\n\tdeletePiece(pos);\t\r\n\r\n\tstd::cout << \"You picked \" << Command << std::endl;\r\n\r\n\tplacePiece(newType, pos, color);\r\n\r\n}\r\n\r\nbool board::placePiece(PieceType piece, coord pos, TeamColor color)\r\n{\r\n\tauto current = &squares[pos.x][pos.y];\r\n\r\n\tif (!current->occupied())\r\n\t{\r\n\t\tcurrent->canMove = false;\r\n\t\tcurrent->pieces.push_back(PieceUtils::pieceFromType(piece, pos));\r\n\t\tcurrent->pieces.front()->team = color;\r\n\t\t\r\n\t\tstd::cout << colorToString(color) << \" \" << pieceToString(piece) << \" is Placed at (\" << pos.x << \", \" << pos.y << \")\" << std::endl;\r\n\t\t\r\n\t\treturn true;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tstd::cout << \"unable to place Piece \" << pieceToString(piece) << \" at (\" << pos.x << \", \" << pos.y << \"). \"\r\n\t\t\t\t << pieceToString(current->pieces.front()->type) << \" is Occupying the space.\" << std::endl;\r\n\r\n\t\treturn false;\r\n\t}\r\n}\r\n\r\nbool board::movePiece(coord oldPos, coord newPos)\r\n{\r\n\t\/\/ Input validation\r\n\tif (oldPos.x > boardSize::x || oldPos.x < 0) {\r\n\t\tstd::cout << \"Old position X out of bounds (0, \" << boardSize::x << \")\" << std::endl;\r\n\t\treturn false;\r\n\t}\r\n\tif (oldPos.y > boardSize::y || oldPos.y < 0) {\r\n\t\tstd::cout << \"Old position Y out of bounds (0, \" << boardSize::y << \")\" << std::endl;\r\n\t\treturn false;\r\n\t}\r\n\tif (newPos.x > boardSize::x || newPos.x < 0) {\r\n\t\tstd::cout << \"Old position X out of bounds (0, \" << boardSize::x << \")\" << std::endl;\r\n\t\treturn false;\r\n\t}\r\n\tif (newPos.y > boardSize::y || newPos.y < 0) {\r\n\t\tstd::cout << \"Old position Y out of bounds (0, \" << boardSize::y << \")\" << std::endl;\r\n\t\treturn false;\r\n\t}\r\n\r\n\tauto oldS = &squares[oldPos.x][oldPos.y];\r\n\tif (oldS->pieces.empty()) {\r\n\t\tstd::cout << \"No piece to move at (\" << oldPos.x << \", \" << oldPos.y << \")\" << std::endl;\r\n\t\treturn false;\r\n\t}\r\n\r\n\tauto newS = &squares[newPos.x][newPos.y];\r\n\r\n\t\/\/ Get the moves for the piece located in the old square\r\n\tauto availableMoves = oldS->pieces.front()->calculateMoves({boardSize::x, boardSize::y}, squares);\r\n\tif (availableMoves.empty()) {\r\n\t\tstd::cout << \"No available moves for (\" << oldPos.x << \", \" << oldPos.y << \")\" << std::endl;\r\n\t\treturn false;\r\n\t}\r\n\t\/*\r\n\tfor (auto move : availableMoves) {\r\n\t\tstd::cout << \"(\" << move.x << \", \" << move.y << \") \";\r\n\t}\r\n\tstd::cout << std::endl;\r\n\t*\/\r\n\tif (std::find(availableMoves.begin(), availableMoves.end(), newPos) != availableMoves.end()) {\r\n\t\t\/\/ move to newpos.\r\n\t\tstd::cout << colorToString(oldS->pieces.front()->team) << \" \" << pieceToString(oldS->pieces.front()->type) << \" Attempting to move to (\" << newPos.x << \", \" << newPos.y << \")\" << std::endl;\r\n\r\n\t\tif (!newS->pieces.empty()) {\r\n\t\t\tif (newS->pieces.front()->team == oldS->pieces.front()->team) {\r\n\t\t\t\t std::cout << \"Friendly piece at (\" << newPos.x << \", \" << newPos.y << \"), against the rules.\" << std::endl;\r\n\t\t\t\t return false;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tstd::cout << \"(\" << newPos.x << \", \" << newPos.y << \") \" << \"is occupied by \" << colorToString(newS->pieces.front()->team) << \" \" << pieceToString(newS->pieces.front()->type) << std::endl;\r\n\t\t\tstd::cout << colorToString(newS->pieces.front()->team) << \" \" << pieceToString(newS->pieces.front()->type) << \" destroyed by \" << colorToString(oldS->pieces.front()->team) << \" \" << pieceToString(oldS->pieces.front()->type) << \" at (\" << newPos.x << \", \" << newPos.y << \")\" << std::endl;\r\n\t\t\tnewS->pieces.clear();\r\n\t\t}\r\n\r\n\r\n\t\tnewS->pieces.push_back(oldS->pieces.front());\r\n\t\tnewS->pieces.front()->setPosition(newPos); \/\/position needs to change to the new position otherwise the piece pointer will still have the old positions\r\n\t\toldS->pieces.clear();\r\n\r\n\t\t\/* made for testing purpose\r\n\t\t\tcoord pos = newS->pieces.front()->getPosition(); \r\n\t\t\tstd::cout << pos.x << pos.y;\r\n\t\t*\/\r\n\t\tstd::cout << \"Successful move. \" << colorToString(newS->pieces.front()->team) << \" \" << pieceToString(newS->pieces.front()->type) << \" was moved to (\" << newPos.x << \", \" << newPos.y << \")\" << std::endl;\r\n\t\t\r\n\t\t\/*\r\n\t\t\tcall promote if a Pawn Piece type reaches a y coordinate of 0 or 7 depending on their color\r\n\t\t*\/\r\n\t\tif (newS->pieces.front()->type == PieceType::Pawn)\r\n\t\t{\r\n\t\t\tif (newS->pieces.front()->team == TeamColor::White && newPos.y == 7)\r\n\t\t\t{\r\n\t\t\t\tpromote(newPos, TeamColor::White);\r\n\t\t\t}\r\n\t\t\telse if (newS->pieces.front()->team == TeamColor::Black && newPos.y == 0)\r\n\t\t\t{\r\n\t\t\t\tpromote(newPos, TeamColor::Black);\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\r\n\t} else {\r\n\t\t\/\/ Not in the move list.\r\n\t\tstd::cout << \"Cannot move to (\" << newPos.x << \", \" << newPos.y << \"), against the rules.\" << std::endl;\r\n\t\treturn false;\r\n\t}\r\n\r\n\treturn true;\r\n}\r\n\r\nbool board::deletePiece(coord pos)\r\n{\r\n\tauto current = &squares[pos.x][pos.y];\r\n\tif (current->occupied())\r\n\t{\r\n\t\tcurrent->canMove = true;\r\n\t\t\/\/don't change the boardTag\r\n\t\tcurrent->pieces.pop_back();\r\n\t\treturn true;\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nvoid board::initializeBoard()\r\n{\r\n\tint Ascii = 65;\r\n\tstd::string boardTag = \"\";\r\n\r\n\tfor (int index = 0; index < boardSize::y; ++index)\r\n\t{\r\n\t\tfor (int jindex = 0; jindex < boardSize::x; ++jindex)\r\n\t\t{\r\n\t\t\tboardTag = (char(Ascii));\r\n\t\t\tboardTag += std::to_string(jindex);\r\n\t\t\tauto current = &squares[index][jindex];\r\n\t\t\tcurrent->canMove = true;\r\n\t\t\t\/\/squares[index]->tag = (char(Ascii) + '-' + char(index));\r\n\t\t\tcurrent->tag = boardTag;\r\n\t\t}\r\n\t\tAscii++;\r\n\t}\r\n}\r\n\r\n\r\nPieceType board::getSquareType(coord pos) const\r\n{\r\n\tif (squares[pos.x][pos.y].occupied()) {\r\n\t\treturn squares[pos.x][pos.y].pieces.front()->type;\r\n\t}\r\n\treturn PieceType::None;\r\n}\r\n\r\nTeamColor board::getSquareColor(coord pos) const\r\n{\r\n\tif (squares[pos.x][pos.y].occupied()) {\r\n\t\treturn squares[pos.x][pos.y].pieces.front()->team;\r\n\t}\r\n\treturn TeamColor::None;\r\n}\r\n\r\n\/\/created for testing purpose\r\nvoid board::printBoard()\r\n{\r\n\tfor (int index = 0; index < boardSize::y; ++index)\r\n\t{\r\n\t\tfor (int jindex = 0; jindex < boardSize::x; ++jindex)\r\n\t\t{\r\n\t\t\tstd::cout << squares[index][jindex].tag;\r\n\t\t}\r\n\r\n\t\tstd::cout << std::endl;\r\n\t}\r\n}\r\nRemoved Can Move\/\/Author: Julian Yi\r\n\/\/Date: 14 July 2017\r\n\/\/board functions\r\n\r\n#include \r\n#include \"board.h\"\r\n#include \"pieceutils.h\"\r\n\r\nboard::board() : squares()\r\n{ }\r\n\r\nvoid board::promote(coord pos, TeamColor color)\r\n{\r\n\tauto current = &squares[pos.x][pos.y];\r\n\r\n\tstd::string Command = \"\";\r\n\r\n\tstd::cout << colorToString(current->pieces.front()->team) << \" Pawn has reached a promotion area Pick a type: \";\r\n\tstd::cin >> Command;\r\n\tPieceType newType = pieceFromString(Command);\r\n\r\n\tdeletePiece(pos);\t\r\n\r\n\tstd::cout << \"You picked \" << Command << std::endl;\r\n\r\n\tplacePiece(newType, pos, color);\r\n\r\n}\r\n\r\nbool board::placePiece(PieceType piece, coord pos, TeamColor color)\r\n{\r\n\tauto current = &squares[pos.x][pos.y];\r\n\r\n\tif (!current->occupied())\r\n\t{\r\n\t\tcurrent->pieces.push_back(PieceUtils::pieceFromType(piece, pos));\r\n\t\tcurrent->pieces.front()->team = color;\r\n\t\t\r\n\t\tstd::cout << colorToString(color) << \" \" << pieceToString(piece) << \" is Placed at (\" << pos.x << \", \" << pos.y << \")\" << std::endl;\r\n\t\t\r\n\t\treturn true;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tstd::cout << \"unable to place Piece \" << pieceToString(piece) << \" at (\" << pos.x << \", \" << pos.y << \"). \"\r\n\t\t\t\t << pieceToString(current->pieces.front()->type) << \" is Occupying the space.\" << std::endl;\r\n\r\n\t\treturn false;\r\n\t}\r\n}\r\n\r\nbool board::movePiece(coord oldPos, coord newPos)\r\n{\r\n\t\/\/ Input validation\r\n\tif (oldPos.x > boardSize::x || oldPos.x < 0) {\r\n\t\tstd::cout << \"Old position X out of bounds (0, \" << boardSize::x << \")\" << std::endl;\r\n\t\treturn false;\r\n\t}\r\n\tif (oldPos.y > boardSize::y || oldPos.y < 0) {\r\n\t\tstd::cout << \"Old position Y out of bounds (0, \" << boardSize::y << \")\" << std::endl;\r\n\t\treturn false;\r\n\t}\r\n\tif (newPos.x > boardSize::x || newPos.x < 0) {\r\n\t\tstd::cout << \"Old position X out of bounds (0, \" << boardSize::x << \")\" << std::endl;\r\n\t\treturn false;\r\n\t}\r\n\tif (newPos.y > boardSize::y || newPos.y < 0) {\r\n\t\tstd::cout << \"Old position Y out of bounds (0, \" << boardSize::y << \")\" << std::endl;\r\n\t\treturn false;\r\n\t}\r\n\r\n\tauto oldS = &squares[oldPos.x][oldPos.y];\r\n\tif (oldS->pieces.empty()) {\r\n\t\tstd::cout << \"No piece to move at (\" << oldPos.x << \", \" << oldPos.y << \")\" << std::endl;\r\n\t\treturn false;\r\n\t}\r\n\r\n\tauto newS = &squares[newPos.x][newPos.y];\r\n\r\n\t\/\/ Get the moves for the piece located in the old square\r\n\tauto availableMoves = oldS->pieces.front()->calculateMoves({boardSize::x, boardSize::y}, squares);\r\n\tif (availableMoves.empty()) {\r\n\t\tstd::cout << \"No available moves for (\" << oldPos.x << \", \" << oldPos.y << \")\" << std::endl;\r\n\t\treturn false;\r\n\t}\r\n\t\/*\r\n\tfor (auto move : availableMoves) {\r\n\t\tstd::cout << \"(\" << move.x << \", \" << move.y << \") \";\r\n\t}\r\n\tstd::cout << std::endl;\r\n\t*\/\r\n\tif (std::find(availableMoves.begin(), availableMoves.end(), newPos) != availableMoves.end()) {\r\n\t\t\/\/ move to newpos.\r\n\t\tstd::cout << colorToString(oldS->pieces.front()->team) << \" \" << pieceToString(oldS->pieces.front()->type) << \" Attempting to move to (\" << newPos.x << \", \" << newPos.y << \")\" << std::endl;\r\n\r\n\t\tif (!newS->pieces.empty()) {\r\n\t\t\tif (newS->pieces.front()->team == oldS->pieces.front()->team) {\r\n\t\t\t\t std::cout << \"Friendly piece at (\" << newPos.x << \", \" << newPos.y << \"), against the rules.\" << std::endl;\r\n\t\t\t\t return false;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tstd::cout << \"(\" << newPos.x << \", \" << newPos.y << \") \" << \"is occupied by \" << colorToString(newS->pieces.front()->team) << \" \" << pieceToString(newS->pieces.front()->type) << std::endl;\r\n\t\t\tstd::cout << colorToString(newS->pieces.front()->team) << \" \" << pieceToString(newS->pieces.front()->type) << \" destroyed by \" << colorToString(oldS->pieces.front()->team) << \" \" << pieceToString(oldS->pieces.front()->type) << \" at (\" << newPos.x << \", \" << newPos.y << \")\" << std::endl;\r\n\t\t\tnewS->pieces.clear();\r\n\t\t}\r\n\r\n\r\n\t\tnewS->pieces.push_back(oldS->pieces.front());\r\n\t\tnewS->pieces.front()->setPosition(newPos); \/\/position needs to change to the new position otherwise the piece pointer will still have the old positions\r\n\t\toldS->pieces.clear();\r\n\r\n\t\t\/* made for testing purpose\r\n\t\t\tcoord pos = newS->pieces.front()->getPosition(); \r\n\t\t\tstd::cout << pos.x << pos.y;\r\n\t\t*\/\r\n\t\tstd::cout << \"Successful move. \" << colorToString(newS->pieces.front()->team) << \" \" << pieceToString(newS->pieces.front()->type) << \" was moved to (\" << newPos.x << \", \" << newPos.y << \")\" << std::endl;\r\n\t\t\r\n\t\t\/*\r\n\t\t\tcall promote if a Pawn Piece type reaches a y coordinate of 0 or 7 depending on their color\r\n\t\t*\/\r\n\t\tif (newS->pieces.front()->type == PieceType::Pawn)\r\n\t\t{\r\n\t\t\tif (newS->pieces.front()->team == TeamColor::White && newPos.y == 7)\r\n\t\t\t{\r\n\t\t\t\tpromote(newPos, TeamColor::White);\r\n\t\t\t}\r\n\t\t\telse if (newS->pieces.front()->team == TeamColor::Black && newPos.y == 0)\r\n\t\t\t{\r\n\t\t\t\tpromote(newPos, TeamColor::Black);\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\r\n\t} else {\r\n\t\t\/\/ Not in the move list.\r\n\t\tstd::cout << \"Cannot move to (\" << newPos.x << \", \" << newPos.y << \"), against the rules.\" << std::endl;\r\n\t\treturn false;\r\n\t}\r\n\r\n\treturn true;\r\n}\r\n\r\nbool board::deletePiece(coord pos)\r\n{\r\n\tauto current = &squares[pos.x][pos.y];\r\n\tif (current->occupied())\r\n\t{\r\n\t\t\/\/don't change the boardTag\r\n\t\tcurrent->pieces.pop_back();\r\n\t\treturn true;\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nvoid board::initializeBoard()\r\n{\r\n\tint Ascii = 65;\r\n\tstd::string boardTag = \"\";\r\n\r\n\tfor (int index = 0; index < boardSize::y; ++index)\r\n\t{\r\n\t\tfor (int jindex = 0; jindex < boardSize::x; ++jindex)\r\n\t\t{\r\n\t\t\tboardTag = (char(Ascii));\r\n\t\t\tboardTag += std::to_string(jindex);\r\n\t\t\tauto current = &squares[index][jindex];\r\n\t\t\t\/\/squares[index]->tag = (char(Ascii) + '-' + char(index));\r\n\t\t\tcurrent->tag = boardTag;\r\n\t\t}\r\n\t\tAscii++;\r\n\t}\r\n}\r\n\r\n\r\nPieceType board::getSquareType(coord pos) const\r\n{\r\n\tif (squares[pos.x][pos.y].occupied()) {\r\n\t\treturn squares[pos.x][pos.y].pieces.front()->type;\r\n\t}\r\n\treturn PieceType::None;\r\n}\r\n\r\nTeamColor board::getSquareColor(coord pos) const\r\n{\r\n\tif (squares[pos.x][pos.y].occupied()) {\r\n\t\treturn squares[pos.x][pos.y].pieces.front()->team;\r\n\t}\r\n\treturn TeamColor::None;\r\n}\r\n\r\n\/\/created for testing purpose\r\nvoid board::printBoard()\r\n{\r\n\tfor (int index = 0; index < boardSize::y; ++index)\r\n\t{\r\n\t\tfor (int jindex = 0; jindex < boardSize::x; ++jindex)\r\n\t\t{\r\n\t\t\tstd::cout << squares[index][jindex].tag;\r\n\t\t}\r\n\r\n\t\tstd::cout << std::endl;\r\n\t}\r\n}\r\n<|endoftext|>"} {"text":"\/\/ -*- mode: c++; c-basic-offset:4 -*-\n\n\/\/ This file is part of libdap, A C++ implementation of the OPeNDAP Data\n\/\/ Access Protocol.\n\n\/\/ Copyright (c) 2002,2003 OPeNDAP, Inc.\n\/\/ Author: James Gallagher \n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\/\/\n\/\/ You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.\n\n#include \"config.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \"Byte.h\"\n#include \"Int8.h\"\n#include \"Int16.h\"\n#include \"UInt16.h\"\n#include \"Int32.h\"\n#include \"UInt32.h\"\n#include \"Int64.h\"\n#include \"UInt64.h\"\n#include \"Float32.h\"\n#include \"Float64.h\"\n#include \"Str.h\"\n#include \"Url.h\"\n#include \"Array.h\"\n#include \"Structure.h\"\n#include \"Sequence.h\"\n#include \"Grid.h\"\n#include \"crc.h\"\n\n#include \"DDS.h\"\n\n#include \"GNURegex.h\"\n#include \"GetOpt.h\"\n#include \"util.h\"\n#include \"debug.h\"\n#include \"ce_expr.tab.hh\"\n\n#include \"testFile.h\"\n#include \"test_config.h\"\n\nstatic bool debug = false;\n\n#undef DBG\n#define DBG(x) do { if (debug) {x;} } while(false)\n\nusing namespace CppUnit;\nusing namespace std;\n\nnamespace libdap {\n\nclass UInt16Test: public TestFixture {\nprivate:\n UInt16 *i1, *i2;\n char a[1024];\n \npublic:\n UInt16Test() : i1(0), i2(0)\n {\n }\n ~UInt16Test()\n {\n }\n\n void setUp()\n {\n i1 = new UInt16(\"a\", \"b\");\n i2 = new UInt16(\"e\");\n }\n\n void tearDown()\n {\n delete i1;\n delete i2;\n }\n\n CPPUNIT_TEST_SUITE(UInt16Test);\n\n CPPUNIT_TEST(cons_UInt16_test);\n CPPUNIT_TEST(checksum_test);\n CPPUNIT_TEST(val2buf_test);\n CPPUNIT_TEST(buf2val_test);\n CPPUNIT_TEST(set_value_test);\n CPPUNIT_TEST(equals_test);\n CPPUNIT_TEST(type_compare_test);\n CPPUNIT_TEST(ops_exception_1_test);\n CPPUNIT_TEST(ops_exception_2_test);\n CPPUNIT_TEST(dump_test);\n CPPUNIT_TEST(print_test);\n CPPUNIT_TEST(check_types);\n\n CPPUNIT_TEST_SUITE_END();\n\n void cons_UInt16_test()\n {\n CPPUNIT_ASSERT(i1->value() == 0 && i1->dataset() == \"b\" && i1->name() == \"a\" &&\n i1->type() == dods_uint16_c);\n CPPUNIT_ASSERT(i2->value() == 0);\n }\n\n void checksum_test()\n {\n Crc32 cs;\n i2->compute_checksum(cs);\n }\n\n void val2buf_test()\n {\n int i = 42;\n i2->val2buf(&i, true);\n CPPUNIT_ASSERT(i2->value() == 42); \n CPPUNIT_ASSERT_THROW(i2->val2buf(NULL, true), InternalErr);\n }\n\n void buf2val_test()\n {\n int i = 42;\n void *v = &i;\n void *v2 = NULL;\n CPPUNIT_ASSERT(i2->set_value(0));\n CPPUNIT_ASSERT(i2->buf2val(&v) == 2 && i == 0);\n \/\/ CPPUNIT_ASSERT_THROW(i2->buf2val(NULL), InternalErr);\n \/\/ CPPUNIT_ASSERT(i2->buf2val(&v2) == 2 && *(int *)v2 == 0);\n }\n\n void set_value_test()\n {\n CPPUNIT_ASSERT(i2->set_value(42) && i2->value() == 42); \n }\n\n void equals_test()\n {\n UInt16 i3 = UInt16(\"a\", \"b\");\n UInt16 i4 = UInt16(\"e\");\n CPPUNIT_ASSERT(i4.set_value(42) && i4.value() == 42);\n i3 = i4;\n CPPUNIT_ASSERT(i3.value() == 42);\n i3 = i3;\n } \n\n void type_compare_test()\n {\n Byte b1 = Byte(\"a\");\n Int8 i8 = Int8(\"a\");\n Int16 i16 = Int16(\"a\");\n UInt16 ui16 = UInt16(\"a\");\n Int32 i32 = Int32(\"a\", \"b\");\n UInt32 ui32 = UInt32(\"a\", \"b\");\n Int64 i64 = Int64(\"a\", \"b\");\n UInt64 ui64 = UInt64(\"a\", \"b\");\n Float32 f32 = Float32(\"a\");\n Float64 f64 = Float64(\"a\");\n Url url = Url(\"a\");\n Str str = Str(\"a\");\n Array array = Array(\"a\", &i16, true);\n \n b1.set_value(42);\n i8.set_value(42);\n i16.set_value(42);\n ui16.set_value(42);\n i32.set_value(42);\n ui32.set_value(42);\n i64.set_value(42);\n ui64.set_value(42);\n f32.set_value(42);\n f64.set_value(42);\n CPPUNIT_ASSERT(ui16.value() == 42);\n CPPUNIT_ASSERT(ui16.ops(&b1, SCAN_EQUAL));\n CPPUNIT_ASSERT(ui16.ops(&b1, SCAN_EQUAL));\n CPPUNIT_ASSERT(ui16.ops(&i8, SCAN_EQUAL));\n CPPUNIT_ASSERT(ui16.ops(&i16, SCAN_EQUAL));\n CPPUNIT_ASSERT(ui16.ops(&ui16, SCAN_EQUAL));\n CPPUNIT_ASSERT(ui16.ops(&i32, SCAN_EQUAL));\n CPPUNIT_ASSERT(ui16.ops(&ui32, SCAN_EQUAL));\n CPPUNIT_ASSERT(ui16.ops(&i64, SCAN_EQUAL));\n CPPUNIT_ASSERT(ui16.ops(&ui64, SCAN_EQUAL));\n CPPUNIT_ASSERT(ui16.ops(&f32, SCAN_EQUAL));\n CPPUNIT_ASSERT(ui16.ops(&f64, SCAN_EQUAL));\n\n CPPUNIT_ASSERT_THROW(ui16.ops(&url, SCAN_EQUAL), Error);\n CPPUNIT_ASSERT_THROW(ui16.ops(&str, SCAN_EQUAL), Error);\n CPPUNIT_ASSERT_THROW(ui16.ops(&array, SCAN_EQUAL), Error);\n } \n\n void ops_exception_1_test()\n {\n Byte b1 = Byte(\"a\");\n UInt16 ui16 = UInt16(\"a\", \"b\");\n b1.set_read_p(false);\n CPPUNIT_ASSERT_THROW(ui16.ops(&b1, SCAN_EQUAL), InternalErr); \n } \n\n void ops_exception_2_test()\n {\n Byte b1 = Byte(\"a\");\n UInt16 ui16 = UInt16(\"a\", \"b\");\n ui16.set_read_p(false);\n CPPUNIT_ASSERT_THROW(ui16.ops(&b1, SCAN_EQUAL), InternalErr); \n } \n\n void dump_test()\n {\n ofstream ofs(\"UInt16Test_dump.output\", ios::trunc);\n i1->set_value(21);\n i1->dump(ofs);\n ofs.close();\n ifstream ifs(\"UInt16Test_dump.output\");\n while(!ifs.eof())\n ifs >> a;\n ifs.close();\n CPPUNIT_ASSERT(!strcmp(a, \"21\"));\n }\n\n void print_test()\n {\n FILE *fp;\n CPPUNIT_ASSERT(fp = fopen(\"UInt16Test.output\", \"w\"));\n i1->set_value(22);\n i1->print_val(fp, \" \", true);\n fclose(fp);\n ifstream ifs(\"UInt16Test.output\");\n while(!ifs.eof())\n ifs >> a;\n ifs.close();\n CPPUNIT_ASSERT(!strcmp(a, \"22;\"));\n }\n\n void check_types()\n {\n Byte *b1 = new Byte(\"b\");\n b1->set_value(14);\n i1->set_value(14);\n\/\/ CPPUNIT_ASSERT(b1 == i1);\n delete b1;\n }\n\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION(UInt16Test);\n\n} \/\/ namespace libdap\n\nint main(int argc, char *argv[])\n{\n GetOpt getopt(argc, argv, \"dh\");\n int option_char;\n\n while ((option_char = getopt()) != -1)\n switch (option_char) {\n case 'd':\n debug = 1; \/\/ debug is a static global\n break;\n\n case 'h': { \/\/ help - show test names\n cerr << \"Usage: UInt16Test has the following tests:\" << endl;\n const std::vector &tests = libdap::UInt16Test::suite()->getTests();\n unsigned int prefix_len = libdap::UInt16Test::suite()->getName().append(\"::\").length();\n for (std::vector::const_iterator i = tests.begin(), e = tests.end(); i != e; ++i) {\n cerr << (*i)->getName().replace(0, prefix_len, \"\") << endl;\n }\n return 1;\n break;\n }\n\n default:\n break;\n }\n\n CppUnit::TextTestRunner runner;\n runner.addTest(CppUnit::TestFactoryRegistry::getRegistry().makeTest());\n\n bool wasSuccessful = true;\n string test = \"\";\n int i = getopt.optind;\n if (i == argc) {\n \/\/ run them all\n wasSuccessful = runner.run(\"\");\n }\n else {\n for (; i < argc; ++i) {\n if (debug) cerr << \"Running \" << argv[i] << endl;\n test = libdap::UInt16Test::suite()->getName().append(\"::\").append(argv[i]);\n wasSuccessful = wasSuccessful && runner.run(test);\n }\n }\n\n return wasSuccessful ? 0 : 1;\n}\n\nattempting to fix second problem with travis\/\/ -*- mode: c++; c-basic-offset:4 -*-\n\n\/\/ This file is part of libdap, A C++ implementation of the OPeNDAP Data\n\/\/ Access Protocol.\n\n\/\/ Copyright (c) 2002,2003 OPeNDAP, Inc.\n\/\/ Author: James Gallagher \n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\/\/\n\/\/ You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.\n\n#include \"config.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \"Byte.h\"\n#include \"Int8.h\"\n#include \"Int16.h\"\n#include \"UInt16.h\"\n#include \"Int32.h\"\n#include \"UInt32.h\"\n#include \"Int64.h\"\n#include \"UInt64.h\"\n#include \"Float32.h\"\n#include \"Float64.h\"\n#include \"Str.h\"\n#include \"Url.h\"\n#include \"Array.h\"\n#include \"Structure.h\"\n#include \"Sequence.h\"\n#include \"Grid.h\"\n#include \"crc.h\"\n\n#include \"DDS.h\"\n\n#include \"GNURegex.h\"\n#include \"GetOpt.h\"\n#include \"util.h\"\n#include \"debug.h\"\n#include \"ce_expr.tab.hh\"\n\n#include \"testFile.h\"\n#include \"test_config.h\"\n\nstatic bool debug = false;\n\n#undef DBG\n#define DBG(x) do { if (debug) {x;} } while(false)\n\nusing namespace CppUnit;\nusing namespace std;\n\nnamespace libdap {\n\nclass UInt16Test: public TestFixture {\nprivate:\n UInt16 *i1, *i2;\n char a[1024];\n \npublic:\n UInt16Test() : i1(0), i2(0)\n {\n }\n ~UInt16Test()\n {\n }\n\n void setUp()\n {\n i1 = new UInt16(\"a\", \"b\");\n i2 = new UInt16(\"e\");\n }\n\n void tearDown()\n {\n delete i1;\n delete i2;\n }\n\n CPPUNIT_TEST_SUITE(UInt16Test);\n\n CPPUNIT_TEST(cons_UInt16_test);\n CPPUNIT_TEST(checksum_test);\n CPPUNIT_TEST(val2buf_test);\n CPPUNIT_TEST(buf2val_test);\n CPPUNIT_TEST(set_value_test);\n CPPUNIT_TEST(equals_test);\n CPPUNIT_TEST(type_compare_test);\n CPPUNIT_TEST(ops_exception_1_test);\n CPPUNIT_TEST(ops_exception_2_test);\n CPPUNIT_TEST(dump_test);\n CPPUNIT_TEST(print_test);\n CPPUNIT_TEST(check_types);\n\n CPPUNIT_TEST_SUITE_END();\n\n void cons_UInt16_test()\n {\n CPPUNIT_ASSERT(i1->value() == 0 && i1->dataset() == \"b\" && i1->name() == \"a\" &&\n i1->type() == dods_uint16_c);\n CPPUNIT_ASSERT(i2->value() == 0);\n }\n\n void checksum_test()\n {\n Crc32 cs;\n i2->compute_checksum(cs);\n }\n\n void val2buf_test()\n {\n int i = 42;\n i2->val2buf(&i, true);\n CPPUNIT_ASSERT(i2->value() == 42); \n CPPUNIT_ASSERT_THROW(i2->val2buf(NULL, true), InternalErr);\n }\n\n void buf2val_test()\n {\n int i = 42;\n void *v = &i;\n void *v2 = NULL;\n CPPUNIT_ASSERT(i2->set_value(0));\n CPPUNIT_ASSERT(i2->buf2val(&v) == 2 && i == 0);\n CPPUNIT_ASSERT_THROW(i2->buf2val(NULL), InternalErr);\n \/\/ CPPUNIT_ASSERT(i2->buf2val(&v2) == 2 && *(int *)v2 == 0);\n }\n\n void set_value_test()\n {\n CPPUNIT_ASSERT(i2->set_value(42) && i2->value() == 42); \n }\n\n void equals_test()\n {\n UInt16 i3 = UInt16(\"a\", \"b\");\n UInt16 i4 = UInt16(\"e\");\n CPPUNIT_ASSERT(i4.set_value(42) && i4.value() == 42);\n i3 = i4;\n CPPUNIT_ASSERT(i3.value() == 42);\n i3 = i3;\n } \n\n void type_compare_test()\n {\n Byte b1 = Byte(\"a\");\n Int8 i8 = Int8(\"a\");\n Int16 i16 = Int16(\"a\");\n UInt16 ui16 = UInt16(\"a\");\n Int32 i32 = Int32(\"a\", \"b\");\n UInt32 ui32 = UInt32(\"a\", \"b\");\n Int64 i64 = Int64(\"a\", \"b\");\n UInt64 ui64 = UInt64(\"a\", \"b\");\n Float32 f32 = Float32(\"a\");\n Float64 f64 = Float64(\"a\");\n Url url = Url(\"a\");\n Str str = Str(\"a\");\n Array array = Array(\"a\", &i16, true);\n \n b1.set_value(42);\n i8.set_value(42);\n i16.set_value(42);\n ui16.set_value(42);\n i32.set_value(42);\n ui32.set_value(42);\n i64.set_value(42);\n ui64.set_value(42);\n f32.set_value(42);\n f64.set_value(42);\n CPPUNIT_ASSERT(ui16.value() == 42);\n CPPUNIT_ASSERT(ui16.ops(&b1, SCAN_EQUAL));\n CPPUNIT_ASSERT(ui16.ops(&b1, SCAN_EQUAL));\n CPPUNIT_ASSERT(ui16.ops(&i8, SCAN_EQUAL));\n CPPUNIT_ASSERT(ui16.ops(&i16, SCAN_EQUAL));\n CPPUNIT_ASSERT(ui16.ops(&ui16, SCAN_EQUAL));\n CPPUNIT_ASSERT(ui16.ops(&i32, SCAN_EQUAL));\n CPPUNIT_ASSERT(ui16.ops(&ui32, SCAN_EQUAL));\n CPPUNIT_ASSERT(ui16.ops(&i64, SCAN_EQUAL));\n CPPUNIT_ASSERT(ui16.ops(&ui64, SCAN_EQUAL));\n CPPUNIT_ASSERT(ui16.ops(&f32, SCAN_EQUAL));\n CPPUNIT_ASSERT(ui16.ops(&f64, SCAN_EQUAL));\n\n CPPUNIT_ASSERT_THROW(ui16.ops(&url, SCAN_EQUAL), Error);\n CPPUNIT_ASSERT_THROW(ui16.ops(&str, SCAN_EQUAL), Error);\n CPPUNIT_ASSERT_THROW(ui16.ops(&array, SCAN_EQUAL), Error);\n } \n\n void ops_exception_1_test()\n {\n Byte b1 = Byte(\"a\");\n UInt16 ui16 = UInt16(\"a\", \"b\");\n b1.set_read_p(false);\n CPPUNIT_ASSERT_THROW(ui16.ops(&b1, SCAN_EQUAL), InternalErr); \n } \n\n void ops_exception_2_test()\n {\n Byte b1 = Byte(\"a\");\n UInt16 ui16 = UInt16(\"a\", \"b\");\n ui16.set_read_p(false);\n CPPUNIT_ASSERT_THROW(ui16.ops(&b1, SCAN_EQUAL), InternalErr); \n } \n\n void dump_test()\n {\n ofstream ofs(\"UInt16Test_dump.output\", ios::trunc);\n i1->set_value(21);\n i1->dump(ofs);\n ofs.close();\n ifstream ifs(\"UInt16Test_dump.output\");\n while(!ifs.eof())\n ifs >> a;\n ifs.close();\n CPPUNIT_ASSERT(!strcmp(a, \"21\"));\n }\n\n void print_test()\n {\n FILE *fp;\n CPPUNIT_ASSERT(fp = fopen(\"UInt16Test.output\", \"w\"));\n i1->set_value(22);\n i1->print_val(fp, \" \", true);\n fclose(fp);\n ifstream ifs(\"UInt16Test.output\");\n while(!ifs.eof())\n ifs >> a;\n ifs.close();\n CPPUNIT_ASSERT(!strcmp(a, \"22;\"));\n }\n\n void check_types()\n {\n Byte *b1 = new Byte(\"b\");\n b1->set_value(14);\n i1->set_value(14);\n\/\/ CPPUNIT_ASSERT(b1 == i1);\n delete b1;\n }\n\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION(UInt16Test);\n\n} \/\/ namespace libdap\n\nint main(int argc, char *argv[])\n{\n GetOpt getopt(argc, argv, \"dh\");\n int option_char;\n\n while ((option_char = getopt()) != -1)\n switch (option_char) {\n case 'd':\n debug = 1; \/\/ debug is a static global\n break;\n\n case 'h': { \/\/ help - show test names\n cerr << \"Usage: UInt16Test has the following tests:\" << endl;\n const std::vector &tests = libdap::UInt16Test::suite()->getTests();\n unsigned int prefix_len = libdap::UInt16Test::suite()->getName().append(\"::\").length();\n for (std::vector::const_iterator i = tests.begin(), e = tests.end(); i != e; ++i) {\n cerr << (*i)->getName().replace(0, prefix_len, \"\") << endl;\n }\n return 1;\n break;\n }\n\n default:\n break;\n }\n\n CppUnit::TextTestRunner runner;\n runner.addTest(CppUnit::TestFactoryRegistry::getRegistry().makeTest());\n\n bool wasSuccessful = true;\n string test = \"\";\n int i = getopt.optind;\n if (i == argc) {\n \/\/ run them all\n wasSuccessful = runner.run(\"\");\n }\n else {\n for (; i < argc; ++i) {\n if (debug) cerr << \"Running \" << argv[i] << endl;\n test = libdap::UInt16Test::suite()->getName().append(\"::\").append(argv[i]);\n wasSuccessful = wasSuccessful && runner.run(test);\n }\n }\n\n return wasSuccessful ? 0 : 1;\n}\n\n<|endoftext|>"} {"text":"\/\/ For conditions of distribution and use, see copyright notice in LICENSE\n\n#include \"StableHeaders.h\"\n#define MATH_BULLET_INTEROP\n#include \"DebugOperatorNew.h\"\n\n#include \"PhysicsWorld.h\"\n#include \"EC_PhysicsConstraint.h\"\n#include \"EC_RigidBody.h\"\n\n#include \"FrameAPI.h\"\n#include \"Scene.h\"\n#include \"Entity.h\"\n#include \"Math\/MathFunc.h\"\n#include \"EC_Placeable.h\"\n\n#include \"BulletDynamics\/ConstraintSolver\/btTypedConstraint.h\"\n#include \"BulletDynamics\/ConstraintSolver\/btHingeConstraint.h\"\n#include \"BulletDynamics\/ConstraintSolver\/btPoint2PointConstraint.h\"\n#include \"BulletDynamics\/ConstraintSolver\/btSliderConstraint.h\"\n#include \"BulletDynamics\/ConstraintSolver\/btConeTwistConstraint.h\"\n#include \"BulletDynamics\/Dynamics\/btDiscreteDynamicsWorld.h\"\n\n#include \"AttributeMetadata.h\"\n\nusing namespace Physics;\n\nQuat FromEulerDegToQuat(float3 degEuler)\n{\n float3 radEuler = DegToRad(degEuler);\n return Quat::FromEulerXYZ(radEuler.x, radEuler.y, radEuler.z);\n}\n\nEC_PhysicsConstraint::EC_PhysicsConstraint(Scene* scene):\n IComponent(scene),\n constraint_(0),\n checkForRigidBodies(false),\n INIT_ATTRIBUTE_VALUE(enabled, \"Enabled\", false),\n INIT_ATTRIBUTE_VALUE(disableCollision, \"Disable collision\", false),\n INIT_ATTRIBUTE_VALUE(type, \"Constraint type\", 0),\n INIT_ATTRIBUTE_VALUE(otherEntity, \"Other entity\", EntityReference()),\n INIT_ATTRIBUTE_VALUE(position, \"Position\", float3::zero),\n INIT_ATTRIBUTE_VALUE(otherPosition, \"Other position\", float3::zero),\n INIT_ATTRIBUTE_VALUE(rotation, \"Rotation\", float3::zero),\n INIT_ATTRIBUTE_VALUE(otherRotation, \"Other rotation\", float3::zero), \n INIT_ATTRIBUTE_VALUE(linearLimit, \"Linear limit\", float2::zero),\n INIT_ATTRIBUTE_VALUE(angularLimit, \"Angular limit\", float2::zero)\n{\n static AttributeMetadata constraintTypeMetadata;\n static bool metadataInitialized = false;\n if(!metadataInitialized)\n {\n constraintTypeMetadata.enums[Hinge] = \"Hinge\";\n constraintTypeMetadata.enums[PointToPoint] = \"Point to point\";\n constraintTypeMetadata.enums[Slider] = \"Slider\";\n constraintTypeMetadata.enums[ConeTwist] = \"Cone twist\";\n metadataInitialized = true;\n }\n type.SetMetadata(&constraintTypeMetadata);\n\n connect(this, SIGNAL(ParentEntitySet()), this, SLOT(UpdateSignals()), Qt::UniqueConnection);\n}\n\nEC_PhysicsConstraint::~EC_PhysicsConstraint()\n{\n Remove();\n}\n\nvoid EC_PhysicsConstraint::UpdateSignals()\n{\n Entity *parentEntity = ParentEntity();\n if (!parentEntity)\n return;\n\n Scene* scene = parentEntity->ParentScene();\n physicsWorld_ = scene->GetWorld();\n\n connect(GetFramework()->Frame(), SIGNAL(Updated(float)), SLOT(CheckForBulletRigidBody()), Qt::UniqueConnection);\n connect(parentEntity, SIGNAL(ComponentAdded(IComponent*, AttributeChange::Type)), SLOT(OnComponentAdded(IComponent*)), Qt::UniqueConnection);\n connect(parentEntity, SIGNAL(ComponentRemoved(IComponent*, AttributeChange::Type)), SLOT(OnComponentRemoved(IComponent*)), Qt::UniqueConnection);\n}\n\nvoid EC_PhysicsConstraint::OnComponentAdded(IComponent *component)\n{\n if (component->TypeId() == EC_RigidBody::TypeIdStatic())\n Create();\n}\n\nvoid EC_PhysicsConstraint::OnComponentRemoved(IComponent *component)\n{\n if (component->TypeId() == EC_RigidBody::TypeIdStatic())\n Remove();\n}\n\nvoid EC_PhysicsConstraint::CheckForBulletRigidBody()\n{\n if (!checkForRigidBodies)\n return;\n\n EC_RigidBody *rigidBody = rigidBody_.lock().get();\n EC_RigidBody *otherRigidBody = otherRigidBody_.lock().get();\n bool rigidBodyCreated = rigidBody && rigidBody->GetRigidBody();\n bool otherBodyCreated = otherRigidBody && otherRigidBody->GetRigidBody();\n\n if (rigidBodyCreated || otherBodyCreated)\n {\n Create();\n if (constraint_)\n checkForRigidBodies = false;\n }\n}\n\nvoid EC_PhysicsConstraint::AttributesChanged()\n{\n bool recreate = false;\n bool applyAttributes = false;\n bool applyLimits = false;\n\n if (enabled.ValueChanged())\n {\n if (constraint_)\n constraint_->setEnabled(getenabled());\n else\n recreate = true;\n }\n\n if (disableCollision.ValueChanged())\n recreate = true;\n if (type.ValueChanged())\n recreate = true;\n if (otherEntity.ValueChanged())\n recreate = true;\n if (position.ValueChanged())\n applyAttributes = true;\n if (otherPosition.ValueChanged())\n applyAttributes = true;\n if (rotation.ValueChanged())\n applyAttributes = true;\n if (otherRotation.ValueChanged())\n applyAttributes = true;\n if (linearLimit.ValueChanged())\n applyLimits = true;\n if (angularLimit.ValueChanged())\n applyLimits = true;\n\n if (recreate)\n Create();\n if (!recreate && applyAttributes)\n ApplyAttributes();\n if (!recreate && applyLimits)\n ApplyLimits();\n}\n\nvoid EC_PhysicsConstraint::Create()\n{\n if (!ParentEntity() || physicsWorld_.expired())\n return;\n\n Remove();\n\n rigidBody_ = ParentEntity()->GetComponent();\n\n Entity *otherEntity = 0;\n if (!getotherEntity().IsEmpty())\n {\n otherEntity = getotherEntity().Lookup(ParentScene()).get();\n if (otherEntity)\n {\n otherRigidBody_ = otherEntity->GetComponent();\n connect(otherEntity, SIGNAL(EntityRemoved(Entity*, AttributeChange::Type)), SLOT(Remove()), Qt::UniqueConnection);\n connect(otherEntity, SIGNAL(ComponentAdded(IComponent*, AttributeChange::Type)), SLOT(OnComponentAdded(IComponent*)), Qt::UniqueConnection);\n connect(otherEntity, SIGNAL(ComponentRemoved(IComponent*, AttributeChange::Type)), SLOT(OnComponentRemoved(IComponent*)), Qt::UniqueConnection);\n }\n else\n otherRigidBody_.reset();\n }\n else\n otherRigidBody_.reset();\n\n EC_RigidBody *rigidBodyComp = rigidBody_.lock().get();\n EC_RigidBody *otherRigidBodyComp = otherRigidBody_.lock().get();\n btRigidBody *ownBody = rigidBodyComp ? rigidBodyComp->GetRigidBody() : 0;\n btRigidBody *otherBody = otherRigidBodyComp ? otherRigidBodyComp->GetRigidBody() : 0;\n\n if (!ownBody && !rigidBodyComp)\n return;\n\n else if (!ownBody && rigidBodyComp)\n {\n checkForRigidBodies = true;\n return;\n }\n\n if (!otherBody && !otherRigidBodyComp)\n otherBody = &btTypedConstraint::getFixedBody();\n else if (!otherBody && otherRigidBodyComp)\n {\n checkForRigidBodies = true;\n return;\n }\n\n float3 worldScale(1,1,1);\n float3 otherWorldScale(1,1,1);\n \n EC_Placeable *placeable = ParentEntity()->GetComponent().get();\n EC_Placeable *otherPlaceable = 0;\n if (otherEntity)\n otherPlaceable = otherEntity->GetComponent().get();\n \n if (placeable)\n worldScale = placeable->WorldScale();\n if (otherPlaceable)\n otherWorldScale = otherPlaceable->WorldScale();\n\n btTransform ownTransform(FromEulerDegToQuat(getrotation()), getposition().Mul(worldScale));\n btTransform otherTransform(FromEulerDegToQuat(getotherRotation()), getotherPosition().Mul(otherWorldScale));\n\n switch(gettype())\n {\n case PointToPoint:\n constraint_ = new btPoint2PointConstraint(*ownBody, *otherBody, getposition().Mul(worldScale), getotherPosition().Mul(otherWorldScale));\n break;\n\n case Hinge:\n constraint_ = new btHingeConstraint(*ownBody, *otherBody, ownTransform, otherTransform);\n break;\n\n case Slider:\n constraint_ = new btSliderConstraint(*ownBody, *otherBody, ownTransform, otherTransform, false);\n break;\n\n case ConeTwist:\n constraint_ = new btConeTwistConstraint(*ownBody, *otherBody, ownTransform, otherTransform);\n break;\n\n default:\n break;\n }\n\n if (constraint_)\n {\n constraint_->setUserConstraintPtr(this);\n constraint_->setEnabled(getenabled());\n ApplyLimits();\n\n PhysicsWorld *world = physicsWorld_.lock().get();\n world->BulletWorld()->addConstraint(constraint_, getdisableCollision());\n world->BulletWorld()->debugDrawConstraint(constraint_);\n }\n}\n\nvoid EC_PhysicsConstraint::Remove()\n{\n if (constraint_)\n {\n EC_RigidBody *ownRigidComp = rigidBody_.lock().get();\n EC_RigidBody *otherRigidComp = otherRigidBody_.lock().get();\n if (otherRigidComp && otherRigidComp->GetRigidBody())\n otherRigidComp->GetRigidBody()->removeConstraintRef(constraint_);\n if (ownRigidComp && ownRigidComp->GetRigidBody())\n ownRigidComp->GetRigidBody()->removeConstraintRef(constraint_);\n\n PhysicsWorld *world = physicsWorld_.lock().get();\n if (world && world->BulletWorld())\n world->BulletWorld()->removeConstraint(constraint_);\n\n rigidBody_.reset();\n otherRigidBody_.reset();\n delete constraint_;\n constraint_ = 0;\n }\n}\n\nvoid EC_PhysicsConstraint::ApplyAttributes()\n{\n if (!constraint_)\n return;\n\n float3 worldScale(1,1,1);\n float3 otherWorldScale(1,1,1);\n\n EC_Placeable *placeable = ParentEntity()->GetComponent().get();\n Entity *entity = getotherEntity().Lookup(ParentScene()).get();\n EC_Placeable *otherPlaceable = 0;\n if (entity)\n otherPlaceable = entity->GetComponent().get();\n\n if (placeable)\n worldScale = placeable->WorldScale();\n if (otherPlaceable)\n otherWorldScale = otherPlaceable->WorldScale();\n\n btTransform ownTransform(FromEulerDegToQuat(getrotation()), getposition().Mul(worldScale));\n btTransform otherTransform(FromEulerDegToQuat(getotherRotation()), getotherPosition().Mul(otherWorldScale));\n\n switch (constraint_->getConstraintType())\n {\n case POINT2POINT_CONSTRAINT_TYPE:\n {\n btPoint2PointConstraint* pointConstraint = static_cast(constraint_);\n pointConstraint->setPivotA(getposition().Mul(worldScale));\n pointConstraint->setPivotB(getotherPosition().Mul(otherWorldScale));\n }\n break;\n \n case HINGE_CONSTRAINT_TYPE:\n {\n btHingeConstraint* hingeConstraint = static_cast(constraint_);\n hingeConstraint->setFrames(ownTransform, otherTransform);\n }\n break;\n \n case SLIDER_CONSTRAINT_TYPE:\n {\n btSliderConstraint* sliderConstraint = static_cast(constraint_);\n sliderConstraint->setFrames(ownTransform, otherTransform);\n }\n break;\n \n case CONETWIST_CONSTRAINT_TYPE:\n {\n btConeTwistConstraint* coneTwistConstraint = static_cast(constraint_);\n coneTwistConstraint->setFrames(ownTransform, otherTransform);\n }\n break;\n\n default:\n break;\n }\n}\n\nvoid EC_PhysicsConstraint::ApplyLimits()\n{\n if (!constraint_)\n return;\n\n switch (constraint_->getConstraintType())\n {\n case HINGE_CONSTRAINT_TYPE:\n {\n btHingeConstraint* hingeConstraint = static_cast(constraint_);\n hingeConstraint->setLimit(DegToRad(getangularLimit().x), DegToRad(getangularLimit().y));\n }\n break;\n \n case SLIDER_CONSTRAINT_TYPE:\n {\n btSliderConstraint* sliderConstraint = static_cast(constraint_);\n \n sliderConstraint->setLowerLinLimit(getlinearLimit().x);\n sliderConstraint->setUpperLinLimit(getlinearLimit().y);\n\n sliderConstraint->setLowerAngLimit(DegToRad(getangularLimit().x));\n sliderConstraint->setUpperAngLimit(DegToRad(getangularLimit().y));\n }\n break;\n \n case CONETWIST_CONSTRAINT_TYPE:\n {\n btConeTwistConstraint* coneTwistConstraint = static_cast(constraint_);\n coneTwistConstraint->setLimit(DegToRad(getangularLimit().y), DegToRad(getangularLimit().y), DegToRad(getlinearLimit().y));\n }\n break;\n \n default:\n break;\n }\n}Marked todo's for EC_PhysicsConstraint.\/\/ For conditions of distribution and use, see copyright notice in LICENSE\n\n#include \"StableHeaders.h\"\n#define MATH_BULLET_INTEROP\n#include \"DebugOperatorNew.h\"\n\n#include \"PhysicsWorld.h\"\n#include \"EC_PhysicsConstraint.h\"\n#include \"EC_RigidBody.h\"\n\n#include \"FrameAPI.h\"\n#include \"Scene.h\"\n#include \"Entity.h\"\n#include \"Math\/MathFunc.h\"\n#include \"EC_Placeable.h\"\n\n#include \"BulletDynamics\/ConstraintSolver\/btTypedConstraint.h\"\n#include \"BulletDynamics\/ConstraintSolver\/btHingeConstraint.h\"\n#include \"BulletDynamics\/ConstraintSolver\/btPoint2PointConstraint.h\"\n#include \"BulletDynamics\/ConstraintSolver\/btSliderConstraint.h\"\n#include \"BulletDynamics\/ConstraintSolver\/btConeTwistConstraint.h\"\n#include \"BulletDynamics\/Dynamics\/btDiscreteDynamicsWorld.h\"\n\n#include \"AttributeMetadata.h\"\n\nusing namespace Physics;\n\nQuat FromEulerDegToQuat(float3 degEuler)\n{\n float3 radEuler = DegToRad(degEuler);\n return Quat::FromEulerXYZ(radEuler.x, radEuler.y, radEuler.z);\n}\n\nEC_PhysicsConstraint::EC_PhysicsConstraint(Scene* scene):\n IComponent(scene),\n constraint_(0),\n checkForRigidBodies(false),\n INIT_ATTRIBUTE_VALUE(enabled, \"Enabled\", false),\n INIT_ATTRIBUTE_VALUE(disableCollision, \"Disable collision\", false),\n INIT_ATTRIBUTE_VALUE(type, \"Constraint type\", 0),\n INIT_ATTRIBUTE_VALUE(otherEntity, \"Other entity\", EntityReference()),\n INIT_ATTRIBUTE_VALUE(position, \"Position\", float3::zero),\n INIT_ATTRIBUTE_VALUE(otherPosition, \"Other position\", float3::zero),\n INIT_ATTRIBUTE_VALUE(rotation, \"Rotation\", float3::zero),\n INIT_ATTRIBUTE_VALUE(otherRotation, \"Other rotation\", float3::zero), \n INIT_ATTRIBUTE_VALUE(linearLimit, \"Linear limit\", float2::zero),\n INIT_ATTRIBUTE_VALUE(angularLimit, \"Angular limit\", float2::zero)\n{\n static AttributeMetadata constraintTypeMetadata;\n static bool metadataInitialized = false;\n if(!metadataInitialized)\n {\n constraintTypeMetadata.enums[Hinge] = \"Hinge\";\n constraintTypeMetadata.enums[PointToPoint] = \"Point to point\";\n constraintTypeMetadata.enums[Slider] = \"Slider\";\n constraintTypeMetadata.enums[ConeTwist] = \"Cone twist\";\n metadataInitialized = true;\n }\n type.SetMetadata(&constraintTypeMetadata);\n\n connect(this, SIGNAL(ParentEntitySet()), this, SLOT(UpdateSignals()), Qt::UniqueConnection);\n}\n\nEC_PhysicsConstraint::~EC_PhysicsConstraint()\n{\n Remove();\n}\n\nvoid EC_PhysicsConstraint::UpdateSignals()\n{\n Entity *parentEntity = ParentEntity();\n if (!parentEntity)\n return;\n\n Scene* scene = parentEntity->ParentScene();\n physicsWorld_ = scene->GetWorld();\n\n connect(GetFramework()->Frame(), SIGNAL(Updated(float)), SLOT(CheckForBulletRigidBody()), Qt::UniqueConnection);\n connect(parentEntity, SIGNAL(ComponentAdded(IComponent*, AttributeChange::Type)), SLOT(OnComponentAdded(IComponent*)), Qt::UniqueConnection);\n connect(parentEntity, SIGNAL(ComponentRemoved(IComponent*, AttributeChange::Type)), SLOT(OnComponentRemoved(IComponent*)), Qt::UniqueConnection);\n}\n\nvoid EC_PhysicsConstraint::OnComponentAdded(IComponent *component)\n{\n if (component->TypeId() == EC_RigidBody::TypeIdStatic())\n Create();\n}\n\nvoid EC_PhysicsConstraint::OnComponentRemoved(IComponent *component)\n{\n if (component->TypeId() == EC_RigidBody::TypeIdStatic())\n Remove();\n}\n\nvoid EC_PhysicsConstraint::CheckForBulletRigidBody()\n{\n if (!checkForRigidBodies)\n return;\n\n EC_RigidBody *rigidBody = rigidBody_.lock().get();\n EC_RigidBody *otherRigidBody = otherRigidBody_.lock().get();\n bool rigidBodyCreated = rigidBody && rigidBody->GetRigidBody();\n bool otherBodyCreated = otherRigidBody && otherRigidBody->GetRigidBody();\n\n if (rigidBodyCreated || otherBodyCreated)\n {\n Create();\n if (constraint_)\n checkForRigidBodies = false;\n }\n}\n\nvoid EC_PhysicsConstraint::AttributesChanged()\n{\n bool recreate = false;\n bool applyAttributes = false;\n bool applyLimits = false;\n\n if (enabled.ValueChanged())\n {\n if (constraint_)\n constraint_->setEnabled(getenabled());\n else\n recreate = true;\n }\n\n if (disableCollision.ValueChanged())\n recreate = true;\n if (type.ValueChanged())\n recreate = true;\n if (otherEntity.ValueChanged())\n recreate = true;\n if (position.ValueChanged())\n applyAttributes = true;\n if (otherPosition.ValueChanged())\n applyAttributes = true;\n if (rotation.ValueChanged())\n applyAttributes = true;\n if (otherRotation.ValueChanged())\n applyAttributes = true;\n if (linearLimit.ValueChanged())\n applyLimits = true;\n if (angularLimit.ValueChanged())\n applyLimits = true;\n\n if (recreate)\n Create();\n if (!recreate && applyAttributes)\n ApplyAttributes();\n if (!recreate && applyLimits)\n ApplyLimits();\n}\n\nvoid EC_PhysicsConstraint::Create()\n{\n if (!ParentEntity() || physicsWorld_.expired())\n return;\n\n Remove();\n\n rigidBody_ = ParentEntity()->GetComponent();\n\n \/\/\/ \\todo If the other entity is not yet loaded, the constraint will be mistakenly created as a static one\n \/\/\/ \\todo Add warning logging if the other entity is not found, or for other error situations\n Entity *otherEntity = 0;\n if (!getotherEntity().IsEmpty())\n {\n otherEntity = getotherEntity().Lookup(ParentScene()).get();\n if (otherEntity)\n {\n otherRigidBody_ = otherEntity->GetComponent();\n \/\/\/ \\todo Disconnect these signals at constraint removal time, in case the other entity ID is changed at runtime\n connect(otherEntity, SIGNAL(EntityRemoved(Entity*, AttributeChange::Type)), SLOT(Remove()), Qt::UniqueConnection);\n connect(otherEntity, SIGNAL(ComponentAdded(IComponent*, AttributeChange::Type)), SLOT(OnComponentAdded(IComponent*)), Qt::UniqueConnection);\n connect(otherEntity, SIGNAL(ComponentRemoved(IComponent*, AttributeChange::Type)), SLOT(OnComponentRemoved(IComponent*)), Qt::UniqueConnection);\n }\n else\n otherRigidBody_.reset();\n }\n else\n otherRigidBody_.reset();\n\n EC_RigidBody *rigidBodyComp = rigidBody_.lock().get();\n EC_RigidBody *otherRigidBodyComp = otherRigidBody_.lock().get();\n btRigidBody *ownBody = rigidBodyComp ? rigidBodyComp->GetRigidBody() : 0;\n btRigidBody *otherBody = otherRigidBodyComp ? otherRigidBodyComp->GetRigidBody() : 0;\n\n if (!ownBody && !rigidBodyComp)\n return;\n\n else if (!ownBody && rigidBodyComp)\n {\n checkForRigidBodies = true;\n return;\n }\n\n if (!otherBody && !otherRigidBodyComp)\n otherBody = &btTypedConstraint::getFixedBody();\n else if (!otherBody && otherRigidBodyComp)\n {\n checkForRigidBodies = true;\n return;\n }\n\n float3 worldScale(1,1,1);\n float3 otherWorldScale(1,1,1);\n \n EC_Placeable *placeable = ParentEntity()->GetComponent().get();\n EC_Placeable *otherPlaceable = 0;\n if (otherEntity)\n otherPlaceable = otherEntity->GetComponent().get();\n \n if (placeable)\n worldScale = placeable->WorldScale();\n if (otherPlaceable)\n otherWorldScale = otherPlaceable->WorldScale();\n\n btTransform ownTransform(FromEulerDegToQuat(getrotation()), getposition().Mul(worldScale));\n btTransform otherTransform(FromEulerDegToQuat(getotherRotation()), getotherPosition().Mul(otherWorldScale));\n\n switch(gettype())\n {\n case PointToPoint:\n constraint_ = new btPoint2PointConstraint(*ownBody, *otherBody, getposition().Mul(worldScale), getotherPosition().Mul(otherWorldScale));\n break;\n\n case Hinge:\n constraint_ = new btHingeConstraint(*ownBody, *otherBody, ownTransform, otherTransform);\n break;\n\n case Slider:\n constraint_ = new btSliderConstraint(*ownBody, *otherBody, ownTransform, otherTransform, false);\n break;\n\n case ConeTwist:\n constraint_ = new btConeTwistConstraint(*ownBody, *otherBody, ownTransform, otherTransform);\n break;\n\n default:\n break;\n }\n\n if (constraint_)\n {\n constraint_->setUserConstraintPtr(this);\n constraint_->setEnabled(getenabled());\n ApplyLimits();\n\n PhysicsWorld *world = physicsWorld_.lock().get();\n world->BulletWorld()->addConstraint(constraint_, getdisableCollision());\n world->BulletWorld()->debugDrawConstraint(constraint_);\n }\n}\n\nvoid EC_PhysicsConstraint::Remove()\n{\n if (constraint_)\n {\n EC_RigidBody *ownRigidComp = rigidBody_.lock().get();\n EC_RigidBody *otherRigidComp = otherRigidBody_.lock().get();\n if (otherRigidComp && otherRigidComp->GetRigidBody())\n otherRigidComp->GetRigidBody()->removeConstraintRef(constraint_);\n if (ownRigidComp && ownRigidComp->GetRigidBody())\n ownRigidComp->GetRigidBody()->removeConstraintRef(constraint_);\n\n PhysicsWorld *world = physicsWorld_.lock().get();\n if (world && world->BulletWorld())\n world->BulletWorld()->removeConstraint(constraint_);\n\n rigidBody_.reset();\n otherRigidBody_.reset();\n delete constraint_;\n constraint_ = 0;\n }\n}\n\nvoid EC_PhysicsConstraint::ApplyAttributes()\n{\n if (!constraint_)\n return;\n\n float3 worldScale(1,1,1);\n float3 otherWorldScale(1,1,1);\n\n EC_Placeable *placeable = ParentEntity()->GetComponent().get();\n Entity *entity = getotherEntity().Lookup(ParentScene()).get();\n EC_Placeable *otherPlaceable = 0;\n if (entity)\n otherPlaceable = entity->GetComponent().get();\n\n if (placeable)\n worldScale = placeable->WorldScale();\n if (otherPlaceable)\n otherWorldScale = otherPlaceable->WorldScale();\n\n btTransform ownTransform(FromEulerDegToQuat(getrotation()), getposition().Mul(worldScale));\n btTransform otherTransform(FromEulerDegToQuat(getotherRotation()), getotherPosition().Mul(otherWorldScale));\n\n switch (constraint_->getConstraintType())\n {\n case POINT2POINT_CONSTRAINT_TYPE:\n {\n btPoint2PointConstraint* pointConstraint = static_cast(constraint_);\n pointConstraint->setPivotA(getposition().Mul(worldScale));\n pointConstraint->setPivotB(getotherPosition().Mul(otherWorldScale));\n }\n break;\n \n case HINGE_CONSTRAINT_TYPE:\n {\n btHingeConstraint* hingeConstraint = static_cast(constraint_);\n hingeConstraint->setFrames(ownTransform, otherTransform);\n }\n break;\n \n case SLIDER_CONSTRAINT_TYPE:\n {\n btSliderConstraint* sliderConstraint = static_cast(constraint_);\n sliderConstraint->setFrames(ownTransform, otherTransform);\n }\n break;\n \n case CONETWIST_CONSTRAINT_TYPE:\n {\n btConeTwistConstraint* coneTwistConstraint = static_cast(constraint_);\n coneTwistConstraint->setFrames(ownTransform, otherTransform);\n }\n break;\n\n default:\n break;\n }\n}\n\nvoid EC_PhysicsConstraint::ApplyLimits()\n{\n if (!constraint_)\n return;\n\n switch (constraint_->getConstraintType())\n {\n case HINGE_CONSTRAINT_TYPE:\n {\n btHingeConstraint* hingeConstraint = static_cast(constraint_);\n hingeConstraint->setLimit(DegToRad(getangularLimit().x), DegToRad(getangularLimit().y));\n }\n break;\n \n case SLIDER_CONSTRAINT_TYPE:\n {\n btSliderConstraint* sliderConstraint = static_cast(constraint_);\n \n sliderConstraint->setLowerLinLimit(getlinearLimit().x);\n sliderConstraint->setUpperLinLimit(getlinearLimit().y);\n\n sliderConstraint->setLowerAngLimit(DegToRad(getangularLimit().x));\n sliderConstraint->setUpperAngLimit(DegToRad(getangularLimit().y));\n }\n break;\n \n case CONETWIST_CONSTRAINT_TYPE:\n {\n btConeTwistConstraint* coneTwistConstraint = static_cast(constraint_);\n coneTwistConstraint->setLimit(DegToRad(getangularLimit().y), DegToRad(getangularLimit().y), DegToRad(getlinearLimit().y));\n }\n break;\n \n default:\n break;\n }\n}<|endoftext|>"} {"text":"\/*\n * Copyright 2011, 2012 Esrille Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n\n#include \"WindowImp.h\"\n#include \"Test.util.h\"\n#include \"http\/HTTPConnection.h\"\n\nusing namespace org::w3c::dom::bootstrap;\nusing namespace org::w3c::dom;\n\nextern html::Window window;\n\nvoid reshape(int w, int h)\n{\n glViewport(0, 0, w, h);\n\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n glOrtho(0, w, h, 0, -1000.0, 1.0);\n\n glMatrixMode(GL_TEXTURE);\n glLoadIdentity();\n\n glMatrixMode(GL_MODELVIEW);\n glLoadIdentity();\n\n if (WindowImp* imp = static_cast(window.self()))\n imp->setSize(w, h);\n}\n\nvoid display()\n{\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);\n if (WindowImp* imp = static_cast(window.self()))\n imp->render();\n glutSwapBuffers(); \/\/ This would block until the sync happens\n}\n\nunsigned getCharKeyCode(int key)\n{\n \/\/ US Qwerty\n static unsigned map[] = {\n 0, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 12, 13, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 27, 0, 0, 0, 0,\n 32, 49 \/* ! *\/, 222 \/* \" *\/, 51 \/* # *\/, 52 \/* $ *\/, 53 \/* % *\/, 55 \/* & *\/, 222 \/* ' *\/,\n 57 \/* ( *\/, 48 \/* ) *\/, 56 \/* * *\/, 187 \/* + *\/, 188 \/* , *\/, 189 \/* - *\/, 190 \/* . *\/, 191 \/* \/ *\/,\n 48 \/* 0 *\/, 49 \/* 1 *\/, 50 \/* 2 *\/, 51 \/* 3 *\/, 52 \/* 4 *\/, 53 \/* 5 *\/, 54 \/* 6 *\/, 55 \/* 7 *\/,\n 56 \/* 8 *\/, 57 \/* 9 *\/, 186 \/* : *\/, 186 \/* ; *\/, 188 \/* < *\/, 187 \/* = *\/, 190 \/* > *\/, 191 \/* ? *\/,\n 50 \/* @ *\/, 65 \/* A *\/, 66 \/* B *\/, 67 \/* C *\/, 68 \/* D *\/, 69 \/* E *\/, 70 \/* F *\/, 71 \/* G *\/,\n 72 \/* H *\/, 73 \/* I *\/, 74 \/* J *\/, 75 \/* K *\/, 76 \/* L *\/, 77 \/* M *\/, 78 \/* N *\/, 79 \/* O *\/,\n 80 \/* P *\/, 81 \/* Q *\/, 82 \/* R *\/, 83 \/* S *\/, 84 \/* T *\/, 85 \/* U *\/, 86 \/* V *\/, 87 \/* W *\/,\n 88 \/* X *\/, 89 \/* Y *\/, 90 \/* Z *\/, 219 \/* [ *\/, 220 \/* \\ *\/, 221 \/* ] *\/, 54 \/* ^ *\/, 189 \/* _ *\/,\n 192 \/* ` *\/, 65 \/* a *\/, 66 \/* b *\/, 67 \/* c *\/, 68 \/* d *\/, 69 \/* e *\/, 70 \/* f *\/, 71 \/* g *\/,\n 72 \/* h *\/, 73 \/* i *\/, 74 \/* j *\/, 75 \/* k *\/, 76 \/* l *\/, 77 \/* m *\/, 78 \/* n *\/, 79 \/* o *\/,\n 80 \/* p *\/, 81 \/* q *\/, 82 \/* r *\/, 83 \/* s *\/, 84 \/* t *\/, 85 \/* u *\/, 86 \/* v *\/, 87 \/* w *\/,\n 88 \/* x *\/, 89 \/* y *\/, 90 \/* z *\/, 219 \/* { *\/, 220 \/* | *\/, 221 \/* } *\/, 192 \/* ~ *\/, 46 \/* DEL *\/\n };\n static_assert(sizeof map \/sizeof map[0] == 128, \"invalid map\");\n return (0 <= key && key <= 127) ? map[key] : 0;\n}\n\nvoid keyboard(unsigned char key, int x, int y)\n{\n if (WindowImp* imp = static_cast(window.self()))\n imp->keydown(isprint(key) ? key : 0, getCharKeyCode(key), glutGetModifiers());\n}\n\nvoid keyboardUp(unsigned char key, int x, int y)\n{\n if (WindowImp* imp = static_cast(window.self()))\n imp->keyup(isprint(key) ? key : 0, getCharKeyCode(key), glutGetModifiers());\n}\n\nunsigned getSpecialKeyCode(int key)\n{\n switch (key) {\n case GLUT_KEY_F1:\n return 112;\n case GLUT_KEY_F2:\n return 113;\n case GLUT_KEY_F3:\n return 114;\n case GLUT_KEY_F4:\n return 115;\n case GLUT_KEY_F5:\n return 116;\n case GLUT_KEY_F6:\n return 117;\n case GLUT_KEY_F7:\n return 118;\n case GLUT_KEY_F8:\n return 119;\n case GLUT_KEY_F9:\n return 120;\n case GLUT_KEY_F10:\n return 121;\n case GLUT_KEY_F11:\n return 122;\n case GLUT_KEY_F12:\n return 123;\n case GLUT_KEY_LEFT:\n return 37;\n case GLUT_KEY_UP:\n return 38;\n case GLUT_KEY_RIGHT:\n return 39;\n case GLUT_KEY_DOWN:\n return 40;\n case GLUT_KEY_PAGE_UP:\n return 33;\n case GLUT_KEY_PAGE_DOWN:\n return 34;\n case GLUT_KEY_HOME:\n return 36;\n case GLUT_KEY_END:\n return 35;\n case GLUT_KEY_INSERT:\n return 45;\n case 109: \/\/ Num Lock\n return 144;\n default:\n return 0;\n }\n}\n\nvoid special(int key, int x, int y)\n{\n unsigned keycode = getSpecialKeyCode(key);\n if (keycode) {\n if (WindowImp* imp = static_cast(window.self()))\n imp->keydown(0, keycode, glutGetModifiers());\n }\n}\n\nvoid specialUp(int key, int x, int y)\n{\n unsigned keycode = getSpecialKeyCode(key);\n if (keycode) {\n if (WindowImp* imp = static_cast(window.self()))\n imp->keyup(0, keycode, glutGetModifiers());\n }\n}\n\nvoid mouse(int button, int state, int x, int y)\n{\n if (WindowImp* imp = static_cast(window.self()))\n imp->mouse(button, state, x, y, glutGetModifiers());\n}\n\nvoid mouseMove(int x, int y)\n{\n if (WindowImp* imp = static_cast(window.self()))\n imp->mouseMove(x, y, glutGetModifiers());\n}\n\nvoid timer(int value)\n{\n HttpConnectionManager::getInstance().poll(); \/\/ TODO: This line should not be necessary.\n if (WindowImp* imp = static_cast(window.self())) {\n if (imp->poll())\n glutPostRedisplay();\n }\n glutTimerFunc(50, timer, 0);\n \/\/ TODO: do GC here or maybe in the idle proc\n}\n\nvoid init(int* argc, char* argv[])\n{\n glutInit(argc, argv);\n glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH | GLUT_STENCIL);\n glutInitWindowSize(816, 1056);\n glutCreateWindow(argv[0]);\n glutReshapeFunc(reshape);\n glutDisplayFunc(display);\n glClearColor(1.0, 1.0, 1.0, 1.0);\n glEnable(GL_TEXTURE_2D);\n glDepthFunc(GL_LEQUAL);\n glDisable(GL_CULL_FACE);\n glDisable(GL_DEPTH_TEST);\n glDisable(GL_ALPHA_TEST);\n glEnable(GL_BLEND);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n glPixelStorei(GL_UNPACK_ALIGNMENT, 1);\n glutKeyboardFunc(keyboard);\n glutKeyboardUpFunc(keyboardUp);\n glutSpecialFunc(special);\n glutSpecialUpFunc(specialUp);\n glutMouseFunc(mouse);\n glutMotionFunc(mouseMove);\n glutPassiveMotionFunc(mouseMove);\n glutTimerFunc(50, timer, 0);\n glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_CONTINUE_EXECUTION);\n\n#ifndef NDEBUG\n GLint stencilBits;\n glGetIntegerv(GL_STENCIL_BITS, &stencilBits);\n std::cout << \"GL_STENCIL_BITS: \" << stencilBits << '\\n';\n#endif\n \/\/ TODO: assuming 8 <= stencilBits for now\n glClearStencil(0x00);\n glEnable(GL_STENCIL_TEST);\n}\n(init) : Check GL_STENCIL_BITS.\/*\n * Copyright 2011, 2012 Esrille Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n\n#include \"WindowImp.h\"\n#include \"Test.util.h\"\n#include \"http\/HTTPConnection.h\"\n\nusing namespace org::w3c::dom::bootstrap;\nusing namespace org::w3c::dom;\n\nextern html::Window window;\n\nvoid reshape(int w, int h)\n{\n glViewport(0, 0, w, h);\n\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n glOrtho(0, w, h, 0, -1000.0, 1.0);\n\n glMatrixMode(GL_TEXTURE);\n glLoadIdentity();\n\n glMatrixMode(GL_MODELVIEW);\n glLoadIdentity();\n\n if (WindowImp* imp = static_cast(window.self()))\n imp->setSize(w, h);\n}\n\nvoid display()\n{\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);\n if (WindowImp* imp = static_cast(window.self()))\n imp->render();\n glutSwapBuffers(); \/\/ This would block until the sync happens\n}\n\nunsigned getCharKeyCode(int key)\n{\n \/\/ US Qwerty\n static unsigned map[] = {\n 0, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 12, 13, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 27, 0, 0, 0, 0,\n 32, 49 \/* ! *\/, 222 \/* \" *\/, 51 \/* # *\/, 52 \/* $ *\/, 53 \/* % *\/, 55 \/* & *\/, 222 \/* ' *\/,\n 57 \/* ( *\/, 48 \/* ) *\/, 56 \/* * *\/, 187 \/* + *\/, 188 \/* , *\/, 189 \/* - *\/, 190 \/* . *\/, 191 \/* \/ *\/,\n 48 \/* 0 *\/, 49 \/* 1 *\/, 50 \/* 2 *\/, 51 \/* 3 *\/, 52 \/* 4 *\/, 53 \/* 5 *\/, 54 \/* 6 *\/, 55 \/* 7 *\/,\n 56 \/* 8 *\/, 57 \/* 9 *\/, 186 \/* : *\/, 186 \/* ; *\/, 188 \/* < *\/, 187 \/* = *\/, 190 \/* > *\/, 191 \/* ? *\/,\n 50 \/* @ *\/, 65 \/* A *\/, 66 \/* B *\/, 67 \/* C *\/, 68 \/* D *\/, 69 \/* E *\/, 70 \/* F *\/, 71 \/* G *\/,\n 72 \/* H *\/, 73 \/* I *\/, 74 \/* J *\/, 75 \/* K *\/, 76 \/* L *\/, 77 \/* M *\/, 78 \/* N *\/, 79 \/* O *\/,\n 80 \/* P *\/, 81 \/* Q *\/, 82 \/* R *\/, 83 \/* S *\/, 84 \/* T *\/, 85 \/* U *\/, 86 \/* V *\/, 87 \/* W *\/,\n 88 \/* X *\/, 89 \/* Y *\/, 90 \/* Z *\/, 219 \/* [ *\/, 220 \/* \\ *\/, 221 \/* ] *\/, 54 \/* ^ *\/, 189 \/* _ *\/,\n 192 \/* ` *\/, 65 \/* a *\/, 66 \/* b *\/, 67 \/* c *\/, 68 \/* d *\/, 69 \/* e *\/, 70 \/* f *\/, 71 \/* g *\/,\n 72 \/* h *\/, 73 \/* i *\/, 74 \/* j *\/, 75 \/* k *\/, 76 \/* l *\/, 77 \/* m *\/, 78 \/* n *\/, 79 \/* o *\/,\n 80 \/* p *\/, 81 \/* q *\/, 82 \/* r *\/, 83 \/* s *\/, 84 \/* t *\/, 85 \/* u *\/, 86 \/* v *\/, 87 \/* w *\/,\n 88 \/* x *\/, 89 \/* y *\/, 90 \/* z *\/, 219 \/* { *\/, 220 \/* | *\/, 221 \/* } *\/, 192 \/* ~ *\/, 46 \/* DEL *\/\n };\n static_assert(sizeof map \/sizeof map[0] == 128, \"invalid map\");\n return (0 <= key && key <= 127) ? map[key] : 0;\n}\n\nvoid keyboard(unsigned char key, int x, int y)\n{\n if (WindowImp* imp = static_cast(window.self()))\n imp->keydown(isprint(key) ? key : 0, getCharKeyCode(key), glutGetModifiers());\n}\n\nvoid keyboardUp(unsigned char key, int x, int y)\n{\n if (WindowImp* imp = static_cast(window.self()))\n imp->keyup(isprint(key) ? key : 0, getCharKeyCode(key), glutGetModifiers());\n}\n\nunsigned getSpecialKeyCode(int key)\n{\n switch (key) {\n case GLUT_KEY_F1:\n return 112;\n case GLUT_KEY_F2:\n return 113;\n case GLUT_KEY_F3:\n return 114;\n case GLUT_KEY_F4:\n return 115;\n case GLUT_KEY_F5:\n return 116;\n case GLUT_KEY_F6:\n return 117;\n case GLUT_KEY_F7:\n return 118;\n case GLUT_KEY_F8:\n return 119;\n case GLUT_KEY_F9:\n return 120;\n case GLUT_KEY_F10:\n return 121;\n case GLUT_KEY_F11:\n return 122;\n case GLUT_KEY_F12:\n return 123;\n case GLUT_KEY_LEFT:\n return 37;\n case GLUT_KEY_UP:\n return 38;\n case GLUT_KEY_RIGHT:\n return 39;\n case GLUT_KEY_DOWN:\n return 40;\n case GLUT_KEY_PAGE_UP:\n return 33;\n case GLUT_KEY_PAGE_DOWN:\n return 34;\n case GLUT_KEY_HOME:\n return 36;\n case GLUT_KEY_END:\n return 35;\n case GLUT_KEY_INSERT:\n return 45;\n case 109: \/\/ Num Lock\n return 144;\n default:\n return 0;\n }\n}\n\nvoid special(int key, int x, int y)\n{\n unsigned keycode = getSpecialKeyCode(key);\n if (keycode) {\n if (WindowImp* imp = static_cast(window.self()))\n imp->keydown(0, keycode, glutGetModifiers());\n }\n}\n\nvoid specialUp(int key, int x, int y)\n{\n unsigned keycode = getSpecialKeyCode(key);\n if (keycode) {\n if (WindowImp* imp = static_cast(window.self()))\n imp->keyup(0, keycode, glutGetModifiers());\n }\n}\n\nvoid mouse(int button, int state, int x, int y)\n{\n if (WindowImp* imp = static_cast(window.self()))\n imp->mouse(button, state, x, y, glutGetModifiers());\n}\n\nvoid mouseMove(int x, int y)\n{\n if (WindowImp* imp = static_cast(window.self()))\n imp->mouseMove(x, y, glutGetModifiers());\n}\n\nvoid timer(int value)\n{\n HttpConnectionManager::getInstance().poll(); \/\/ TODO: This line should not be necessary.\n if (WindowImp* imp = static_cast(window.self())) {\n if (imp->poll())\n glutPostRedisplay();\n }\n glutTimerFunc(50, timer, 0);\n \/\/ TODO: do GC here or maybe in the idle proc\n}\n\nvoid init(int* argc, char* argv[])\n{\n glutInit(argc, argv);\n glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH | GLUT_STENCIL);\n glutInitWindowSize(816, 1056);\n glutCreateWindow(argv[0]);\n glutReshapeFunc(reshape);\n glutDisplayFunc(display);\n glClearColor(1.0, 1.0, 1.0, 1.0);\n glEnable(GL_TEXTURE_2D);\n glDepthFunc(GL_LEQUAL);\n glDisable(GL_CULL_FACE);\n glDisable(GL_DEPTH_TEST);\n glDisable(GL_ALPHA_TEST);\n glEnable(GL_BLEND);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n glPixelStorei(GL_UNPACK_ALIGNMENT, 1);\n glutKeyboardFunc(keyboard);\n glutKeyboardUpFunc(keyboardUp);\n glutSpecialFunc(special);\n glutSpecialUpFunc(specialUp);\n glutMouseFunc(mouse);\n glutMotionFunc(mouseMove);\n glutPassiveMotionFunc(mouseMove);\n glutTimerFunc(50, timer, 0);\n glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_CONTINUE_EXECUTION);\n\n GLint stencilBits;\n glGetIntegerv(GL_STENCIL_BITS, &stencilBits);\n if (stencilBits < 8) {\n std::cout << \"error: The number of the OpenGL stencil bits needs to be greater than or equal to 8. Current: \" << stencilBits << \".\\n\";\n exit(EXIT_FAILURE);\n }\n glClearStencil(0x00);\n glEnable(GL_STENCIL_TEST);\n}\n<|endoftext|>"} {"text":"\/\/\/\n\/\/\/ @file nth_prime.cpp\n\/\/\/\n\/\/\/ Copyright (C) 2014 Kim Walisch, \n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include \n#include \n#include \n\nnamespace primecount {\n\n\/\/\/ Calculate the nth prime using a combination of an efficient prime\n\/\/\/ counting function implementation and the sieve of Eratosthenes.\n\/\/\/ Run time: O(x\/(log x)^4) operations, O(x^0.5) space.\n\/\/\/\nint64_t nth_prime(int64_t n, int threads)\n{\n if (n < 1)\n return 0;\n\n int64_t prime_approx = 0;\n int64_t count_approx = 0;\n\n if (n > 100000)\n {\n \/\/ Li_inverse(n) < nth_prime(n) for 7 <= n <= ~ 10^316\n prime_approx = Li_inverse(n);\n count_approx = pi(prime_approx, threads);\n }\n\n primesieve::set_num_threads(threads);\n int64_t prime = primesieve::parallel_nth_prime(n - count_approx, prime_approx);\n\n return prime;\n}\n\n} \/\/ namespace primecount\nPort to primesieve-5.2\/\/\/\n\/\/\/ @file nth_prime.cpp\n\/\/\/\n\/\/\/ Copyright (C) 2014 Kim Walisch, \n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include \n#include \n#include \n\nnamespace primecount {\n\n\/\/\/ Calculate the nth prime using a combination of an efficient prime\n\/\/\/ counting function implementation and the sieve of Eratosthenes.\n\/\/\/ Run time: O(x\/(log x)^4) operations, O(x^0.5) space.\n\/\/\/\nint64_t nth_prime(int64_t n, int threads)\n{\n if (n < 0)\n return 0;\n\n if (n == 0)\n n = 1;\n\n int64_t prime_approx = 0;\n int64_t count_approx = 0;\n\n if (n > 100000)\n {\n \/\/ Li_inverse(n) < nth_prime(n) for 7 <= n <= ~ 10^316\n prime_approx = Li_inverse(n);\n count_approx = pi(prime_approx, threads);\n }\n\n primesieve::set_num_threads(threads);\n int64_t prime = primesieve::parallel_nth_prime(n - count_approx, prime_approx);\n\n return prime;\n}\n\n} \/\/ namespace primecount\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2013, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of Image Engine Design nor the names of any\n\/\/ other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"boost\/python.hpp\"\n\n#include \n\n#include \"maya\/MFnDependencyNode.h\"\n\n#include \"IECore\/SceneInterface.h\"\n\n#include \"IECoreMaya\/bindings\/FnSceneShapeBinding.h\"\n#include \"IECoreMaya\/StatusException.h\"\n#include \"IECoreMaya\/SceneShapeInterface.h\"\n\nusing namespace IECoreMaya;\nusing namespace boost::python;\n\nstatic IECore::SceneInterfacePtr sceneInterface( MFnDependencyNode *fnDN )\n{\n\tassert( fnDN );\n\tMPxNode *userNode = fnDN->userNode();\n\tSceneShapeInterface *sc = dynamic_cast( userNode );\n\tassert( sc );\n\tIECore::ConstSceneInterfacePtr scnInterface = sc->getSceneInterface();\n\treturn const_cast( scnInterface.get() );\n}\n\nstatic list componentNames( MFnDependencyNode *fnDN )\n{\n\tassert( fnDN );\n\tMPxNode *userNode = fnDN->userNode();\n\tSceneShapeInterface *sc = dynamic_cast( userNode );\n\tassert( sc );\n\tstd::vector names = sc->componentNames();\n\t\n\tlist result;\n\tfor( std::vector::const_iterator it = names.begin(); it!=names.end(); it++ )\n\t{\n\t\tresult.append( (*it).value() );\n\t}\n\t\t\t\n\treturn result;\n}\n\nvoid IECoreMaya::bindFnSceneShape()\n{\n\n\tdef( \"_sceneShapeSceneInterface\", &sceneInterface );\n\tdef( \"_sceneShapeComponentNames\", &componentNames );\n\n}\nPreventing maya crashes when nodes are not scene shapes in scene shape bindings.\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2013, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of Image Engine Design nor the names of any\n\/\/ other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"boost\/python.hpp\"\n\n#include \n\n#include \"maya\/MFnDependencyNode.h\"\n\n#include \"IECore\/SceneInterface.h\"\n\n#include \"IECoreMaya\/bindings\/FnSceneShapeBinding.h\"\n#include \"IECoreMaya\/StatusException.h\"\n#include \"IECoreMaya\/SceneShapeInterface.h\"\n\nusing namespace IECoreMaya;\nusing namespace boost::python;\n\nstatic IECore::SceneInterfacePtr sceneInterface( MFnDependencyNode *fnDN )\n{\n\tassert( fnDN );\n\tMPxNode *userNode = fnDN->userNode();\n\tSceneShapeInterface *sc = dynamic_cast( userNode );\n\tif( sc )\n\t{\n\t\tIECore::ConstSceneInterfacePtr scnInterface = sc->getSceneInterface();\n\t\treturn const_cast( scnInterface.get() );\n\t}\n\t\n\t\/\/ failed\n\tthrow IECore::Exception( ( MString(\"Node \\\"\") + fnDN->name() + \"\\\" is not a SceneShape\" ).asChar() );\n}\n\nstatic list componentNames( MFnDependencyNode *fnDN )\n{\n\tassert( fnDN );\n\tMPxNode *userNode = fnDN->userNode();\n\tSceneShapeInterface *sc = dynamic_cast( userNode );\n\tif( sc )\n\t{\n\t\tstd::vector names = sc->componentNames();\n\t\n\t\tlist result;\n\t\tfor( std::vector::const_iterator it = names.begin(); it!=names.end(); it++ )\n\t\t{\n\t\t\tresult.append( (*it).value() );\n\t\t}\n\t\t\t\t\n\t\treturn result;\n\t}\n\t\/\/ failed\n\tthrow IECore::Exception( ( MString(\"Node \\\"\") + fnDN->name() + \"\\\" is not a SceneShape\" ).asChar() );\n}\n\nvoid IECoreMaya::bindFnSceneShape()\n{\n\n\tdef( \"_sceneShapeSceneInterface\", &sceneInterface );\n\tdef( \"_sceneShapeComponentNames\", &componentNames );\n\n}\n<|endoftext|>"} {"text":"\/*\n For more information, please see: http:\/\/software.sci.utah.edu\n\n The MIT License\n\n Copyright (c) 2012 Scientific Computing and Imaging Institute,\n University of Utah.\n\n License for the specific language governing rights and limitations under\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace SCIRun::Modules::Visualization;\nusing namespace SCIRun::Core::Datatypes;\nusing namespace SCIRun::Dataflow::Networks;\nusing namespace SCIRun::Core::Algorithms;\nusing namespace SCIRun::Core::Geometry;\nusing namespace SCIRun;\n\nShowColorMapModule::ShowColorMapModule() : GeometryGeneratingModule(ModuleLookupInfo(\"ShowColorMap\", \"Visualization\", \"SCIRun\"))\n{\n INITIALIZE_PORT(ColorMapObject);\n INITIALIZE_PORT(GeometryOutput);\n}\n\nvoid ShowColorMapModule::setStateDefaults()\n{\n auto state = get_state();\n state->setValue(DisplaySide, 0);\n state->setValue(DisplayLength, 0);\n state->setValue(TextSize, 2);\n state->setValue(TextRed, 1.);\n state->setValue(TextGreen, 1.);\n state->setValue(TextBlue, 1.);\n state->setValue(Labels, 10);\n state->setValue(Scale, 1.0);\n state->setValue(Units, std::string(\"\"));\n state->setValue(SignificantDigits, 2);\n state->setValue(AddExtraSpace, false);\n}\n\nvoid ShowColorMapModule::execute()\n{\n auto colorMap = getRequiredInput(ColorMapObject);\n if (needToExecute())\n {\n std::ostringstream ostr;\n ostr << get_id() << \"_\" <<\n colorMap->getColorMapInvert() << colorMap->getColorMapName() << colorMap->getColorMapRescaleScale() <<\n colorMap->getColorMapRescaleShift() << colorMap->getColorMapResolution() << colorMap.get() <<\n colorMap->getColorMapShift();\n GeometryHandle geom = buildGeometryObject(colorMap, get_state(), ostr.str());\n sendOutput(GeometryOutput, geom);\n }\n}\n\nGeometryHandle\nShowColorMapModule::buildGeometryObject(ColorMapHandle cm, ModuleStateHandle state, const std::string& id)\n{\n std::vector points;\n std::vector colors;\n std::vector indices;\n int32_t numVBOElements = 0;\n ColorMap * map = cm.get();\n double resolution = 1. \/ static_cast(map->getColorMapResolution());\n \/\/show colormap does not rescale colors, so reset them. we want to see the whole colormap on the scale.\n ColorMap new_map(map->getColorMapName(),map->getColorMapResolution(),\n map->getColorMapShift(),map->getColorMapInvert(), 1.,0.);\n for (double i = 0.; std::abs(i - 1.) > 0.000001; i += resolution) {\n ColorRGB col = new_map.valueToColor(i);\n uint32_t offset = (uint32_t)points.size();\n points.push_back(Vector(0., i, +0.001));\n colors.push_back(col);\n points.push_back(Vector(1., i, +0.001));\n colors.push_back(col);\n points.push_back(Vector(0., i + resolution, +0.001));\n colors.push_back(col);\n points.push_back(Vector(1., i + resolution, +0.001));\n colors.push_back(col);\n numVBOElements += 2;\n indices.push_back(offset + 0);\n indices.push_back(offset + 1);\n indices.push_back(offset + 3);\n indices.push_back(offset + 3);\n indices.push_back(offset + 2);\n indices.push_back(offset + 0);\n }\n\n \/\/ IBO\/VBOs and sizes\n uint32_t iboSize = sizeof(uint32_t) * (uint32_t)indices.size();\n uint32_t vboSize = sizeof(float) * 7 * (uint32_t)points.size();\n\n std::shared_ptr iboBufferSPtr(\n new CPM_VAR_BUFFER_NS::VarBuffer(vboSize));\n std::shared_ptr vboBufferSPtr(\n new CPM_VAR_BUFFER_NS::VarBuffer(iboSize));\n\n CPM_VAR_BUFFER_NS::VarBuffer* iboBuffer = iboBufferSPtr.get();\n CPM_VAR_BUFFER_NS::VarBuffer* vboBuffer = vboBufferSPtr.get();\n\n for (auto a : indices) iboBuffer->write(a);\n\n for (size_t i = 0; i < points.size(); i++) {\n vboBuffer->write(static_cast(points[i].x()));\n vboBuffer->write(static_cast(points[i].y()));\n vboBuffer->write(static_cast(points[i].z()));\n vboBuffer->write(static_cast(colors[i].r()));\n vboBuffer->write(static_cast(colors[i].g()));\n vboBuffer->write(static_cast(colors[i].b()));\n vboBuffer->write(static_cast(1.f));\n }\n\n \/\/add the actual points and colors\n\n auto st = get_state();\n int sigdig = st->getValue(SignificantDigits).toInt();\n int numlabel = st->getValue(Labels).toInt();\n int txtsize = st->getValue(TextSize).toInt();\n double scale = st->getValue(Scale).toDouble();\n int displaySide = state->getValue(DisplaySide).toInt();\n float red = static_cast(st->getValue(TextRed).toDouble());\n float green = static_cast(st->getValue(TextGreen).toDouble());\n float blue = static_cast(st->getValue(TextBlue).toDouble());\n std::stringstream ss;\n ss << resolution << sigdig << txtsize << numlabel << st->getValue(Units).toString() <<\n scale << displaySide << red << green << blue;\n\n std::string uniqueNodeID = id + \"colorMapLegend\" + ss.str();\n std::string vboName = uniqueNodeID + \"VBO\";\n std::string iboName = uniqueNodeID + \"IBO\";\n std::string passName = uniqueNodeID + \"Pass\";\n\n \/\/ NOTE: Attributes will depend on the color scheme. We will want to\n \/\/ normalize the colors if the color scheme is COLOR_IN_SITU.\n\n \/\/ Construct VBO.\n std::string shader = \"Shaders\/ColorMapLegend\";\n std::vector attribs;\n attribs.push_back(GeometryObject::SpireVBO::AttributeData(\"aPos\", 3 * sizeof(float)));\n attribs.push_back(GeometryObject::SpireVBO::AttributeData(\"aColor\", 4 * sizeof(float)));\n std::vector uniforms;\n bool extraSpace = state->getValue(AddExtraSpace).toBool();\n uniforms.push_back(GeometryObject::SpireSubPass::Uniform(\"uExtraSpace\", extraSpace ? 1.f : 0.f));\n uniforms.push_back(GeometryObject::SpireSubPass::Uniform(\"uDisplaySide\", static_cast(displaySide)));\n int displayLength = state->getValue(DisplayLength).toInt();\n uniforms.push_back(GeometryObject::SpireSubPass::Uniform(\"uDisplayLength\", static_cast(displayLength)));\n GeometryObject::SpireVBO geomVBO = GeometryObject::SpireVBO(vboName, attribs, vboBufferSPtr,\n numVBOElements, Core::Geometry::BBox(), true);\n\n \/\/ Construct IBO.\n\n GeometryObject::SpireIBO geomIBO(iboName, GeometryObject::SpireIBO::TRIANGLES, sizeof(uint32_t), iboBufferSPtr);\n\n RenderState renState;\n renState.set(RenderState::IS_ON, true);\n renState.set(RenderState::HAS_DATA, true);\n \n GeometryObject::SpireSubPass pass(passName, vboName, iboName, shader,\n GeometryObject::COLOR_MAP, renState, GeometryObject::RENDER_VBO_IBO, geomVBO, geomIBO);\n\n \/\/ Add all uniforms generated above to the pass.\n for (const auto& uniform : uniforms) { pass.addUniform(uniform); }\n\n Core::Datatypes::GeometryHandle geom(new Core::Datatypes::GeometryObject(nullptr, *this, \"ShowColorMap\"));\n\n geom->mColorMap = cm->getColorMapName();\n geom->mIBOs.push_back(geomIBO);\n geom->mVBOs.push_back(geomVBO);\n geom->mPasses.push_back(pass);\n \/\/########################################\n \/\/ Now render the numbers for the scale bar\n\n char str2[128];\n std::stringstream sd;\n sd << \"%.\" << sigdig << \"f\";\n points.clear();\n indices.clear();\n std::vector txt_coords;\n numVBOElements = 0;\n uint32_t count = 0;\n double increment = 1. \/ static_cast(numlabel - 1);\n double textSize = 10. * static_cast(txtsize + 1) + 30.;\n\n for (double i = 0.; i <= 1.000000001; i += increment) {\n std::stringstream ss;\n sprintf(str2, sd.str().c_str(), i \/ cm->getColorMapRescaleScale() - cm->getColorMapRescaleShift());\n ss << str2 << \" \" << st->getValue(Units).toString();\n text_.reset(ss.str(), textSize, Vector((displaySide == 0) ? 80. : 1., (displaySide == 0) ? 0. : 40., i));\n std::vector tmp;\n std::vector coords;\n text_.getStringVerts(tmp, coords);\n if (displaySide != 0)\n text_.reset(\"|\", 40., Vector(1., 0., i));\n else\n text_.reset(\"____\", 20., Vector(10., 0., i));\n text_.getStringVerts(tmp, coords);\n for (auto a : tmp) {\n points.push_back(a);\n indices.push_back(count);\n count++;\n }\n for (auto a : coords)\n txt_coords.push_back(a);\n }\n numVBOElements = (uint32_t)points.size();\n\n \/\/ IBO\/VBOs and sizes\n iboSize = sizeof(uint32_t) * (uint32_t)indices.size();\n vboSize = sizeof(float) * 5 * (uint32_t)points.size();\n\n std::shared_ptr iboBufferSPtr2(\n new CPM_VAR_BUFFER_NS::VarBuffer(vboSize));\n std::shared_ptr vboBufferSPtr2(\n new CPM_VAR_BUFFER_NS::VarBuffer(iboSize));\n\n CPM_VAR_BUFFER_NS::VarBuffer* iboBuffer2 = iboBufferSPtr2.get();\n CPM_VAR_BUFFER_NS::VarBuffer* vboBuffer2 = vboBufferSPtr2.get();\n\n for (auto a : indices) iboBuffer2->write(a);\n for (size_t i = 0; i < points.size(); i++) {\n vboBuffer2->write(static_cast(points[i].x()));\n vboBuffer2->write(static_cast(points[i].y()));\n vboBuffer2->write(static_cast(points[i].z()));\n vboBuffer2->write(static_cast(txt_coords[i].x()));\n vboBuffer2->write(static_cast(txt_coords[i].y()));\n }\n\n \/\/add the actual points and colors\n\n uniqueNodeID = id + \"colorMapLegendTextFont\" + ss.str();\n vboName = uniqueNodeID + \"VBO\";\n iboName = uniqueNodeID + \"IBO\";\n passName = uniqueNodeID + \"Pass2\";\n\n \/\/ NOTE: Attributes will depend on the color scheme. We will want to\n \/\/ normalize the colors if the color scheme is COLOR_IN_SITU.\n\n \/\/ Construct VBO.\n shader = \"Shaders\/ColorMapLegendText\";\n attribs.clear();\n attribs.push_back(GeometryObject::SpireVBO::AttributeData(\"aPos\", 3 * sizeof(float)));\n attribs.push_back(GeometryObject::SpireVBO::AttributeData(\"aTexCoord\", 2 * sizeof(float)));\n uniforms.clear();\n uniforms.push_back(GeometryObject::SpireSubPass::Uniform(\"uExtraSpace\", extraSpace ? 1. : 0.));\n uniforms.push_back(GeometryObject::SpireSubPass::Uniform(\"uDisplaySide\", static_cast(displaySide)));\n uniforms.push_back(GeometryObject::SpireSubPass::Uniform(\"uDisplayLength\", static_cast(displayLength)));\n uniforms.push_back(GeometryObject::SpireSubPass::Uniform(\"uColor\", glm::vec4(red,green,blue,1.0f)));\n GeometryObject::SpireVBO geomVBO2 = GeometryObject::SpireVBO(vboName, attribs, vboBufferSPtr2,\n numVBOElements, Core::Geometry::BBox(), true);\n\n geom->mVBOs.push_back(geomVBO2);\n\n \/\/ Construct IBO.\n\n GeometryObject::SpireIBO geomIBO2(iboName, GeometryObject::SpireIBO::TRIANGLES, sizeof(uint32_t), iboBufferSPtr2);\n geom->mIBOs.push_back(geomIBO2);\n renState.set(RenderState::USE_COLORMAP, false);\n renState.set(RenderState::USE_TRANSPARENCY, true);\n GeometryObject::SpireSubPass pass2(passName, vboName, iboName, shader,\n GeometryObject::COLOR_MAP, renState, GeometryObject::RENDER_VBO_IBO, geomVBO2, geomIBO2);\n\n \/\/ Add all uniforms generated above to the pass.\n for (const auto& uniform : uniforms) { pass2.addUniform(uniform); }\n\n geom->mPasses.push_back(pass2);\n\n return geom;\n}\n\nAlgorithmParameterName ShowColorMapModule::DisplaySide(\"DisplaySide\");\nAlgorithmParameterName ShowColorMapModule::DisplayLength(\"DisplayLength\");\nAlgorithmParameterName ShowColorMapModule::TextSize(\"TextSize\");\nAlgorithmParameterName ShowColorMapModule::TextColor(\"TextColor\");\nAlgorithmParameterName ShowColorMapModule::Labels(\"Labels\");\nAlgorithmParameterName ShowColorMapModule::Scale(\"Scale\");\nAlgorithmParameterName ShowColorMapModule::Units(\"Units\");\nAlgorithmParameterName ShowColorMapModule::SignificantDigits(\"SignificantDigits\");\nAlgorithmParameterName ShowColorMapModule::AddExtraSpace(\"AddExtraSpace\");\nAlgorithmParameterName ShowColorMapModule::TextRed(\"TextRed\");\nAlgorithmParameterName ShowColorMapModule::TextGreen(\"TextGreen\");\nAlgorithmParameterName ShowColorMapModule::TextBlue(\"TextBlue\");\nFont geometry not added for now until debugged to work on windows.\/*\n For more information, please see: http:\/\/software.sci.utah.edu\n\n The MIT License\n\n Copyright (c) 2012 Scientific Computing and Imaging Institute,\n University of Utah.\n\n License for the specific language governing rights and limitations under\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace SCIRun::Modules::Visualization;\nusing namespace SCIRun::Core::Datatypes;\nusing namespace SCIRun::Dataflow::Networks;\nusing namespace SCIRun::Core::Algorithms;\nusing namespace SCIRun::Core::Geometry;\nusing namespace SCIRun;\n\nShowColorMapModule::ShowColorMapModule() : GeometryGeneratingModule(ModuleLookupInfo(\"ShowColorMap\", \"Visualization\", \"SCIRun\"))\n{\n INITIALIZE_PORT(ColorMapObject);\n INITIALIZE_PORT(GeometryOutput);\n}\n\nvoid ShowColorMapModule::setStateDefaults()\n{\n auto state = get_state();\n state->setValue(DisplaySide, 0);\n state->setValue(DisplayLength, 0);\n state->setValue(TextSize, 2);\n state->setValue(TextRed, 1.);\n state->setValue(TextGreen, 1.);\n state->setValue(TextBlue, 1.);\n state->setValue(Labels, 10);\n state->setValue(Scale, 1.0);\n state->setValue(Units, std::string(\"\"));\n state->setValue(SignificantDigits, 2);\n state->setValue(AddExtraSpace, false);\n}\n\nvoid ShowColorMapModule::execute()\n{\n auto colorMap = getRequiredInput(ColorMapObject);\n if (needToExecute())\n {\n std::ostringstream ostr;\n ostr << get_id() << \"_\" <<\n colorMap->getColorMapInvert() << colorMap->getColorMapName() << colorMap->getColorMapRescaleScale() <<\n colorMap->getColorMapRescaleShift() << colorMap->getColorMapResolution() << colorMap.get() <<\n colorMap->getColorMapShift();\n GeometryHandle geom = buildGeometryObject(colorMap, get_state(), ostr.str());\n sendOutput(GeometryOutput, geom);\n }\n}\n\nGeometryHandle\nShowColorMapModule::buildGeometryObject(ColorMapHandle cm, ModuleStateHandle state, const std::string& id)\n{\n std::vector points;\n std::vector colors;\n std::vector indices;\n int32_t numVBOElements = 0;\n ColorMap * map = cm.get();\n double resolution = 1. \/ static_cast(map->getColorMapResolution());\n \/\/show colormap does not rescale colors, so reset them. we want to see the whole colormap on the scale.\n ColorMap new_map(map->getColorMapName(),map->getColorMapResolution(),\n map->getColorMapShift(),map->getColorMapInvert(), 1.,0.);\n for (double i = 0.; std::abs(i - 1.) > 0.000001; i += resolution) {\n ColorRGB col = new_map.valueToColor(i);\n uint32_t offset = (uint32_t)points.size();\n points.push_back(Vector(0., i, +0.001));\n colors.push_back(col);\n points.push_back(Vector(1., i, +0.001));\n colors.push_back(col);\n points.push_back(Vector(0., i + resolution, +0.001));\n colors.push_back(col);\n points.push_back(Vector(1., i + resolution, +0.001));\n colors.push_back(col);\n numVBOElements += 2;\n indices.push_back(offset + 0);\n indices.push_back(offset + 1);\n indices.push_back(offset + 3);\n indices.push_back(offset + 3);\n indices.push_back(offset + 2);\n indices.push_back(offset + 0);\n }\n\n \/\/ IBO\/VBOs and sizes\n uint32_t iboSize = sizeof(uint32_t) * (uint32_t)indices.size();\n uint32_t vboSize = sizeof(float) * 7 * (uint32_t)points.size();\n\n std::shared_ptr iboBufferSPtr(\n new CPM_VAR_BUFFER_NS::VarBuffer(vboSize));\n std::shared_ptr vboBufferSPtr(\n new CPM_VAR_BUFFER_NS::VarBuffer(iboSize));\n\n CPM_VAR_BUFFER_NS::VarBuffer* iboBuffer = iboBufferSPtr.get();\n CPM_VAR_BUFFER_NS::VarBuffer* vboBuffer = vboBufferSPtr.get();\n\n for (auto a : indices) iboBuffer->write(a);\n\n for (size_t i = 0; i < points.size(); i++) {\n vboBuffer->write(static_cast(points[i].x()));\n vboBuffer->write(static_cast(points[i].y()));\n vboBuffer->write(static_cast(points[i].z()));\n vboBuffer->write(static_cast(colors[i].r()));\n vboBuffer->write(static_cast(colors[i].g()));\n vboBuffer->write(static_cast(colors[i].b()));\n vboBuffer->write(static_cast(1.f));\n }\n\n \/\/add the actual points and colors\n\n auto st = get_state();\n int sigdig = st->getValue(SignificantDigits).toInt();\n int numlabel = st->getValue(Labels).toInt();\n int txtsize = st->getValue(TextSize).toInt();\n double scale = st->getValue(Scale).toDouble();\n int displaySide = state->getValue(DisplaySide).toInt();\n float red = static_cast(st->getValue(TextRed).toDouble());\n float green = static_cast(st->getValue(TextGreen).toDouble());\n float blue = static_cast(st->getValue(TextBlue).toDouble());\n std::stringstream ss;\n ss << resolution << sigdig << txtsize << numlabel << st->getValue(Units).toString() <<\n scale << displaySide << red << green << blue;\n\n std::string uniqueNodeID = id + \"colorMapLegend\" + ss.str();\n std::string vboName = uniqueNodeID + \"VBO\";\n std::string iboName = uniqueNodeID + \"IBO\";\n std::string passName = uniqueNodeID + \"Pass\";\n\n \/\/ NOTE: Attributes will depend on the color scheme. We will want to\n \/\/ normalize the colors if the color scheme is COLOR_IN_SITU.\n\n \/\/ Construct VBO.\n std::string shader = \"Shaders\/ColorMapLegend\";\n std::vector attribs;\n attribs.push_back(GeometryObject::SpireVBO::AttributeData(\"aPos\", 3 * sizeof(float)));\n attribs.push_back(GeometryObject::SpireVBO::AttributeData(\"aColor\", 4 * sizeof(float)));\n std::vector uniforms;\n bool extraSpace = state->getValue(AddExtraSpace).toBool();\n uniforms.push_back(GeometryObject::SpireSubPass::Uniform(\"uExtraSpace\", extraSpace ? 1.f : 0.f));\n uniforms.push_back(GeometryObject::SpireSubPass::Uniform(\"uDisplaySide\", static_cast(displaySide)));\n int displayLength = state->getValue(DisplayLength).toInt();\n uniforms.push_back(GeometryObject::SpireSubPass::Uniform(\"uDisplayLength\", static_cast(displayLength)));\n GeometryObject::SpireVBO geomVBO = GeometryObject::SpireVBO(vboName, attribs, vboBufferSPtr,\n numVBOElements, Core::Geometry::BBox(), true);\n\n \/\/ Construct IBO.\n\n GeometryObject::SpireIBO geomIBO(iboName, GeometryObject::SpireIBO::TRIANGLES, sizeof(uint32_t), iboBufferSPtr);\n\n RenderState renState;\n renState.set(RenderState::IS_ON, true);\n renState.set(RenderState::HAS_DATA, true);\n \n GeometryObject::SpireSubPass pass(passName, vboName, iboName, shader,\n GeometryObject::COLOR_MAP, renState, GeometryObject::RENDER_VBO_IBO, geomVBO, geomIBO);\n\n \/\/ Add all uniforms generated above to the pass.\n for (const auto& uniform : uniforms) { pass.addUniform(uniform); }\n\n Core::Datatypes::GeometryHandle geom(new Core::Datatypes::GeometryObject(nullptr, *this, \"ShowColorMap\"));\n\n geom->mColorMap = cm->getColorMapName();\n geom->mIBOs.push_back(geomIBO);\n geom->mVBOs.push_back(geomVBO);\n geom->mPasses.push_back(pass);\n \/\/########################################\n \/\/ Now render the numbers for the scale bar\n\n char str2[128];\n std::stringstream sd;\n sd << \"%.\" << sigdig << \"f\";\n points.clear();\n indices.clear();\n std::vector txt_coords;\n numVBOElements = 0;\n uint32_t count = 0;\n double increment = 1. \/ static_cast(numlabel - 1);\n double textSize = 10. * static_cast(txtsize + 1) + 30.;\n\n for (double i = 0.; i <= 1.000000001; i += increment) {\n std::stringstream ss;\n sprintf(str2, sd.str().c_str(), i \/ cm->getColorMapRescaleScale() - cm->getColorMapRescaleShift());\n ss << str2 << \" \" << st->getValue(Units).toString();\n text_.reset(ss.str(), textSize, Vector((displaySide == 0) ? 80. : 1., (displaySide == 0) ? 0. : 40., i));\n std::vector tmp;\n std::vector coords;\n text_.getStringVerts(tmp, coords);\n if (displaySide != 0)\n text_.reset(\"|\", 40., Vector(1., 0., i));\n else\n text_.reset(\"____\", 20., Vector(10., 0., i));\n text_.getStringVerts(tmp, coords);\n for (auto a : tmp) {\n points.push_back(a);\n indices.push_back(count);\n count++;\n }\n for (auto a : coords)\n txt_coords.push_back(a);\n }\n numVBOElements = (uint32_t)points.size();\n\n \/\/ IBO\/VBOs and sizes\n iboSize = sizeof(uint32_t) * (uint32_t)indices.size();\n vboSize = sizeof(float) * 5 * (uint32_t)points.size();\n\n std::shared_ptr iboBufferSPtr2(\n new CPM_VAR_BUFFER_NS::VarBuffer(vboSize));\n std::shared_ptr vboBufferSPtr2(\n new CPM_VAR_BUFFER_NS::VarBuffer(iboSize));\n\n CPM_VAR_BUFFER_NS::VarBuffer* iboBuffer2 = iboBufferSPtr2.get();\n CPM_VAR_BUFFER_NS::VarBuffer* vboBuffer2 = vboBufferSPtr2.get();\n\n for (auto a : indices) iboBuffer2->write(a);\n for (size_t i = 0; i < points.size(); i++) {\n vboBuffer2->write(static_cast(points[i].x()));\n vboBuffer2->write(static_cast(points[i].y()));\n vboBuffer2->write(static_cast(points[i].z()));\n vboBuffer2->write(static_cast(txt_coords[i].x()));\n vboBuffer2->write(static_cast(txt_coords[i].y()));\n }\n\n \/\/add the actual points and colors\n\n uniqueNodeID = id + \"colorMapLegendTextFont\" + ss.str();\n vboName = uniqueNodeID + \"VBO\";\n iboName = uniqueNodeID + \"IBO\";\n passName = uniqueNodeID + \"Pass2\";\n\n \/\/ NOTE: Attributes will depend on the color scheme. We will want to\n \/\/ normalize the colors if the color scheme is COLOR_IN_SITU.\n\n \/\/ Construct VBO.\n shader = \"Shaders\/ColorMapLegendText\";\n attribs.clear();\n attribs.push_back(GeometryObject::SpireVBO::AttributeData(\"aPos\", 3 * sizeof(float)));\n attribs.push_back(GeometryObject::SpireVBO::AttributeData(\"aTexCoord\", 2 * sizeof(float)));\n uniforms.clear();\n uniforms.push_back(GeometryObject::SpireSubPass::Uniform(\"uExtraSpace\", extraSpace ? 1. : 0.));\n uniforms.push_back(GeometryObject::SpireSubPass::Uniform(\"uDisplaySide\", static_cast(displaySide)));\n uniforms.push_back(GeometryObject::SpireSubPass::Uniform(\"uDisplayLength\", static_cast(displayLength)));\n uniforms.push_back(GeometryObject::SpireSubPass::Uniform(\"uColor\", glm::vec4(red,green,blue,1.0f)));\n GeometryObject::SpireVBO geomVBO2 = GeometryObject::SpireVBO(vboName, attribs, vboBufferSPtr2,\n numVBOElements, Core::Geometry::BBox(), true);\n\n geom->mVBOs.push_back(geomVBO2);\n\n \/\/ Construct IBO.\n\n GeometryObject::SpireIBO geomIBO2(iboName, GeometryObject::SpireIBO::TRIANGLES, sizeof(uint32_t), iboBufferSPtr2);\n geom->mIBOs.push_back(geomIBO2);\n renState.set(RenderState::USE_COLORMAP, false);\n renState.set(RenderState::USE_TRANSPARENCY, true);\n GeometryObject::SpireSubPass pass2(passName, vboName, iboName, shader,\n GeometryObject::COLOR_MAP, renState, GeometryObject::RENDER_VBO_IBO, geomVBO2, geomIBO2);\n\n \/\/ Add all uniforms generated above to the pass.\n for (const auto& uniform : uniforms) { pass2.addUniform(uniform); }\n \/*******************************************************************************************\n \/\/ TODO we're not adding this geometry (font) until we debug for it to work on Windows.\n geom->mPasses.push_back(pass2);\n *******************************************************************************************\/\n return geom;\n}\n\nAlgorithmParameterName ShowColorMapModule::DisplaySide(\"DisplaySide\");\nAlgorithmParameterName ShowColorMapModule::DisplayLength(\"DisplayLength\");\nAlgorithmParameterName ShowColorMapModule::TextSize(\"TextSize\");\nAlgorithmParameterName ShowColorMapModule::TextColor(\"TextColor\");\nAlgorithmParameterName ShowColorMapModule::Labels(\"Labels\");\nAlgorithmParameterName ShowColorMapModule::Scale(\"Scale\");\nAlgorithmParameterName ShowColorMapModule::Units(\"Units\");\nAlgorithmParameterName ShowColorMapModule::SignificantDigits(\"SignificantDigits\");\nAlgorithmParameterName ShowColorMapModule::AddExtraSpace(\"AddExtraSpace\");\nAlgorithmParameterName ShowColorMapModule::TextRed(\"TextRed\");\nAlgorithmParameterName ShowColorMapModule::TextGreen(\"TextGreen\");\nAlgorithmParameterName ShowColorMapModule::TextBlue(\"TextBlue\");\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: javachild.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2004-11-03 16:05:04 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\n#ifdef SOLAR_JAVA\n#include \n#endif\n\n#ifndef _COMPHELPER_PROCESSFACTORY_HXX_\n#include \n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifndef _SV_SVSYS_HXX\n#include \n#endif\n#ifndef _SV_SALINST_HXX\n#include \n#endif\n#ifndef _SV_SALFRAME_HXX\n#include \n#endif\n#include \n#ifndef _SV_SALOBJ_HXX\n#include \n#endif\n#include \"javachild.hxx\"\n#include \n#include \n\nusing namespace ::com::sun::star;\n\n\/\/ -------------------\n\/\/ - JavaChildWindow -\n\/\/ -------------------\n\nJavaChildWindow::JavaChildWindow( Window* pParent, WinBits nStyle ) :\n SystemChildWindow( pParent, nStyle )\n{\n}\n\n\/\/ -----------------------------------------------------------------------\n\nJavaChildWindow::JavaChildWindow( Window* pParent, const ResId& rResId ) :\n SystemChildWindow( pParent, rResId )\n{\n}\n\n\/\/ -----------------------------------------------------------------------\n\nJavaChildWindow::~JavaChildWindow()\n{\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid JavaChildWindow::implTestJavaException( void* pEnv )\n{\n#ifdef SOLAR_JAVA\n JNIEnv* pJavaEnv = reinterpret_cast< JNIEnv* >( pEnv );\n jthrowable jtThrowable = pJavaEnv->ExceptionOccurred();\n\n if( jtThrowable )\n { \/\/ is it a java exception ?\n#if OSL_DEBUG_LEVEL > 1\n pJavaEnv->ExceptionDescribe();\n#endif \/\/ OSL_DEBUG_LEVEL > 1\n pJavaEnv->ExceptionClear();\n\n jclass jcThrowable = pJavaEnv->FindClass(\"java\/lang\/Throwable\");\n jmethodID jmThrowable_getMessage = pJavaEnv->GetMethodID(jcThrowable, \"getMessage\", \"()Ljava\/lang\/String;\");\n jstring jsMessage = (jstring) pJavaEnv->CallObjectMethod(jtThrowable, jmThrowable_getMessage);\n ::rtl::OUString ouMessage;\n\n if(jsMessage)\n {\n const jchar * jcMessage = pJavaEnv->GetStringChars(jsMessage, NULL);\n ouMessage = ::rtl::OUString(jcMessage);\n pJavaEnv->ReleaseStringChars(jsMessage, jcMessage);\n }\n\n throw uno::RuntimeException(ouMessage, uno::Reference());\n }\n#endif \/\/ SOLAR_JAVA\n}\n\n\/\/ -----------------------------------------------------------------------\n\nsal_Int32 JavaChildWindow::getParentWindowHandleForJava()\n{\n sal_Int32 nRet = 0;\n\n#if defined WNT\n nRet = reinterpret_cast< sal_Int32 >( GetSystemData()->hWnd );\n#elif defined UNX\n#ifdef SOLAR_JAVA\n uno::Reference< lang::XMultiServiceFactory > xFactory( vcl::unohelper::GetMultiServiceFactory() );\n\n if( xFactory.is() && ( GetSystemData()->aWindow > 0 ) )\n {\n JavaVM* pJVM;\n ::rtl::Reference< ::jvmaccess::VirtualMachine > xVM;\n uno::Reference< java::XJavaVM > xJavaVM( xFactory->createInstance( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.java.JavaVirtualMachine\") ) ), uno::UNO_QUERY );\n uno::Sequence< sal_Int8 > aProcessID( 17 );\n\n rtl_getGlobalProcessId( (sal_uInt8*) aProcessID.getArray() );\n aProcessID[ 16 ] = 0;\n OSL_ENSURE(sizeof (sal_Int64) >= sizeof (jvmaccess::VirtualMachine *), \"Pointer cannot be represented as sal_Int64\");\n sal_Int64 nPointer = reinterpret_cast< sal_Int64 >( static_cast< jvmaccess::VirtualMachine * >(0));\n xJavaVM->getJavaVM(aProcessID) >>= nPointer;\n xVM = reinterpret_cast< jvmaccess::VirtualMachine * >(nPointer);\n\n if( xVM.is() )\n {\n try\n {\n ::jvmaccess::VirtualMachine::AttachGuard aVMAttachGuard( xVM );\n JNIEnv* pEnv = aVMAttachGuard.getEnvironment();\n\n jclass jcToolkit = pEnv->FindClass(\"java\/awt\/Toolkit\");\n implTestJavaException(pEnv);\n\n jmethodID jmToolkit_getDefaultToolkit = pEnv->GetStaticMethodID( jcToolkit, \"getDefaultToolkit\", \"()Ljava\/awt\/Toolkit;\" );\n implTestJavaException(pEnv);\n\n pEnv->CallStaticObjectMethod(jcToolkit, jmToolkit_getDefaultToolkit);\n implTestJavaException(pEnv);\n\n jclass jcMotifAppletViewer = pEnv->FindClass(\"sun\/plugin\/navig\/motif\/MotifAppletViewer\");\n if( pEnv->ExceptionOccurred() )\n {\n pEnv->ExceptionClear();\n\n jcMotifAppletViewer = pEnv->FindClass( \"sun\/plugin\/viewer\/MNetscapePluginContext\");\n implTestJavaException(pEnv);\n }\n\n jclass jcClassLoader = pEnv->FindClass(\"java\/lang\/ClassLoader\");\n implTestJavaException(pEnv);\n\n jmethodID jmClassLoader_loadLibrary = pEnv->GetStaticMethodID( jcClassLoader, \"loadLibrary\", \"(Ljava\/lang\/Class;Ljava\/lang\/String;Z)V\");\n implTestJavaException(pEnv);\n\n jstring jsplugin = pEnv->NewStringUTF(\"javaplugin_jni\");\n implTestJavaException(pEnv);\n\n pEnv->CallStaticVoidMethod(jcClassLoader, jmClassLoader_loadLibrary, jcMotifAppletViewer, jsplugin, JNI_FALSE);\n implTestJavaException(pEnv);\n\n jmethodID jmMotifAppletViewer_getWidget = pEnv->GetStaticMethodID( jcMotifAppletViewer, \"getWidget\", \"(IIIII)I\" );\n implTestJavaException(pEnv);\n\n const Size aSize( GetOutputSizePixel() );\n jint ji_widget = pEnv->CallStaticIntMethod( jcMotifAppletViewer, jmMotifAppletViewer_getWidget,\n GetSystemData()->aWindow, 0, 0, aSize.Width(), aSize.Height() );\n implTestJavaException(pEnv);\n\n nRet = (sal_Int32) ji_widget;\n }\n catch( ::jvmaccess::VirtualMachine::AttachGuard::CreationException& )\n {\n throw uno::RuntimeException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(\n \"JavaChildWindow::getJavaWindowHandle: Could not create jvmaccess::VirtualMachine::AttachGuard!\")), 0);\n }\n }\n }\n#endif \/\/ SOLAR_JAVA\n#else \/\/ WNT || UNX\n \/\/ TBD\n#endif\n\n return nRet;\n}\nINTEGRATION: CWS jre5issues (1.3.24); FILE MERGED 2004\/11\/29 13:36:20 ka 1.3.24.1: #i37962#: added support for Java 1.5\/*************************************************************************\n *\n * $RCSfile: javachild.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2005-01-31 09:48:09 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\n#ifdef SOLAR_JAVA\n#include \n#endif\n\n#ifndef _COMPHELPER_PROCESSFACTORY_HXX_\n#include \n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifndef _SV_SVSYS_HXX\n#include \n#endif\n#ifndef _SV_SALINST_HXX\n#include \n#endif\n#ifndef _SV_SALFRAME_HXX\n#include \n#endif\n#include \n#ifndef _SV_SALOBJ_HXX\n#include \n#endif\n#include \"javachild.hxx\"\n#include \n#include \n\nusing namespace ::com::sun::star;\n\n\/\/ -------------------\n\/\/ - JavaChildWindow -\n\/\/ -------------------\n\nJavaChildWindow::JavaChildWindow( Window* pParent, WinBits nStyle ) :\n SystemChildWindow( pParent, nStyle )\n{\n}\n\n\/\/ -----------------------------------------------------------------------\n\nJavaChildWindow::JavaChildWindow( Window* pParent, const ResId& rResId ) :\n SystemChildWindow( pParent, rResId )\n{\n}\n\n\/\/ -----------------------------------------------------------------------\n\nJavaChildWindow::~JavaChildWindow()\n{\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid JavaChildWindow::implTestJavaException( void* pEnv )\n{\n#ifdef SOLAR_JAVA\n JNIEnv* pJavaEnv = reinterpret_cast< JNIEnv* >( pEnv );\n jthrowable jtThrowable = pJavaEnv->ExceptionOccurred();\n\n if( jtThrowable )\n { \/\/ is it a java exception ?\n#if OSL_DEBUG_LEVEL > 1\n pJavaEnv->ExceptionDescribe();\n#endif \/\/ OSL_DEBUG_LEVEL > 1\n pJavaEnv->ExceptionClear();\n\n jclass jcThrowable = pJavaEnv->FindClass(\"java\/lang\/Throwable\");\n jmethodID jmThrowable_getMessage = pJavaEnv->GetMethodID(jcThrowable, \"getMessage\", \"()Ljava\/lang\/String;\");\n jstring jsMessage = (jstring) pJavaEnv->CallObjectMethod(jtThrowable, jmThrowable_getMessage);\n ::rtl::OUString ouMessage;\n\n if(jsMessage)\n {\n const jchar * jcMessage = pJavaEnv->GetStringChars(jsMessage, NULL);\n ouMessage = ::rtl::OUString(jcMessage);\n pJavaEnv->ReleaseStringChars(jsMessage, jcMessage);\n }\n\n throw uno::RuntimeException(ouMessage, uno::Reference());\n }\n#endif \/\/ SOLAR_JAVA\n}\n\n\/\/ -----------------------------------------------------------------------\n\nsal_Int32 JavaChildWindow::getParentWindowHandleForJava()\n{\n sal_Int32 nRet = 0;\n\n#if defined WNT\n nRet = reinterpret_cast< sal_Int32 >( GetSystemData()->hWnd );\n#elif defined UNX\n#ifdef SOLAR_JAVA\n uno::Reference< lang::XMultiServiceFactory > xFactory( vcl::unohelper::GetMultiServiceFactory() );\n\n if( xFactory.is() && ( GetSystemData()->aWindow > 0 ) )\n {\n try\n {\n JavaVM* pJVM;\n ::rtl::Reference< ::jvmaccess::VirtualMachine > xVM;\n uno::Reference< java::XJavaVM > xJavaVM( xFactory->createInstance( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.java.JavaVirtualMachine\") ) ), uno::UNO_QUERY );\n uno::Sequence< sal_Int8 > aProcessID( 17 );\n\n rtl_getGlobalProcessId( (sal_uInt8*) aProcessID.getArray() );\n aProcessID[ 16 ] = 0;\n OSL_ENSURE(sizeof (sal_Int64) >= sizeof (jvmaccess::VirtualMachine *), \"Pointer cannot be represented as sal_Int64\");\n sal_Int64 nPointer = reinterpret_cast< sal_Int64 >( static_cast< jvmaccess::VirtualMachine * >(0));\n xJavaVM->getJavaVM(aProcessID) >>= nPointer;\n xVM = reinterpret_cast< jvmaccess::VirtualMachine * >(nPointer);\n\n if( xVM.is() )\n {\n try\n {\n ::jvmaccess::VirtualMachine::AttachGuard aVMAttachGuard( xVM );\n JNIEnv* pEnv = aVMAttachGuard.getEnvironment();\n\n jclass jcToolkit = pEnv->FindClass(\"java\/awt\/Toolkit\");\n implTestJavaException(pEnv);\n\n jmethodID jmToolkit_getDefaultToolkit = pEnv->GetStaticMethodID( jcToolkit, \"getDefaultToolkit\", \"()Ljava\/awt\/Toolkit;\" );\n implTestJavaException(pEnv);\n\n pEnv->CallStaticObjectMethod(jcToolkit, jmToolkit_getDefaultToolkit);\n implTestJavaException(pEnv);\n\n jclass jcMotifAppletViewer = pEnv->FindClass(\"sun\/plugin\/navig\/motif\/MotifAppletViewer\");\n if( pEnv->ExceptionOccurred() )\n {\n pEnv->ExceptionClear();\n\n jcMotifAppletViewer = pEnv->FindClass( \"sun\/plugin\/viewer\/MNetscapePluginContext\");\n implTestJavaException(pEnv);\n }\n\n jclass jcClassLoader = pEnv->FindClass(\"java\/lang\/ClassLoader\");\n implTestJavaException(pEnv);\n\n jmethodID jmClassLoader_loadLibrary = pEnv->GetStaticMethodID( jcClassLoader, \"loadLibrary\", \"(Ljava\/lang\/Class;Ljava\/lang\/String;Z)V\");\n implTestJavaException(pEnv);\n\n jstring jsplugin = pEnv->NewStringUTF(\"javaplugin_jni\");\n implTestJavaException(pEnv);\n\n pEnv->CallStaticVoidMethod(jcClassLoader, jmClassLoader_loadLibrary, jcMotifAppletViewer, jsplugin, JNI_FALSE);\n implTestJavaException(pEnv);\n\n jmethodID jmMotifAppletViewer_getWidget = pEnv->GetStaticMethodID( jcMotifAppletViewer, \"getWidget\", \"(IIIII)I\" );\n implTestJavaException(pEnv);\n\n const Size aSize( GetOutputSizePixel() );\n jint ji_widget = pEnv->CallStaticIntMethod( jcMotifAppletViewer, jmMotifAppletViewer_getWidget,\n GetSystemData()->aWindow, 0, 0, aSize.Width(), aSize.Height() );\n implTestJavaException(pEnv);\n\n nRet = static_cast< sal_Int32 >( ji_widget );\n }\n catch( uno::RuntimeException& )\n {\n }\n\n if( !nRet )\n nRet = static_cast< sal_Int32 >( GetSystemData()->aWindow );\n }\n }\n catch( ... )\n {\n }\n }\n#endif \/\/ SOLAR_JAVA\n#else \/\/ WNT || UNX\n \/\/ TBD\n#endif\n\n return nRet;\n}\n<|endoftext|>"} {"text":"#include \"boost\/filesystem.hpp\"\n\n#include \n#include \"itkCenteredSimilarity2DTransform.h\"\n\n\/\/ my files\n#include \"Stack.hpp\"\n#include \"NormalizeImages.hpp\"\n#include \"StackInitializers.hpp\"\n#include \"RegistrationBuilder.hpp\"\n#include \"StackAligner.hpp\"\n#include \"StackIOHelpers.hpp\"\n#include \"IOHelpers.hpp\"\n#include \"Dirs.hpp\"\n#include \"Parameters.hpp\"\n#include \"StackTransforms.hpp\"\n#include \"OptimizerConfig.hpp\"\n#include \"Profiling.hpp\"\n\nvoid checkUsage(int argc, char const *argv[]) {\n if( argc < 3 )\n {\n cerr << \"\\nUsage: \" << endl;\n cerr << argv[0] << \" dataSet outputDir (slice)\\n\\n\";\n exit(EXIT_FAILURE);\n }\n}\n\nint main(int argc, char const *argv[]) {\n using namespace boost::filesystem;\n \n \/\/ Verify the number of parameters in the command line\n checkUsage(argc, argv);\n \n \/\/ Process command line arguments\n Dirs::SetDataSet(argv[1]);\n Dirs::SetOutputDirName(argv[2]);\n vector< string > LoResFileNames, HiResFileNames;\n if( argc >= 4)\n {\n LoResFileNames.push_back(Dirs::BlockDir() + argv[3]);\n HiResFileNames.push_back(Dirs::SliceDir() + argv[3]);\n }\n else\n {\n LoResFileNames = getFilePaths(Dirs::BlockDir(), Dirs::SliceFile());\n HiResFileNames = getFilePaths(Dirs::SliceDir(), Dirs::SliceFile());\n }\n \n \/\/ initialise stack objects with correct spacings, sizes etc\n typedef Stack< float, itk::ResampleImageFilter, itk::LinearInterpolateImageFunction > StackType;\n StackType::SliceVectorType LoResImages = readImages< StackType >(LoResFileNames);\n StackType::SliceVectorType HiResImages = readImages< StackType >(HiResFileNames);\n normalizeImages< StackType >(LoResImages);\n normalizeImages< StackType >(HiResImages);\n boost::shared_ptr< StackType > LoResStack = InitializeLoResStack(LoResImages);\n boost::shared_ptr< StackType > HiResStack = InitializeHiResStack(HiResImages);\n \n \/\/ Assert stacks have the same number of slices\n assert(LoResStack->GetSize() == HiResStack->GetSize());\n \n \/\/ initialize stacks' transforms so that 2D images line up at their centres.\n StackTransforms::InitializeWithTranslation( *LoResStack, StackTransforms::GetLoResTranslation(\"whole_heart\") );\n ApplyAdjustments( *LoResStack, LoResFileNames, Dirs::ConfigDir() + \"LoRes_adjustments\/\");\n StackTransforms::InitializeToCommonCentre( *HiResStack );\n StackTransforms::SetMovingStackCenterWithFixedStack( *LoResStack, *HiResStack );\n \n \/\/ create output dir before write operations\n create_directory( Dirs::ResultsDir() );\n \n \/\/ Generate fixed images to register against\n LoResStack->updateVolumes();\n if( argc < 4)\n {\n writeImage< StackType::VolumeType >( LoResStack->GetVolume(), Dirs::ResultsDir() + \"LoResStack.mha\" );\n }\n \n \/\/ initialise registration framework\n typedef RegistrationBuilder< StackType > RegistrationBuilderType;\n RegistrationBuilderType registrationBuilder;\n RegistrationBuilderType::RegistrationType::Pointer registration = registrationBuilder.GetRegistration();\n StackAligner< StackType > stackAligner(*LoResStack, *HiResStack, registration);\n \n \/\/ Scale parameter space\n OptimizerConfig::SetOptimizerScalesForCenteredRigid2DTransform( registration->GetOptimizer() );\n \n \/\/ Add time and memory probes\n itkProbesCreate();\n \n \/\/ perform centered rigid 2D registration on each pair of slices\n itkProbesStart( \"Aligning stacks\" );\n stackAligner.Update();\n itkProbesStop( \"Aligning stacks\" );\n \n \/\/ Report the time and memory taken by the registration\n itkProbesReport( std::cout );\n \n \/\/ write rigid transforms\n if( argc < 4)\n {\n HiResStack->updateVolumes();\n writeImage< StackType::VolumeType >( HiResStack->GetVolume(), Dirs::ResultsDir() + \"HiResRigidStack.mha\" );\n \/\/ writeImage< StackType::MaskVolumeType >( HiResStack->Get3DMask()->GetImage(), Dirs::ResultsDir() + \"HiResRigidMask.mha\" );\n }\n StackTransforms::InitializeFromCurrentTransforms< StackType, itk::CenteredSimilarity2DTransform< double > >(*HiResStack);\n \n \/\/ Scale parameter space\n OptimizerConfig::SetOptimizerScalesForCenteredSimilarity2DTransform( registration->GetOptimizer() );\n \n \/\/ perform similarity rigid 2D registration\n stackAligner.Update();\n \n \/\/ write similarity transforms\n if(argc < 4)\n {\n HiResStack->updateVolumes();\n writeImage< StackType::VolumeType >( HiResStack->GetVolume(), Dirs::ResultsDir() + \"HiResSimilarityStack.mha\" );\n }\n \n \/\/ repeat registration with affine transform\n StackTransforms::InitializeFromCurrentTransforms< StackType, itk::CenteredAffineTransform< double, 2 > >(*HiResStack);\n OptimizerConfig::SetOptimizerScalesForCenteredAffineTransform( registration->GetOptimizer() );\n stackAligner.Update();\n \n if(argc < 4)\n {\n HiResStack->updateVolumes();\n writeImage< StackType::VolumeType >( HiResStack->GetVolume(), Dirs::ResultsDir() + \"HiResAffineStack.mha\" );\n \/\/ writeImage< StackType::MaskVolumeType >( HiResStack->Get3DMask()->GetImage(), Dirs::ResultsDir() + \"HiResAffineMask.mha\" );\n }\n \n \/\/ Update LoRes as the masks might have shrunk\n LoResStack->updateVolumes();\n \n \/\/ persist mask numberOfTimesTooBig\n saveNumberOfTimesTooBig(*HiResStack, Dirs::ResultsDir() + \"numberOfTimesTooBig.txt\");\n \n \/\/ write transforms to directories labeled by both ds ratios\n create_directory(Dirs::LoResTransformsDir());\n create_directory(Dirs::HiResTransformsDir());\n Save(*LoResStack, LoResFileNames, Dirs::LoResTransformsDir());\n Save(*HiResStack, HiResFileNames, Dirs::HiResTransformsDir());\n \n return EXIT_SUCCESS;\n}\nBuildVolumes uses boost::program_options.#include \"boost\/filesystem.hpp\"\n#include \"boost\/program_options.hpp\"\n\n#include \n#include \"itkCenteredSimilarity2DTransform.h\"\n\n\/\/ my files\n#include \"Stack.hpp\"\n#include \"NormalizeImages.hpp\"\n#include \"StackInitializers.hpp\"\n#include \"RegistrationBuilder.hpp\"\n#include \"StackAligner.hpp\"\n#include \"StackIOHelpers.hpp\"\n#include \"IOHelpers.hpp\"\n#include \"Dirs.hpp\"\n#include \"Parameters.hpp\"\n#include \"StackTransforms.hpp\"\n#include \"OptimizerConfig.hpp\"\n#include \"Profiling.hpp\"\n\n\nnamespace po = boost::program_options;\nusing namespace boost::filesystem;\n\npo::variables_map parse_arguments(int argc, char *argv[])\n{\n \/\/ Declare the supported options.\n po::options_description opts(\"Options\");\n opts.add_options()\n (\"help,h\", \"produce help message\")\n (\"dataSet\", po::value(), \"which rat to use\")\n (\"outputDir\", po::value(), \"directory to place results\")\n (\"slice\", po::value(), \"optional individual slice to register\")\n ;\n \n po::positional_options_description p;\n p.add(\"dataSet\", 1)\n .add(\"outputDir\", 1)\n .add(\"slice\", 1);\n \n \/\/ parse command line\n po::variables_map vm;\n\ttry\n\t{\n po::store(po::command_line_parser(argc, argv)\n .options(opts)\n .positional(p)\n .run(),\n vm);\n\t}\n\tcatch (std::exception& e)\n\t{\n\t cerr << \"caught command-line parsing error\" << endl;\n std::cerr << e.what() << std::endl;\n exit(EXIT_FAILURE);\n }\n po::notify(vm);\n \n \/\/ if help is specified, or positional args aren't present\n if (vm.count(\"help\") || !vm.count(\"dataSet\") || !vm.count(\"outputDir\")) {\n cerr << \"Usage: \"\n << argv[0] << \" [--dataSet=]RatX [--outputDir=]my_dir\"\n << \" [[--slice=]0530.bmp] [Options]\"\n << endl << endl;\n cerr << opts << \"\\n\";\n exit(EXIT_FAILURE);\n }\n \n return vm;\n}\n\nint main(int argc, char *argv[]) {\n \n \/\/ Parse command line arguments\n po::variables_map vm = parse_arguments(argc, argv);\n \n \/\/ Process command line arguments\n Dirs::SetDataSet( vm[\"dataSet\"].as() );\n Dirs::SetOutputDirName( vm[\"outputDir\"].as() );\n \n vector< string > LoResFileNames, HiResFileNames;\n if( vm.count(\"slice\") )\n {\n LoResFileNames.push_back(Dirs::BlockDir() + vm[\"slice\"].as());\n HiResFileNames.push_back(Dirs::SliceDir() + vm[\"slice\"].as());\n }\n else\n {\n LoResFileNames = getFilePaths(Dirs::BlockDir(), Dirs::SliceFile());\n HiResFileNames = getFilePaths(Dirs::SliceDir(), Dirs::SliceFile());\n }\n \n \/\/ initialise stack objects with correct spacings, sizes etc\n typedef Stack< float, itk::ResampleImageFilter, itk::LinearInterpolateImageFunction > StackType;\n StackType::SliceVectorType LoResImages = readImages< StackType >(LoResFileNames);\n StackType::SliceVectorType HiResImages = readImages< StackType >(HiResFileNames);\n normalizeImages< StackType >(LoResImages);\n normalizeImages< StackType >(HiResImages);\n boost::shared_ptr< StackType > LoResStack = InitializeLoResStack(LoResImages);\n boost::shared_ptr< StackType > HiResStack = InitializeHiResStack(HiResImages);\n \n \/\/ Assert stacks have the same number of slices\n assert(LoResStack->GetSize() == HiResStack->GetSize());\n \n \/\/ initialize stacks' transforms so that 2D images line up at their centres.\n StackTransforms::InitializeWithTranslation( *LoResStack, StackTransforms::GetLoResTranslation(\"whole_heart\") );\n ApplyAdjustments( *LoResStack, LoResFileNames, Dirs::ConfigDir() + \"LoRes_adjustments\/\");\n StackTransforms::InitializeToCommonCentre( *HiResStack );\n StackTransforms::SetMovingStackCenterWithFixedStack( *LoResStack, *HiResStack );\n \n \/\/ create output dir before write operations\n create_directory( Dirs::ResultsDir() );\n \n \/\/ Generate fixed images to register against\n LoResStack->updateVolumes();\n if( vm.count(\"slice\") )\n {\n writeImage< StackType::VolumeType >( LoResStack->GetVolume(), Dirs::ResultsDir() + \"LoResStack.mha\" );\n }\n \n \/\/ initialise registration framework\n typedef RegistrationBuilder< StackType > RegistrationBuilderType;\n RegistrationBuilderType registrationBuilder;\n RegistrationBuilderType::RegistrationType::Pointer registration = registrationBuilder.GetRegistration();\n StackAligner< StackType > stackAligner(*LoResStack, *HiResStack, registration);\n \n \/\/ Scale parameter space\n OptimizerConfig::SetOptimizerScalesForCenteredRigid2DTransform( registration->GetOptimizer() );\n \n \/\/ Add time and memory probes\n itkProbesCreate();\n \n \/\/ perform centered rigid 2D registration on each pair of slices\n itkProbesStart( \"Aligning stacks\" );\n stackAligner.Update();\n itkProbesStop( \"Aligning stacks\" );\n \n \/\/ Report the time and memory taken by the registration\n itkProbesReport( std::cout );\n \n \/\/ write rigid transforms\n if( vm.count(\"slice\") )\n {\n HiResStack->updateVolumes();\n writeImage< StackType::VolumeType >( HiResStack->GetVolume(), Dirs::ResultsDir() + \"HiResRigidStack.mha\" );\n \/\/ writeImage< StackType::MaskVolumeType >( HiResStack->Get3DMask()->GetImage(), Dirs::ResultsDir() + \"HiResRigidMask.mha\" );\n }\n StackTransforms::InitializeFromCurrentTransforms< StackType, itk::CenteredSimilarity2DTransform< double > >(*HiResStack);\n \n \/\/ Scale parameter space\n OptimizerConfig::SetOptimizerScalesForCenteredSimilarity2DTransform( registration->GetOptimizer() );\n \n \/\/ perform similarity rigid 2D registration\n stackAligner.Update();\n \n \/\/ write similarity transforms\n if( vm.count(\"slice\") )\n {\n HiResStack->updateVolumes();\n writeImage< StackType::VolumeType >( HiResStack->GetVolume(), Dirs::ResultsDir() + \"HiResSimilarityStack.mha\" );\n }\n \n \/\/ repeat registration with affine transform\n StackTransforms::InitializeFromCurrentTransforms< StackType, itk::CenteredAffineTransform< double, 2 > >(*HiResStack);\n OptimizerConfig::SetOptimizerScalesForCenteredAffineTransform( registration->GetOptimizer() );\n stackAligner.Update();\n \n if( vm.count(\"slice\") )\n {\n HiResStack->updateVolumes();\n writeImage< StackType::VolumeType >( HiResStack->GetVolume(), Dirs::ResultsDir() + \"HiResAffineStack.mha\" );\n \/\/ writeImage< StackType::MaskVolumeType >( HiResStack->Get3DMask()->GetImage(), Dirs::ResultsDir() + \"HiResAffineMask.mha\" );\n }\n \n \/\/ Update LoRes as the masks might have shrunk\n LoResStack->updateVolumes();\n \n \/\/ persist mask numberOfTimesTooBig\n saveNumberOfTimesTooBig(*HiResStack, Dirs::ResultsDir() + \"numberOfTimesTooBig.txt\");\n \n \/\/ write transforms to directories labeled by both ds ratios\n create_directory(Dirs::LoResTransformsDir());\n create_directory(Dirs::HiResTransformsDir());\n Save(*LoResStack, LoResFileNames, Dirs::LoResTransformsDir());\n Save(*HiResStack, HiResFileNames, Dirs::HiResTransformsDir());\n \n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"\/*\n * main.cpp\n * Copyright (C) 2015 Chris Waltrip \n *\n * This file is part of EvoComp-SantaFe\n *\n * EvoComp-SantaFe is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * EvoComp-SantaFe is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with EvoComp-SantaFe. If not, see .\n *\/\n\/**\n * Source file containing the overall execution of the genetic program.\n * Reads in command line arguments from the user including a map file to be\n * used as a test for the Ant. It then creates a population of potential\n * solutions, runs the evolution process and writes the results to file.\n *\n * @file\n * @date 23 November 2015\n *\n * @todo\tDetermine how and where to store Ant's position data.\n *\/\n\n#include \n#include \n#include \n#include \n#include \"trail_map.h\"\nnamespace po = boost::program_options;\n\n\/**\n * Reads command line arguments for the program. Certain arguments will cause\n * the execution of the program to halt, e.g. `--help` or `--input` with an\n * an invalid filename.\n * @param[in]\targc\tNumber of items in argv.\n * @param[in]\targv\tList of command line arguments.\n * @return\tReturns the filenames as a `std::vector`.\n * @todo\tAllow for some maps to be withheld as a final test (after \n *\t\t\tevolution is complete) to test the bias of the genetic program \n *\t\t\ttowards a specialized solution versus a generalized solution.\n *\/\n std::vector ParseCommandLine(int argc, char **argv);\n \/**\n * Returns the utility usage syntax.\n * @param[in]\tprogram_name\tName of the exectued program (i.e, argv[0]).\n * @return\tReturns a `std::string` of usage details with the name of the \n *\t\t\tcalling program inserted into the string.\n *\/\n std::string GetUsageString(std::string program_name);\n \/** \n * Returns a vector of the lines in the given file. This is passed to the\n * TrailMap to construct a new map object.\n * @param[in]\tfilename\tName of the file to parse.\n * @return\tReturns a `std::vector` containing the\n *\t\t\tcontents of the file read in.\n *\/\nstd::vector ParseDataFile(std::string filename);\n\/** \n * Returns string representation of map.\n * @param[in]\tmap\t\tMap to print.\n * @param[in]\tlatex\tAdd LaTeX wrappings or not.\n * @return\tReturns a `std::string` containing contents of the map.\n *\/\nstd::string PrintMap(std::vector> map, bool latex);\n\nint main(int argc, char **argv, char **envp) {\n\t\/* Genetic Program Constants *\/\n\tconst size_t kEvolutionCount = 1000;\n\tconst size_t kElitismCount = 2;\n\n\t\/* Map Constants *\/\n\tconst size_t kStepLimit = 300;\n\n\t\/* Population Constants *\/\n\tconst size_t kPopulationSize = 100;\n\tconst double kMutationRate = 0.03;\n\tconst double kNonterminalCrossoverRate = 0.90;\n\tconst size_t kTournamentSize = 3;\n\n\t\/* Individual\/Node Constants *\/\n\tconst size_t kTreeDepthMin = 3;\n\tconst size_t kTreeDepthMax = 6;\n\n\t\n\tstd::vector files = ParseCommandLine(argc, argv);\n\tfor (std::string f : files) {\n\t\tTrailMap map(ParseDataFile(f), kStepLimit);\n\t\tstd::cout << map.ToString(false) << std::endl << std::endl << std::endl;\n\t}\n\n\treturn 0;\n}\nstd::vector ParseCommandLine(int argc, char **argv) {\n\t\/* Vector to hold return values *\/\n\tstd::vector filenames;\n\n\t\/* Parse Command Line arguments and return filename string *\/\n\tpo::options_description opts(\"Options\");\n\topts.add_options()\n\t\t(\"help,h\", \"print this help and exit\")\n\t\t(\"verbose,v\", \"print extra logging information\")\n\t\t(\"input,i\", po::value>(),\n\t\t \"specify input file(s)\");\n\tpo::positional_options_description positional_opts;\n\tpositional_opts.add(\"input\", -1);\n\n\tpo::variables_map vm;\n\tpo::store(po::command_line_parser(argc, argv).options(opts)\n\t\t\t .positional(positional_opts).run(), vm);\n\tpo::notify(vm);\n\n\tif (vm.count(\"help\")) {\n\t\tstd::cout << GetUsageString(std::string(argv[0])) << std::endl;\n\t\tstd::cout << opts << std::endl;\n\t\texit(EXIT_SUCCESS);\n\t}\n\n\tif (!vm.count(\"verbose\")) {\n\t\tstd::clog.rdbuf(nullptr);\n\t}\n\n\tif (vm.count(\"input\")) {\n\t\tfilenames = vm[\"input\"].as>();\n\t\tfor (auto fn : filenames) {\n\t\t\tif (!(std::ifstream(fn).good())) {\n\t\t\t\tstd::cerr << fn << \" not found!\" << std::endl;\n\t\t\t\texit(EXIT_FAILURE);\n\t\t\t}\n\t\t}\n\t} else {\n\t\tstd::cerr << \"Please specify input files\" << std::endl;\n\t\tstd::cerr << GetUsageString(std::string(argv[0])) << std::endl;\n\t\tstd::cerr << opts << std::endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\treturn filenames;\n}\nstd::string GetUsageString(std::string program_name) {\n\tsize_t found = program_name.find_last_of(\"\/\\\\\");\n\tstd::string usage = \"Usage: \" + program_name.substr(found + 1);\n\tusage += \" [options] input_file_1 [input_file_2...]\";\n\n\treturn usage;\n}\nstd::vector ParseDataFile(std::string filename) {\n\tstd::ifstream inf;\n\tstd::string line;\n\tstd::vector map_file_contents;\n\n\tinf.open(filename);\n\tif (!inf) {\n\t\tstd::cerr << \"Failed to open file: \" << filename << std::endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\t\/* Parse input file *\/\n\twhile (std::getline(inf, line)) {\n\t\tmap_file_contents.push_back(line);\n\t}\n\treturn map_file_contents;\n}\nstd::string PrintMap(TrailMap map, bool latex) {\n\treturn map.ToString(latex);\n}Small meaningless changes to the main file.\/*\n * main.cpp\n * Copyright (C) 2015 Chris Waltrip \n *\n * This file is part of EvoComp-SantaFe\n *\n * EvoComp-SantaFe is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * EvoComp-SantaFe is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with EvoComp-SantaFe. If not, see .\n *\/\n\/**\n * Source file containing the overall execution of the genetic program.\n * Reads in command line arguments from the user including a map file to be\n * used as a test for the Ant. It then creates a population of potential\n * solutions, runs the evolution process and writes the results to file.\n *\n * @file\n * @date 23 November 2015\n *\n * @todo\tDetermine how and where to store Ant's position data.\n *\/\n\n#include \n#include \n#include \n#include \n#include \"trail_map.h\"\nnamespace po = boost::program_options;\n\n\/**\n * Reads command line arguments for the program. Certain arguments will cause\n * the execution of the program to halt, e.g. `--help` or `--input` with an\n * an invalid filename.\n * @param[in]\targc\tNumber of items in argv.\n * @param[in]\targv\tList of command line arguments.\n * @return\tReturns the filenames as a `std::vector`.\n * @todo\tAllow for some maps to be withheld as a final test (after \n *\t\t\tevolution is complete) to test the bias of the genetic program \n *\t\t\ttowards a specialized solution versus a generalized solution.\n *\/\n std::vector ParseCommandLine(int argc, char **argv);\n \/**\n * Returns the utility usage syntax.\n * @param[in]\tprogram_name\tName of the exectued program (i.e, argv[0]).\n * @return\tReturns a `std::string` of usage details with the name of the \n *\t\t\tcalling program inserted into the string.\n *\/\n std::string GetUsageString(std::string program_name);\n \/** \n * Returns a vector of the lines in the given file. This is passed to the\n * TrailMap to construct a new map object.\n * @param[in]\tfilename\tName of the file to parse.\n * @return\tReturns a `std::vector` containing the\n *\t\t\tcontents of the file read in.\n *\/\nstd::vector ParseDataFile(std::string filename);\n\/** \n * Returns string representation of map.\n * @param[in]\tmap\t\tMap to print.\n * @param[in]\tlatex\tAdd LaTeX wrappings or not.\n * @return\tReturns a `std::string` containing contents of the map.\n *\/\nstd::string PrintMap(std::vector> map, bool latex);\n\nint main(int argc, char **argv, char **envp) {\n\t\/* Genetic Program Constants *\/\n\tconst size_t kEvolutionCount = 1000;\n\tconst size_t kElitismCount = 2;\n\n\t\/* Map Constants *\/\n\tconst size_t kStepLimit = 400;\n\n\t\/* Population Constants *\/\n\tconst size_t kPopulationSize = 100;\n\tconst double kMutationRate = 0.03;\n\tconst double kNonterminalCrossoverRate = 0.90;\n\tconst size_t kTournamentSize = 3;\n\n\t\/* Individual\/Node Constants *\/\n\tconst size_t kTreeDepthMin = 3;\n\tconst size_t kTreeDepthMax = 6;\n\n\t\n\tstd::vector files = ParseCommandLine(argc, argv);\n\tfor (std::string f : files) {\n\t\tTrailMap map(ParseDataFile(f), kStepLimit);\n\t\tstd::cout << PrintMap(map, false);\n\t\tstd::cout << std::endl << std::endl;\n\t}\n\n\treturn 0;\n}\nstd::vector ParseCommandLine(int argc, char **argv) {\n\t\/* Vector to hold return values *\/\n\tstd::vector filenames;\n\n\t\/* Parse Command Line arguments and return filename string *\/\n\tpo::options_description opts(\"Options\");\n\topts.add_options()\n\t\t(\"help,h\", \"print this help and exit\")\n\t\t(\"verbose,v\", \"print extra logging information\")\n\t\t(\"input,i\", po::value>(),\n\t\t \"specify input file(s)\");\n\tpo::positional_options_description positional_opts;\n\tpositional_opts.add(\"input\", -1);\n\n\tpo::variables_map vm;\n\tpo::store(po::command_line_parser(argc, argv).options(opts)\n\t\t\t .positional(positional_opts).run(), vm);\n\tpo::notify(vm);\n\n\tif (vm.count(\"help\")) {\n\t\tstd::cout << GetUsageString(std::string(argv[0])) << std::endl;\n\t\tstd::cout << opts << std::endl;\n\t\texit(EXIT_SUCCESS);\n\t}\n\n\tif (!vm.count(\"verbose\")) {\n\t\tstd::clog.rdbuf(nullptr);\n\t}\n\n\tif (vm.count(\"input\")) {\n\t\tfilenames = vm[\"input\"].as>();\n\t\tfor (auto fn : filenames) {\n\t\t\tif (!(std::ifstream(fn).good())) {\n\t\t\t\tstd::cerr << fn << \" not found!\" << std::endl;\n\t\t\t\texit(EXIT_FAILURE);\n\t\t\t}\n\t\t}\n\t} else {\n\t\tstd::cerr << \"Please specify input files\" << std::endl;\n\t\tstd::cerr << GetUsageString(std::string(argv[0])) << std::endl;\n\t\tstd::cerr << opts << std::endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\treturn filenames;\n}\nstd::string GetUsageString(std::string program_name) {\n\tsize_t found = program_name.find_last_of(\"\/\\\\\");\n\tstd::string usage = \"Usage: \" + program_name.substr(found + 1);\n\tusage += \" [options] input_file_1 [input_file_2...]\";\n\n\treturn usage;\n}\nstd::vector ParseDataFile(std::string filename) {\n\tstd::ifstream inf;\n\tstd::string line;\n\tstd::vector map_file_contents;\n\n\tinf.open(filename);\n\tif (!inf) {\n\t\tstd::cerr << \"Failed to open file: \" << filename << std::endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\t\/* Parse input file *\/\n\twhile (std::getline(inf, line)) {\n\t\tmap_file_contents.push_back(line);\n\t}\n\treturn map_file_contents;\n}\nstd::string PrintMap(TrailMap map, bool latex) {\n\treturn map.ToString(latex);\n}<|endoftext|>"} {"text":"#include \"occaTools.hpp\"\n#include \"occa.hpp\" \/\/ For kernelInfo\n\nnamespace occa {\n mutex_t::mutex_t(){\n#if (OCL_OS == OCL_LINUX_OS) || (OCL_OS == OCL_OSX_OS)\n int error = pthread_mutex_init(&mutexHandle, NULL);\n\n if(error){\n std::cout << \"Error initializing mutex\\n\";\n throw 1;\n }\n#else\n mutexHandle = CreateMutex(NULL, FALSE, NULL);\n#endif\n }\n\n void mutex_t::free(){\n#if (OCL_OS == OCL_LINUX_OS) || (OCL_OS == OCL_OSX_OS)\n int error = pthread_mutex_destroy(&mutexHandle);\n\n if(error){\n std::cout << \"Error freeing mutex\\n\";\n throw 1;\n }\n#else\n CloseHandle(mutexHandle);\n#endif\n }\n\n void mutex_t::lock(){\n#if (OCL_OS == OCL_LINUX_OS) || (OCL_OS == OCL_OSX_OS)\n pthread_mutex_lock(&mutexHandle);\n#else\n WaitForSingleObject(mutexHandle, INFINITE);\n#endif\n }\n\n void mutex_t::unlock(){\n#if (OCL_OS == OCL_LINUX_OS) || (OCL_OS == OCL_OSX_OS)\n pthread_mutex_unlock(&mutexHandle);\n#else\n ReleaseMutex(mutexHandle);\n#endif\n }\n\n double currentTime(){\n#if OCCA_OS == LINUX_OS\n\n timespec ct;\n clock_gettime(CLOCK_MONOTONIC, &ct);\n\n return (double) (ct.tv_sec + (1.0e-9 * ct.tv_nsec));\n\n#elif OCCA_OS == OSX_OS\n\n uint64_t ct;\n ct = mach_absolute_time();\n\n const Nanoseconds ct2 = AbsoluteToNanoseconds(*(AbsoluteTime *) &ct);\n\n return ((double) 1.0e-9) * ((double) ( *((uint64_t*) &ct2) ));\n\n#elif OCCA_OS == WINDOWS_OS\n LARGE_INTEGER timestamp, timerfreq;\n\n QueryPerformanceFrequency(&timerfreq);\n QueryPerformanceCounter(×tamp);\n\n return ((double) timestamp.QuadPart) \/ ((double) timerfreq.QuadPart);\n#endif\n }\n\n std::string getFileExtension(const std::string &filename){\n const char *c = filename.c_str();\n const char *i = NULL;\n\n while(*c != '\\0'){\n if(*c == '.')\n i = c;\n\n ++c;\n }\n\n if(i != NULL)\n return filename.substr(i - filename.c_str() + 1);\n\n return \"\";\n }\n\n void getFilePrefixAndName(const std::string &fullFilename,\n std::string &prefix,\n std::string &filename){\n int lastSlash = 0;\n const int chars = fullFilename.size();\n\n#if (OCCA_OS == LINUX_OS) || (OCCA_OS == OSX_OS)\n for(int i = 0; i < chars; ++i)\n if(fullFilename[i] == '\/')\n lastSlash = i;\n#else\n for(int i = 0; i < chars; ++i)\n if((fullFilename[i] == '\/') ||\n (fullFilename[i] == '\\\\'))\n lastSlash = i;\n#endif\n\n ++lastSlash;\n\n prefix = fullFilename.substr(0, lastSlash);\n filename = fullFilename.substr(lastSlash, chars - lastSlash);\n }\n\n std::string getMidCachedBinaryName(const std::string &cachedBinary,\n const std::string &namePrefix){\n std::string prefix, name;\n getFilePrefixAndName(cachedBinary, prefix, name);\n\n return (prefix + namePrefix + \"_\" + name);\n }\n\n std::string getFileLock(const std::string &filename){\n std::string prefix, name;\n getFilePrefixAndName(filename, prefix, name);\n\n return (prefix + \"._occa_dir_\" + name);\n }\n\n bool haveFile(const std::string &filename){\n std::string lockDir = getFileLock(filename);\n#if (OCCA_OS == LINUX_OS) || (OCCA_OS == OSX_OS)\n int mkdirStatus = mkdir(lockDir.c_str(), 0755);\n\n \/\/ Someone else is making it\n if(mkdirStatus && (errno == EEXIST))\n return false;\n\n return true;\n#else\n LPCSTR lockDirStr = lockDir.c_str();\n BOOL mkdirStatus = CreateDirectoryA(lockDirStr, NULL);\n\n if( mkdirStatus == FALSE) {\n assert(GetLastError() == ERROR_ALREADY_EXISTS);\n return false;\n }\n return true;\n#endif\n }\n\n void waitForFile(const std::string &filename){\n struct stat buffer;\n\n std::string lockDir = getFileLock(filename);\n const char *c_lockDir = lockDir.c_str();\n\n while(stat(c_lockDir, &buffer) == 0)\n \/* Do Nothing *\/;\n }\n\n void releaseFile(const std::string &filename){\n std::string lockDir = getFileLock(filename);\n#if (OCCA_OS == LINUX_OS) || (OCCA_OS == OSX_OS)\n rmdir(lockDir.c_str());\n#else\n BOOL retStatus = RemoveDirectoryA(lockDir.c_str());\n assert(retStatus == TRUE);\n#endif\n }\n\n parsedKernelInfo parseFileForFunction(const std::string &filename,\n const std::string &cachedBinary,\n const std::string &functionName,\n const kernelInfo &info){\n const std::string iCachedBinary = getMidCachedBinaryName(cachedBinary, \"i\");\n const std::string pCachedBinary = getMidCachedBinaryName(cachedBinary, \"p\");\n\n parser fileParser;\n\n std::ofstream fs;\n fs.open(pCachedBinary.c_str());\n\n fs << info.header << readFile(filename);\n\n fs.close();\n fs.clear();\n\n fs.open(iCachedBinary.c_str());\n fs << info.occaKeywords << fileParser.parseFile(pCachedBinary);\n\n fs.close();\n\n kernelInfoIterator kIt = fileParser.kernelInfoMap.find(functionName);\n\n if(kIt != fileParser.kernelInfoMap.end()){\n return parsedKernelInfo( *((kIt++)->second) );\n }\n\n std::cout << \"Could not find function [\"\n << functionName << \"] in file [\"\n << filename << \"].\\n\";\n throw 1;\n\n return parsedKernelInfo();\n }\n\n std::string fnv(const std::string &saltedString){\n const int len = saltedString.size();\n std::stringstream ss;\n\n int h[8] = {101527, 101531,\n 101533, 101537,\n 101561, 101573,\n 101581, 101599};\n\n const int p[8] = {102679, 102701,\n 102761, 102763,\n 102769, 102793,\n 102797, 102811};\n\n for(int c = 0; c < len; ++c)\n for(int i = 0; i < 8; ++i)\n h[i] = (h[i] * p[i]) ^ saltedString[c];\n\n \/\/ int h2[8];\n\n \/\/ for(int i = 0; i < 8; ++i)\n \/\/ h2[i] = ((h[0] & (0xFF << (8*i))) << (8*i + 0))\n \/\/ | ((h[1] & (0xFF << (8*i))) << (8*i + 1))\n \/\/ | ((h[2] & (0xFF << (8*i))) << (8*i + 2))\n \/\/ | ((h[3] & (0xFF << (8*i))) << (8*i + 3))\n \/\/ | ((h[4] & (0xFF << (8*i))) << (8*i + 4))\n \/\/ | ((h[5] & (0xFF << (8*i))) << (8*i + 5))\n \/\/ | ((h[6] & (0xFF << (8*i))) << (8*i + 6))\n \/\/ | ((h[7] & (0xFF << (8*i))) << (8*i + 7));\n\n for(int i = 0; i < 8; ++i)\n ss << std::hex << h[i];\n\n return ss.str();\n }\n\n bool fileExists(const std::string &filename){\n struct stat buffer;\n return (stat(filename.c_str(), &buffer) == 0);\n }\n\n std::string readFile(const std::string &filename){\n \/\/ NBN: handle EOL chars on Windows\n FILE *fp = fopen(filename.c_str(), \"r\");\n\n if(!fp){\n printf(\"Failed to open: %s\\n\", filename.c_str());\n throw 1;\n }\n\n struct stat statbuf;\n stat(filename.c_str(), &statbuf);\n\n const size_t nchars = statbuf.st_size;\n\n char *buffer = (char*) calloc(nchars + 1, sizeof(char));\n size_t nread = fread(buffer, sizeof(char), nchars, fp);\n\n buffer[nread] = '\\0';\n\n fclose(fp);\n\n std::string contents(buffer, nread);\n\n free(buffer);\n\n return contents;\n }\n\n std::string getOCCADir(){\n char *c_occaPath = getenv(\"OCCA_DIR\");\n\n if(c_occaPath != NULL)\n return c_occaPath;\n\n std::cout << \"Environment variable [OCCA_DIR] is not set.\\n\";\n throw 1;\n\n return \"\";\n }\n\n std::string getCachePath(){\n char *c_cachePath = getenv(\"OCCA_CACHE_DIR\");\n\n bool hasDir = false;\n\n std::string occaCachePath;\n\n if(c_cachePath != NULL)\n occaCachePath = c_cachePath;\n else{\n std::stringstream ss;\n#if (OCCA_OS == LINUX_OS) || (OCCA_OS == OSX_OS)\n char *c_home = getenv(\"HOME\");\n ss << c_home << \"\/._occa\";\n\n occaCachePath = ss.str();\n#else\n char *c_home = getenv(\"USERPROFILE\");\n\n ss << c_home << \"\\\\AppData\\\\Local\\\\OCCA\";\n\n# if OCCA_64_BIT\n ss << \"_amd64\"; \/\/ use different dir's fro 32 and 64 bit\n# else\n ss << \"_x86\"; \/\/ use different dir's fro 32 and 64 bit\n# endif\n\n occaCachePath = ss.str();\n#endif\n }\n\n const int chars = occaCachePath.size();\n\n OCCA_CHECK(0 < chars);\n\n#if (OCCA_OS == LINUX_OS) || (OCCA_OS == OSX_OS)\n const char slashChar = '\/';\n#else\n const char slashChar = '\\\\';\n#endif\n\n \/\/ Take out the pesky \/\/'s\n int pos = 0;\n\n for(int i = 0; i < chars; ++i){\n if(occaCachePath[i] == slashChar)\n while(i < (chars - 1) && occaCachePath[i + 1] == slashChar)\n ++i;\n\n occaCachePath[pos++] = occaCachePath[i];\n }\n\n if(occaCachePath[pos - 1] != slashChar){\n if(pos != chars)\n occaCachePath[pos] = slashChar;\n else\n occaCachePath += slashChar;\n }\n\n if(!fileExists(occaCachePath)){\n#if (OCCA_OS == LINUX_OS) || (OCCA_OS == OSX_OS)\n mkdir(occaCachePath.c_str(), 0755);\n#else\n LPCSTR w_occaCachePath = occaCachePath.c_str();\n BOOL mkdirStatus = CreateDirectoryA(w_occaCachePath, NULL);\n\n if(mkdirStatus == FALSE)\n assert(GetLastError() == ERROR_ALREADY_EXISTS);\n#endif\n }\n\n return occaCachePath;\n }\n\n bool fileNeedsParser(const std::string &filename){\n std::string ext = getFileExtension(filename);\n\n return ((ext == \"okl\") ||\n (ext == \"cl\") ||\n (ext == \"cu\"));\n }\n\n std::string getCachedName(const std::string &filename,\n const std::string &salt){\n\n std::string occaCachePath = getCachePath();\n \/\/================================\n\n const std::string fileContents = readFile(filename);\n const std::string contentsSHA = fnv(fileContents + salt);\n\n \/\/ Only taking the first 16 characters\n return occaCachePath + contentsSHA.substr(0, 16);\n }\n\n std::string createIntermediateSource(const std::string &filename,\n const std::string &cachedBinary,\n const kernelInfo &info){\n std::string prefix, name;\n getFilePrefixAndName(cachedBinary, prefix, name);\n\n const std::string iCachedBinary = prefix + \"i_\" + name;\n\n if(fileNeedsParser(filename)){\n const std::string pCachedBinary = prefix + \"p_\" + name;\n parser fileParser;\n\n std::ofstream fs;\n fs.open(pCachedBinary.c_str());\n\n fs << info.header << readFile(filename);\n\n fs.close();\n\n fs.open(iCachedBinary.c_str());\n fs << info.occaKeywords << fileParser.parseFile(pCachedBinary);\n\n fs.close();\n }\n else{\n std::ofstream fs;\n fs.open(iCachedBinary.c_str());\n\n fs << info.occaKeywords << info.header << readFile(filename);\n\n fs.close();\n }\n\n return iCachedBinary;\n }\n};\n[OCCA] Fixed file reading to include null-terminated chars (binaries)#include \"occaTools.hpp\"\n#include \"occa.hpp\" \/\/ For kernelInfo\n\nnamespace occa {\n mutex_t::mutex_t(){\n#if (OCL_OS == OCL_LINUX_OS) || (OCL_OS == OCL_OSX_OS)\n int error = pthread_mutex_init(&mutexHandle, NULL);\n\n if(error){\n std::cout << \"Error initializing mutex\\n\";\n throw 1;\n }\n#else\n mutexHandle = CreateMutex(NULL, FALSE, NULL);\n#endif\n }\n\n void mutex_t::free(){\n#if (OCL_OS == OCL_LINUX_OS) || (OCL_OS == OCL_OSX_OS)\n int error = pthread_mutex_destroy(&mutexHandle);\n\n if(error){\n std::cout << \"Error freeing mutex\\n\";\n throw 1;\n }\n#else\n CloseHandle(mutexHandle);\n#endif\n }\n\n void mutex_t::lock(){\n#if (OCL_OS == OCL_LINUX_OS) || (OCL_OS == OCL_OSX_OS)\n pthread_mutex_lock(&mutexHandle);\n#else\n WaitForSingleObject(mutexHandle, INFINITE);\n#endif\n }\n\n void mutex_t::unlock(){\n#if (OCL_OS == OCL_LINUX_OS) || (OCL_OS == OCL_OSX_OS)\n pthread_mutex_unlock(&mutexHandle);\n#else\n ReleaseMutex(mutexHandle);\n#endif\n }\n\n double currentTime(){\n#if OCCA_OS == LINUX_OS\n\n timespec ct;\n clock_gettime(CLOCK_MONOTONIC, &ct);\n\n return (double) (ct.tv_sec + (1.0e-9 * ct.tv_nsec));\n\n#elif OCCA_OS == OSX_OS\n\n uint64_t ct;\n ct = mach_absolute_time();\n\n const Nanoseconds ct2 = AbsoluteToNanoseconds(*(AbsoluteTime *) &ct);\n\n return ((double) 1.0e-9) * ((double) ( *((uint64_t*) &ct2) ));\n\n#elif OCCA_OS == WINDOWS_OS\n LARGE_INTEGER timestamp, timerfreq;\n\n QueryPerformanceFrequency(&timerfreq);\n QueryPerformanceCounter(×tamp);\n\n return ((double) timestamp.QuadPart) \/ ((double) timerfreq.QuadPart);\n#endif\n }\n\n std::string getFileExtension(const std::string &filename){\n const char *c = filename.c_str();\n const char *i = NULL;\n\n while(*c != '\\0'){\n if(*c == '.')\n i = c;\n\n ++c;\n }\n\n if(i != NULL)\n return filename.substr(i - filename.c_str() + 1);\n\n return \"\";\n }\n\n void getFilePrefixAndName(const std::string &fullFilename,\n std::string &prefix,\n std::string &filename){\n int lastSlash = 0;\n const int chars = fullFilename.size();\n\n#if (OCCA_OS == LINUX_OS) || (OCCA_OS == OSX_OS)\n for(int i = 0; i < chars; ++i)\n if(fullFilename[i] == '\/')\n lastSlash = i;\n#else\n for(int i = 0; i < chars; ++i)\n if((fullFilename[i] == '\/') ||\n (fullFilename[i] == '\\\\'))\n lastSlash = i;\n#endif\n\n ++lastSlash;\n\n prefix = fullFilename.substr(0, lastSlash);\n filename = fullFilename.substr(lastSlash, chars - lastSlash);\n }\n\n std::string getMidCachedBinaryName(const std::string &cachedBinary,\n const std::string &namePrefix){\n std::string prefix, name;\n getFilePrefixAndName(cachedBinary, prefix, name);\n\n return (prefix + namePrefix + \"_\" + name);\n }\n\n std::string getFileLock(const std::string &filename){\n std::string prefix, name;\n getFilePrefixAndName(filename, prefix, name);\n\n return (prefix + \"._occa_dir_\" + name);\n }\n\n bool haveFile(const std::string &filename){\n std::string lockDir = getFileLock(filename);\n#if (OCCA_OS == LINUX_OS) || (OCCA_OS == OSX_OS)\n int mkdirStatus = mkdir(lockDir.c_str(), 0755);\n\n \/\/ Someone else is making it\n if(mkdirStatus && (errno == EEXIST))\n return false;\n\n return true;\n#else\n LPCSTR lockDirStr = lockDir.c_str();\n BOOL mkdirStatus = CreateDirectoryA(lockDirStr, NULL);\n\n if( mkdirStatus == FALSE) {\n assert(GetLastError() == ERROR_ALREADY_EXISTS);\n return false;\n }\n return true;\n#endif\n }\n\n void waitForFile(const std::string &filename){\n struct stat buffer;\n\n std::string lockDir = getFileLock(filename);\n const char *c_lockDir = lockDir.c_str();\n\n while(stat(c_lockDir, &buffer) == 0)\n \/* Do Nothing *\/;\n }\n\n void releaseFile(const std::string &filename){\n std::string lockDir = getFileLock(filename);\n#if (OCCA_OS == LINUX_OS) || (OCCA_OS == OSX_OS)\n rmdir(lockDir.c_str());\n#else\n BOOL retStatus = RemoveDirectoryA(lockDir.c_str());\n assert(retStatus == TRUE);\n#endif\n }\n\n parsedKernelInfo parseFileForFunction(const std::string &filename,\n const std::string &cachedBinary,\n const std::string &functionName,\n const kernelInfo &info){\n const std::string iCachedBinary = getMidCachedBinaryName(cachedBinary, \"i\");\n const std::string pCachedBinary = getMidCachedBinaryName(cachedBinary, \"p\");\n\n parser fileParser;\n\n std::ofstream fs;\n fs.open(pCachedBinary.c_str());\n\n fs << info.header << readFile(filename);\n\n fs.close();\n fs.clear();\n\n fs.open(iCachedBinary.c_str());\n fs << info.occaKeywords << fileParser.parseFile(pCachedBinary);\n\n fs.close();\n\n kernelInfoIterator kIt = fileParser.kernelInfoMap.find(functionName);\n\n if(kIt != fileParser.kernelInfoMap.end()){\n return parsedKernelInfo( *((kIt++)->second) );\n }\n\n std::cout << \"Could not find function [\"\n << functionName << \"] in file [\"\n << filename << \"].\\n\";\n throw 1;\n\n return parsedKernelInfo();\n }\n\n std::string fnv(const std::string &saltedString){\n const int len = saltedString.size();\n std::stringstream ss;\n\n int h[8] = {101527, 101531,\n 101533, 101537,\n 101561, 101573,\n 101581, 101599};\n\n const int p[8] = {102679, 102701,\n 102761, 102763,\n 102769, 102793,\n 102797, 102811};\n\n for(int c = 0; c < len; ++c)\n for(int i = 0; i < 8; ++i)\n h[i] = (h[i] * p[i]) ^ saltedString[c];\n\n \/\/ int h2[8];\n\n \/\/ for(int i = 0; i < 8; ++i)\n \/\/ h2[i] = ((h[0] & (0xFF << (8*i))) << (8*i + 0))\n \/\/ | ((h[1] & (0xFF << (8*i))) << (8*i + 1))\n \/\/ | ((h[2] & (0xFF << (8*i))) << (8*i + 2))\n \/\/ | ((h[3] & (0xFF << (8*i))) << (8*i + 3))\n \/\/ | ((h[4] & (0xFF << (8*i))) << (8*i + 4))\n \/\/ | ((h[5] & (0xFF << (8*i))) << (8*i + 5))\n \/\/ | ((h[6] & (0xFF << (8*i))) << (8*i + 6))\n \/\/ | ((h[7] & (0xFF << (8*i))) << (8*i + 7));\n\n for(int i = 0; i < 8; ++i)\n ss << std::hex << h[i];\n\n return ss.str();\n }\n\n bool fileExists(const std::string &filename){\n struct stat buffer;\n return (stat(filename.c_str(), &buffer) == 0);\n }\n\n std::string readFile(const std::string &filename){\n \/\/ NBN: handle EOL chars on Windows\n FILE *fp = fopen(filename.c_str(), \"r\");\n\n if(!fp){\n printf(\"Failed to open: %s\\n\", filename.c_str());\n throw 1;\n }\n\n struct stat statbuf;\n stat(filename.c_str(), &statbuf);\n\n const size_t nchars = statbuf.st_size;\n\n char *buffer = (char*) calloc(nchars + 1, sizeof(char));\n size_t nread = fread(buffer, sizeof(char), nchars, fp);\n\n buffer[nread] = '\\0';\n\n fclose(fp);\n\n std::string contents(buffer, nread + 1);\n\n free(buffer);\n\n return contents;\n }\n\n std::string getOCCADir(){\n char *c_occaPath = getenv(\"OCCA_DIR\");\n\n if(c_occaPath != NULL)\n return c_occaPath;\n\n std::cout << \"Environment variable [OCCA_DIR] is not set.\\n\";\n throw 1;\n\n return \"\";\n }\n\n std::string getCachePath(){\n char *c_cachePath = getenv(\"OCCA_CACHE_DIR\");\n\n bool hasDir = false;\n\n std::string occaCachePath;\n\n if(c_cachePath != NULL)\n occaCachePath = c_cachePath;\n else{\n std::stringstream ss;\n#if (OCCA_OS == LINUX_OS) || (OCCA_OS == OSX_OS)\n char *c_home = getenv(\"HOME\");\n ss << c_home << \"\/._occa\";\n\n occaCachePath = ss.str();\n#else\n char *c_home = getenv(\"USERPROFILE\");\n\n ss << c_home << \"\\\\AppData\\\\Local\\\\OCCA\";\n\n# if OCCA_64_BIT\n ss << \"_amd64\"; \/\/ use different dir's fro 32 and 64 bit\n# else\n ss << \"_x86\"; \/\/ use different dir's fro 32 and 64 bit\n# endif\n\n occaCachePath = ss.str();\n#endif\n }\n\n const int chars = occaCachePath.size();\n\n OCCA_CHECK(0 < chars);\n\n#if (OCCA_OS == LINUX_OS) || (OCCA_OS == OSX_OS)\n const char slashChar = '\/';\n#else\n const char slashChar = '\\\\';\n#endif\n\n \/\/ Take out the pesky \/\/'s\n int pos = 0;\n\n for(int i = 0; i < chars; ++i){\n if(occaCachePath[i] == slashChar)\n while(i < (chars - 1) && occaCachePath[i + 1] == slashChar)\n ++i;\n\n occaCachePath[pos++] = occaCachePath[i];\n }\n\n if(occaCachePath[pos - 1] != slashChar){\n if(pos != chars)\n occaCachePath[pos] = slashChar;\n else\n occaCachePath += slashChar;\n }\n\n if(!fileExists(occaCachePath)){\n#if (OCCA_OS == LINUX_OS) || (OCCA_OS == OSX_OS)\n mkdir(occaCachePath.c_str(), 0755);\n#else\n LPCSTR w_occaCachePath = occaCachePath.c_str();\n BOOL mkdirStatus = CreateDirectoryA(w_occaCachePath, NULL);\n\n if(mkdirStatus == FALSE)\n assert(GetLastError() == ERROR_ALREADY_EXISTS);\n#endif\n }\n\n return occaCachePath;\n }\n\n bool fileNeedsParser(const std::string &filename){\n std::string ext = getFileExtension(filename);\n\n return ((ext == \"okl\") ||\n (ext == \"cl\") ||\n (ext == \"cu\"));\n }\n\n std::string getCachedName(const std::string &filename,\n const std::string &salt){\n\n std::string occaCachePath = getCachePath();\n \/\/================================\n\n const std::string fileContents = readFile(filename);\n const std::string contentsSHA = fnv(fileContents + salt);\n\n \/\/ Only taking the first 16 characters\n return occaCachePath + contentsSHA.substr(0, 16);\n }\n\n std::string createIntermediateSource(const std::string &filename,\n const std::string &cachedBinary,\n const kernelInfo &info){\n std::string prefix, name;\n getFilePrefixAndName(cachedBinary, prefix, name);\n\n const std::string iCachedBinary = prefix + \"i_\" + name;\n\n if(fileNeedsParser(filename)){\n const std::string pCachedBinary = prefix + \"p_\" + name;\n parser fileParser;\n\n std::ofstream fs;\n fs.open(pCachedBinary.c_str());\n\n fs << info.header << readFile(filename);\n\n fs.close();\n\n fs.open(iCachedBinary.c_str());\n fs << info.occaKeywords << fileParser.parseFile(pCachedBinary);\n\n fs.close();\n }\n else{\n std::ofstream fs;\n fs.open(iCachedBinary.c_str());\n\n fs << info.occaKeywords << info.header << readFile(filename);\n\n fs.close();\n }\n\n return iCachedBinary;\n }\n};\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2018 Bilibili, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Authors: Jiashun Zhu(zhujiashun@bilibili.com)\n\n#include \n#include \n#include \n#include \"brpc\/controller.h\" \/\/ Controller\n#include \"brpc\/server.h\" \/\/ Server\n#include \"brpc\/closure_guard.h\" \/\/ ClosureGuard\n#include \"brpc\/builtin\/prometheus_metrics_service.h\"\n#include \"brpc\/builtin\/common.h\"\n#include \"bvar\/bvar.h\"\n\nnamespace bvar {\nDECLARE_int32(bvar_latency_p1);\nDECLARE_int32(bvar_latency_p2);\nDECLARE_int32(bvar_latency_p3);\n}\n\nnamespace brpc {\n\n\/\/ This is a class that convert bvar result to prometheus output.\n\/\/ Currently the output only includes gauge and summary for two\n\/\/ reasons:\n\/\/ 1) We cannot tell gauge and counter just from name and what's\n\/\/ more counter is just another gauge.\n\/\/ 2) Histogram and summary is equivalent except that histogram\n\/\/ calculates quantiles in the server side.\nclass PrometheusMetricsDumper : public bvar::Dumper {\npublic:\n explicit PrometheusMetricsDumper(butil::IOBufBuilder* os,\n const std::string& server_prefix)\n : _os(os)\n , _server_prefix(server_prefix) {\n }\n\n bool dump(const std::string& name, const butil::StringPiece& desc) override;\n\nprivate:\n DISALLOW_COPY_AND_ASSIGN(PrometheusMetricsDumper);\n\n \/\/ Return true iff name ends with suffix output by LatencyRecorder.\n bool DumpLatencyRecorderSuffix(const butil::StringPiece& name,\n const butil::StringPiece& desc);\n\n \/\/ 6 is the number of bvars in LatencyRecorder that indicating percentiles\n static const int NPERCENTILES = 6;\n\n struct SummaryItems {\n std::string latency_percentiles[NPERCENTILES];\n std::string latency_avg;\n std::string count;\n std::string metric_name;\n };\n \/\/ Return true iff name ends with suffix output by LatencyRecorder.\n \/\/ If all bvars in LatencyRecorder have been gathered and are ready\n \/\/ to output a summary, *si_out is set properly.\n bool ProcessLatencyRecorderSuffix(const butil::StringPiece& name,\n const butil::StringPiece& desc,\n SummaryItems** si_out);\n\nprivate:\n butil::IOBufBuilder* _os;\n const std::string _server_prefix;\n std::map _m;\n};\n\nbool PrometheusMetricsDumper::dump(const std::string& name,\n const butil::StringPiece& desc) {\n if (!desc.empty() && desc[0] == '\"') {\n \/\/ there is no necessary to monitor string in prometheus\n return true;\n }\n if (DumpLatencyRecorderSuffix(name, desc)) {\n \/\/ Has encountered name with suffix exposed by LatencyRecorder,\n \/\/ Leave it to DumpLatencyRecorderSuffix to output Summary.\n return true;\n }\n *_os << \"# HELP \" << name << '\\n'\n << \"# TYPE \" << name << \" gauge\" << '\\n'\n << name << \" \" << desc << '\\n';\n return true;\n}\n\nbool PrometheusMetricsDumper::ProcessLatencyRecorderSuffix(\n const butil::StringPiece& name,\n const butil::StringPiece& desc,\n PrometheusMetricsDumper::SummaryItems** si_out) {\n static std::string latency_names[] = {\n butil::string_printf(\"_latency_%d\", (int)bvar::FLAGS_bvar_latency_p1),\n butil::string_printf(\"_latency_%d\", (int)bvar::FLAGS_bvar_latency_p2),\n butil::string_printf(\"_latency_%d\", (int)bvar::FLAGS_bvar_latency_p3),\n \"_latency_999\", \"_latency_9999\", \"_max_latency\"\n };\n CHECK(NPERCENTILES == arraysize(latency_names));\n butil::StringPiece metric_name(name);\n for (int i = 0; i < NPERCENTILES; ++i) {\n if (!metric_name.ends_with(latency_names[i])) {\n continue;\n }\n metric_name.remove_suffix(latency_names[i].size());\n SummaryItems* si = &_m[metric_name.as_string()];\n si->latency_percentiles[i] = desc.as_string();\n if (i == NPERCENTILES - 1) {\n \/\/ 'max_latency' is the last suffix name that appear in the sorted bvar\n \/\/ list, which means all related percentiles have been gathered and we are\n \/\/ ready to output a Summary.\n si->metric_name = metric_name.as_string();\n *si_out = si;\n }\n return true;\n }\n \/\/ Get the average of latency in recent window size\n if (metric_name.ends_with(\"_latency\")) {\n metric_name.remove_suffix(8);\n _m[metric_name.as_string()].latency_avg = desc.as_string();\n return true;\n }\n if (metric_name.ends_with(\"_count\")) {\n metric_name.remove_suffix(6);\n _m[metric_name.as_string()].count = desc.as_string();\n return true;\n }\n return false;\n}\n\nbool PrometheusMetricsDumper::DumpLatencyRecorderSuffix(\n const butil::StringPiece& name,\n const butil::StringPiece& desc) {\n if (!name.starts_with(_server_prefix)) {\n return false;\n }\n SummaryItems* si = NULL;\n if (!ProcessLatencyRecorderSuffix(name, desc, &si)) {\n return false;\n }\n if (!si) {\n return true;\n }\n *_os << \"# HELP \" << si->metric_name << '\\n'\n << \"# TYPE \" << si->metric_name << \" summary\\n\"\n << si->metric_name << \"{quantile=\\\"\"\n << (double)(bvar::FLAGS_bvar_latency_p1) \/ 100 << \"\\\"} \"\n << si->latency_percentiles[0] << '\\n'\n << si->metric_name << \"{quantile=\\\"\"\n << (double)(bvar::FLAGS_bvar_latency_p2) \/ 100 << \"\\\"} \"\n << si->latency_percentiles[1] << '\\n'\n << si->metric_name << \"{quantile=\\\"\"\n << (double)(bvar::FLAGS_bvar_latency_p3) \/ 100 << \"\\\"} \"\n << si->latency_percentiles[2] << '\\n'\n << si->metric_name << \"{quantile=\\\"0.999\\\"} \"\n << si->latency_percentiles[3] << '\\n'\n << si->metric_name << \"{quantile=\\\"0.9999\\\"} \"\n << si->latency_percentiles[4] << '\\n'\n << si->metric_name << \"{quantile=\\\"1\\\"} \"\n << si->latency_percentiles[5] << '\\n'\n << si->metric_name << \"_sum \"\n \/\/ There is no sum of latency in bvar output, just use\n \/\/ average * count as approximation\n << strtoll(si->latency_avg.data(), NULL, 10) *\n strtoll(si->count.data(), NULL, 10) << '\\n'\n << si->metric_name << \"_count \" << si->count << '\\n';\n return true;\n}\n\nvoid PrometheusMetricsService::default_method(::google::protobuf::RpcController* cntl_base,\n const ::brpc::MetricsRequest*,\n ::brpc::MetricsResponse*,\n ::google::protobuf::Closure* done) {\n ClosureGuard done_guard(done);\n Controller *cntl = static_cast(cntl_base);\n cntl->http_response().set_content_type(\"text\/plain\");\n butil::IOBufBuilder os;\n PrometheusMetricsDumper dumper(&os, _server->ServerPrefix());\n const int ndump = bvar::Variable::dump_exposed(&dumper, NULL);\n if (ndump < 0) {\n cntl->SetFailed(\"Fail to dump metrics\");\n return;\n }\n os.move_to(cntl->response_attachment());\n}\n\n} \/\/ namespace brpc\nadd IsComplete() to SummaryItems\/\/ Copyright (c) 2018 Bilibili, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Authors: Jiashun Zhu(zhujiashun@bilibili.com)\n\n#include \n#include \n#include \n#include \"brpc\/controller.h\" \/\/ Controller\n#include \"brpc\/server.h\" \/\/ Server\n#include \"brpc\/closure_guard.h\" \/\/ ClosureGuard\n#include \"brpc\/builtin\/prometheus_metrics_service.h\"\n#include \"brpc\/builtin\/common.h\"\n#include \"bvar\/bvar.h\"\n\nnamespace bvar {\nDECLARE_int32(bvar_latency_p1);\nDECLARE_int32(bvar_latency_p2);\nDECLARE_int32(bvar_latency_p3);\n}\n\nnamespace brpc {\n\n\/\/ This is a class that convert bvar result to prometheus output.\n\/\/ Currently the output only includes gauge and summary for two\n\/\/ reasons:\n\/\/ 1) We cannot tell gauge and counter just from name and what's\n\/\/ more counter is just another gauge.\n\/\/ 2) Histogram and summary is equivalent except that histogram\n\/\/ calculates quantiles in the server side.\nclass PrometheusMetricsDumper : public bvar::Dumper {\npublic:\n explicit PrometheusMetricsDumper(butil::IOBufBuilder* os,\n const std::string& server_prefix)\n : _os(os)\n , _server_prefix(server_prefix) {\n }\n\n bool dump(const std::string& name, const butil::StringPiece& desc) override;\n\nprivate:\n DISALLOW_COPY_AND_ASSIGN(PrometheusMetricsDumper);\n\n \/\/ Return true iff name ends with suffix output by LatencyRecorder.\n bool DumpLatencyRecorderSuffix(const butil::StringPiece& name,\n const butil::StringPiece& desc);\n\n \/\/ 6 is the number of bvars in LatencyRecorder that indicating percentiles\n static const int NPERCENTILES = 6;\n\n struct SummaryItems {\n std::string latency_percentiles[NPERCENTILES];\n std::string latency_avg;\n std::string count;\n std::string metric_name;\n\n bool IsComplete() const { return !metric_name.empty(); }\n };\n const SummaryItems* ProcessLatencyRecorderSuffix(const butil::StringPiece& name,\n const butil::StringPiece& desc);\n\nprivate:\n butil::IOBufBuilder* _os;\n const std::string _server_prefix;\n std::map _m;\n};\n\nbool PrometheusMetricsDumper::dump(const std::string& name,\n const butil::StringPiece& desc) {\n if (!desc.empty() && desc[0] == '\"') {\n \/\/ there is no necessary to monitor string in prometheus\n return true;\n }\n if (DumpLatencyRecorderSuffix(name, desc)) {\n \/\/ Has encountered name with suffix exposed by LatencyRecorder,\n \/\/ Leave it to DumpLatencyRecorderSuffix to output Summary.\n return true;\n }\n *_os << \"# HELP \" << name << '\\n'\n << \"# TYPE \" << name << \" gauge\" << '\\n'\n << name << \" \" << desc << '\\n';\n return true;\n}\n\nconst PrometheusMetricsDumper::SummaryItems*\nPrometheusMetricsDumper::ProcessLatencyRecorderSuffix(const butil::StringPiece& name,\n const butil::StringPiece& desc) {\n static std::string latency_names[] = {\n butil::string_printf(\"_latency_%d\", (int)bvar::FLAGS_bvar_latency_p1),\n butil::string_printf(\"_latency_%d\", (int)bvar::FLAGS_bvar_latency_p2),\n butil::string_printf(\"_latency_%d\", (int)bvar::FLAGS_bvar_latency_p3),\n \"_latency_999\", \"_latency_9999\", \"_max_latency\"\n };\n CHECK(NPERCENTILES == arraysize(latency_names));\n butil::StringPiece metric_name(name);\n for (int i = 0; i < NPERCENTILES; ++i) {\n if (!metric_name.ends_with(latency_names[i])) {\n continue;\n }\n metric_name.remove_suffix(latency_names[i].size());\n SummaryItems* si = &_m[metric_name.as_string()];\n si->latency_percentiles[i] = desc.as_string();\n if (i == NPERCENTILES - 1) {\n \/\/ '_max_latency' is the last suffix name that appear in the sorted bvar\n \/\/ list, which means all related percentiles have been gathered and we are\n \/\/ ready to output a Summary.\n si->metric_name = metric_name.as_string();\n }\n return si;\n }\n \/\/ Get the average of latency in recent window size\n if (metric_name.ends_with(\"_latency\")) {\n metric_name.remove_suffix(8);\n SummaryItems* si = &_m[metric_name.as_string()];\n si->latency_avg = desc.as_string();\n return si;\n }\n if (metric_name.ends_with(\"_count\")) {\n metric_name.remove_suffix(6);\n SummaryItems* si = &_m[metric_name.as_string()];\n si->count = desc.as_string();\n return si;\n }\n return NULL;\n}\n\nbool PrometheusMetricsDumper::DumpLatencyRecorderSuffix(\n const butil::StringPiece& name,\n const butil::StringPiece& desc) {\n if (!name.starts_with(_server_prefix)) {\n return false;\n }\n const SummaryItems* si = ProcessLatencyRecorderSuffix(name, desc);\n if (!si) {\n return false;\n }\n if (!si->IsComplete()) {\n return true;\n }\n *_os << \"# HELP \" << si->metric_name << '\\n'\n << \"# TYPE \" << si->metric_name << \" summary\\n\"\n << si->metric_name << \"{quantile=\\\"\"\n << (double)(bvar::FLAGS_bvar_latency_p1) \/ 100 << \"\\\"} \"\n << si->latency_percentiles[0] << '\\n'\n << si->metric_name << \"{quantile=\\\"\"\n << (double)(bvar::FLAGS_bvar_latency_p2) \/ 100 << \"\\\"} \"\n << si->latency_percentiles[1] << '\\n'\n << si->metric_name << \"{quantile=\\\"\"\n << (double)(bvar::FLAGS_bvar_latency_p3) \/ 100 << \"\\\"} \"\n << si->latency_percentiles[2] << '\\n'\n << si->metric_name << \"{quantile=\\\"0.999\\\"} \"\n << si->latency_percentiles[3] << '\\n'\n << si->metric_name << \"{quantile=\\\"0.9999\\\"} \"\n << si->latency_percentiles[4] << '\\n'\n << si->metric_name << \"{quantile=\\\"1\\\"} \"\n << si->latency_percentiles[5] << '\\n'\n << si->metric_name << \"_sum \"\n \/\/ There is no sum of latency in bvar output, just use\n \/\/ average * count as approximation\n << strtoll(si->latency_avg.data(), NULL, 10) *\n strtoll(si->count.data(), NULL, 10) << '\\n'\n << si->metric_name << \"_count \" << si->count << '\\n';\n return true;\n}\n\nvoid PrometheusMetricsService::default_method(::google::protobuf::RpcController* cntl_base,\n const ::brpc::MetricsRequest*,\n ::brpc::MetricsResponse*,\n ::google::protobuf::Closure* done) {\n ClosureGuard done_guard(done);\n Controller *cntl = static_cast(cntl_base);\n cntl->http_response().set_content_type(\"text\/plain\");\n butil::IOBufBuilder os;\n PrometheusMetricsDumper dumper(&os, _server->ServerPrefix());\n const int ndump = bvar::Variable::dump_exposed(&dumper, NULL);\n if (ndump < 0) {\n cntl->SetFailed(\"Fail to dump metrics\");\n return;\n }\n os.move_to(cntl->response_attachment());\n}\n\n} \/\/ namespace brpc\n<|endoftext|>"} {"text":"\/\/ Copyright 2014 BVLC and contributors.\n\n#include \n#include \n#include \n\n#include \"gtest\/gtest.h\"\n#include \"caffe\/common.hpp\"\n#include \"caffe\/syncedmem.hpp\"\n#include \"caffe\/util\/math_functions.hpp\"\n#include \"caffe\/test\/test_caffe_main.hpp\"\n\nnamespace caffe {\n\ntemplate \nclass RandomNumberGeneratorTest : public ::testing::Test {\n public:\n virtual ~RandomNumberGeneratorTest() {}\n\n Dtype sample_mean(const Dtype* const seqs, const size_t sample_size) {\n double sum = 0;\n for (int i = 0; i < sample_size; ++i) {\n sum += seqs[i];\n }\n return sum \/ sample_size;\n }\n\n Dtype sample_mean(const int* const seqs, const size_t sample_size) {\n Dtype sum = 0;\n for (int i = 0; i < sample_size; ++i) {\n sum += Dtype(seqs[i]);\n }\n return sum \/ sample_size;\n }\n\n Dtype mean_bound(const Dtype std, const size_t sample_size) {\n return std\/sqrt(static_cast(sample_size));\n }\n};\n\n\ntypedef ::testing::Types Dtypes;\nTYPED_TEST_CASE(RandomNumberGeneratorTest, Dtypes);\n\n\nTYPED_TEST(RandomNumberGeneratorTest, TestRngGaussian) {\n size_t sample_size = 10000;\n SyncedMemory data_a(sample_size * sizeof(TypeParam));\n Caffe::set_random_seed(1701);\n TypeParam mu = 0;\n TypeParam sigma = 1;\n caffe_vRngGaussian(sample_size,\n reinterpret_cast(data_a.mutable_cpu_data()), mu, sigma);\n TypeParam true_mean = mu;\n TypeParam true_std = sigma;\n TypeParam bound = this->mean_bound(true_std, sample_size);\n TypeParam empirical_mean =\n this->sample_mean(reinterpret_cast(data_a.cpu_data()),\n sample_size);\n EXPECT_NEAR(empirical_mean, true_mean, bound);\n}\n\n\nTYPED_TEST(RandomNumberGeneratorTest, TestRngUniform) {\n size_t sample_size = 10000;\n SyncedMemory data_a(sample_size * sizeof(TypeParam));\n Caffe::set_random_seed(1701);\n TypeParam lower = 0;\n TypeParam upper = 1;\n caffe_vRngUniform(sample_size,\n reinterpret_cast(data_a.mutable_cpu_data()), lower, upper);\n TypeParam true_mean = (lower + upper) \/ 2;\n TypeParam true_std = (upper - lower) \/ sqrt(12);\n TypeParam bound = this->mean_bound(true_std, sample_size);\n TypeParam empirical_mean =\n this->sample_mean(reinterpret_cast(data_a.cpu_data()),\n sample_size);\n EXPECT_NEAR(empirical_mean, true_mean, bound);\n}\n\n\nTYPED_TEST(RandomNumberGeneratorTest, TestRngBernoulli) {\n size_t sample_size = 10000;\n SyncedMemory data_a(sample_size * sizeof(int));\n Caffe::set_random_seed(1701);\n double p = 0.3;\n caffe_vRngBernoulli(sample_size,\n static_cast(data_a.mutable_cpu_data()), p);\n TypeParam true_mean = p;\n TypeParam true_std = sqrt(p * (1 - p));\n TypeParam bound = this->mean_bound(true_std, sample_size);\n TypeParam empirical_mean =\n this->sample_mean((const int *)data_a.cpu_data(), sample_size);\n EXPECT_NEAR(empirical_mean, true_mean, bound);\n}\n\n\nTYPED_TEST(RandomNumberGeneratorTest, TestRngGaussianTimesBernoulli) {\n size_t sample_size = 10000;\n SyncedMemory gaussian_data(sample_size * sizeof(TypeParam));\n SyncedMemory bernoulli_data(sample_size * sizeof(int));\n Caffe::set_random_seed(1701);\n \/\/ Sample from 0 mean Gaussian\n TypeParam mu = 0;\n TypeParam sigma = 1;\n caffe_vRngGaussian(sample_size, reinterpret_cast(\n gaussian_data.mutable_cpu_data()), mu, sigma);\n TypeParam true_mean = mu;\n TypeParam true_std = sigma;\n TypeParam bound = this->mean_bound(true_std, sample_size);\n TypeParam empirical_mean = this->sample_mean(\n reinterpret_cast(gaussian_data.cpu_data()),\n sample_size);\n EXPECT_NEAR(empirical_mean, true_mean, bound);\n int num_pos = 0;\n int num_neg = 0;\n int num_zeros = 0;\n TypeParam* samples =\n static_cast(gaussian_data.mutable_cpu_data());\n for (int i = 0; i < sample_size; ++i) {\n if (samples[i] == TypeParam(0)) {\n ++num_zeros;\n } else if (samples[i] > TypeParam(0)) {\n ++num_pos;\n } else if (samples[i] < TypeParam(0)) {\n ++num_neg;\n }\n }\n \/\/ Check that we have no zeros (possible to generate 0s, but highly\n \/\/ improbable), and roughly half positives and half negatives (with bound\n \/\/ computed from a Bernoulli with p = 0.5).\n EXPECT_EQ(0, num_zeros);\n double p = 0.5;\n true_mean = p;\n true_std = sqrt(p * (1 - p));\n bound = this->mean_bound(true_std, sample_size);\n TypeParam expected_num_each_sign = sample_size * p;\n LOG(INFO) << \"Gaussian: Expected \" << expected_num_each_sign << \" positives\"\n << \"; got \" << num_pos;\n LOG(INFO) << \"Gaussian: Expected \" << expected_num_each_sign << \" negatives\"\n << \"; got \" << num_neg;\n EXPECT_NEAR(expected_num_each_sign, num_pos, sample_size * bound);\n EXPECT_NEAR(expected_num_each_sign, num_neg, sample_size * bound);\n \/\/ Sample from Bernoulli with p = 0.3\n p = 0.3;\n caffe_vRngBernoulli(sample_size,\n reinterpret_cast(bernoulli_data.mutable_cpu_data()), p);\n true_mean = p;\n true_std = sqrt(p * (1 - p));\n bound = this->mean_bound(true_std, sample_size);\n empirical_mean =\n this->sample_mean((const int *)bernoulli_data.cpu_data(), sample_size);\n LOG(INFO) << \"Bernoulli: Expected mean = \" << true_mean\n << \"; sample mean = \" << empirical_mean;\n EXPECT_NEAR(empirical_mean, true_mean, bound);\n int bernoulli_num_zeros = 0;\n int num_ones = 0;\n int num_other = 0;\n const int* bernoulli_samples =\n reinterpret_cast(bernoulli_data.cpu_data());\n for (int i = 0; i < sample_size; ++i) {\n if (bernoulli_samples[i] == 0) {\n ++bernoulli_num_zeros;\n } else if (bernoulli_samples[i] == 1) {\n ++num_ones;\n } else {\n ++num_other;\n }\n }\n LOG(INFO) << \"Bernoulli: zeros: \" << bernoulli_num_zeros\n << \"; ones: \" << num_ones << \"; other: \" << num_other;\n EXPECT_EQ(0, num_other);\n EXPECT_EQ(sample_size * empirical_mean, num_ones);\n EXPECT_EQ(sample_size * (1.0 - empirical_mean), bernoulli_num_zeros);\n \/\/ Multiply Gaussian by Bernoulli\n for (int i = 0; i < sample_size; ++i) {\n samples[i] *= bernoulli_samples[i];\n }\n num_pos = 0;\n num_neg = 0;\n num_zeros = 0;\n for (int i = 0; i < sample_size; ++i) {\n if (samples[i] == TypeParam(0)) {\n ++num_zeros;\n } else if (samples[i] > TypeParam(0)) {\n ++num_pos;\n } else if (samples[i] < TypeParam(0)) {\n ++num_neg;\n }\n }\n \/\/ Check that we have as many zeros as Bernoulli, and roughly half positives\n \/\/ and half negatives (with bound computed from a Bernoulli with p = 0.5).\n EXPECT_EQ(bernoulli_num_zeros, num_zeros);\n p = 0.5;\n true_mean = p;\n true_std = sqrt(p * (1 - p));\n int sub_sample_size = sample_size - bernoulli_num_zeros;\n bound = this->mean_bound(true_std, sub_sample_size);\n expected_num_each_sign = sub_sample_size * p;\n LOG(INFO) << \"Gaussian: Expected \" << expected_num_each_sign << \" positives\"\n << \"; got \" << num_pos;\n LOG(INFO) << \"Gaussian: Expected \" << expected_num_each_sign << \" negatives\"\n << \"; got \" << num_neg;\n EXPECT_NEAR(expected_num_each_sign, num_pos, sample_size * bound);\n EXPECT_NEAR(expected_num_each_sign, num_neg, sample_size * bound);\n}\n\n\nTYPED_TEST(RandomNumberGeneratorTest, TestRngUniformTimesBernoulli) {\n size_t sample_size = 10000;\n SyncedMemory uniform_data(sample_size * sizeof(TypeParam));\n SyncedMemory bernoulli_data(sample_size * sizeof(int));\n Caffe::set_random_seed(1701);\n \/\/ Sample from Uniform on [-1, 1]\n TypeParam a = -1;\n TypeParam b = 1;\n caffe_vRngUniform(sample_size, reinterpret_cast(\n uniform_data.mutable_cpu_data()), a, b);\n TypeParam true_mean = (a + b) \/ 2;\n TypeParam true_std = (b - a) \/ sqrt(12);\n TypeParam bound = this->mean_bound(true_std, sample_size);\n TypeParam empirical_mean = this->sample_mean(\n reinterpret_cast(uniform_data.cpu_data()),\n sample_size);\n EXPECT_NEAR(empirical_mean, true_mean, bound);\n int num_pos = 0;\n int num_neg = 0;\n int num_zeros = 0;\n TypeParam* samples =\n static_cast(uniform_data.mutable_cpu_data());\n for (int i = 0; i < sample_size; ++i) {\n if (samples[i] == TypeParam(0)) {\n ++num_zeros;\n } else if (samples[i] > TypeParam(0)) {\n ++num_pos;\n } else if (samples[i] < TypeParam(0)) {\n ++num_neg;\n }\n }\n \/\/ Check that we have no zeros (possible to generate 0s, but highly\n \/\/ improbable), and roughly half positives and half negatives (with bound\n \/\/ computed from a Bernoulli with p = 0.5).\n EXPECT_EQ(0, num_zeros);\n double p = 0.5;\n true_mean = p;\n true_std = sqrt(p * (1 - p));\n bound = this->mean_bound(true_std, sample_size);\n TypeParam expected_num_each_sign = sample_size * p;\n LOG(INFO) << \"Uniform: Expected \" << expected_num_each_sign << \" positives\"\n << \"; got \" << num_pos;\n LOG(INFO) << \"Uniform: Expected \" << expected_num_each_sign << \" negatives\"\n << \"; got \" << num_neg;\n EXPECT_NEAR(expected_num_each_sign, num_pos, sample_size * bound);\n EXPECT_NEAR(expected_num_each_sign, num_neg, sample_size * bound);\n \/\/ Sample from Bernoulli with p = 0.3\n p = 0.3;\n caffe_vRngBernoulli(sample_size,\n reinterpret_cast(bernoulli_data.mutable_cpu_data()), p);\n true_mean = p;\n true_std = sqrt(p * (1 - p));\n bound = this->mean_bound(true_std, sample_size);\n empirical_mean =\n this->sample_mean((const int *)bernoulli_data.cpu_data(), sample_size);\n LOG(INFO) << \"Bernoulli: Expected mean = \" << true_mean\n << \"; sample mean = \" << empirical_mean;\n EXPECT_NEAR(empirical_mean, true_mean, bound);\n int bernoulli_num_zeros = 0;\n int num_ones = 0;\n int num_other = 0;\n const int* bernoulli_samples =\n reinterpret_cast(bernoulli_data.cpu_data());\n for (int i = 0; i < sample_size; ++i) {\n if (bernoulli_samples[i] == 0) {\n ++bernoulli_num_zeros;\n } else if (bernoulli_samples[i] == 1) {\n ++num_ones;\n } else {\n ++num_other;\n }\n }\n LOG(INFO) << \"Bernoulli: zeros: \" << bernoulli_num_zeros\n << \"; ones: \" << num_ones << \"; other: \" << num_other;\n EXPECT_EQ(0, num_other);\n EXPECT_EQ(sample_size * empirical_mean, num_ones);\n EXPECT_EQ(sample_size * (1.0 - empirical_mean), bernoulli_num_zeros);\n \/\/ Multiply Uniform by Bernoulli\n for (int i = 0; i < sample_size; ++i) {\n samples[i] *= bernoulli_samples[i];\n }\n num_pos = 0;\n num_neg = 0;\n num_zeros = 0;\n for (int i = 0; i < sample_size; ++i) {\n if (samples[i] == TypeParam(0)) {\n ++num_zeros;\n } else if (samples[i] > TypeParam(0)) {\n ++num_pos;\n } else if (samples[i] < TypeParam(0)) {\n ++num_neg;\n }\n }\n \/\/ Check that we have as many zeros as Bernoulli, and roughly half positives\n \/\/ and half negatives (with bound computed from a Bernoulli with p = 0.5).\n EXPECT_EQ(bernoulli_num_zeros, num_zeros);\n p = 0.5;\n true_mean = p;\n true_std = sqrt(p * (1 - p));\n int sub_sample_size = sample_size - bernoulli_num_zeros;\n bound = this->mean_bound(true_std, sub_sample_size);\n expected_num_each_sign = sub_sample_size * p;\n LOG(INFO) << \"Uniform: Expected \" << expected_num_each_sign << \" positives\"\n << \"; got \" << num_pos;\n LOG(INFO) << \"Uniform: Expected \" << expected_num_each_sign << \" negatives\"\n << \"; got \" << num_neg;\n EXPECT_NEAR(expected_num_each_sign, num_pos, sample_size * bound);\n EXPECT_NEAR(expected_num_each_sign, num_neg, sample_size * bound);\n}\n\n\n} \/\/ namespace caffe\ncleanup log messages\/\/ Copyright 2014 BVLC and contributors.\n\n#include \n#include \n#include \n\n#include \"gtest\/gtest.h\"\n#include \"caffe\/common.hpp\"\n#include \"caffe\/syncedmem.hpp\"\n#include \"caffe\/util\/math_functions.hpp\"\n#include \"caffe\/test\/test_caffe_main.hpp\"\n\nnamespace caffe {\n\ntemplate \nclass RandomNumberGeneratorTest : public ::testing::Test {\n public:\n virtual ~RandomNumberGeneratorTest() {}\n\n Dtype sample_mean(const Dtype* const seqs, const size_t sample_size) {\n double sum = 0;\n for (int i = 0; i < sample_size; ++i) {\n sum += seqs[i];\n }\n return sum \/ sample_size;\n }\n\n Dtype sample_mean(const int* const seqs, const size_t sample_size) {\n Dtype sum = 0;\n for (int i = 0; i < sample_size; ++i) {\n sum += Dtype(seqs[i]);\n }\n return sum \/ sample_size;\n }\n\n Dtype mean_bound(const Dtype std, const size_t sample_size) {\n return std\/sqrt(static_cast(sample_size));\n }\n};\n\n\ntypedef ::testing::Types Dtypes;\nTYPED_TEST_CASE(RandomNumberGeneratorTest, Dtypes);\n\n\nTYPED_TEST(RandomNumberGeneratorTest, TestRngGaussian) {\n size_t sample_size = 10000;\n SyncedMemory data_a(sample_size * sizeof(TypeParam));\n Caffe::set_random_seed(1701);\n TypeParam mu = 0;\n TypeParam sigma = 1;\n caffe_vRngGaussian(sample_size,\n reinterpret_cast(data_a.mutable_cpu_data()), mu, sigma);\n TypeParam true_mean = mu;\n TypeParam true_std = sigma;\n TypeParam bound = this->mean_bound(true_std, sample_size);\n TypeParam empirical_mean =\n this->sample_mean(reinterpret_cast(data_a.cpu_data()),\n sample_size);\n EXPECT_NEAR(empirical_mean, true_mean, bound);\n}\n\n\nTYPED_TEST(RandomNumberGeneratorTest, TestRngUniform) {\n size_t sample_size = 10000;\n SyncedMemory data_a(sample_size * sizeof(TypeParam));\n Caffe::set_random_seed(1701);\n TypeParam lower = 0;\n TypeParam upper = 1;\n caffe_vRngUniform(sample_size,\n reinterpret_cast(data_a.mutable_cpu_data()), lower, upper);\n TypeParam true_mean = (lower + upper) \/ 2;\n TypeParam true_std = (upper - lower) \/ sqrt(12);\n TypeParam bound = this->mean_bound(true_std, sample_size);\n TypeParam empirical_mean =\n this->sample_mean(reinterpret_cast(data_a.cpu_data()),\n sample_size);\n EXPECT_NEAR(empirical_mean, true_mean, bound);\n}\n\n\nTYPED_TEST(RandomNumberGeneratorTest, TestRngBernoulli) {\n size_t sample_size = 10000;\n SyncedMemory data_a(sample_size * sizeof(int));\n Caffe::set_random_seed(1701);\n double p = 0.3;\n caffe_vRngBernoulli(sample_size,\n static_cast(data_a.mutable_cpu_data()), p);\n TypeParam true_mean = p;\n TypeParam true_std = sqrt(p * (1 - p));\n TypeParam bound = this->mean_bound(true_std, sample_size);\n TypeParam empirical_mean =\n this->sample_mean((const int *)data_a.cpu_data(), sample_size);\n EXPECT_NEAR(empirical_mean, true_mean, bound);\n}\n\n\nTYPED_TEST(RandomNumberGeneratorTest, TestRngGaussianTimesBernoulli) {\n size_t sample_size = 10000;\n SyncedMemory gaussian_data(sample_size * sizeof(TypeParam));\n SyncedMemory bernoulli_data(sample_size * sizeof(int));\n Caffe::set_random_seed(1701);\n \/\/ Sample from 0 mean Gaussian\n TypeParam mu = 0;\n TypeParam sigma = 1;\n caffe_vRngGaussian(sample_size, reinterpret_cast(\n gaussian_data.mutable_cpu_data()), mu, sigma);\n TypeParam true_mean = mu;\n TypeParam true_std = sigma;\n TypeParam bound = this->mean_bound(true_std, sample_size);\n TypeParam empirical_mean = this->sample_mean(\n reinterpret_cast(gaussian_data.cpu_data()),\n sample_size);\n EXPECT_NEAR(empirical_mean, true_mean, bound);\n int num_pos = 0;\n int num_neg = 0;\n int num_zeros = 0;\n TypeParam* samples =\n static_cast(gaussian_data.mutable_cpu_data());\n for (int i = 0; i < sample_size; ++i) {\n if (samples[i] == TypeParam(0)) {\n ++num_zeros;\n } else if (samples[i] > TypeParam(0)) {\n ++num_pos;\n } else if (samples[i] < TypeParam(0)) {\n ++num_neg;\n }\n }\n \/\/ Check that we have no zeros (possible to generate 0s, but highly\n \/\/ improbable), and roughly half positives and half negatives (with bound\n \/\/ computed from a Bernoulli with p = 0.5).\n EXPECT_EQ(0, num_zeros);\n double p = 0.5;\n true_mean = p;\n true_std = sqrt(p * (1 - p));\n bound = this->mean_bound(true_std, sample_size);\n TypeParam expected_num_each_sign = sample_size * p;\n LOG(INFO) << \"Gaussian: Expected \" << expected_num_each_sign << \" positives\"\n << \"; got \" << num_pos;\n LOG(INFO) << \"Gaussian: Expected \" << expected_num_each_sign << \" negatives\"\n << \"; got \" << num_neg;\n EXPECT_NEAR(expected_num_each_sign, num_pos, sample_size * bound);\n EXPECT_NEAR(expected_num_each_sign, num_neg, sample_size * bound);\n \/\/ Sample from Bernoulli with p = 0.3\n p = 0.3;\n caffe_vRngBernoulli(sample_size,\n reinterpret_cast(bernoulli_data.mutable_cpu_data()), p);\n true_mean = p;\n true_std = sqrt(p * (1 - p));\n bound = this->mean_bound(true_std, sample_size);\n empirical_mean =\n this->sample_mean((const int *)bernoulli_data.cpu_data(), sample_size);\n LOG(INFO) << \"Bernoulli: Expected mean = \" << true_mean\n << \"; sample mean = \" << empirical_mean;\n EXPECT_NEAR(empirical_mean, true_mean, bound);\n int bernoulli_num_zeros = 0;\n int num_ones = 0;\n int num_other = 0;\n const int* bernoulli_samples =\n reinterpret_cast(bernoulli_data.cpu_data());\n for (int i = 0; i < sample_size; ++i) {\n if (bernoulli_samples[i] == 0) {\n ++bernoulli_num_zeros;\n } else if (bernoulli_samples[i] == 1) {\n ++num_ones;\n } else {\n ++num_other;\n }\n }\n LOG(INFO) << \"Bernoulli: zeros: \" << bernoulli_num_zeros\n << \"; ones: \" << num_ones << \"; other: \" << num_other;\n EXPECT_EQ(0, num_other);\n EXPECT_EQ(sample_size * empirical_mean, num_ones);\n EXPECT_EQ(sample_size * (1.0 - empirical_mean), bernoulli_num_zeros);\n \/\/ Multiply Gaussian by Bernoulli\n for (int i = 0; i < sample_size; ++i) {\n samples[i] *= bernoulli_samples[i];\n }\n num_pos = 0;\n num_neg = 0;\n num_zeros = 0;\n for (int i = 0; i < sample_size; ++i) {\n if (samples[i] == TypeParam(0)) {\n ++num_zeros;\n } else if (samples[i] > TypeParam(0)) {\n ++num_pos;\n } else if (samples[i] < TypeParam(0)) {\n ++num_neg;\n }\n }\n \/\/ Check that we have as many zeros as Bernoulli, and roughly half positives\n \/\/ and half negatives (with bound computed from a Bernoulli with p = 0.5).\n EXPECT_EQ(bernoulli_num_zeros, num_zeros);\n p = 0.5;\n true_mean = p;\n true_std = sqrt(p * (1 - p));\n int sub_sample_size = sample_size - bernoulli_num_zeros;\n bound = this->mean_bound(true_std, sub_sample_size);\n expected_num_each_sign = sub_sample_size * p;\n LOG(INFO) << \"Gaussian*Bernoulli: Expected \" << expected_num_each_sign\n << \" positives; got \" << num_pos;\n LOG(INFO) << \"Gaussian*Bernoulli: Expected \" << expected_num_each_sign\n << \" negatives; got \" << num_neg;\n EXPECT_NEAR(expected_num_each_sign, num_pos, sample_size * bound);\n EXPECT_NEAR(expected_num_each_sign, num_neg, sample_size * bound);\n}\n\n\nTYPED_TEST(RandomNumberGeneratorTest, TestRngUniformTimesBernoulli) {\n size_t sample_size = 10000;\n SyncedMemory uniform_data(sample_size * sizeof(TypeParam));\n SyncedMemory bernoulli_data(sample_size * sizeof(int));\n Caffe::set_random_seed(1701);\n \/\/ Sample from Uniform on [-1, 1]\n TypeParam a = -1;\n TypeParam b = 1;\n caffe_vRngUniform(sample_size, reinterpret_cast(\n uniform_data.mutable_cpu_data()), a, b);\n TypeParam true_mean = (a + b) \/ 2;\n TypeParam true_std = (b - a) \/ sqrt(12);\n TypeParam bound = this->mean_bound(true_std, sample_size);\n TypeParam empirical_mean = this->sample_mean(\n reinterpret_cast(uniform_data.cpu_data()),\n sample_size);\n EXPECT_NEAR(empirical_mean, true_mean, bound);\n int num_pos = 0;\n int num_neg = 0;\n int num_zeros = 0;\n TypeParam* samples =\n static_cast(uniform_data.mutable_cpu_data());\n for (int i = 0; i < sample_size; ++i) {\n if (samples[i] == TypeParam(0)) {\n ++num_zeros;\n } else if (samples[i] > TypeParam(0)) {\n ++num_pos;\n } else if (samples[i] < TypeParam(0)) {\n ++num_neg;\n }\n }\n \/\/ Check that we have no zeros (possible to generate 0s, but highly\n \/\/ improbable), and roughly half positives and half negatives (with bound\n \/\/ computed from a Bernoulli with p = 0.5).\n EXPECT_EQ(0, num_zeros);\n double p = 0.5;\n true_mean = p;\n true_std = sqrt(p * (1 - p));\n bound = this->mean_bound(true_std, sample_size);\n TypeParam expected_num_each_sign = sample_size * p;\n LOG(INFO) << \"Uniform: Expected \" << expected_num_each_sign << \" positives\"\n << \"; got \" << num_pos;\n LOG(INFO) << \"Uniform: Expected \" << expected_num_each_sign << \" negatives\"\n << \"; got \" << num_neg;\n EXPECT_NEAR(expected_num_each_sign, num_pos, sample_size * bound);\n EXPECT_NEAR(expected_num_each_sign, num_neg, sample_size * bound);\n \/\/ Sample from Bernoulli with p = 0.3\n p = 0.3;\n caffe_vRngBernoulli(sample_size,\n reinterpret_cast(bernoulli_data.mutable_cpu_data()), p);\n true_mean = p;\n true_std = sqrt(p * (1 - p));\n bound = this->mean_bound(true_std, sample_size);\n empirical_mean =\n this->sample_mean((const int *)bernoulli_data.cpu_data(), sample_size);\n LOG(INFO) << \"Bernoulli: Expected mean = \" << true_mean\n << \"; sample mean = \" << empirical_mean;\n EXPECT_NEAR(empirical_mean, true_mean, bound);\n int bernoulli_num_zeros = 0;\n int num_ones = 0;\n int num_other = 0;\n const int* bernoulli_samples =\n reinterpret_cast(bernoulli_data.cpu_data());\n for (int i = 0; i < sample_size; ++i) {\n if (bernoulli_samples[i] == 0) {\n ++bernoulli_num_zeros;\n } else if (bernoulli_samples[i] == 1) {\n ++num_ones;\n } else {\n ++num_other;\n }\n }\n LOG(INFO) << \"Bernoulli: zeros: \" << bernoulli_num_zeros\n << \"; ones: \" << num_ones << \"; other: \" << num_other;\n EXPECT_EQ(0, num_other);\n EXPECT_EQ(sample_size * empirical_mean, num_ones);\n EXPECT_EQ(sample_size * (1.0 - empirical_mean), bernoulli_num_zeros);\n \/\/ Multiply Uniform by Bernoulli\n for (int i = 0; i < sample_size; ++i) {\n samples[i] *= bernoulli_samples[i];\n }\n num_pos = 0;\n num_neg = 0;\n num_zeros = 0;\n for (int i = 0; i < sample_size; ++i) {\n if (samples[i] == TypeParam(0)) {\n ++num_zeros;\n } else if (samples[i] > TypeParam(0)) {\n ++num_pos;\n } else if (samples[i] < TypeParam(0)) {\n ++num_neg;\n }\n }\n \/\/ Check that we have as many zeros as Bernoulli, and roughly half positives\n \/\/ and half negatives (with bound computed from a Bernoulli with p = 0.5).\n EXPECT_EQ(bernoulli_num_zeros, num_zeros);\n p = 0.5;\n true_mean = p;\n true_std = sqrt(p * (1 - p));\n int sub_sample_size = sample_size - bernoulli_num_zeros;\n bound = this->mean_bound(true_std, sub_sample_size);\n expected_num_each_sign = sub_sample_size * p;\n LOG(INFO) << \"Uniform*Bernoulli: Expected \" << expected_num_each_sign\n << \" positives; got \" << num_pos;\n LOG(INFO) << \"Uniform*Bernoulli: Expected \" << expected_num_each_sign\n << \" negatives; got \" << num_neg;\n EXPECT_NEAR(expected_num_each_sign, num_pos, sample_size * bound);\n EXPECT_NEAR(expected_num_each_sign, num_neg, sample_size * bound);\n}\n\n\n} \/\/ namespace caffe\n<|endoftext|>"} {"text":"#include \".\/chunk.h\"\n\nnamespace mcmap {\n\nChunk::Chunk() : data_version(-1) {}\n\nChunk::Chunk(const nbt::NBT &data, const Colors::Palette &palette) : Chunk() {\n \/\/ If there is nothing to render\n if (data.is_end() || !assert_chunk(data))\n return;\n\n \/\/ This value is primordial: it states which version of minecraft the chunk\n \/\/ was created under, and we use it to know which interpreter to use later\n \/\/ in the sections\n data_version = data[\"DataVersion\"].get();\n\n for (const auto &raw_section : data[\"Level\"][\"Sections\"]) {\n Section section(raw_section, data_version);\n section.loadPalette(palette);\n sections.push_back(std::move(section));\n }\n}\n\nChunk::Chunk(Chunk &&other) { *this = std::move(other); }\n\nChunk &Chunk::operator=(Chunk &&other) {\n data_version = other.data_version;\n sections = std::move(other.sections);\n\n return *this;\n}\n\nbool Chunk::assert_chunk(const nbt::NBT &chunk) {\n if (chunk.is_end() \/\/ Catch uninitialized chunks\n || !chunk.contains(\"DataVersion\") \/\/ Dataversion is required\n || !chunk.contains(\"Level\") \/\/ Level data is required\n || !chunk[\"Level\"].contains(\"Sections\") \/\/ No sections mean no blocks\n || !chunk[\"Level\"].contains(\"Status\")) \/\/ Ensure the status is `full`\n return false;\n\n long version = chunk[\"DataVersion\"].get();\n\n if (version > 1628) {\n return chunk[\"Level\"][\"Status\"].get() == \"full\";\n }\n\n return chunk[\"Level\"][\"Status\"].get() ==\n \"postprocessed\";\n}\n\n} \/\/ namespace mcmap\n\nmcmap::Chunk::coordinates left_in(Map::Orientation o) {\n switch (o) {\n case Map::NW:\n return {0, 1};\n case Map::SW:\n return {1, 0};\n case Map::SE:\n return {0, -1};\n case Map::NE:\n return {-1, 0};\n }\n\n return {0, 0};\n}\n\nmcmap::Chunk::coordinates right_in(Map::Orientation o) {\n switch (o) {\n case Map::NW:\n return {1, 0};\n case Map::SW:\n return {0, -1};\n case Map::SE:\n return {-1, 0};\n case Map::NE:\n return {0, 1};\n }\n\n return {0, 0};\n}\nSupport for 21w43#include \".\/chunk.h\"\n\nnamespace mcmap {\n\nnamespace versions {\nnamespace assert {\nbool v2844(const nbt::NBT &chunk) {\n \/\/ Snapshot 21w43a\n return chunk.contains(\"sections\") \/\/ No sections mean no blocks\n && chunk.contains(\"Status\") \/\/ Ensure the status is `full`\n && chunk[\"Status\"].get() == \"full\";\n}\n\nbool v2840(const nbt::NBT &chunk) {\n \/\/ Snapshot 21w42a\n return chunk.contains(\"Level\") && \/\/ Level data is required\n chunk[\"Level\"].contains(\"Sections\") \/\/ No sections mean no blocks\n && chunk[\"Level\"].contains(\"Status\") \/\/ Ensure the status is `full`\n && chunk[\"Level\"][\"Status\"].get() == \"full\";\n}\n\nbool vbetween(const nbt::NBT &chunk) {\n return chunk.contains(\"Level\") \/\/ Level data is required\n && chunk[\"Level\"].contains(\"Sections\") \/\/ No sections mean no blocks\n && chunk[\"Level\"].contains(\"Status\") \/\/ Ensure the status is `full`\n && chunk[\"Level\"][\"Status\"].get() == \"full\";\n}\n\nbool v1628(const nbt::NBT &chunk) {\n \/\/ 1.13\n return chunk.contains(\"Level\") \/\/ Level data is required\n && chunk[\"Level\"].contains(\"Sections\") \/\/ No sections mean no blocks\n && chunk[\"Level\"].contains(\"Status\") \/\/ Ensure the status is `full`\n && chunk[\"Level\"][\"Status\"].get() ==\n \"postprocessed\";\n}\n} \/\/ namespace assert\n\nnamespace sections {\nnbt::NBT v2844(const nbt::NBT &chunk) { return chunk[\"sections\"]; }\nnbt::NBT v1628(const nbt::NBT &chunk) { return chunk[\"Level\"][\"Sections\"]; }\n} \/\/ namespace sections\n} \/\/ namespace versions\n\nChunk::Chunk() : data_version(-1) {}\n\nChunk::Chunk(const nbt::NBT &data, const Colors::Palette &palette) : Chunk() {\n \/\/ If there is nothing to render\n if (data.is_end() || !assert_chunk(data))\n return;\n\n \/\/ This value is primordial: it states which version of minecraft the chunk\n \/\/ was created under, and we use it to know which interpreter to use later\n \/\/ in the sections\n data_version = data[\"DataVersion\"].get();\n\n nbt::NBT sections_list;\n\n if (data_version >= 2844) {\n sections_list = versions::sections::v2844(data);\n } else {\n sections_list = versions::sections::v1628(data);\n }\n\n for (const auto &raw_section : sections_list) {\n Section section(raw_section, data_version);\n section.loadPalette(palette);\n sections.push_back(std::move(section));\n }\n}\n\nChunk::Chunk(Chunk &&other) { *this = std::move(other); }\n\nChunk &Chunk::operator=(Chunk &&other) {\n data_version = other.data_version;\n sections = std::move(other.sections);\n\n return *this;\n}\n\nbool Chunk::assert_chunk(const nbt::NBT &chunk) {\n if (chunk.is_end() \/\/ Catch uninitialized chunks\n || !chunk.contains(\"DataVersion\")) \/\/ Dataversion is required\n return false;\n\n const int version = chunk[\"DataVersion\"].get();\n\n if (version >= 2844) {\n return versions::assert::v2844(chunk);\n } else if (version >= 2840) {\n return versions::assert::v2840(chunk);\n } else if (version > 1628) {\n return versions::assert::vbetween(chunk);\n } else {\n return versions::assert::v1628(chunk);\n }\n}\n\n} \/\/ namespace mcmap\n\nmcmap::Chunk::coordinates left_in(Map::Orientation o) {\n switch (o) {\n case Map::NW:\n return {0, 1};\n case Map::SW:\n return {1, 0};\n case Map::SE:\n return {0, -1};\n case Map::NE:\n return {-1, 0};\n }\n\n return {0, 0};\n}\n\nmcmap::Chunk::coordinates right_in(Map::Orientation o) {\n switch (o) {\n case Map::NW:\n return {1, 0};\n case Map::SW:\n return {0, -1};\n case Map::SE:\n return {-1, 0};\n case Map::NE:\n return {0, 1};\n }\n\n return {0, 0};\n}\n<|endoftext|>"} {"text":"INTEGRATION: CWS dba30c (1.12.10); FILE MERGED 2008\/05\/08 07:15:27 oj 1.12.10.2: #i87131# collect keys only once, getKeys always refetch keys 2008\/05\/05 10:57:50 oj 1.12.10.1: #i87131# collect keys only once, getKeys always refetch the keys<|endoftext|>"} {"text":"\/**\n * @file posix\/net.cpp\n * @brief POSIX network access layer (using cURL)\n *\n * (c) 2013-2014 by Mega Limited, Wellsford, New Zealand\n *\n * This file is part of the MEGA SDK - Client Access Engine.\n *\n * Applications using the MEGA API must present a valid application key\n * and comply with the the rules set forth in the Terms of Service.\n *\n * The MEGA SDK is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n *\n * @copyright Simplified (2-clause) BSD License.\n *\n * You should have received a copy of the license along with this\n * program.\n *\/\n\n#include \"mega.h\"\n\nnamespace mega {\nCurlHttpIO::CurlHttpIO()\n{\n curl_global_init(CURL_GLOBAL_DEFAULT);\n\n curlm = curl_multi_init();\n\n curlsh = curl_share_init();\n curl_share_setopt(curlsh, CURLSHOPT_SHARE, CURL_LOCK_DATA_DNS);\n curl_share_setopt(curlsh, CURLSHOPT_SHARE, CURL_LOCK_DATA_SSL_SESSION);\n\n contenttypejson = curl_slist_append(NULL, \"Content-Type: application\/json\");\n contenttypejson = curl_slist_append(contenttypejson, \"Expect:\");\n\n contenttypebinary = curl_slist_append(NULL, \"Content-Type: application\/octet-stream\");\n contenttypebinary = curl_slist_append(contenttypebinary, \"Expect:\");\n}\n\nCurlHttpIO::~CurlHttpIO()\n{\n curl_global_cleanup();\n}\n\nvoid CurlHttpIO::setuseragent(string* u)\n{\n useragent = u;\n}\n\n\/\/ wake up from cURL I\/O\nvoid CurlHttpIO::addevents(Waiter* w, int flags)\n{\n int t;\n PosixWaiter* pw = (PosixWaiter*)w;\n\n curl_multi_fdset(curlm, &pw->rfds, &pw->wfds, &pw->efds, &t);\n\n pw->bumpmaxfd(t);\n}\n\n\/\/ POST request to URL\nvoid CurlHttpIO::post(HttpReq* req, const char* data, unsigned len)\n{\n if (debug)\n {\n cout << \"POST target URL: \" << req->posturl << endl;\n\n if (req->binary)\n {\n cout << \"[sending \" << req->out->size() << \" bytes of raw data]\" << endl;\n }\n else\n {\n cout << \"Sending: \" << *req->out << endl;\n }\n }\n\n CURL* curl;\n\n req->in.clear();\n\n if ((curl = curl_easy_init()))\n {\n curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, 1);\n curl_easy_setopt(curl, CURLOPT_TCP_KEEPIDLE, 10);\n curl_easy_setopt(curl, CURLOPT_TCP_KEEPINTVL, 5);\n curl_easy_setopt(curl, CURLOPT_URL, req->posturl.c_str());\n curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data ? data : req->out->data());\n curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, data ? len : req->out->size());\n curl_easy_setopt(curl, CURLOPT_USERAGENT, useragent->c_str());\n curl_easy_setopt(curl, CURLOPT_HTTPHEADER, req->type == REQ_JSON ? contenttypejson : contenttypebinary);\n curl_easy_setopt(curl, CURLOPT_ENCODING, \"\");\n curl_easy_setopt(curl, CURLOPT_SHARE, curlsh);\n curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);\n curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)req);\n curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, check_header);\n curl_easy_setopt(curl, CURLOPT_HEADERDATA, (void*)req);\n curl_easy_setopt(curl, CURLOPT_PRIVATE, (void*)req);\n curl_easy_setopt(curl, CURLOPT_SSL_CTX_FUNCTION, ssl_ctx_function);\n curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);\n curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);\n\n\n curl_multi_add_handle(curlm, curl);\n\n req->status = REQ_INFLIGHT;\n\n req->httpiohandle = (void*)curl;\n }\n else\n {\n req->status = REQ_FAILURE;\n }\n}\n\n\/\/ cancel pending HTTP request\nvoid CurlHttpIO::cancel(HttpReq* req)\n{\n if (req->httpiohandle)\n {\n curl_multi_remove_handle(curlm, (CURL*)req->httpiohandle);\n curl_easy_cleanup((CURL*)req->httpiohandle);\n\n req->httpstatus = 0;\n req->status = REQ_FAILURE;\n req->httpiohandle = NULL;\n }\n}\n\n\/\/ real-time progress information on POST data\nm_off_t CurlHttpIO::postpos(void* handle)\n{\n double bytes;\n\n curl_easy_getinfo(handle, CURLINFO_SIZE_UPLOAD, &bytes);\n\n return (m_off_t)bytes;\n}\n\n\/\/ process events\nbool CurlHttpIO::doio()\n{\n bool done = false;\n\n CURLMsg *msg;\n int dummy;\n\n curl_multi_perform(curlm, &dummy);\n\n while ((msg = curl_multi_info_read(curlm, &dummy)))\n {\n HttpReq* req;\n\n if ((curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE, (char**)&req) == CURLE_OK) && req)\n {\n req->httpio = NULL;\n\n if (msg->msg == CURLMSG_DONE)\n {\n curl_easy_getinfo(msg->easy_handle, CURLINFO_RESPONSE_CODE, &req->httpstatus);\n\n if (debug)\n {\n cout << \"CURLMSG_DONE with HTTP status: \" << req->httpstatus << endl;\n\n if (req->httpstatus)\n {\n if (req->binary)\n {\n cout << \"[received \" << req->in.size() << \" bytes of raw data]\" << endl;\n }\n else\n {\n cout << \"Received: \" << req->in.c_str() << endl;\n }\n }\n }\n\n \/\/ check httpstatus and response length\n req->status = (req->httpstatus == 200\n && req->contentlength == (req->buf ? req->bufpos : req->in.size()))\n ? REQ_SUCCESS : REQ_FAILURE;\n\n inetstatus(req->status);\n\n success = true;\n done = true;\n }\n else\n {\n req->status = REQ_FAILURE;\n }\n }\n\n curl_multi_remove_handle(curlm, msg->easy_handle);\n curl_easy_cleanup(msg->easy_handle);\n }\n\n return done;\n}\n\n\/\/ callback for incoming HTTP payload\nsize_t CurlHttpIO::write_data(void* ptr, size_t, size_t nmemb, void* target)\n{\n ((HttpReq*)target)->put(ptr, nmemb);\n\n return nmemb;\n}\n\n\/\/ set contentlength according to Original-Content-Length header\nsize_t CurlHttpIO::check_header(void* ptr, size_t, size_t nmemb, void* target)\n{\n if (!memcmp(ptr, \"Content-Length:\", 15))\n {\n if (((HttpReq*)target)->contentlength < 0) ((HttpReq*)target)->setcontentlength(atol((char*)ptr+15));\n }\n else\n {\n if (!memcmp(ptr, \"Original-Content-Length:\", 24))\n {\n ((HttpReq*)target)->setcontentlength(atol((char*)ptr+24));\n }\n }\n\n return nmemb;\n}\n\nCURLcode CurlHttpIO::ssl_ctx_function(CURL* curl, void* sslctx, void*)\n{\n SSL_CTX_set_cert_verify_callback((SSL_CTX*)sslctx, cert_verify_callback, NULL);\n\n return CURLE_OK;\n}\n\n\/\/ SSL public key pinning\nint CurlHttpIO::cert_verify_callback(X509_STORE_CTX* ctx, void*)\n{\n unsigned char buf[sizeof(APISSLMODULUS) - 1];\n EVP_PKEY* evp;\n int ok = 0;\n\n if ((evp = X509_PUBKEY_get(X509_get_X509_PUBKEY(ctx->cert))))\n {\n if (BN_num_bytes(evp->pkey.rsa->n) == sizeof APISSLMODULUS - 1\n && BN_num_bytes(evp->pkey.rsa->e) == sizeof APISSLEXPONENT - 1)\n {\n BN_bn2bin(evp->pkey.rsa->n, buf);\n\n if (!memcmp(buf, APISSLMODULUS, sizeof APISSLMODULUS - 1))\n {\n BN_bn2bin(evp->pkey.rsa->e, buf);\n\n if (!memcmp(buf, APISSLEXPONENT, sizeof APISSLEXPONENT - 1))\n {\n ok = 1;\n }\n }\n }\n\n EVP_PKEY_free(evp);\n }\n\n return ok;\n}\n\n} \/\/ namespace\nPOSIX\/Net: Formatting\/**\n * @file posix\/net.cpp\n * @brief POSIX network access layer (using cURL)\n *\n * (c) 2013-2014 by Mega Limited, Wellsford, New Zealand\n *\n * This file is part of the MEGA SDK - Client Access Engine.\n *\n * Applications using the MEGA API must present a valid application key\n * and comply with the the rules set forth in the Terms of Service.\n *\n * The MEGA SDK is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n *\n * @copyright Simplified (2-clause) BSD License.\n *\n * You should have received a copy of the license along with this\n * program.\n *\/\n\n#include \"mega.h\"\n\nnamespace mega {\nCurlHttpIO::CurlHttpIO()\n{\n curl_global_init(CURL_GLOBAL_DEFAULT);\n\n curlm = curl_multi_init();\n\n curlsh = curl_share_init();\n curl_share_setopt(curlsh, CURLSHOPT_SHARE, CURL_LOCK_DATA_DNS);\n curl_share_setopt(curlsh, CURLSHOPT_SHARE, CURL_LOCK_DATA_SSL_SESSION);\n\n contenttypejson = curl_slist_append(NULL, \"Content-Type: application\/json\");\n contenttypejson = curl_slist_append(contenttypejson, \"Expect:\");\n\n contenttypebinary = curl_slist_append(NULL, \"Content-Type: application\/octet-stream\");\n contenttypebinary = curl_slist_append(contenttypebinary, \"Expect:\");\n}\n\nCurlHttpIO::~CurlHttpIO()\n{\n curl_global_cleanup();\n}\n\nvoid CurlHttpIO::setuseragent(string* u)\n{\n useragent = u;\n}\n\n\/\/ wake up from cURL I\/O\nvoid CurlHttpIO::addevents(Waiter* w, int flags)\n{\n int t;\n PosixWaiter* pw = (PosixWaiter*)w;\n\n curl_multi_fdset(curlm, &pw->rfds, &pw->wfds, &pw->efds, &t);\n\n pw->bumpmaxfd(t);\n}\n\n\/\/ POST request to URL\nvoid CurlHttpIO::post(HttpReq* req, const char* data, unsigned len)\n{\n if (debug)\n {\n cout << \"POST target URL: \" << req->posturl << endl;\n\n if (req->binary)\n {\n cout << \"[sending \" << req->out->size() << \" bytes of raw data]\" << endl;\n }\n else\n {\n cout << \"Sending: \" << *req->out << endl;\n }\n }\n\n CURL* curl;\n\n req->in.clear();\n\n if ((curl = curl_easy_init()))\n {\n curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, 1);\n curl_easy_setopt(curl, CURLOPT_TCP_KEEPIDLE, 10);\n curl_easy_setopt(curl, CURLOPT_TCP_KEEPINTVL, 5);\n curl_easy_setopt(curl, CURLOPT_URL, req->posturl.c_str());\n curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data ? data : req->out->data());\n curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, data ? len : req->out->size());\n curl_easy_setopt(curl, CURLOPT_USERAGENT, useragent->c_str());\n curl_easy_setopt(curl, CURLOPT_HTTPHEADER, req->type == REQ_JSON ? contenttypejson : contenttypebinary);\n curl_easy_setopt(curl, CURLOPT_ENCODING, \"\");\n curl_easy_setopt(curl, CURLOPT_SHARE, curlsh);\n curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);\n curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)req);\n curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, check_header);\n curl_easy_setopt(curl, CURLOPT_HEADERDATA, (void*)req);\n curl_easy_setopt(curl, CURLOPT_PRIVATE, (void*)req);\n curl_easy_setopt(curl, CURLOPT_SSL_CTX_FUNCTION, ssl_ctx_function);\n curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);\n curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);\n\n curl_multi_add_handle(curlm, curl);\n\n req->status = REQ_INFLIGHT;\n\n req->httpiohandle = (void*)curl;\n }\n else\n {\n req->status = REQ_FAILURE;\n }\n}\n\n\/\/ cancel pending HTTP request\nvoid CurlHttpIO::cancel(HttpReq* req)\n{\n if (req->httpiohandle)\n {\n curl_multi_remove_handle(curlm, (CURL*)req->httpiohandle);\n curl_easy_cleanup((CURL*)req->httpiohandle);\n\n req->httpstatus = 0;\n req->status = REQ_FAILURE;\n req->httpiohandle = NULL;\n }\n}\n\n\/\/ real-time progress information on POST data\nm_off_t CurlHttpIO::postpos(void* handle)\n{\n double bytes;\n\n curl_easy_getinfo(handle, CURLINFO_SIZE_UPLOAD, &bytes);\n\n return (m_off_t)bytes;\n}\n\n\/\/ process events\nbool CurlHttpIO::doio()\n{\n bool done = false;\n\n CURLMsg *msg;\n int dummy;\n\n curl_multi_perform(curlm, &dummy);\n\n while ((msg = curl_multi_info_read(curlm, &dummy)))\n {\n HttpReq* req;\n\n if ((curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE, (char**)&req) == CURLE_OK) && req)\n {\n req->httpio = NULL;\n\n if (msg->msg == CURLMSG_DONE)\n {\n curl_easy_getinfo(msg->easy_handle, CURLINFO_RESPONSE_CODE, &req->httpstatus);\n\n if (debug)\n {\n cout << \"CURLMSG_DONE with HTTP status: \" << req->httpstatus << endl;\n\n if (req->httpstatus)\n {\n if (req->binary)\n {\n cout << \"[received \" << req->in.size() << \" bytes of raw data]\" << endl;\n }\n else\n {\n cout << \"Received: \" << req->in.c_str() << endl;\n }\n }\n }\n\n \/\/ check httpstatus and response length\n req->status = (req->httpstatus == 200\n && req->contentlength == (req->buf ? req->bufpos : req->in.size()))\n ? REQ_SUCCESS : REQ_FAILURE;\n\n inetstatus(req->status);\n\n success = true;\n done = true;\n }\n else\n {\n req->status = REQ_FAILURE;\n }\n }\n\n curl_multi_remove_handle(curlm, msg->easy_handle);\n curl_easy_cleanup(msg->easy_handle);\n }\n\n return done;\n}\n\n\/\/ callback for incoming HTTP payload\nsize_t CurlHttpIO::write_data(void* ptr, size_t, size_t nmemb, void* target)\n{\n ((HttpReq*)target)->put(ptr, nmemb);\n\n return nmemb;\n}\n\n\/\/ set contentlength according to Original-Content-Length header\nsize_t CurlHttpIO::check_header(void* ptr, size_t, size_t nmemb, void* target)\n{\n if (!memcmp(ptr, \"Content-Length:\", 15))\n {\n if (((HttpReq*)target)->contentlength < 0) ((HttpReq*)target)->setcontentlength(atol((char*)ptr + 15));\n }\n else\n {\n if (!memcmp(ptr, \"Original-Content-Length:\", 24))\n {\n ((HttpReq*)target)->setcontentlength(atol((char*)ptr + 24));\n }\n }\n\n return nmemb;\n}\n\nCURLcode CurlHttpIO::ssl_ctx_function(CURL* curl, void* sslctx, void*)\n{\n SSL_CTX_set_cert_verify_callback((SSL_CTX*)sslctx, cert_verify_callback, NULL);\n\n return CURLE_OK;\n}\n\n\/\/ SSL public key pinning\nint CurlHttpIO::cert_verify_callback(X509_STORE_CTX* ctx, void*)\n{\n unsigned char buf[sizeof(APISSLMODULUS) - 1];\n EVP_PKEY* evp;\n int ok = 0;\n\n if ((evp = X509_PUBKEY_get(X509_get_X509_PUBKEY(ctx->cert))))\n {\n if (BN_num_bytes(evp->pkey.rsa->n) == sizeof APISSLMODULUS - 1\n && BN_num_bytes(evp->pkey.rsa->e) == sizeof APISSLEXPONENT - 1)\n {\n BN_bn2bin(evp->pkey.rsa->n, buf);\n\n if (!memcmp(buf, APISSLMODULUS, sizeof APISSLMODULUS - 1))\n {\n BN_bn2bin(evp->pkey.rsa->e, buf);\n\n if (!memcmp(buf, APISSLEXPONENT, sizeof APISSLEXPONENT - 1))\n {\n ok = 1;\n }\n }\n }\n\n EVP_PKEY_free(evp);\n }\n\n return ok;\n}\n} \/\/ namespace\n<|endoftext|>"} {"text":"\/*\n\nCopyright (c) 2008, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/session.hpp\"\n#include \"libtorrent\/session_settings.hpp\"\n#include \"libtorrent\/hasher.hpp\"\n#include \"libtorrent\/thread.hpp\"\n#include \n\n#include \"test.hpp\"\n#include \"setup_transfer.hpp\"\n\nvoid test_lsd()\n{\n\tusing namespace libtorrent;\n\n\tsession ses1(fingerprint(\"LT\", 0, 1, 0, 0), std::make_pair(48100, 49000), \"0.0.0.0\", 0);\n\tsession ses2(fingerprint(\"LT\", 0, 1, 0, 0), std::make_pair(49100, 50000), \"0.0.0.0\", 0);\n\tsession ses3(fingerprint(\"LT\", 0, 1, 0, 0), std::make_pair(50100, 51000), \"0.0.0.0\", 0);\n\n\t\/\/ this is to avoid everything finish from a single peer\n\t\/\/ immediately. To make the swarm actually connect all\n\t\/\/ three peers before finishing.\n\tfloat rate_limit = 180000;\n\tses1.set_upload_rate_limit(int(rate_limit));\n\tses2.set_download_rate_limit(int(rate_limit));\n\tses3.set_download_rate_limit(int(rate_limit));\n\tses2.set_upload_rate_limit(int(rate_limit \/ 2));\n\tses3.set_upload_rate_limit(int(rate_limit \/ 2));\n\n\tsession_settings settings;\n\tsettings.allow_multiple_connections_per_ip = true;\n\tsettings.ignore_limits_on_local_network = false;\n\tses1.set_settings(settings);\n\tses2.set_settings(settings);\n\tses3.set_settings(settings);\n\n\tses1.start_lsd();\n\tses2.start_lsd();\n\tses3.start_lsd();\n\n#ifndef TORRENT_DISABLE_ENCRYPTION\n\tpe_settings pes;\n\tpes.out_enc_policy = pe_settings::forced;\n\tpes.in_enc_policy = pe_settings::forced;\n\tses1.set_pe_settings(pes);\n\tses2.set_pe_settings(pes);\n\tses3.set_pe_settings(pes);\n#endif\n\n\ttorrent_handle tor1;\n\ttorrent_handle tor2;\n\ttorrent_handle tor3;\n\n\tboost::tie(tor1, tor2, tor3) = setup_transfer(&ses1, &ses2, &ses3, true, false, false, \"_lsd\");\n\n\tfor (int i = 0; i < 30; ++i)\n\t{\n\t\tprint_alerts(ses1, \"ses1\", true);\n\t\tprint_alerts(ses2, \"ses2\", true);\n\t\tprint_alerts(ses3, \"ses3\", true);\n\n\t\ttorrent_status st1 = tor1.status();\n\t\ttorrent_status st2 = tor2.status();\n\t\ttorrent_status st3 = tor3.status();\n\n\t\tstd::cerr\n\t\t\t<< \"\\033[33m\" << int(st1.upload_payload_rate \/ 1000.f) << \"kB\/s \"\n\t\t\t<< st1.num_peers << \": \"\n\t\t\t<< \"\\033[32m\" << int(st2.download_payload_rate \/ 1000.f) << \"kB\/s \"\n\t\t\t<< \"\\033[31m\" << int(st2.upload_payload_rate \/ 1000.f) << \"kB\/s \"\n\t\t\t<< \"\\033[0m\" << int(st2.progress * 100) << \"% \"\n\t\t\t<< st2.num_peers << \" - \"\n\t\t\t<< \"\\033[32m\" << int(st3.download_payload_rate \/ 1000.f) << \"kB\/s \"\n\t\t\t<< \"\\033[31m\" << int(st3.upload_payload_rate \/ 1000.f) << \"kB\/s \"\n\t\t\t<< \"\\033[0m\" << int(st3.progress * 100) << \"% \"\n\t\t\t<< st3.num_peers\n\t\t\t<< std::endl;\n\n\t\tif (tor2.is_seed() && tor3.is_seed()) break;\n\t\ttest_sleep(1000);\n\t}\n\n\tTEST_CHECK(tor2.is_seed());\n\tTEST_CHECK(tor3.is_seed());\n\n\tif (tor2.is_seed() && tor3.is_seed()) std::cerr << \"done\\n\";\n}\n\nint test_main()\n{\n\tusing namespace libtorrent;\n\n\t\/\/ in case the previous run was terminated\n\terror_code ec;\n\tremove_all(\".\/tmp1_lsd\", ec);\n\tremove_all(\".\/tmp2_lsd\", ec);\n\tremove_all(\".\/tmp3_lsd\", ec);\n\n\ttest_lsd();\n\t\n\tremove_all(\".\/tmp1_lsd\", ec);\n\tremove_all(\".\/tmp2_lsd\", ec);\n\tremove_all(\".\/tmp3_lsd\", ec);\n\n\treturn 0;\n}\n\n\n\noptimized local peer discovery unittest\/*\n\nCopyright (c) 2008, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/session.hpp\"\n#include \"libtorrent\/session_settings.hpp\"\n#include \"libtorrent\/hasher.hpp\"\n#include \"libtorrent\/thread.hpp\"\n#include \n\n#include \"test.hpp\"\n#include \"setup_transfer.hpp\"\n\nvoid test_lsd()\n{\n\tusing namespace libtorrent;\n\n\tsession ses1(fingerprint(\"LT\", 0, 1, 0, 0), std::make_pair(48100, 49000), \"0.0.0.0\", 0);\n\tsession ses2(fingerprint(\"LT\", 0, 1, 0, 0), std::make_pair(49100, 50000), \"0.0.0.0\", 0);\n\n\tsession_settings settings;\n\tsettings.allow_multiple_connections_per_ip = true;\n\tses1.set_settings(settings);\n\tses2.set_settings(settings);\n\n\tses1.start_lsd();\n\tses2.start_lsd();\n\ttorrent_handle tor1;\n\ttorrent_handle tor2;\n\n\tusing boost::tuples::ignore;\n\tboost::tie(tor1, tor2, ignore) = setup_transfer(&ses1, &ses2, 0, true, false, false, \"_lsd\");\n\n\tfor (int i = 0; i < 30; ++i)\n\t{\n\t\tprint_alerts(ses1, \"ses1\", true);\n\t\tprint_alerts(ses2, \"ses2\", true);\n\n\t\ttorrent_status st1 = tor1.status();\n\t\ttorrent_status st2 = tor2.status();\n\n\t\tstd::cerr\n\t\t\t<< \"\\033[33m\" << int(st1.upload_payload_rate \/ 1000.f) << \"kB\/s \"\n\t\t\t<< \"\\033[32m\" << int(st2.download_payload_rate \/ 1000.f) << \"kB\/s \"\n\t\t\t<< \"\\033[31m\" << int(st2.upload_payload_rate \/ 1000.f) << \"kB\/s \"\n\t\t\t<< \"\\033[0m\" << int(st2.progress * 100) << \"% \"\n\t\t\t<< std::endl;\n\n\t\tif (tor2.is_seed() \/*&& tor3.is_seed()*\/) break;\n\t\ttest_sleep(1000);\n\t}\n\n\tTEST_CHECK(tor2.is_seed());\n\n\tif (tor2.is_seed()) std::cerr << \"done\\n\";\n}\n\nint test_main()\n{\n\tusing namespace libtorrent;\n\n\t\/\/ in case the previous run was terminated\n\terror_code ec;\n\tremove_all(\".\/tmp1_lsd\", ec);\n\tremove_all(\".\/tmp2_lsd\", ec);\n\tremove_all(\".\/tmp3_lsd\", ec);\n\n\ttest_lsd();\n\t\n\tremove_all(\".\/tmp1_lsd\", ec);\n\tremove_all(\".\/tmp2_lsd\", ec);\n\tremove_all(\".\/tmp3_lsd\", ec);\n\n\treturn 0;\n}\n\n\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\nint main( int argc, char *argv[] )\n{\n\tusing namespace std;\n\n\tunsigned int sampling_rate = 44100;\n\n\tif( argc == 2 )\n\t{\n\t\tmist::array< signed int > sound;\n\t\tmist::read_wav( sound, argv[1], sampling_rate );\n\t\tmist::write_wav( sound, std::string( argv[1] ) + \".wav\", 16, sampling_rate );\n\t}\n\n\treturn( 0 );\n}\nincludeファイルミス#include \n#include \n\nint main( int argc, char *argv[] )\n{\n\tusing namespace std;\n\n\tunsigned int sampling_rate = 44100;\n\n\tif( argc == 2 )\n\t{\n\t\tmist::array< signed int > sound;\n\t\tmist::read_wav( sound, argv[1], sampling_rate );\n\t\tmist::write_wav( sound, std::string( argv[1] ) + \".wav\", 16, sampling_rate );\n\t}\n\n\treturn( 0 );\n}\n<|endoftext|>"} {"text":"#pragma once\n\n#include \"arm.hpp\"\n\nnamespace bandit{\n\nclass BernoulliArm : public Arm{\n const double theta;\n std::uniform_real_distribution unif;\npublic:\n BernoulliArm(double theta): theta(theta), unif(0.0, 1.0) {\n }\n virtual double pull(){\n double rand = unif(randomEngine);\n if(rand <= theta){\n return 1;\n }else{\n return 0;\n }\n }\n virtual double getExpectedReward(){\n return theta;\n }\n virtual std::string toString(){\n std::string str=\"Bernoulli Arm with theta=\"+dtos(theta);\n return str;\n }\n};\n\n} \/\/namespace\nnotation: theta->mu#pragma once\n\n#include \"arm.hpp\"\n\nnamespace bandit{\n\nclass BernoulliArm : public Arm{\n const double mu;\n std::uniform_real_distribution unif;\npublic:\n BernoulliArm(double mu): mu(mu), unif(0.0, 1.0) {\n }\n virtual double pull(){\n double rand = unif(randomEngine);\n if(rand <= mu){\n return 1;\n }else{\n return 0;\n }\n }\n virtual double getExpectedReward(){\n return mu;\n }\n virtual std::string toString(){\n std::string str=\"Bernoulli Arm with mu=\"+dtos(mu);\n return str;\n }\n};\n\n} \/\/namespace\n<|endoftext|>"} {"text":"core: keep old index file resolution<|endoftext|>"} {"text":"\r\n\/*!\r\n\t\\file\r\n\r\n\t\\author Igor Mironchik (igor.mironchik at gmail dot com).\r\n\r\n\tCopyright (c) 2014 Igor Mironchik\r\n\r\n\tPermission is hereby granted, free of charge, to any person\r\n\tobtaining a copy of this software and associated documentation\r\n\tfiles (the \"Software\"), to deal in the Software without\r\n\trestriction, including without limitation the rights to use,\r\n\tcopy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n\tcopies of the Software, and to permit persons to whom the\r\n\tSoftware is furnished to do so, subject to the following\r\n\tconditions:\r\n\r\n\tThe above copyright notice and this permission notice shall be\r\n\tincluded in all copies or substantial portions of the Software.\r\n\r\n\tTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\r\n\tEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\r\n\tOF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r\n\tNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\r\n\tHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\r\n\tWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n\tFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\r\n\tOTHER DEALINGS IN THE SOFTWARE.\r\n*\/\r\n\r\n\/\/ QtMWidgets include.\r\n#include \"color.hpp\"\r\n\r\n\r\nnamespace QtMWidgets {\r\n\r\n\/\/\r\n\/\/ lighterColor\r\n\/\/\r\n\r\nQColor\r\nlighterColor( const QColor & c, int b )\r\n{\r\n\tif( b <= 0 )\r\n\t\treturn c;\r\n\r\n\tint h = 0;\r\n\tint s = 0;\r\n\tint v = 0;\r\n\tint a = 0;\r\n\r\n\tQColor hsv = c.toHsv();\r\n\thsv.getHsv( &h, &s, &v, &a );\r\n\r\n\tv += b;\r\n\r\n\tif( v > 255 )\r\n\t{\r\n\t\ts -= v - 255;\r\n\r\n\t\tif( s < 0 ) s = 0;\r\n\r\n\t\tv = 255;\r\n\t}\r\n\r\n\thsv.setHsv( h, s, v, a );\r\n\r\n\treturn hsv.convertTo( c.spec() );\r\n}\r\n\r\n\r\n\/\/\r\n\/\/ darkerColor\r\n\/\/\r\n\r\nQColor\r\ndarkerColor( const QColor & c, int b )\r\n{\r\n\tif( b <= 0 )\r\n\t\treturn c;\r\n\r\n\tint h = 0;\r\n\tint s = 0;\r\n\tint v = 0;\r\n\tint a = 0;\r\n\r\n\tQColor hsv = c.toHsv();\r\n\thsv.getHsv( &h, &s, &v, &a );\r\n\r\n\tv -= b;\r\n\r\n\thsv.setHsv( h, s, v, a );\r\n\r\n\treturn hsv.convertTo( c.spec() );\r\n}\r\n\r\n} \/* namespace QtMWidgets *\/\r\nFixed issue in darkerColor().\r\n\/*!\r\n\t\\file\r\n\r\n\t\\author Igor Mironchik (igor.mironchik at gmail dot com).\r\n\r\n\tCopyright (c) 2014 Igor Mironchik\r\n\r\n\tPermission is hereby granted, free of charge, to any person\r\n\tobtaining a copy of this software and associated documentation\r\n\tfiles (the \"Software\"), to deal in the Software without\r\n\trestriction, including without limitation the rights to use,\r\n\tcopy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n\tcopies of the Software, and to permit persons to whom the\r\n\tSoftware is furnished to do so, subject to the following\r\n\tconditions:\r\n\r\n\tThe above copyright notice and this permission notice shall be\r\n\tincluded in all copies or substantial portions of the Software.\r\n\r\n\tTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\r\n\tEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\r\n\tOF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r\n\tNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\r\n\tHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\r\n\tWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n\tFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\r\n\tOTHER DEALINGS IN THE SOFTWARE.\r\n*\/\r\n\r\n\/\/ QtMWidgets include.\r\n#include \"color.hpp\"\r\n\r\n\r\nnamespace QtMWidgets {\r\n\r\n\/\/\r\n\/\/ lighterColor\r\n\/\/\r\n\r\nQColor\r\nlighterColor( const QColor & c, int b )\r\n{\r\n\tif( b <= 0 )\r\n\t\treturn c;\r\n\r\n\tint h = 0;\r\n\tint s = 0;\r\n\tint v = 0;\r\n\tint a = 0;\r\n\r\n\tQColor hsv = c.toHsv();\r\n\thsv.getHsv( &h, &s, &v, &a );\r\n\r\n\tv += b;\r\n\r\n\tif( v > 255 )\r\n\t{\r\n\t\ts -= v - 255;\r\n\r\n\t\tif( s < 0 ) s = 0;\r\n\r\n\t\tv = 255;\r\n\t}\r\n\r\n\thsv.setHsv( h, s, v, a );\r\n\r\n\treturn hsv.convertTo( c.spec() );\r\n}\r\n\r\n\r\n\/\/\r\n\/\/ darkerColor\r\n\/\/\r\n\r\nQColor\r\ndarkerColor( const QColor & c, int b )\r\n{\r\n\tif( b <= 0 )\r\n\t\treturn c;\r\n\r\n\tint h = 0;\r\n\tint s = 0;\r\n\tint v = 0;\r\n\tint a = 0;\r\n\r\n\tQColor hsv = c.toHsv();\r\n\thsv.getHsv( &h, &s, &v, &a );\r\n\r\n\tv -= b;\r\n\r\n\tif( v < 0 )\r\n\t\tv = 0;\r\n\r\n\thsv.setHsv( h, s, v, a );\r\n\r\n\treturn hsv.convertTo( c.spec() );\r\n}\r\n\r\n} \/* namespace QtMWidgets *\/\r\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#ifdef Q_OS_MAC\n#include \n#endif\n\n#include \"Canvas.h\"\n#include \"Manager.h\"\n#include \"Object.h\"\n\n\/\/ Declarations for part of Qt's internal API\nQ_DECL_IMPORT const QVariant::Handler* qcoreVariantHandler();\nnamespace QVariantPrivate {\nQ_DECL_IMPORT void registerHandler(\n const int name, const QVariant::Handler *handler);\n}\n\nstatic const char* cCounterNames[] = {\n \"ClassCounter\",\n \"ObjectCounter\",\n \"QObjectCounter\",\n \"VariantCounter\",\n \"ClassSerial\",\n \"ObjectSerial\"\n};\n\nextern \"C\" void hsqml_dump_counters()\n{\n Q_ASSERT (gManager);\n if (gManager->checkLogLevel(1)) {\n for (int i=0; ilog(QString().sprintf(\"%s = %d.\",\n cCounterNames[i], gManager->updateCounter(\n static_cast(i), 0)));\n }\n }\n}\n\nstatic void hooked_construct(QVariant::Private* p, const void* copy)\n{\n gManager->hookedConstruct(p, copy);\n}\n\nstatic void hooked_clear(QVariant::Private* p)\n{\n gManager->hookedClear(p);\n}\n\nManagerPointer gManager;\n\nHsQMLManager::HsQMLManager(\n void (*freeFun)(HsFunPtr),\n void (*freeStable)(HsStablePtr))\n : mLogLevel(0)\n , mAtExit(false)\n , mFreeFun(freeFun)\n , mFreeStable(freeStable)\n , mOriginalHandler(qcoreVariantHandler())\n , mHookedHandler(*mOriginalHandler)\n , mApp(NULL)\n , mLock(QMutex::Recursive)\n , mRunning(false)\n , mRunCount(0)\n , mStackBase(NULL)\n , mStartCb(NULL)\n , mJobsCb(NULL)\n , mYieldCb(NULL)\n , mActiveEngine(NULL)\n{\n \/\/ Get log level from environment\n const char* env = std::getenv(\"HSQML_DEBUG_LOG_LEVEL\");\n if (env) {\n setLogLevel(QString(env).toInt());\n }\n\n \/\/ Set hooked handler functions\n mHookedHandler.construct = &hooked_construct;\n mHookedHandler.clear = &hooked_clear;\n}\n\nvoid HsQMLManager::setLogLevel(int ll)\n{\n mLogLevel = ll;\n if (ll > 0 && !mAtExit) {\n if (atexit(&hsqml_dump_counters) == 0) {\n mAtExit = true;\n }\n else {\n log(\"Failed to register callback with atexit().\");\n }\n }\n}\n\nbool HsQMLManager::checkLogLevel(int ll)\n{\n return mLogLevel >= ll;\n}\n\nvoid HsQMLManager::log(const QString& msg)\n{\n QMutexLocker locker(&mLogLock);\n fprintf(stderr, \"HsQML: %s\\n\", msg.toUtf8().data());\n}\n\nint HsQMLManager::updateCounter(CounterId id, int delta)\n{\n return mCounters[id].fetchAndAddRelaxed(delta);\n}\n\nvoid HsQMLManager::freeFun(HsFunPtr funPtr)\n{\n mFreeFun(funPtr);\n}\n\nvoid HsQMLManager::freeStable(HsStablePtr stablePtr)\n{\n mFreeStable(stablePtr);\n}\n\nvoid HsQMLManager::registerObject(const QObject* obj)\n{\n mObjectSet.insert(obj);\n}\n\nvoid HsQMLManager::unregisterObject(const QObject* obj)\n{\n bool removed = mObjectSet.remove(obj);\n Q_ASSERT(removed);\n}\n\nvoid HsQMLManager::hookedConstruct(QVariant::Private* p, const void* copy)\n{\n char guard;\n mOriginalHandler->construct(p, copy);\n void* pp = reinterpret_cast(p);\n \/\/ The QVariant internals sometimes use a special code path for pointer\n \/\/ values which avoids calling the handler functions. This makes it\n \/\/ difficult to use them to keep a reference count. However, it's my\n \/\/ observation that this only affects transient QVariants created on the\n \/\/ stack inside the JavaScript engine's marshalling code. The persistent\n \/\/ QVariants stored in the heap are manipulated using a more restricted set\n \/\/ of operations which always use the handler functions. Hence, by assuming\n \/\/ that the stack can be discounted, it's possible to keep an accurate\n \/\/ count of heap references using these hooks.\n if ((pp < &guard || pp > mStackBase) && p->type == QMetaType::QObjectStar) {\n if (isEventThread() && mObjectSet.contains(p->data.o)) {\n HsQMLObject* obj = static_cast(p->data.o);\n HsQMLObjectProxy* proxy = obj->proxy();\n proxy->ref(HsQMLObjectProxy::Variant);\n proxy->tryGCLock();\n updateCounter(VariantCount, 1);\n }\n }\n}\n\nvoid HsQMLManager::hookedClear(QVariant::Private* p)\n{\n char guard;\n void* pp = reinterpret_cast(p);\n if ((pp < &guard || pp > mStackBase) && p->type == QMetaType::QObjectStar) {\n if (isEventThread() && mObjectSet.contains(p->data.o)) {\n HsQMLObject* obj = static_cast(p->data.o);\n obj->proxy()->deref(HsQMLObjectProxy::Variant);\n updateCounter(VariantCount, -1);\n }\n }\n mOriginalHandler->clear(p);\n}\n\nbool HsQMLManager::isEventThread()\n{\n return mApp && mApp->thread() == QThread::currentThread();\n}\n\nHsQMLManager::EventLoopStatus HsQMLManager::runEventLoop(\n HsQMLTrivialCb startCb,\n HsQMLTrivialCb jobsCb,\n HsQMLTrivialCb yieldCb)\n{\n QMutexLocker locker(&mLock);\n\n \/\/ Check if already running\n if (mRunning) {\n return HSQML_EVLOOP_ALREADY_RUNNING;\n }\n\n \/\/ Check if event loop bound to a different thread\n if (mApp && !isEventThread()) {\n return HSQML_EVLOOP_WRONG_THREAD;\n }\n\n#ifdef Q_OS_MAC\n if (!pthread_main_np()) {\n \/\/ Cocoa can only be run on the primordial thread and exec() doesn't\n \/\/ check this.\n return HSQML_EVLOOP_WRONG_THREAD;\n }\n#endif\n\n \/\/ Check for non-threaded RTS\n if (yieldCb) {\n HSQML_LOG(0,\n \"Warning: CPU cannot idle when using the non-threaded RTS.\");\n }\n\n \/\/ Perform one-time initialisation\n if (!mApp) {\n \/\/ Install hooked handler for QVariants\n QVariantPrivate::registerHandler(0, &mHookedHandler);\n\n \/\/ Register custom types\n qRegisterMetaType(\"HsQMLEngineConfig\");\n qmlRegisterType(\"HsQML.Canvas\", 1, 0, \"HaskellCanvas\");\n\n \/\/ Create application object\n mApp = new HsQMLManagerApp();\n }\n\n \/\/ Save stack base and callbacks\n mStackBase = &locker;\n mStartCb = startCb;\n mJobsCb = jobsCb;\n mYieldCb = yieldCb;\n\n \/\/ Setup events\n QCoreApplication::postEvent(\n mApp, new QEvent(HsQMLManagerApp::StartedLoopEvent),\n Qt::HighEventPriority);\n QBasicTimer idleTimer;\n if (yieldCb) {\n idleTimer.start(0, mApp);\n }\n\n \/\/ Run loop\n int ret;\n do {\n ret = mApp->exec();\n\n \/\/ Kill all engines\n const QObjectList& cs = gManager->mApp->children();\n while (!cs.empty()) {\n delete cs.front();\n }\n\n \/\/ Cmd-Q on MacOS can kill the event loop before we're ready\n \/\/ Keep it running until a StopLoopEvent is received\n } while (ret == 0 && mRunning);\n\n \/\/ Remove redundant events\n QCoreApplication::removePostedEvents(\n mApp, HsQMLManagerApp::RemoveGCLockEvent);\n\n \/\/ Cleanup callbacks\n freeFun(startCb);\n mStartCb = NULL;\n freeFun(jobsCb);\n mJobsCb = NULL;\n if (yieldCb) {\n freeFun(yieldCb);\n mYieldCb = NULL;\n }\n\n \/\/ Return\n if (ret == 0) {\n return HSQML_EVLOOP_OK;\n }\n else {\n QCoreApplication::removePostedEvents(\n mApp, HsQMLManagerApp::StartedLoopEvent);\n return HSQML_EVLOOP_OTHER_ERROR;\n }\n}\n\nHsQMLManager::EventLoopStatus HsQMLManager::requireEventLoop()\n{\n QMutexLocker locker(&mLock);\n if (mRunCount > 0) {\n mRunCount++;\n return HSQML_EVLOOP_OK;\n }\n else {\n return HSQML_EVLOOP_NOT_RUNNING;\n }\n}\n\nvoid HsQMLManager::releaseEventLoop()\n{\n QMutexLocker locker(&mLock);\n if (--mRunCount == 0) {\n QCoreApplication::postEvent(\n mApp, new QEvent(HsQMLManagerApp::StopLoopEvent),\n Qt::LowEventPriority);\n }\n}\n\nvoid HsQMLManager::notifyJobs()\n{\n QMutexLocker locker(&mLock);\n if (mRunCount > 0) {\n QCoreApplication::postEvent(\n mApp, new QEvent(HsQMLManagerApp::PendingJobsEvent));\n }\n}\n\nvoid HsQMLManager::createEngine(const HsQMLEngineConfig& config)\n{\n Q_ASSERT (mApp);\n QMetaObject::invokeMethod(\n mApp, \"createEngine\", Q_ARG(HsQMLEngineConfig, config));\n}\n\nvoid HsQMLManager::setActiveEngine(HsQMLEngine* engine)\n{\n Q_ASSERT(!mActiveEngine || !engine);\n mActiveEngine = engine;\n}\n\nHsQMLEngine* HsQMLManager::activeEngine()\n{\n return mActiveEngine;\n}\n\nvoid HsQMLManager::postObjectEvent(HsQMLObjectEvent* ev)\n{\n QCoreApplication::postEvent(mApp, ev);\n}\n\nHsQMLManagerApp::HsQMLManagerApp()\n : mArgC(1)\n , mArg0(0)\n , mArgV(&mArg0)\n , mApp(mArgC, &mArgV)\n{\n mApp.setQuitOnLastWindowClosed(false);\n}\n\nHsQMLManagerApp::~HsQMLManagerApp()\n{}\n\nvoid HsQMLManagerApp::customEvent(QEvent* ev)\n{\n switch (ev->type()) {\n case HsQMLManagerApp::StartedLoopEvent: {\n gManager->mRunning = true;\n gManager->mRunCount++;\n gManager->mLock.unlock();\n gManager->mStartCb();\n gManager->mJobsCb();\n break;}\n case HsQMLManagerApp::StopLoopEvent: {\n gManager->mLock.lock();\n gManager->mRunning = false;\n gManager->mApp->mApp.quit();\n break;}\n case HsQMLManagerApp::PendingJobsEvent: {\n gManager->mJobsCb();\n break;}\n case HsQMLManagerApp::RemoveGCLockEvent: {\n static_cast(ev)->process();\n break;}\n }\n}\n\nvoid HsQMLManagerApp::timerEvent(QTimerEvent*)\n{\n Q_ASSERT(gManager->mYieldCb);\n gManager->mYieldCb();\n}\n\nvoid HsQMLManagerApp::createEngine(HsQMLEngineConfig config)\n{\n HsQMLEngine* engine = new HsQMLEngine(config);\n engine->setParent(this);\n}\n\nint HsQMLManagerApp::exec()\n{\n return mApp.exec();\n}\n\nextern \"C\" void hsqml_init(\n void (*freeFun)(HsFunPtr),\n void (*freeStable)(HsStablePtr))\n{\n if (gManager == NULL) {\n HsQMLManager* manager = new HsQMLManager(freeFun, freeStable);\n if (!gManager.testAndSetOrdered(NULL, manager)) {\n delete manager;\n }\n }\n}\n\nextern \"C\" HsQMLEventLoopStatus hsqml_evloop_run(\n HsQMLTrivialCb startCb,\n HsQMLTrivialCb jobsCb,\n HsQMLTrivialCb yieldCb)\n{\n return gManager->runEventLoop(startCb, jobsCb, yieldCb);\n}\n\nextern \"C\" HsQMLEventLoopStatus hsqml_evloop_require()\n{\n return gManager->requireEventLoop();\n}\n\nextern \"C\" void hsqml_evloop_release()\n{\n gManager->releaseEventLoop();\n}\n\nextern \"C\" void hsqml_evloop_notify_jobs()\n{\n gManager->notifyJobs();\n}\n\nextern \"C\" void hsqml_set_debug_loglevel(int ll)\n{\n Q_ASSERT (gManager);\n gManager->setLogLevel(ll);\n}\nChange to not export dump counters function.#include \n#include \n#include \n#include \n#include \n#include \n#ifdef Q_OS_MAC\n#include \n#endif\n\n#include \"Canvas.h\"\n#include \"Manager.h\"\n#include \"Object.h\"\n\n\/\/ Declarations for part of Qt's internal API\nQ_DECL_IMPORT const QVariant::Handler* qcoreVariantHandler();\nnamespace QVariantPrivate {\nQ_DECL_IMPORT void registerHandler(\n const int name, const QVariant::Handler *handler);\n}\n\nstatic const char* cCounterNames[] = {\n \"ClassCounter\",\n \"ObjectCounter\",\n \"QObjectCounter\",\n \"VariantCounter\",\n \"ClassSerial\",\n \"ObjectSerial\"\n};\n\nstatic void dump_counters()\n{\n Q_ASSERT (gManager);\n if (gManager->checkLogLevel(1)) {\n for (int i=0; ilog(QString().sprintf(\"%s = %d.\",\n cCounterNames[i], gManager->updateCounter(\n static_cast(i), 0)));\n }\n }\n}\n\nstatic void hooked_construct(QVariant::Private* p, const void* copy)\n{\n gManager->hookedConstruct(p, copy);\n}\n\nstatic void hooked_clear(QVariant::Private* p)\n{\n gManager->hookedClear(p);\n}\n\nManagerPointer gManager;\n\nHsQMLManager::HsQMLManager(\n void (*freeFun)(HsFunPtr),\n void (*freeStable)(HsStablePtr))\n : mLogLevel(0)\n , mAtExit(false)\n , mFreeFun(freeFun)\n , mFreeStable(freeStable)\n , mOriginalHandler(qcoreVariantHandler())\n , mHookedHandler(*mOriginalHandler)\n , mApp(NULL)\n , mLock(QMutex::Recursive)\n , mRunning(false)\n , mRunCount(0)\n , mStackBase(NULL)\n , mStartCb(NULL)\n , mJobsCb(NULL)\n , mYieldCb(NULL)\n , mActiveEngine(NULL)\n{\n \/\/ Get log level from environment\n const char* env = std::getenv(\"HSQML_DEBUG_LOG_LEVEL\");\n if (env) {\n setLogLevel(QString(env).toInt());\n }\n\n \/\/ Set hooked handler functions\n mHookedHandler.construct = &hooked_construct;\n mHookedHandler.clear = &hooked_clear;\n}\n\nvoid HsQMLManager::setLogLevel(int ll)\n{\n mLogLevel = ll;\n if (ll > 0 && !mAtExit) {\n if (atexit(&dump_counters) == 0) {\n mAtExit = true;\n }\n else {\n log(\"Failed to register callback with atexit().\");\n }\n }\n}\n\nbool HsQMLManager::checkLogLevel(int ll)\n{\n return mLogLevel >= ll;\n}\n\nvoid HsQMLManager::log(const QString& msg)\n{\n QMutexLocker locker(&mLogLock);\n fprintf(stderr, \"HsQML: %s\\n\", msg.toUtf8().data());\n}\n\nint HsQMLManager::updateCounter(CounterId id, int delta)\n{\n return mCounters[id].fetchAndAddRelaxed(delta);\n}\n\nvoid HsQMLManager::freeFun(HsFunPtr funPtr)\n{\n mFreeFun(funPtr);\n}\n\nvoid HsQMLManager::freeStable(HsStablePtr stablePtr)\n{\n mFreeStable(stablePtr);\n}\n\nvoid HsQMLManager::registerObject(const QObject* obj)\n{\n mObjectSet.insert(obj);\n}\n\nvoid HsQMLManager::unregisterObject(const QObject* obj)\n{\n bool removed = mObjectSet.remove(obj);\n Q_ASSERT(removed);\n}\n\nvoid HsQMLManager::hookedConstruct(QVariant::Private* p, const void* copy)\n{\n char guard;\n mOriginalHandler->construct(p, copy);\n void* pp = reinterpret_cast(p);\n \/\/ The QVariant internals sometimes use a special code path for pointer\n \/\/ values which avoids calling the handler functions. This makes it\n \/\/ difficult to use them to keep a reference count. However, it's my\n \/\/ observation that this only affects transient QVariants created on the\n \/\/ stack inside the JavaScript engine's marshalling code. The persistent\n \/\/ QVariants stored in the heap are manipulated using a more restricted set\n \/\/ of operations which always use the handler functions. Hence, by assuming\n \/\/ that the stack can be discounted, it's possible to keep an accurate\n \/\/ count of heap references using these hooks.\n if ((pp < &guard || pp > mStackBase) && p->type == QMetaType::QObjectStar) {\n if (isEventThread() && mObjectSet.contains(p->data.o)) {\n HsQMLObject* obj = static_cast(p->data.o);\n HsQMLObjectProxy* proxy = obj->proxy();\n proxy->ref(HsQMLObjectProxy::Variant);\n proxy->tryGCLock();\n updateCounter(VariantCount, 1);\n }\n }\n}\n\nvoid HsQMLManager::hookedClear(QVariant::Private* p)\n{\n char guard;\n void* pp = reinterpret_cast(p);\n if ((pp < &guard || pp > mStackBase) && p->type == QMetaType::QObjectStar) {\n if (isEventThread() && mObjectSet.contains(p->data.o)) {\n HsQMLObject* obj = static_cast(p->data.o);\n obj->proxy()->deref(HsQMLObjectProxy::Variant);\n updateCounter(VariantCount, -1);\n }\n }\n mOriginalHandler->clear(p);\n}\n\nbool HsQMLManager::isEventThread()\n{\n return mApp && mApp->thread() == QThread::currentThread();\n}\n\nHsQMLManager::EventLoopStatus HsQMLManager::runEventLoop(\n HsQMLTrivialCb startCb,\n HsQMLTrivialCb jobsCb,\n HsQMLTrivialCb yieldCb)\n{\n QMutexLocker locker(&mLock);\n\n \/\/ Check if already running\n if (mRunning) {\n return HSQML_EVLOOP_ALREADY_RUNNING;\n }\n\n \/\/ Check if event loop bound to a different thread\n if (mApp && !isEventThread()) {\n return HSQML_EVLOOP_WRONG_THREAD;\n }\n\n#ifdef Q_OS_MAC\n if (!pthread_main_np()) {\n \/\/ Cocoa can only be run on the primordial thread and exec() doesn't\n \/\/ check this.\n return HSQML_EVLOOP_WRONG_THREAD;\n }\n#endif\n\n \/\/ Check for non-threaded RTS\n if (yieldCb) {\n HSQML_LOG(0,\n \"Warning: CPU cannot idle when using the non-threaded RTS.\");\n }\n\n \/\/ Perform one-time initialisation\n if (!mApp) {\n \/\/ Install hooked handler for QVariants\n QVariantPrivate::registerHandler(0, &mHookedHandler);\n\n \/\/ Register custom types\n qRegisterMetaType(\"HsQMLEngineConfig\");\n qmlRegisterType(\"HsQML.Canvas\", 1, 0, \"HaskellCanvas\");\n\n \/\/ Create application object\n mApp = new HsQMLManagerApp();\n }\n\n \/\/ Save stack base and callbacks\n mStackBase = &locker;\n mStartCb = startCb;\n mJobsCb = jobsCb;\n mYieldCb = yieldCb;\n\n \/\/ Setup events\n QCoreApplication::postEvent(\n mApp, new QEvent(HsQMLManagerApp::StartedLoopEvent),\n Qt::HighEventPriority);\n QBasicTimer idleTimer;\n if (yieldCb) {\n idleTimer.start(0, mApp);\n }\n\n \/\/ Run loop\n int ret;\n do {\n ret = mApp->exec();\n\n \/\/ Kill all engines\n const QObjectList& cs = gManager->mApp->children();\n while (!cs.empty()) {\n delete cs.front();\n }\n\n \/\/ Cmd-Q on MacOS can kill the event loop before we're ready\n \/\/ Keep it running until a StopLoopEvent is received\n } while (ret == 0 && mRunning);\n\n \/\/ Remove redundant events\n QCoreApplication::removePostedEvents(\n mApp, HsQMLManagerApp::RemoveGCLockEvent);\n\n \/\/ Cleanup callbacks\n freeFun(startCb);\n mStartCb = NULL;\n freeFun(jobsCb);\n mJobsCb = NULL;\n if (yieldCb) {\n freeFun(yieldCb);\n mYieldCb = NULL;\n }\n\n \/\/ Return\n if (ret == 0) {\n return HSQML_EVLOOP_OK;\n }\n else {\n QCoreApplication::removePostedEvents(\n mApp, HsQMLManagerApp::StartedLoopEvent);\n return HSQML_EVLOOP_OTHER_ERROR;\n }\n}\n\nHsQMLManager::EventLoopStatus HsQMLManager::requireEventLoop()\n{\n QMutexLocker locker(&mLock);\n if (mRunCount > 0) {\n mRunCount++;\n return HSQML_EVLOOP_OK;\n }\n else {\n return HSQML_EVLOOP_NOT_RUNNING;\n }\n}\n\nvoid HsQMLManager::releaseEventLoop()\n{\n QMutexLocker locker(&mLock);\n if (--mRunCount == 0) {\n QCoreApplication::postEvent(\n mApp, new QEvent(HsQMLManagerApp::StopLoopEvent),\n Qt::LowEventPriority);\n }\n}\n\nvoid HsQMLManager::notifyJobs()\n{\n QMutexLocker locker(&mLock);\n if (mRunCount > 0) {\n QCoreApplication::postEvent(\n mApp, new QEvent(HsQMLManagerApp::PendingJobsEvent));\n }\n}\n\nvoid HsQMLManager::createEngine(const HsQMLEngineConfig& config)\n{\n Q_ASSERT (mApp);\n QMetaObject::invokeMethod(\n mApp, \"createEngine\", Q_ARG(HsQMLEngineConfig, config));\n}\n\nvoid HsQMLManager::setActiveEngine(HsQMLEngine* engine)\n{\n Q_ASSERT(!mActiveEngine || !engine);\n mActiveEngine = engine;\n}\n\nHsQMLEngine* HsQMLManager::activeEngine()\n{\n return mActiveEngine;\n}\n\nvoid HsQMLManager::postObjectEvent(HsQMLObjectEvent* ev)\n{\n QCoreApplication::postEvent(mApp, ev);\n}\n\nHsQMLManagerApp::HsQMLManagerApp()\n : mArgC(1)\n , mArg0(0)\n , mArgV(&mArg0)\n , mApp(mArgC, &mArgV)\n{\n mApp.setQuitOnLastWindowClosed(false);\n}\n\nHsQMLManagerApp::~HsQMLManagerApp()\n{}\n\nvoid HsQMLManagerApp::customEvent(QEvent* ev)\n{\n switch (ev->type()) {\n case HsQMLManagerApp::StartedLoopEvent: {\n gManager->mRunning = true;\n gManager->mRunCount++;\n gManager->mLock.unlock();\n gManager->mStartCb();\n gManager->mJobsCb();\n break;}\n case HsQMLManagerApp::StopLoopEvent: {\n gManager->mLock.lock();\n gManager->mRunning = false;\n gManager->mApp->mApp.quit();\n break;}\n case HsQMLManagerApp::PendingJobsEvent: {\n gManager->mJobsCb();\n break;}\n case HsQMLManagerApp::RemoveGCLockEvent: {\n static_cast(ev)->process();\n break;}\n }\n}\n\nvoid HsQMLManagerApp::timerEvent(QTimerEvent*)\n{\n Q_ASSERT(gManager->mYieldCb);\n gManager->mYieldCb();\n}\n\nvoid HsQMLManagerApp::createEngine(HsQMLEngineConfig config)\n{\n HsQMLEngine* engine = new HsQMLEngine(config);\n engine->setParent(this);\n}\n\nint HsQMLManagerApp::exec()\n{\n return mApp.exec();\n}\n\nextern \"C\" void hsqml_init(\n void (*freeFun)(HsFunPtr),\n void (*freeStable)(HsStablePtr))\n{\n if (gManager == NULL) {\n HsQMLManager* manager = new HsQMLManager(freeFun, freeStable);\n if (!gManager.testAndSetOrdered(NULL, manager)) {\n delete manager;\n }\n }\n}\n\nextern \"C\" HsQMLEventLoopStatus hsqml_evloop_run(\n HsQMLTrivialCb startCb,\n HsQMLTrivialCb jobsCb,\n HsQMLTrivialCb yieldCb)\n{\n return gManager->runEventLoop(startCb, jobsCb, yieldCb);\n}\n\nextern \"C\" HsQMLEventLoopStatus hsqml_evloop_require()\n{\n return gManager->requireEventLoop();\n}\n\nextern \"C\" void hsqml_evloop_release()\n{\n gManager->releaseEventLoop();\n}\n\nextern \"C\" void hsqml_evloop_notify_jobs()\n{\n gManager->notifyJobs();\n}\n\nextern \"C\" void hsqml_set_debug_loglevel(int ll)\n{\n Q_ASSERT (gManager);\n gManager->setLogLevel(ll);\n}\n<|endoftext|>"} {"text":"\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2013-2014.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#ifndef SPINLOCK_H\n#define SPINLOCK_H\n\nstruct spinlock {\nprivate:\n volatile size_t lock = 0;\n\npublic:\n void acquire(){\n while(!__sync_bool_compare_and_swap(&lock, 0, 1));\n }\n\n void release(){\n __sync_synchronize();\n lock = 0;\n }\n};\n\n#endif\nMore safety for spinlock\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2013-2014.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#ifndef SPINLOCK_H\n#define SPINLOCK_H\n\nstruct spinlock {\nprivate:\n volatile size_t lock = 0;\n\npublic:\n void acquire(){\n while(!__sync_bool_compare_and_swap(&lock, 0, 1));\n __sync_synchronize();\n }\n\n void release(){\n __sync_synchronize();\n lock = 0;\n }\n};\n\n#endif\n<|endoftext|>"} {"text":"\/* Copyright (c) 2016, 2017 Dennis Wölfing\n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\/\n\n\/* kernel\/src\/addressspace.cpp\n * Address space class.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#define RECURSIVE_MAPPING 0xFFC00000\n\n#define PAGE_PRESENT (1 << 0)\n#define PAGE_WRITABLE (1 << 1)\n#define PAGE_USER (1 << 2)\n\nextern \"C\" {\nextern symbol_t bootstrapBegin;\nextern symbol_t bootstrapEnd;\nextern symbol_t kernelPageDirectory;\nextern symbol_t kernelVirtualBegin;\nextern symbol_t kernelReadOnlyEnd;\nextern symbol_t kernelVirtualEnd;\n}\n\nAddressSpace AddressSpace::_kernelSpace;\nAddressSpace* kernelSpace;\nstatic AddressSpace* firstAddressSpace = nullptr;\nstatic kthread_mutex_t listMutex = KTHREAD_MUTEX_INITIALIZER;\n\nstatic inline vaddr_t indexToAddress(size_t pdIndex, size_t ptIndex) {\n assert(pdIndex <= 0x3FF);\n assert(ptIndex <= 0x3FF);\n return (pdIndex << 22) | (ptIndex << 12);\n}\n\nstatic inline void addressToIndex(\n vaddr_t virtualAddress, size_t& pdIndex, size_t& ptIndex) {\n assert(!(virtualAddress & 0xFFF));\n pdIndex = virtualAddress >> 22;\n ptIndex = (virtualAddress >> 12) & 0x3FF;\n}\n\nstatic inline int protectionToFlags(int protection) {\n int flags = PAGE_PRESENT;\n if (protection & PROT_WRITE) flags |= PAGE_WRITABLE;\n return flags;\n}\n\nstatic vaddr_t mapTemporarily(paddr_t physicalAddress, int protection) {\n return kernelSpace->mapAt(0xFF7FF000, physicalAddress, protection);\n}\n\nAddressSpace::AddressSpace() {\n if (this == &_kernelSpace) {\n pageDir = 0;\n pageDirMapped = RECURSIVE_MAPPING + 0x3FF000;\n firstSegment = nullptr;\n prev = nullptr;\n next = nullptr;\n } else {\n pageDir = PhysicalMemory::popPageFrame();\n\n \/\/ Copy the page directory to the new address space\n vaddr_t kernelPageDir = kernelSpace->pageDirMapped;\n pageDirMapped = kernelSpace->mapPhysical(pageDir, 0x1000,\n PROT_READ | PROT_WRITE);\n\n firstSegment = new MemorySegment(0, 0x1000, PROT_NONE | SEG_NOUNMAP,\n nullptr, nullptr);\n MemorySegment::addSegment(firstSegment, 0xC0000000, -0xC0000000,\n PROT_NONE | SEG_NOUNMAP);\n\n prev = nullptr;\n AutoLock lock(&listMutex);\n memcpy((void*) pageDirMapped, (const void*) kernelPageDir, 0x1000);\n next = firstAddressSpace;\n if (next) {\n next->prev = this;\n }\n firstAddressSpace = this;\n }\n\n mutex = KTHREAD_MUTEX_INITIALIZER;\n}\n\nAddressSpace::~AddressSpace() {\n kthread_mutex_lock(&listMutex);\n if (prev) {\n prev->next = next;\n }\n if (next) {\n next->prev = prev;\n }\n if (this == firstAddressSpace) {\n firstAddressSpace = next;\n }\n kthread_mutex_unlock(&listMutex);\n\n MemorySegment* currentSegment = firstSegment;\n\n while (currentSegment) {\n MemorySegment* next = currentSegment->next;\n\n if (!(currentSegment->flags & SEG_NOUNMAP)) {\n unmapMemory(currentSegment->address, currentSegment->size);\n }\n currentSegment = next;\n }\n\n PhysicalMemory::pushPageFrame(pageDir);\n}\n\n\/\/ We need to create the initial kernel segments at compile time because\n\/\/ they are needed before memory allocations are possible.\nstatic MemorySegment userSegment(0, 0xC0000000, PROT_NONE, nullptr, nullptr);\nstatic MemorySegment videoSegment(0xC0000000, 0x1000, PROT_READ | PROT_WRITE,\n &userSegment, nullptr);\nstatic MemorySegment readOnlySegment((vaddr_t) &kernelVirtualBegin,\n (vaddr_t) &kernelReadOnlyEnd - (vaddr_t) &kernelVirtualBegin,\n PROT_READ | PROT_EXEC, &videoSegment, nullptr);\nstatic MemorySegment writableSegment((vaddr_t) &kernelReadOnlyEnd,\n (vaddr_t) &kernelVirtualEnd - (vaddr_t) &kernelReadOnlyEnd,\n PROT_READ | PROT_WRITE, &readOnlySegment, nullptr);\nstatic MemorySegment temporarySegment(0xFF7FF000, 0x1000,\n PROT_NONE, &writableSegment, nullptr);\nstatic MemorySegment physicalMemorySegment(RECURSIVE_MAPPING - 0x400000,\n 0x400000, PROT_READ | PROT_WRITE, &temporarySegment, nullptr);\nstatic MemorySegment recursiveMappingSegment(RECURSIVE_MAPPING,\n -RECURSIVE_MAPPING, PROT_READ | PROT_WRITE, &physicalMemorySegment,\n nullptr);\n\nvoid AddressSpace::initialize() {\n kernelSpace = &_kernelSpace;\n kernelSpace->pageDir = (paddr_t) &kernelPageDirectory;\n\n \/\/ Unmap the bootstrap sections\n vaddr_t p = (vaddr_t) &bootstrapBegin;\n\n while (p < (vaddr_t) &bootstrapEnd) {\n kernelSpace->unmap(p);\n p += 0x1000;\n }\n\n \/\/ Remove the mapping for the bootstrap page table\n \/\/ This is the first page table, so know it is mapped at RECURSIVE_MAPPING.\n kernelSpace->unmap(RECURSIVE_MAPPING);\n\n \/\/ Initialize segments for kernel space\n kernelSpace->firstSegment = &userSegment;\n userSegment.next = &videoSegment;\n videoSegment.next = &readOnlySegment;\n readOnlySegment.next = &writableSegment;\n writableSegment.next = &temporarySegment;\n temporarySegment.next = &physicalMemorySegment;\n physicalMemorySegment.next = &recursiveMappingSegment;\n}\n\nvoid AddressSpace::activate() {\n asm volatile (\"mov %0, %%cr3\" :: \"r\"(pageDir));\n}\n\nstatic kthread_mutex_t forkMutex = KTHREAD_MUTEX_INITIALIZER;\n\nAddressSpace* AddressSpace::fork() {\n AutoLock lock(&forkMutex);\n\n AddressSpace* result = new AddressSpace();\n MemorySegment* segment = firstSegment->next;\n while (segment) {\n if (!(segment->flags & SEG_NOUNMAP)) {\n \/\/ Copy the segment\n size_t size = segment->size;\n result->mapMemory(segment->address, size, segment->flags);\n vaddr_t source = kernelSpace->mapFromOtherAddressSpace(this,\n segment->address, size, PROT_READ);\n vaddr_t dest = kernelSpace->mapFromOtherAddressSpace(result,\n segment->address, size, PROT_WRITE);\n memcpy((void*) dest, (const void*) source, size);\n kernelSpace->unmapPhysical(source, size);\n kernelSpace->unmapPhysical(dest, size);\n }\n segment = segment->next;\n }\n\n return result;\n}\n\npaddr_t AddressSpace::getPhysicalAddress(vaddr_t virtualAddress) {\n size_t pdIndex;\n size_t ptIndex;\n addressToIndex(virtualAddress, pdIndex, ptIndex);\n\n uintptr_t* pageDirectory = (uintptr_t*) pageDirMapped;\n\n if (!pageDirectory[pdIndex]) {\n return 0;\n }\n\n uintptr_t* pageTable;\n if (this == kernelSpace) {\n pageTable = (uintptr_t*) (RECURSIVE_MAPPING + 0x1000 * pdIndex);\n } else {\n kthread_mutex_lock(&kernelSpace->mutex);\n pageTable = (uintptr_t*)\n mapTemporarily(pageDirectory[pdIndex] & ~0xFFF, PROT_READ);\n }\n\n paddr_t result = pageTable[ptIndex] & ~0xFFF;\n\n if (this != kernelSpace) {\n kernelSpace->unmap((vaddr_t) pageTable);\n kthread_mutex_unlock(&kernelSpace->mutex);\n }\n\n return result;\n}\n\nvaddr_t AddressSpace::mapAt(\n vaddr_t virtualAddress, paddr_t physicalAddress, int protection) {\n size_t pdIndex;\n size_t ptIndex;\n addressToIndex(virtualAddress, pdIndex, ptIndex);\n return mapAt(pdIndex, ptIndex, physicalAddress, protection);\n}\n\nvaddr_t AddressSpace::mapAt(size_t pdIndex, size_t ptIndex,\n paddr_t physicalAddress, int protection) {\n assert(!(protection & ~_PROT_FLAGS));\n assert(!(physicalAddress & 0xFFF));\n\n int flags = protectionToFlags(protection);\n\n if (this != kernelSpace) {\n \/\/ Memory in user space is always accessible by user.\n flags |= PAGE_USER;\n }\n\n return mapAtWithFlags(pdIndex, ptIndex, physicalAddress, flags);\n}\n\nvaddr_t AddressSpace::mapAtWithFlags(size_t pdIndex, size_t ptIndex,\n paddr_t physicalAddress, int flags) {\n assert(!(flags & ~0xFFF));\n assert(!(physicalAddress & 0xFFF));\n\n uintptr_t* pageDirectory = (uintptr_t*) pageDirMapped;\n uintptr_t* pageTable = nullptr;\n\n if (this == kernelSpace) {\n pageTable = (uintptr_t*) (RECURSIVE_MAPPING + 0x1000 * pdIndex);\n }\n\n if (!pageDirectory[pdIndex]) {\n \/\/ Allocate a new page table and map it in the page directory\n paddr_t pageTablePhys = PhysicalMemory::popPageFrame();\n int pdFlags = PAGE_PRESENT | PAGE_WRITABLE;\n if (this != kernelSpace) pdFlags |= PAGE_USER;\n\n pageDirectory[pdIndex] = pageTablePhys | pdFlags;\n\n if (this != kernelSpace) {\n kthread_mutex_lock(&kernelSpace->mutex);\n pageTable = (uintptr_t*)\n mapTemporarily(pageTablePhys, PROT_READ | PROT_WRITE);\n }\n\n memset(pageTable, 0, 0x1000);\n\n if (this == kernelSpace) {\n \/\/ We need to map that page table in all address spaces\n AutoLock lock(&listMutex);\n\n AddressSpace* addressSpace = firstAddressSpace;\n while (addressSpace) {\n uintptr_t* pd = (uintptr_t*) addressSpace->pageDirMapped;\n pd[pdIndex] = pageTablePhys | PAGE_PRESENT | PAGE_WRITABLE;\n addressSpace = addressSpace->next;\n }\n }\n\n } else if (this != kernelSpace) {\n kthread_mutex_lock(&kernelSpace->mutex);\n pageTable = (uintptr_t*) mapTemporarily(pageDirectory[pdIndex] &\n ~0xFFF, PROT_READ| PROT_WRITE);\n }\n\n pageTable[ptIndex] = physicalAddress | flags;\n\n if (this != kernelSpace) {\n kernelSpace->unmap((vaddr_t) pageTable);\n kthread_mutex_unlock(&kernelSpace->mutex);\n }\n\n vaddr_t virtualAddress = indexToAddress(pdIndex, ptIndex);\n\n \/\/ Flush the TLB\n asm volatile (\"invlpg (%0)\" :: \"r\"(virtualAddress));\n\n return virtualAddress;\n}\n\nvaddr_t AddressSpace::mapFromOtherAddressSpace(AddressSpace* sourceSpace,\n vaddr_t sourceVirtualAddress, size_t size, int protection) {\n kthread_mutex_lock(&mutex);\n vaddr_t destination = MemorySegment::findAndAddNewSegment(firstSegment,\n size, protection);\n kthread_mutex_unlock(&mutex);\n\n for (size_t i = 0 ; i < size; i += 0x1000) {\n kthread_mutex_lock(&sourceSpace->mutex);\n paddr_t physicalAddress =\n sourceSpace->getPhysicalAddress(sourceVirtualAddress + i);\n kthread_mutex_unlock(&sourceSpace->mutex);\n kthread_mutex_lock(&mutex);\n mapAt(destination + i, physicalAddress, protection);\n kthread_mutex_unlock(&mutex);\n }\n\n\n return destination;\n}\n\nvaddr_t AddressSpace::mapMemory(size_t size, int protection) {\n AutoLock lock(&mutex);\n\n vaddr_t virtualAddress = MemorySegment::findAndAddNewSegment(firstSegment,\n size, protection);\n paddr_t physicalAddress;\n\n for (size_t i = 0; i < size; i += 0x1000) {\n physicalAddress = PhysicalMemory::popPageFrame();\n if (!physicalAddress ||\n !mapAt(virtualAddress + i, physicalAddress, protection)) {\n return 0;\n }\n }\n\n return virtualAddress;\n}\n\nvaddr_t AddressSpace::mapMemory(vaddr_t virtualAddress, size_t size,\n int protection) {\n AutoLock lock(&mutex);\n\n MemorySegment::addSegment(firstSegment, virtualAddress, size, protection);\n paddr_t physicalAddress;\n\n for (size_t i = 0; i < size; i += 0x1000) {\n physicalAddress = PhysicalMemory::popPageFrame();\n if (!physicalAddress ||\n !mapAt(virtualAddress + i, physicalAddress, protection)) {\n return 0;\n }\n }\n\n return virtualAddress;\n}\n\nvaddr_t AddressSpace::mapPhysical(paddr_t physicalAddress, size_t size,\n int protection) {\n AutoLock lock(&mutex);\n\n vaddr_t virtualAddress = MemorySegment::findAndAddNewSegment(firstSegment,\n size, protection);\n for (size_t i = 0; i < size; i += 0x1000) {\n if (!mapAt(virtualAddress + i, physicalAddress + i, protection)) {\n return 0;\n }\n }\n\n return virtualAddress;\n}\n\nvoid AddressSpace::unmap(vaddr_t virtualAddress) {\n size_t pdIndex, ptIndex;\n addressToIndex(virtualAddress, pdIndex, ptIndex);\n mapAtWithFlags(pdIndex, ptIndex, 0, 0);\n}\n\nvoid AddressSpace::unmapMemory(vaddr_t virtualAddress, size_t size) {\n AutoLock lock(&mutex);\n\n for (size_t i = 0; i < size; i += 0x1000) {\n paddr_t physicalAddress = getPhysicalAddress(virtualAddress + i);\n unmap(virtualAddress + i);\n PhysicalMemory::pushPageFrame(physicalAddress);\n }\n\n MemorySegment::removeSegment(firstSegment, virtualAddress, size);\n}\n\nvoid AddressSpace::unmapPhysical(vaddr_t virtualAddress, size_t size) {\n AutoLock lock(&mutex);\n\n for (size_t i = 0; i < size; i += 0x1000) {\n unmap(virtualAddress + i);\n }\n\n MemorySegment::removeSegment(firstSegment, virtualAddress, size);\n}\nFix memory leak in AddressSpace::mapMemory().\/* Copyright (c) 2016, 2017, 2018 Dennis Wölfing\n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\/\n\n\/* kernel\/src\/addressspace.cpp\n * Address space class.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#define RECURSIVE_MAPPING 0xFFC00000\n\n#define PAGE_PRESENT (1 << 0)\n#define PAGE_WRITABLE (1 << 1)\n#define PAGE_USER (1 << 2)\n\nextern \"C\" {\nextern symbol_t bootstrapBegin;\nextern symbol_t bootstrapEnd;\nextern symbol_t kernelPageDirectory;\nextern symbol_t kernelVirtualBegin;\nextern symbol_t kernelReadOnlyEnd;\nextern symbol_t kernelVirtualEnd;\n}\n\nAddressSpace AddressSpace::_kernelSpace;\nAddressSpace* kernelSpace;\nstatic AddressSpace* firstAddressSpace = nullptr;\nstatic kthread_mutex_t listMutex = KTHREAD_MUTEX_INITIALIZER;\n\nstatic inline vaddr_t indexToAddress(size_t pdIndex, size_t ptIndex) {\n assert(pdIndex <= 0x3FF);\n assert(ptIndex <= 0x3FF);\n return (pdIndex << 22) | (ptIndex << 12);\n}\n\nstatic inline void addressToIndex(\n vaddr_t virtualAddress, size_t& pdIndex, size_t& ptIndex) {\n assert(!(virtualAddress & 0xFFF));\n pdIndex = virtualAddress >> 22;\n ptIndex = (virtualAddress >> 12) & 0x3FF;\n}\n\nstatic inline int protectionToFlags(int protection) {\n int flags = PAGE_PRESENT;\n if (protection & PROT_WRITE) flags |= PAGE_WRITABLE;\n return flags;\n}\n\nstatic vaddr_t mapTemporarily(paddr_t physicalAddress, int protection) {\n return kernelSpace->mapAt(0xFF7FF000, physicalAddress, protection);\n}\n\nAddressSpace::AddressSpace() {\n if (this == &_kernelSpace) {\n pageDir = 0;\n pageDirMapped = RECURSIVE_MAPPING + 0x3FF000;\n firstSegment = nullptr;\n prev = nullptr;\n next = nullptr;\n } else {\n pageDir = PhysicalMemory::popPageFrame();\n\n \/\/ Copy the page directory to the new address space\n vaddr_t kernelPageDir = kernelSpace->pageDirMapped;\n pageDirMapped = kernelSpace->mapPhysical(pageDir, 0x1000,\n PROT_READ | PROT_WRITE);\n\n firstSegment = new MemorySegment(0, 0x1000, PROT_NONE | SEG_NOUNMAP,\n nullptr, nullptr);\n MemorySegment::addSegment(firstSegment, 0xC0000000, -0xC0000000,\n PROT_NONE | SEG_NOUNMAP);\n\n prev = nullptr;\n AutoLock lock(&listMutex);\n memcpy((void*) pageDirMapped, (const void*) kernelPageDir, 0x1000);\n next = firstAddressSpace;\n if (next) {\n next->prev = this;\n }\n firstAddressSpace = this;\n }\n\n mutex = KTHREAD_MUTEX_INITIALIZER;\n}\n\nAddressSpace::~AddressSpace() {\n kthread_mutex_lock(&listMutex);\n if (prev) {\n prev->next = next;\n }\n if (next) {\n next->prev = prev;\n }\n if (this == firstAddressSpace) {\n firstAddressSpace = next;\n }\n kthread_mutex_unlock(&listMutex);\n\n MemorySegment* currentSegment = firstSegment;\n\n while (currentSegment) {\n MemorySegment* next = currentSegment->next;\n\n if (!(currentSegment->flags & SEG_NOUNMAP)) {\n unmapMemory(currentSegment->address, currentSegment->size);\n }\n currentSegment = next;\n }\n\n PhysicalMemory::pushPageFrame(pageDir);\n}\n\n\/\/ We need to create the initial kernel segments at compile time because\n\/\/ they are needed before memory allocations are possible.\nstatic MemorySegment userSegment(0, 0xC0000000, PROT_NONE, nullptr, nullptr);\nstatic MemorySegment videoSegment(0xC0000000, 0x1000, PROT_READ | PROT_WRITE,\n &userSegment, nullptr);\nstatic MemorySegment readOnlySegment((vaddr_t) &kernelVirtualBegin,\n (vaddr_t) &kernelReadOnlyEnd - (vaddr_t) &kernelVirtualBegin,\n PROT_READ | PROT_EXEC, &videoSegment, nullptr);\nstatic MemorySegment writableSegment((vaddr_t) &kernelReadOnlyEnd,\n (vaddr_t) &kernelVirtualEnd - (vaddr_t) &kernelReadOnlyEnd,\n PROT_READ | PROT_WRITE, &readOnlySegment, nullptr);\nstatic MemorySegment temporarySegment(0xFF7FF000, 0x1000,\n PROT_NONE, &writableSegment, nullptr);\nstatic MemorySegment physicalMemorySegment(RECURSIVE_MAPPING - 0x400000,\n 0x400000, PROT_READ | PROT_WRITE, &temporarySegment, nullptr);\nstatic MemorySegment recursiveMappingSegment(RECURSIVE_MAPPING,\n -RECURSIVE_MAPPING, PROT_READ | PROT_WRITE, &physicalMemorySegment,\n nullptr);\n\nvoid AddressSpace::initialize() {\n kernelSpace = &_kernelSpace;\n kernelSpace->pageDir = (paddr_t) &kernelPageDirectory;\n\n \/\/ Unmap the bootstrap sections\n vaddr_t p = (vaddr_t) &bootstrapBegin;\n\n while (p < (vaddr_t) &bootstrapEnd) {\n kernelSpace->unmap(p);\n p += 0x1000;\n }\n\n \/\/ Remove the mapping for the bootstrap page table\n \/\/ This is the first page table, so know it is mapped at RECURSIVE_MAPPING.\n kernelSpace->unmap(RECURSIVE_MAPPING);\n\n \/\/ Initialize segments for kernel space\n kernelSpace->firstSegment = &userSegment;\n userSegment.next = &videoSegment;\n videoSegment.next = &readOnlySegment;\n readOnlySegment.next = &writableSegment;\n writableSegment.next = &temporarySegment;\n temporarySegment.next = &physicalMemorySegment;\n physicalMemorySegment.next = &recursiveMappingSegment;\n}\n\nvoid AddressSpace::activate() {\n asm volatile (\"mov %0, %%cr3\" :: \"r\"(pageDir));\n}\n\nstatic kthread_mutex_t forkMutex = KTHREAD_MUTEX_INITIALIZER;\n\nAddressSpace* AddressSpace::fork() {\n AutoLock lock(&forkMutex);\n\n AddressSpace* result = new AddressSpace();\n MemorySegment* segment = firstSegment->next;\n while (segment) {\n if (!(segment->flags & SEG_NOUNMAP)) {\n \/\/ Copy the segment\n size_t size = segment->size;\n result->mapMemory(segment->address, size, segment->flags);\n vaddr_t source = kernelSpace->mapFromOtherAddressSpace(this,\n segment->address, size, PROT_READ);\n vaddr_t dest = kernelSpace->mapFromOtherAddressSpace(result,\n segment->address, size, PROT_WRITE);\n memcpy((void*) dest, (const void*) source, size);\n kernelSpace->unmapPhysical(source, size);\n kernelSpace->unmapPhysical(dest, size);\n }\n segment = segment->next;\n }\n\n return result;\n}\n\npaddr_t AddressSpace::getPhysicalAddress(vaddr_t virtualAddress) {\n size_t pdIndex;\n size_t ptIndex;\n addressToIndex(virtualAddress, pdIndex, ptIndex);\n\n uintptr_t* pageDirectory = (uintptr_t*) pageDirMapped;\n\n if (!pageDirectory[pdIndex]) {\n return 0;\n }\n\n uintptr_t* pageTable;\n if (this == kernelSpace) {\n pageTable = (uintptr_t*) (RECURSIVE_MAPPING + 0x1000 * pdIndex);\n } else {\n kthread_mutex_lock(&kernelSpace->mutex);\n pageTable = (uintptr_t*)\n mapTemporarily(pageDirectory[pdIndex] & ~0xFFF, PROT_READ);\n }\n\n paddr_t result = pageTable[ptIndex] & ~0xFFF;\n\n if (this != kernelSpace) {\n kernelSpace->unmap((vaddr_t) pageTable);\n kthread_mutex_unlock(&kernelSpace->mutex);\n }\n\n return result;\n}\n\nvaddr_t AddressSpace::mapAt(\n vaddr_t virtualAddress, paddr_t physicalAddress, int protection) {\n size_t pdIndex;\n size_t ptIndex;\n addressToIndex(virtualAddress, pdIndex, ptIndex);\n return mapAt(pdIndex, ptIndex, physicalAddress, protection);\n}\n\nvaddr_t AddressSpace::mapAt(size_t pdIndex, size_t ptIndex,\n paddr_t physicalAddress, int protection) {\n assert(!(protection & ~_PROT_FLAGS));\n assert(!(physicalAddress & 0xFFF));\n\n int flags = protectionToFlags(protection);\n\n if (this != kernelSpace) {\n \/\/ Memory in user space is always accessible by user.\n flags |= PAGE_USER;\n }\n\n return mapAtWithFlags(pdIndex, ptIndex, physicalAddress, flags);\n}\n\nvaddr_t AddressSpace::mapAtWithFlags(size_t pdIndex, size_t ptIndex,\n paddr_t physicalAddress, int flags) {\n assert(!(flags & ~0xFFF));\n assert(!(physicalAddress & 0xFFF));\n\n uintptr_t* pageDirectory = (uintptr_t*) pageDirMapped;\n uintptr_t* pageTable = nullptr;\n\n if (this == kernelSpace) {\n pageTable = (uintptr_t*) (RECURSIVE_MAPPING + 0x1000 * pdIndex);\n }\n\n if (!pageDirectory[pdIndex]) {\n \/\/ Allocate a new page table and map it in the page directory\n paddr_t pageTablePhys = PhysicalMemory::popPageFrame();\n int pdFlags = PAGE_PRESENT | PAGE_WRITABLE;\n if (this != kernelSpace) pdFlags |= PAGE_USER;\n\n pageDirectory[pdIndex] = pageTablePhys | pdFlags;\n\n if (this != kernelSpace) {\n kthread_mutex_lock(&kernelSpace->mutex);\n pageTable = (uintptr_t*)\n mapTemporarily(pageTablePhys, PROT_READ | PROT_WRITE);\n }\n\n memset(pageTable, 0, 0x1000);\n\n if (this == kernelSpace) {\n \/\/ We need to map that page table in all address spaces\n AutoLock lock(&listMutex);\n\n AddressSpace* addressSpace = firstAddressSpace;\n while (addressSpace) {\n uintptr_t* pd = (uintptr_t*) addressSpace->pageDirMapped;\n pd[pdIndex] = pageTablePhys | PAGE_PRESENT | PAGE_WRITABLE;\n addressSpace = addressSpace->next;\n }\n }\n\n } else if (this != kernelSpace) {\n kthread_mutex_lock(&kernelSpace->mutex);\n pageTable = (uintptr_t*) mapTemporarily(pageDirectory[pdIndex] &\n ~0xFFF, PROT_READ| PROT_WRITE);\n }\n\n pageTable[ptIndex] = physicalAddress | flags;\n\n if (this != kernelSpace) {\n kernelSpace->unmap((vaddr_t) pageTable);\n kthread_mutex_unlock(&kernelSpace->mutex);\n }\n\n vaddr_t virtualAddress = indexToAddress(pdIndex, ptIndex);\n\n \/\/ Flush the TLB\n asm volatile (\"invlpg (%0)\" :: \"r\"(virtualAddress));\n\n return virtualAddress;\n}\n\nvaddr_t AddressSpace::mapFromOtherAddressSpace(AddressSpace* sourceSpace,\n vaddr_t sourceVirtualAddress, size_t size, int protection) {\n kthread_mutex_lock(&mutex);\n vaddr_t destination = MemorySegment::findAndAddNewSegment(firstSegment,\n size, protection);\n kthread_mutex_unlock(&mutex);\n\n for (size_t i = 0 ; i < size; i += 0x1000) {\n kthread_mutex_lock(&sourceSpace->mutex);\n paddr_t physicalAddress =\n sourceSpace->getPhysicalAddress(sourceVirtualAddress + i);\n kthread_mutex_unlock(&sourceSpace->mutex);\n kthread_mutex_lock(&mutex);\n mapAt(destination + i, physicalAddress, protection);\n kthread_mutex_unlock(&mutex);\n }\n\n\n return destination;\n}\n\nvaddr_t AddressSpace::mapMemory(size_t size, int protection) {\n AutoLock lock(&mutex);\n\n vaddr_t virtualAddress = MemorySegment::findAndAddNewSegment(firstSegment,\n size, protection);\n paddr_t physicalAddress;\n\n for (size_t i = 0; i < size; i += 0x1000) {\n physicalAddress = PhysicalMemory::popPageFrame();\n if (!physicalAddress ||\n !mapAt(virtualAddress + i, physicalAddress, protection)) {\n if (physicalAddress) {\n PhysicalMemory::pushPageFrame(physicalAddress);\n }\n for (i = i - 0x1000; i < size; i -= 0x1000) {\n physicalAddress = getPhysicalAddress(virtualAddress + i);\n unmap(virtualAddress + i);\n PhysicalMemory::pushPageFrame(physicalAddress);\n }\n MemorySegment::removeSegment(firstSegment, virtualAddress, size);\n return 0;\n }\n }\n\n return virtualAddress;\n}\n\nvaddr_t AddressSpace::mapMemory(vaddr_t virtualAddress, size_t size,\n int protection) {\n AutoLock lock(&mutex);\n\n MemorySegment::addSegment(firstSegment, virtualAddress, size, protection);\n paddr_t physicalAddress;\n\n for (size_t i = 0; i < size; i += 0x1000) {\n physicalAddress = PhysicalMemory::popPageFrame();\n if (!physicalAddress ||\n !mapAt(virtualAddress + i, physicalAddress, protection)) {\n if (physicalAddress) {\n PhysicalMemory::pushPageFrame(physicalAddress);\n }\n for (i = i - 0x1000; i < size; i -= 0x1000) {\n physicalAddress = getPhysicalAddress(virtualAddress + i);\n unmap(virtualAddress + i);\n PhysicalMemory::pushPageFrame(physicalAddress);\n }\n MemorySegment::removeSegment(firstSegment, virtualAddress, size);\n return 0;\n }\n }\n\n return virtualAddress;\n}\n\nvaddr_t AddressSpace::mapPhysical(paddr_t physicalAddress, size_t size,\n int protection) {\n AutoLock lock(&mutex);\n\n vaddr_t virtualAddress = MemorySegment::findAndAddNewSegment(firstSegment,\n size, protection);\n for (size_t i = 0; i < size; i += 0x1000) {\n if (!mapAt(virtualAddress + i, physicalAddress + i, protection)) {\n return 0;\n }\n }\n\n return virtualAddress;\n}\n\nvoid AddressSpace::unmap(vaddr_t virtualAddress) {\n size_t pdIndex, ptIndex;\n addressToIndex(virtualAddress, pdIndex, ptIndex);\n mapAtWithFlags(pdIndex, ptIndex, 0, 0);\n}\n\nvoid AddressSpace::unmapMemory(vaddr_t virtualAddress, size_t size) {\n AutoLock lock(&mutex);\n\n for (size_t i = 0; i < size; i += 0x1000) {\n paddr_t physicalAddress = getPhysicalAddress(virtualAddress + i);\n unmap(virtualAddress + i);\n PhysicalMemory::pushPageFrame(physicalAddress);\n }\n\n MemorySegment::removeSegment(firstSegment, virtualAddress, size);\n}\n\nvoid AddressSpace::unmapPhysical(vaddr_t virtualAddress, size_t size) {\n AutoLock lock(&mutex);\n\n for (size_t i = 0; i < size; i += 0x1000) {\n unmap(virtualAddress + i);\n }\n\n MemorySegment::removeSegment(firstSegment, virtualAddress, size);\n}\n<|endoftext|>"} {"text":"\/*\n * This file is part of Poedit (https:\/\/poedit.net)\n *\n * Copyright (C) 2017 Vaclav Slavik\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\n *\/\n\n#include \"qa_checks.h\"\n\n#include \n\n#include \n\n\n\/\/ -------------------------------------------------------------\n\/\/ QACheck implementations\n\/\/ -------------------------------------------------------------\n\nnamespace QA\n{\n\n} \/\/ namespace QA\n\n\n\/\/ -------------------------------------------------------------\n\/\/ QACheck support code\n\/\/ -------------------------------------------------------------\n\nbool QACheck::CheckItem(CatalogItemPtr item)\n{\n if (!item->GetTranslation().empty() && CheckString(item, item->GetString(), item->GetTranslation()))\n return true;\n\n if (item->HasPlural())\n {\n unsigned count = item->GetNumberOfTranslations();\n for (unsigned i = 1; i < count; i++)\n {\n auto t = item->GetTranslation(i);\n if (!t.empty() && CheckString(item, item->GetPluralString(), t))\n return true;\n }\n }\n\n return false;\n}\n\n\nbool QACheck::CheckString(CatalogItemPtr \/*item*\/, const wxString& \/*source*\/, const wxString& \/*translation*\/)\n{\n wxFAIL_MSG(\"not implemented - must override CheckString OR CheckItem\");\n return false;\n}\n\n\n\/\/ -------------------------------------------------------------\n\/\/ QAChecker\n\/\/ -------------------------------------------------------------\n\nint QAChecker::Check(Catalog& catalog)\n{\n \/\/ TODO: parallelize this (make async tasks for chunks of the catalog)\n \/\/ doing it per-checker is MT-unsafe with API that calls SetIssue()!\n\n int issues = 0;\n\n for (auto& i: catalog.items())\n issues += Check(i);\n\n return issues;\n}\n\n\nint QAChecker::Check(CatalogItemPtr item)\n{\n int issues = 0;\n\n for (auto& c: m_checks)\n {\n if (item->GetString().empty() || (item->HasPlural() && item->GetPluralString().empty()))\n continue;\n\n if (c->CheckItem(item))\n issues++;\n }\n\n return issues;\n}\n\n\nstd::shared_ptr QAChecker::GetFor(Catalog& \/*catalog*\/)\n{\n auto c = std::make_shared();\n return c;\n}\nImplement a few basic QA checks\/*\n * This file is part of Poedit (https:\/\/poedit.net)\n *\n * Copyright (C) 2017 Vaclav Slavik\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\n *\/\n\n#include \"qa_checks.h\"\n\n#include \n\n#include \n\n\n\/\/ -------------------------------------------------------------\n\/\/ QACheck implementations\n\/\/ -------------------------------------------------------------\n\nnamespace QA\n{\n\nclass NotAllPlurals : public QACheck\n{\npublic:\n bool CheckItem(CatalogItemPtr item) override\n {\n if (!item->HasPlural())\n return false;\n\n bool foundTranslated = false;\n bool foundEmpty = false;\n for (auto& s: item->GetTranslations())\n {\n if (s.empty())\n foundEmpty = true;\n else\n foundTranslated = true;\n }\n\n if (foundEmpty && foundTranslated)\n {\n item->SetIssue(CatalogItem::Issue::Warning, _(\"Not all plural forms are translated.\"));\n return true;\n }\n\n return false;\n }\n};\n\n\nclass CaseMismatch : public QACheck\n{\npublic:\n bool CheckString(CatalogItemPtr item, const wxString& source, const wxString& translation) override\n {\n if (u_isupper(source[0]) && u_islower(translation[0]))\n {\n item->SetIssue(CatalogItem::Issue::Warning, _(\"The translation should start as a sentence.\"));\n return true;\n }\n\n if (u_islower(source[0]) && u_isupper(translation[0]))\n {\n item->SetIssue(CatalogItem::Issue::Warning, _(\"The translation should start with a lowercase character.\"));\n return true;\n }\n\n return false;\n }\n};\n\n\nclass WhitespaceMismatch : public QACheck\n{\npublic:\n bool CheckString(CatalogItemPtr item, const wxString& source, const wxString& translation) override\n {\n if (u_isspace(source[0]) && !u_isspace(translation[0]))\n {\n item->SetIssue(CatalogItem::Issue::Warning, _(L\"The translation doesn’t start with a space.\"));\n return true;\n }\n\n if (!u_isspace(source[0]) && u_isspace(translation[0]))\n {\n item->SetIssue(CatalogItem::Issue::Warning, _(L\"The translation starts with a space, but the source text doesn’t.\"));\n return true;\n }\n\n if (source.Last() == '\\n' && translation.Last() != '\\n')\n {\n item->SetIssue(CatalogItem::Issue::Warning, _(L\"The translation is missing a newline at the end.\"));\n return true;\n }\n\n if (source.Last() != '\\n' && translation.Last() == '\\n')\n {\n item->SetIssue(CatalogItem::Issue::Warning, _(L\"The translation ends with a newline, but the source text doesn’t.\"));\n return true;\n }\n\n if (u_isspace(source.Last()) && !u_isspace(translation.Last()))\n {\n item->SetIssue(CatalogItem::Issue::Warning, _(L\"The translation is missing a space at the end.\"));\n return true;\n }\n\n if (!u_isspace(source.Last()) && u_isspace(translation.Last()))\n {\n item->SetIssue(CatalogItem::Issue::Warning, _(L\"The translation ends with a space, but the source text doesn’t.\"));\n return true;\n }\n\n return false;\n }\n};\n\n\nclass PunctuationMismatch : public QACheck\n{\npublic:\n bool CheckString(CatalogItemPtr item, const wxString& source, const wxString& translation) override\n {\n const UChar32 s_last = source.Last();\n const UChar32 t_last = translation.Last();\n const bool s_punct = u_ispunct(s_last);\n const bool t_punct = u_ispunct(t_last);\n\n if (s_punct && !t_punct)\n {\n item->SetIssue(CatalogItem::Issue::Warning,\n wxString::Format(_(L\"The translation should end with “%s”.\"), wxString(wxUniChar(s_last))));\n return true;\n }\n else if (!s_punct && t_punct)\n {\n item->SetIssue(CatalogItem::Issue::Warning,\n wxString::Format(_(L\"The translation should not end with “%s”.\"), wxString(wxUniChar(t_last))));\n return true;\n }\n else if (s_punct && t_punct && s_last != t_last)\n {\n if (t_last == L'…' && source.EndsWith(\"...\"))\n {\n \/\/ as a special case, allow translating ... (3 dots) as … (ellipsis)\n }\n else\n {\n item->SetIssue(CatalogItem::Issue::Warning,\n wxString::Format(_(L\"The translation ends with “%s”, but the source text ends with “%s”.\"),\n wxString(wxUniChar(s_last)), wxString(wxUniChar(t_last))));\n return true;\n }\n }\n\n return false;\n }\n};\n\n\n} \/\/ namespace QA\n\n\n\/\/ -------------------------------------------------------------\n\/\/ QACheck support code\n\/\/ -------------------------------------------------------------\n\nbool QACheck::CheckItem(CatalogItemPtr item)\n{\n if (!item->GetTranslation().empty() && CheckString(item, item->GetString(), item->GetTranslation()))\n return true;\n\n if (item->HasPlural())\n {\n unsigned count = item->GetNumberOfTranslations();\n for (unsigned i = 1; i < count; i++)\n {\n auto t = item->GetTranslation(i);\n if (!t.empty() && CheckString(item, item->GetPluralString(), t))\n return true;\n }\n }\n\n return false;\n}\n\n\nbool QACheck::CheckString(CatalogItemPtr \/*item*\/, const wxString& \/*source*\/, const wxString& \/*translation*\/)\n{\n wxFAIL_MSG(\"not implemented - must override CheckString OR CheckItem\");\n return false;\n}\n\n\n\/\/ -------------------------------------------------------------\n\/\/ QAChecker\n\/\/ -------------------------------------------------------------\n\nint QAChecker::Check(Catalog& catalog)\n{\n \/\/ TODO: parallelize this (make async tasks for chunks of the catalog)\n \/\/ doing it per-checker is MT-unsafe with API that calls SetIssue()!\n\n int issues = 0;\n\n for (auto& i: catalog.items())\n issues += Check(i);\n\n return issues;\n}\n\n\nint QAChecker::Check(CatalogItemPtr item)\n{\n int issues = 0;\n\n for (auto& c: m_checks)\n {\n if (item->GetString().empty() || (item->HasPlural() && item->GetPluralString().empty()))\n continue;\n\n if (c->CheckItem(item))\n issues++;\n }\n\n return issues;\n}\n\n\nstd::shared_ptr QAChecker::GetFor(Catalog& \/*catalog*\/)\n{\n auto c = std::make_shared();\n c->AddCheck();\n c->AddCheck();\n c->AddCheck();\n c->AddCheck();\n return c;\n}\n<|endoftext|>"} {"text":"[operators.oswaldinterpolation] drop dead code<|endoftext|>"} {"text":"Fix up some unit tests for HostResolver:<|endoftext|>"} {"text":"\/*\n Copyright (C) 2015 Preet Desai (preet.desai@gmail.com)\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n\n#ifndef KS_TEXT_DATATYPES_HPP\n#define KS_TEXT_DATATYPES_HPP\n\n#include \n#include \n\nnamespace ks\n{\n namespace text\n {\n \/\/ =========================================================== \/\/\n\n struct Hint\n {\n enum class FontSearch\n {\n Fallback,\n Explicit\n };\n\n enum class Script\n {\n Single,\n Multiple\n };\n\n enum class Direction\n {\n LeftToRight,\n RightToLeft,\n Multiple\n };\n\n std::vector list_prio_fonts;\n std::vector list_fallback_fonts;\n\n FontSearch font_search{FontSearch::Fallback};\n Direction direction{Direction::LeftToRight};\n Script script{Script::Single};\n\n uint glyph_res_px;\n };\n\n \/\/ =========================================================== \/\/\n\n struct Glyph\n {\n uint cluster;\n uint atlas;\n\n \/\/ texture coords (pixels) for the top\n \/\/ left corner of the glyph tex in its atlas\n u16 tex_x;\n u16 tex_y;\n\n \/\/ sdf quad <--> glyph offset vector (pixels)\n u16 sdf_x;\n u16 sdf_y;\n\n s32 x0;\n s32 y0;\n s32 x1; \/\/ x1 is to the right of x0\n s32 y1; \/\/ y1 is below y0\n };\n\n \/\/ =========================================================== \/\/\n\n struct Line\n {\n uint start;\n uint end;\n\n sint x_min;\n sint x_max;\n sint y_min; \/\/ equivalent to descent\n sint y_max; \/\/ equivalent to ascent\n\n \/\/ This is the vertical spacing between this line\n \/\/ and the next, determined by getting the max line\n \/\/ height of all the font faces used in this line.\n \/\/ Its set by the font designer and not necessarily\n \/\/ equal to y_max-y_min\n uint spacing;\n\n std::vector list_glyphs;\n };\n\n \/\/ =========================================================== \/\/\n }\n} \/\/ raintk\n\n#endif \/\/ KS_TEXT_DATATYPES_HPP\nFixed typo in comment\/*\n Copyright (C) 2015 Preet Desai (preet.desai@gmail.com)\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n\n#ifndef KS_TEXT_DATATYPES_HPP\n#define KS_TEXT_DATATYPES_HPP\n\n#include \n#include \n\nnamespace ks\n{\n namespace text\n {\n \/\/ =========================================================== \/\/\n\n struct Hint\n {\n enum class FontSearch\n {\n Fallback,\n Explicit\n };\n\n enum class Script\n {\n Single,\n Multiple\n };\n\n enum class Direction\n {\n LeftToRight,\n RightToLeft,\n Multiple\n };\n\n std::vector list_prio_fonts;\n std::vector list_fallback_fonts;\n\n FontSearch font_search{FontSearch::Fallback};\n Direction direction{Direction::LeftToRight};\n Script script{Script::Single};\n\n uint glyph_res_px;\n };\n\n \/\/ =========================================================== \/\/\n\n struct Glyph\n {\n uint cluster;\n uint atlas;\n\n \/\/ texture coords (pixels) for the top\n \/\/ left corner of the glyph tex in its atlas\n u16 tex_x;\n u16 tex_y;\n\n \/\/ sdf quad <--> glyph offset vector (pixels)\n u16 sdf_x;\n u16 sdf_y;\n\n s32 x0;\n s32 y0;\n s32 x1; \/\/ x1 is to the right of x0\n s32 y1; \/\/ y1 is above y0\n };\n\n \/\/ =========================================================== \/\/\n\n struct Line\n {\n uint start;\n uint end;\n\n sint x_min;\n sint x_max;\n sint y_min; \/\/ equivalent to descent\n sint y_max; \/\/ equivalent to ascent\n\n \/\/ This is the vertical spacing between this line\n \/\/ and the next, determined by getting the max line\n \/\/ height of all the font faces used in this line.\n \/\/ Its set by the font designer and not necessarily\n \/\/ equal to y_max-y_min\n uint spacing;\n\n std::vector list_glyphs;\n };\n\n \/\/ =========================================================== \/\/\n }\n} \/\/ raintk\n\n#endif \/\/ KS_TEXT_DATATYPES_HPP\n<|endoftext|>"} {"text":"INTEGRATION: CWS warnings01 (1.4.24); FILE MERGED 2006\/04\/07 19:20:29 sb 1.4.24.2: RESYNC: (1.4-1.5); FILE MERGED 2005\/11\/16 16:42:14 pl 1.4.24.1: #i55991# removed warnings<|endoftext|>"} {"text":"\/*****************************************************************************\nCopyright (c) 2001 - 2011, The Board of Trustees of the University of Illinois.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n* Redistributions of source code must retain the above\n copyright notice, this list of conditions and the\n following disclaimer.\n\n* Redistributions in binary form must reproduce the\n above copyright notice, this list of conditions\n and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\n* Neither the name of the University of Illinois\n nor the names of its contributors may be used to\n endorse or promote products derived from this\n software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\nIS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*****************************************************************************\/\n\n\/*****************************************************************************\nwritten by\n Yunhong Gu, last updated 01\/01\/2011\n*****************************************************************************\/\n\n#ifdef LINUX\n #include \n #include \n#endif\n#include \n#include \n#include \n#include \n\n#include \"common.h\"\n#include \"epoll.h\"\n#include \"udt.h\"\n\nusing namespace std;\n\nCEPoll::CEPoll():\nm_iIDSeed(0)\n{\n CGuard::createMutex(m_EPollLock);\n}\n\nCEPoll::~CEPoll()\n{\n CGuard::releaseMutex(m_EPollLock);\n}\n\nint CEPoll::create()\n{\n CGuard pg(m_EPollLock);\n\n int localid = 0;\n\n #ifdef LINUX\n localid = epoll_create(1024);\n if (localid < 0)\n throw CUDTException(-1, 0, errno);\n #else\n \/\/ on BSD, use kqueue\n \/\/ on Solaris, use \/dev\/poll\n \/\/ on Windows, select\n #endif\n\n if (++ m_iIDSeed >= 0x7FFFFFFF)\n m_iIDSeed = 0;\n\n CEPollDesc desc;\n desc.m_iID = m_iIDSeed;\n desc.m_iLocalID = localid;\n m_mPolls[desc.m_iID] = desc;\n\n return desc.m_iID;\n}\n\nint CEPoll::add_usock(const int eid, const UDTSOCKET& u, const int* events)\n{\n CGuard pg(m_EPollLock);\n\n map::iterator p = m_mPolls.find(eid);\n if (p == m_mPolls.end())\n throw CUDTException(5, 13);\n\n if (!events || (*events & UDT_EPOLL_IN))\n p->second.m_sUDTSocksIn.insert(u);\n if (!events || (*events & UDT_EPOLL_OUT))\n p->second.m_sUDTSocksOut.insert(u);\n\n return 0;\n}\n\nint CEPoll::add_ssock(const int eid, const SYSSOCKET& s, const int* events)\n{\n CGuard pg(m_EPollLock);\n\n map::iterator p = m_mPolls.find(eid);\n if (p == m_mPolls.end())\n throw CUDTException(5, 13);\n\n#ifdef LINUX\n epoll_event ev;\n\n if (NULL == events)\n ev.events = EPOLLIN | EPOLLOUT | EPOLLERR;\n else\n {\n ev.events = 0;\n if (*events & UDT_EPOLL_IN)\n ev.events |= EPOLLIN;\n if (*events & UDT_EPOLL_OUT)\n ev.events |= EPOLLOUT;\n if (*events & UDT_EPOLL_ERR)\n ev.events |= EPOLLERR;\n }\n\n ev.data.fd = s;\n if (epoll_ctl(p->second.m_iLocalID, EPOLL_CTL_ADD, s, &ev) < 0)\n throw CUDTException();\n#endif\n\n p->second.m_sLocals.insert(s);\n\n return 0;\n}\n\nint CEPoll::remove_usock(const int eid, const UDTSOCKET& u)\n{\n CGuard pg(m_EPollLock);\n\n map::iterator p = m_mPolls.find(eid);\n if (p == m_mPolls.end())\n throw CUDTException(5, 13);\n\n p->second.m_sUDTSocksIn.erase(u);\n p->second.m_sUDTSocksOut.erase(u);\n\n \/\/ when the socket is removed from a monitoring, it is not available anymore for any IO notification\n p->second.m_sUDTReads.erase(u);\n p->second.m_sUDTWrites.erase(u);\n\n return 0;\n}\n\nint CEPoll::remove_ssock(const int eid, const SYSSOCKET& s)\n{\n CGuard pg(m_EPollLock);\n\n map::iterator p = m_mPolls.find(eid);\n if (p == m_mPolls.end())\n throw CUDTException(5, 13);\n\n#ifdef LINUX\n epoll_event ev; \/\/ ev is ignored, for compatibility with old Linux kernel only.\n if (epoll_ctl(p->second.m_iLocalID, EPOLL_CTL_DEL, s, &ev) < 0)\n throw CUDTException();\n#endif\n\n p->second.m_sLocals.erase(s);\n\n return 0;\n}\n\nint CEPoll::wait(const int eid, set* readfds, set* writefds, int64_t msTimeOut, set* lrfds, set* lwfds)\n{\n \/\/ if all fields is NULL and waiting time is infinite, then this would be a deadlock\n if (!readfds && !writefds && !lrfds && lwfds && (msTimeOut < 0))\n throw CUDTException(5, 3, 0);\n\n \/\/ Clear these sets in case the app forget to do it.\n if (readfds) readfds->clear();\n if (writefds) writefds->clear();\n if (lrfds) lrfds->clear();\n if (lwfds) lwfds->clear();\n\n int total = 0;\n\n int64_t entertime = CTimer::getTime();\n while (true)\n {\n CGuard::enterCS(m_EPollLock);\n\n map::iterator p = m_mPolls.find(eid);\n if (p == m_mPolls.end())\n {\n CGuard::leaveCS(m_EPollLock);\n throw CUDTException(5, 13);\n }\n\n if (p->second.m_sUDTSocksIn.empty() && p->second.m_sUDTSocksOut.empty() && p->second.m_sLocals.empty() && (msTimeOut < 0))\n {\n \/\/ no socket is being monitored, this may be a deadlock\n CGuard::leaveCS(m_EPollLock);\n throw CUDTException(5, 3);\n }\n\n if ((NULL != readfds) && !p->second.m_sUDTReads.empty())\n {\n *readfds = p->second.m_sUDTReads;\n total += p->second.m_sUDTReads.size();\n }\n\n if ((NULL != writefds) && !p->second.m_sUDTWrites.empty())\n {\n *writefds = p->second.m_sUDTWrites;\n total += p->second.m_sUDTWrites.size();\n }\n\n if (lrfds || lwfds)\n {\n #ifdef LINUX\n const int max_events = p->second.m_sLocals.size();\n epoll_event ev[max_events];\n int nfds = epoll_wait(p->second.m_iLocalID, ev, max_events, 0);\n\n for (int i = 0; i < nfds; ++ i)\n {\n if ((NULL != lrfds) && (ev[i].events & EPOLLIN))\n {\n lrfds->insert(ev[i].data.fd);\n ++ total;\n }\n if ((NULL != lwfds) && (ev[i].events & EPOLLOUT))\n {\n lwfds->insert(ev[i].data.fd);\n ++ total;\n }\n }\n #else\n \/\/currently \"select\" is used for all non-Linux platforms.\n \/\/faster approaches can be applied for specific systems in the future.\n\n \/\/\"select\" has a limitation on the number of sockets\n\n fd_set readfds;\n fd_set writefds;\n FD_ZERO(&readfds);\n FD_ZERO(&writefds);\n\n for (set::const_iterator i = p->second.m_sLocals.begin(); i != p->second.m_sLocals.end(); ++ i)\n {\n if (lrfds)\n FD_SET(*i, &readfds);\n if (lwfds)\n FD_SET(*i, &writefds);\n }\n\n timeval tv;\n tv.tv_sec = 0;\n tv.tv_usec = 0;\n if (select(0, &readfds, &writefds, NULL, &tv) > 0\n {\n for (set::const_iterator i = p->second.m_sLocals.begin(); i != p->second.m_sLocals.end(); ++ i)\n {\n if (lrfds && FD_ISSET(*i, &readfds))\n {\n lrfds->insert(*i);\n ++ total;\n }\n if (lwfds && (FD_ISSET(*i, &writefds))\n {\n lwfds->insert(*i);\n ++ total;\n }\n }\n }\n #endif\n }\n\n CGuard::leaveCS(m_EPollLock);\n\n if (total > 0)\n return total;\n\n if ((msTimeOut >= 0) && (int64_t(CTimer::getTime() - entertime) >= msTimeOut * 1000LL))\n break;\n\n CTimer::waitForEvent();\n }\n\n return 0;\n}\n\nint CEPoll::release(const int eid)\n{\n CGuard pg(m_EPollLock);\n\n map::iterator i = m_mPolls.find(eid);\n if (i == m_mPolls.end())\n throw CUDTException(5, 13);\n\n #ifdef LINUX\n \/\/ release local\/system epoll descriptor\n ::close(i->second.m_iLocalID);\n #endif\n\n m_mPolls.erase(i);\n\n return 0;\n}\n\nint CEPoll::enable_write(const UDTSOCKET& uid, set& eids)\n{\n CGuard pg(m_EPollLock);\n\n map::iterator p;\n\n vector lost;\n for (set::iterator i = eids.begin(); i != eids.end(); ++ i)\n {\n p = m_mPolls.find(*i);\n if (p == m_mPolls.end())\n {\n lost.push_back(*i);\n }\n else if (p->second.m_sUDTSocksOut.find(uid) != p->second.m_sUDTSocksOut.end())\n {\n p->second.m_sUDTWrites.insert(uid);\n }\n }\n\n for (vector::iterator i = lost.begin(); i != lost.end(); ++ i)\n eids.erase(*i);\n\n return 0;\n}\n\nint CEPoll::enable_read(const UDTSOCKET& uid, set& eids)\n{\n CGuard pg(m_EPollLock);\n\n map::iterator p;\n\n vector lost;\n for (set::iterator i = eids.begin(); i != eids.end(); ++ i)\n {\n p = m_mPolls.find(*i);\n if (p == m_mPolls.end())\n {\n lost.push_back(*i);\n }\n else if (p->second.m_sUDTSocksIn.find(uid) != p->second.m_sUDTSocksIn.end())\n {\n p->second.m_sUDTReads.insert(uid);\n }\n }\n\n for (vector::iterator i = lost.begin(); i != lost.end(); ++ i)\n eids.erase(*i);\n\n return 0;\n}\n\nint CEPoll::disable_write(const UDTSOCKET& uid, set& eids)\n{\n CGuard pg(m_EPollLock);\n\n map::iterator p;\n\n vector lost;\n for (set::iterator i = eids.begin(); i != eids.end(); ++ i)\n {\n p = m_mPolls.find(*i);\n if (p == m_mPolls.end())\n {\n lost.push_back(*i);\n }\n else\n {\n p->second.m_sUDTWrites.erase(uid);\n }\n }\n\n for (vector::iterator i = lost.begin(); i != lost.end(); ++ i)\n eids.erase(*i);\n\n return 0;\n}\n\nint CEPoll::disable_read(const UDTSOCKET& uid, set& eids)\n{\n CGuard pg(m_EPollLock);\n\n map::iterator p;\n\n vector lost;\n for (set::iterator i = eids.begin(); i != eids.end(); ++ i)\n {\n p = m_mPolls.find(*i);\n if (p == m_mPolls.end())\n {\n lost.push_back(*i);\n }\n else\n {\n p->second.m_sUDTReads.erase(uid);\n }\n }\n\n for (vector::iterator i = lost.begin(); i != lost.end(); ++ i)\n eids.erase(*i);\n\n return 0;\n}\nwindows compile error fix\/*****************************************************************************\nCopyright (c) 2001 - 2011, The Board of Trustees of the University of Illinois.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n* Redistributions of source code must retain the above\n copyright notice, this list of conditions and the\n following disclaimer.\n\n* Redistributions in binary form must reproduce the\n above copyright notice, this list of conditions\n and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\n* Neither the name of the University of Illinois\n nor the names of its contributors may be used to\n endorse or promote products derived from this\n software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\nIS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*****************************************************************************\/\n\n\/*****************************************************************************\nwritten by\n Yunhong Gu, last updated 01\/01\/2011\n*****************************************************************************\/\n\n#ifdef LINUX\n #include \n #include \n#endif\n#include \n#include \n#include \n#include \n\n#include \"common.h\"\n#include \"epoll.h\"\n#include \"udt.h\"\n\nusing namespace std;\n\nCEPoll::CEPoll():\nm_iIDSeed(0)\n{\n CGuard::createMutex(m_EPollLock);\n}\n\nCEPoll::~CEPoll()\n{\n CGuard::releaseMutex(m_EPollLock);\n}\n\nint CEPoll::create()\n{\n CGuard pg(m_EPollLock);\n\n int localid = 0;\n\n #ifdef LINUX\n localid = epoll_create(1024);\n if (localid < 0)\n throw CUDTException(-1, 0, errno);\n #else\n \/\/ on BSD, use kqueue\n \/\/ on Solaris, use \/dev\/poll\n \/\/ on Windows, select\n #endif\n\n if (++ m_iIDSeed >= 0x7FFFFFFF)\n m_iIDSeed = 0;\n\n CEPollDesc desc;\n desc.m_iID = m_iIDSeed;\n desc.m_iLocalID = localid;\n m_mPolls[desc.m_iID] = desc;\n\n return desc.m_iID;\n}\n\nint CEPoll::add_usock(const int eid, const UDTSOCKET& u, const int* events)\n{\n CGuard pg(m_EPollLock);\n\n map::iterator p = m_mPolls.find(eid);\n if (p == m_mPolls.end())\n throw CUDTException(5, 13);\n\n if (!events || (*events & UDT_EPOLL_IN))\n p->second.m_sUDTSocksIn.insert(u);\n if (!events || (*events & UDT_EPOLL_OUT))\n p->second.m_sUDTSocksOut.insert(u);\n\n return 0;\n}\n\nint CEPoll::add_ssock(const int eid, const SYSSOCKET& s, const int* events)\n{\n CGuard pg(m_EPollLock);\n\n map::iterator p = m_mPolls.find(eid);\n if (p == m_mPolls.end())\n throw CUDTException(5, 13);\n\n#ifdef LINUX\n epoll_event ev;\n\n if (NULL == events)\n ev.events = EPOLLIN | EPOLLOUT | EPOLLERR;\n else\n {\n ev.events = 0;\n if (*events & UDT_EPOLL_IN)\n ev.events |= EPOLLIN;\n if (*events & UDT_EPOLL_OUT)\n ev.events |= EPOLLOUT;\n if (*events & UDT_EPOLL_ERR)\n ev.events |= EPOLLERR;\n }\n\n ev.data.fd = s;\n if (epoll_ctl(p->second.m_iLocalID, EPOLL_CTL_ADD, s, &ev) < 0)\n throw CUDTException();\n#endif\n\n p->second.m_sLocals.insert(s);\n\n return 0;\n}\n\nint CEPoll::remove_usock(const int eid, const UDTSOCKET& u)\n{\n CGuard pg(m_EPollLock);\n\n map::iterator p = m_mPolls.find(eid);\n if (p == m_mPolls.end())\n throw CUDTException(5, 13);\n\n p->second.m_sUDTSocksIn.erase(u);\n p->second.m_sUDTSocksOut.erase(u);\n\n \/\/ when the socket is removed from a monitoring, it is not available anymore for any IO notification\n p->second.m_sUDTReads.erase(u);\n p->second.m_sUDTWrites.erase(u);\n\n return 0;\n}\n\nint CEPoll::remove_ssock(const int eid, const SYSSOCKET& s)\n{\n CGuard pg(m_EPollLock);\n\n map::iterator p = m_mPolls.find(eid);\n if (p == m_mPolls.end())\n throw CUDTException(5, 13);\n\n#ifdef LINUX\n epoll_event ev; \/\/ ev is ignored, for compatibility with old Linux kernel only.\n if (epoll_ctl(p->second.m_iLocalID, EPOLL_CTL_DEL, s, &ev) < 0)\n throw CUDTException();\n#endif\n\n p->second.m_sLocals.erase(s);\n\n return 0;\n}\n\nint CEPoll::wait(const int eid, set* readfds, set* writefds, int64_t msTimeOut, set* lrfds, set* lwfds)\n{\n \/\/ if all fields is NULL and waiting time is infinite, then this would be a deadlock\n if (!readfds && !writefds && !lrfds && lwfds && (msTimeOut < 0))\n throw CUDTException(5, 3, 0);\n\n \/\/ Clear these sets in case the app forget to do it.\n if (readfds) readfds->clear();\n if (writefds) writefds->clear();\n if (lrfds) lrfds->clear();\n if (lwfds) lwfds->clear();\n\n int total = 0;\n\n int64_t entertime = CTimer::getTime();\n while (true)\n {\n CGuard::enterCS(m_EPollLock);\n\n map::iterator p = m_mPolls.find(eid);\n if (p == m_mPolls.end())\n {\n CGuard::leaveCS(m_EPollLock);\n throw CUDTException(5, 13);\n }\n\n if (p->second.m_sUDTSocksIn.empty() && p->second.m_sUDTSocksOut.empty() && p->second.m_sLocals.empty() && (msTimeOut < 0))\n {\n \/\/ no socket is being monitored, this may be a deadlock\n CGuard::leaveCS(m_EPollLock);\n throw CUDTException(5, 3);\n }\n\n if ((NULL != readfds) && !p->second.m_sUDTReads.empty())\n {\n *readfds = p->second.m_sUDTReads;\n total += p->second.m_sUDTReads.size();\n }\n\n if ((NULL != writefds) && !p->second.m_sUDTWrites.empty())\n {\n *writefds = p->second.m_sUDTWrites;\n total += p->second.m_sUDTWrites.size();\n }\n\n if (lrfds || lwfds)\n {\n #ifdef LINUX\n const int max_events = p->second.m_sLocals.size();\n epoll_event ev[max_events];\n int nfds = epoll_wait(p->second.m_iLocalID, ev, max_events, 0);\n\n for (int i = 0; i < nfds; ++ i)\n {\n if ((NULL != lrfds) && (ev[i].events & EPOLLIN))\n {\n lrfds->insert(ev[i].data.fd);\n ++ total;\n }\n if ((NULL != lwfds) && (ev[i].events & EPOLLOUT))\n {\n lwfds->insert(ev[i].data.fd);\n ++ total;\n }\n }\n #else\n \/\/currently \"select\" is used for all non-Linux platforms.\n \/\/faster approaches can be applied for specific systems in the future.\n\n \/\/\"select\" has a limitation on the number of sockets\n\n fd_set readfds;\n fd_set writefds;\n FD_ZERO(&readfds);\n FD_ZERO(&writefds);\n\n for (set::const_iterator i = p->second.m_sLocals.begin(); i != p->second.m_sLocals.end(); ++ i)\n {\n if (lrfds)\n FD_SET(*i, &readfds);\n if (lwfds)\n FD_SET(*i, &writefds);\n }\n\n timeval tv;\n tv.tv_sec = 0;\n tv.tv_usec = 0;\n if (select(0, &readfds, &writefds, NULL, &tv) > 0)\n {\n for (set::const_iterator i = p->second.m_sLocals.begin(); i != p->second.m_sLocals.end(); ++ i)\n {\n if (lrfds && FD_ISSET(*i, &readfds))\n {\n lrfds->insert(*i);\n ++ total;\n }\n if (lwfds && FD_ISSET(*i, &writefds))\n {\n lwfds->insert(*i);\n ++ total;\n }\n }\n }\n #endif\n }\n\n CGuard::leaveCS(m_EPollLock);\n\n if (total > 0)\n return total;\n\n if ((msTimeOut >= 0) && (int64_t(CTimer::getTime() - entertime) >= msTimeOut * 1000LL))\n break;\n\n CTimer::waitForEvent();\n }\n\n return 0;\n}\n\nint CEPoll::release(const int eid)\n{\n CGuard pg(m_EPollLock);\n\n map::iterator i = m_mPolls.find(eid);\n if (i == m_mPolls.end())\n throw CUDTException(5, 13);\n\n #ifdef LINUX\n \/\/ release local\/system epoll descriptor\n ::close(i->second.m_iLocalID);\n #endif\n\n m_mPolls.erase(i);\n\n return 0;\n}\n\nint CEPoll::enable_write(const UDTSOCKET& uid, set& eids)\n{\n CGuard pg(m_EPollLock);\n\n map::iterator p;\n\n vector lost;\n for (set::iterator i = eids.begin(); i != eids.end(); ++ i)\n {\n p = m_mPolls.find(*i);\n if (p == m_mPolls.end())\n {\n lost.push_back(*i);\n }\n else if (p->second.m_sUDTSocksOut.find(uid) != p->second.m_sUDTSocksOut.end())\n {\n p->second.m_sUDTWrites.insert(uid);\n }\n }\n\n for (vector::iterator i = lost.begin(); i != lost.end(); ++ i)\n eids.erase(*i);\n\n return 0;\n}\n\nint CEPoll::enable_read(const UDTSOCKET& uid, set& eids)\n{\n CGuard pg(m_EPollLock);\n\n map::iterator p;\n\n vector lost;\n for (set::iterator i = eids.begin(); i != eids.end(); ++ i)\n {\n p = m_mPolls.find(*i);\n if (p == m_mPolls.end())\n {\n lost.push_back(*i);\n }\n else if (p->second.m_sUDTSocksIn.find(uid) != p->second.m_sUDTSocksIn.end())\n {\n p->second.m_sUDTReads.insert(uid);\n }\n }\n\n for (vector::iterator i = lost.begin(); i != lost.end(); ++ i)\n eids.erase(*i);\n\n return 0;\n}\n\nint CEPoll::disable_write(const UDTSOCKET& uid, set& eids)\n{\n CGuard pg(m_EPollLock);\n\n map::iterator p;\n\n vector lost;\n for (set::iterator i = eids.begin(); i != eids.end(); ++ i)\n {\n p = m_mPolls.find(*i);\n if (p == m_mPolls.end())\n {\n lost.push_back(*i);\n }\n else\n {\n p->second.m_sUDTWrites.erase(uid);\n }\n }\n\n for (vector::iterator i = lost.begin(); i != lost.end(); ++ i)\n eids.erase(*i);\n\n return 0;\n}\n\nint CEPoll::disable_read(const UDTSOCKET& uid, set& eids)\n{\n CGuard pg(m_EPollLock);\n\n map::iterator p;\n\n vector lost;\n for (set::iterator i = eids.begin(); i != eids.end(); ++ i)\n {\n p = m_mPolls.find(*i);\n if (p == m_mPolls.end())\n {\n lost.push_back(*i);\n }\n else\n {\n p->second.m_sUDTReads.erase(uid);\n }\n }\n\n for (vector::iterator i = lost.begin(); i != lost.end(); ++ i)\n eids.erase(*i);\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/*\n * This file is part of Poedit (https:\/\/poedit.net)\n *\n * Copyright (C) 2017-2019 Vaclav Slavik\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\n *\/\n\n#include \"qa_checks.h\"\n\n#include \n\n#include \n\n\n\/\/ -------------------------------------------------------------\n\/\/ QACheck implementations\n\/\/ -------------------------------------------------------------\n\nnamespace QA\n{\n\nclass NotAllPlurals : public QACheck\n{\npublic:\n bool CheckItem(CatalogItemPtr item) override\n {\n if (!item->HasPlural())\n return false;\n\n bool foundTranslated = false;\n bool foundEmpty = false;\n for (auto& s: item->GetTranslations())\n {\n if (s.empty())\n foundEmpty = true;\n else\n foundTranslated = true;\n }\n\n if (foundEmpty && foundTranslated)\n {\n item->SetIssue(CatalogItem::Issue::Warning, _(\"Not all plural forms are translated.\"));\n return true;\n }\n\n return false;\n }\n};\n\n\nclass CaseMismatch : public QACheck\n{\npublic:\n CaseMismatch(Language lang) : m_lang(lang.Lang())\n {\n }\n\n bool CheckString(CatalogItemPtr item, const wxString& source, const wxString& translation) override\n {\n if (u_isupper(source[0]) && u_islower(translation[0]))\n {\n item->SetIssue(CatalogItem::Issue::Warning, _(\"The translation should start as a sentence.\"));\n return true;\n }\n\n if (u_islower(source[0]) && u_isupper(translation[0]))\n {\n if (m_lang != \"de\")\n {\n item->SetIssue(CatalogItem::Issue::Warning, _(\"The translation should start with a lowercase character.\"));\n return true;\n }\n \/\/ else: German nouns start uppercased, this would cause too many false positives\n }\n\n return false;\n }\n\nprivate:\n std::string m_lang;\n};\n\n\nclass WhitespaceMismatch : public QACheck\n{\npublic:\n bool CheckString(CatalogItemPtr item, const wxString& source, const wxString& translation) override\n {\n if (u_isspace(source[0]) && !u_isspace(translation[0]))\n {\n item->SetIssue(CatalogItem::Issue::Warning, _(L\"The translation doesn’t start with a space.\"));\n return true;\n }\n\n if (!u_isspace(source[0]) && u_isspace(translation[0]))\n {\n item->SetIssue(CatalogItem::Issue::Warning, _(L\"The translation starts with a space, but the source text doesn’t.\"));\n return true;\n }\n\n if (source.Last() == '\\n' && translation.Last() != '\\n')\n {\n item->SetIssue(CatalogItem::Issue::Warning, _(L\"The translation is missing a newline at the end.\"));\n return true;\n }\n\n if (source.Last() != '\\n' && translation.Last() == '\\n')\n {\n item->SetIssue(CatalogItem::Issue::Warning, _(L\"The translation ends with a newline, but the source text doesn’t.\"));\n return true;\n }\n\n if (u_isspace(source.Last()) && !u_isspace(translation.Last()))\n {\n item->SetIssue(CatalogItem::Issue::Warning, _(L\"The translation is missing a space at the end.\"));\n return true;\n }\n\n if (!u_isspace(source.Last()) && u_isspace(translation.Last()))\n {\n item->SetIssue(CatalogItem::Issue::Warning, _(L\"The translation ends with a space, but the source text doesn’t.\"));\n return true;\n }\n\n return false;\n }\n};\n\n\nclass PunctuationMismatch : public QACheck\n{\npublic:\n PunctuationMismatch(Language lang) : m_lang(lang.Lang())\n {\n }\n\n bool CheckString(CatalogItemPtr item, const wxString& source, const wxString& translation) override\n {\n if (m_lang == \"th\" || m_lang == \"lo\" || m_lang == \"km\" || m_lang == \"my\")\n {\n \/\/ For Thai, Lao, Khmer and Burmese,\n \/\/ the punctuation rules are so different that these checks don't\n \/\/ apply at all (with the possible exception of quote marks - TODO).\n \/\/ It's better to skip them than to spam the user with bogus warnings\n \/\/ on _everything_.\n \/\/ See https:\/\/www.ccjk.com\/punctuation-rule-for-bahasa-vietnamese-and-thai\/\n return false;\n }\n\n const UChar32 s_last = source.Last();\n const UChar32 t_last = translation.Last();\n const bool s_punct = u_ispunct(s_last);\n const bool t_punct = u_ispunct(t_last);\n\n if (u_getIntPropertyValue(s_last, UCHAR_BIDI_PAIRED_BRACKET_TYPE) == U_BPT_CLOSE ||\n u_getIntPropertyValue(t_last, UCHAR_BIDI_PAIRED_BRACKET_TYPE) == U_BPT_CLOSE)\n {\n \/\/ too many reordering related false positives for brackets\n \/\/ e.g. \"your {site} account\" -> \"váš účet na {site}\"\n if ((wchar_t)u_getBidiPairedBracket(s_last) != (wchar_t)source[0])\n {\n return false;\n }\n else\n {\n \/\/ OTOH, it's desirable to check strings fully enclosed in brackets like \"(unsaved)\"\n if (source.find_first_of((wchar_t)s_last, 1) != source.size() - 1)\n {\n \/\/ it's more complicated, possibly something like \"your {foo} on {bar}\"\n return false;\n }\n }\n }\n\n if (u_hasBinaryProperty(s_last, UCHAR_QUOTATION_MARK) || (!s_punct && u_hasBinaryProperty(t_last, UCHAR_QUOTATION_MARK)))\n {\n \/\/ quoted fragments can move around, e.g., so ignore quotes in reporting:\n \/\/ >> Invalid value for ‘{fieldName}’​ field\n \/\/ >> Valor inválido para el campo ‘{fieldName}’\n \/\/ TODO: count quote characters to check if used correctly in translation; don't check position\n return false;\n }\n\n if (s_punct && !t_punct)\n {\n item->SetIssue(CatalogItem::Issue::Warning,\n wxString::Format(_(L\"The translation should end with “%s”.\"), wxString(wxUniChar(s_last))));\n return true;\n }\n else if (!s_punct && t_punct)\n {\n item->SetIssue(CatalogItem::Issue::Warning,\n wxString::Format(_(L\"The translation should not end with “%s”.\"), wxString(wxUniChar(t_last))));\n return true;\n }\n else if (s_punct && t_punct && s_last != t_last)\n {\n if (t_last == L'…' && source.EndsWith(\"...\"))\n {\n \/\/ as a special case, allow translating ... (3 dots) as … (ellipsis)\n }\n else if (u_hasBinaryProperty(s_last, UCHAR_QUOTATION_MARK) && u_hasBinaryProperty(t_last, UCHAR_QUOTATION_MARK))\n {\n \/\/ don't check for correct quotes for now, accept any quotations marks as equal\n }\n else if (IsEquivalent(s_last, t_last))\n {\n \/\/ some characters are mostly equivalent and we shouldn't warn about them\n }\n else\n {\n item->SetIssue(CatalogItem::Issue::Warning,\n wxString::Format(_(L\"The translation ends with “%s”, but the source text ends with “%s”.\"),\n wxString(wxUniChar(t_last)), wxString(wxUniChar(s_last))));\n return true;\n }\n }\n\n return false;\n }\n\nprivate:\n bool IsEquivalent(UChar32 src, UChar32 trans) const\n {\n if (src == trans)\n return true;\n\n if (m_lang == \"zh\" || m_lang == \"ja\")\n {\n \/\/ Chinese uses full-width punctuation.\n \/\/ See https:\/\/en.wikipedia.org\/wiki\/Chinese_punctuation\n switch (src)\n {\n case '.':\n return trans == L'。';\n case ',':\n return trans == L'、';\n case '!':\n return trans == L'!';\n case '?':\n return trans == L'?';\n case ':':\n return trans == L':';\n case '(':\n return trans == L'(';\n case ')':\n return trans == L')';\n default:\n break;\n }\n }\n else if (m_lang == \"ar\" || m_lang == \"fa\")\n {\n \/\/ In Arabic (but not other RTL languages), some punctuation is mirrored.\n switch (src)\n {\n case ';':\n return trans == L'؛';\n case '?':\n return trans == L'؟';\n case ',':\n return trans == L'،';\n default:\n break;\n }\n }\n else if (m_lang == \"el\")\n {\n \/\/ In Greek, questions end with ';' and not '?'.\n if (src == '?')\n return trans == ';';\n }\n\n return false;\n }\n\n std::string m_lang;\n};\n\n\n} \/\/ namespace QA\n\n\n\/\/ -------------------------------------------------------------\n\/\/ QACheck support code\n\/\/ -------------------------------------------------------------\n\nbool QACheck::CheckItem(CatalogItemPtr item)\n{\n if (!item->GetTranslation().empty() && CheckString(item, item->GetString(), item->GetTranslation()))\n return true;\n\n if (item->HasPlural())\n {\n unsigned count = item->GetNumberOfTranslations();\n for (unsigned i = 1; i < count; i++)\n {\n auto t = item->GetTranslation(i);\n if (!t.empty() && CheckString(item, item->GetPluralString(), t))\n return true;\n }\n }\n\n return false;\n}\n\n\nbool QACheck::CheckString(CatalogItemPtr \/*item*\/, const wxString& \/*source*\/, const wxString& \/*translation*\/)\n{\n wxFAIL_MSG(\"not implemented - must override CheckString OR CheckItem\");\n return false;\n}\n\n\n\/\/ -------------------------------------------------------------\n\/\/ QAChecker\n\/\/ -------------------------------------------------------------\n\nint QAChecker::Check(Catalog& catalog)\n{\n \/\/ TODO: parallelize this (make async tasks for chunks of the catalog)\n \/\/ doing it per-checker is MT-unsafe with API that calls SetIssue()!\n\n int issues = 0;\n\n for (auto& i: catalog.items())\n issues += Check(i);\n\n return issues;\n}\n\n\nint QAChecker::Check(CatalogItemPtr item)\n{\n int issues = 0;\n\n for (auto& c: m_checks)\n {\n if (item->GetString().empty() || (item->HasPlural() && item->GetPluralString().empty()))\n continue;\n\n if (c->CheckItem(item))\n issues++;\n }\n\n return issues;\n}\n\n\nstd::shared_ptr QAChecker::GetFor(Catalog& catalog)\n{\n auto lang = catalog.GetLanguage();\n auto c = std::make_shared();\n c->AddCheck();\n c->AddCheck(lang);\n c->AddCheck();\n c->AddCheck(lang);\n return c;\n}\nQA checks: narrower punctuation classification\/*\n * This file is part of Poedit (https:\/\/poedit.net)\n *\n * Copyright (C) 2017-2019 Vaclav Slavik\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\n *\/\n\n#include \"qa_checks.h\"\n\n#include \n\n#include \n\n\n\/\/ -------------------------------------------------------------\n\/\/ QACheck implementations\n\/\/ -------------------------------------------------------------\n\nnamespace QA\n{\n\nclass NotAllPlurals : public QACheck\n{\npublic:\n bool CheckItem(CatalogItemPtr item) override\n {\n if (!item->HasPlural())\n return false;\n\n bool foundTranslated = false;\n bool foundEmpty = false;\n for (auto& s: item->GetTranslations())\n {\n if (s.empty())\n foundEmpty = true;\n else\n foundTranslated = true;\n }\n\n if (foundEmpty && foundTranslated)\n {\n item->SetIssue(CatalogItem::Issue::Warning, _(\"Not all plural forms are translated.\"));\n return true;\n }\n\n return false;\n }\n};\n\n\nclass CaseMismatch : public QACheck\n{\npublic:\n CaseMismatch(Language lang) : m_lang(lang.Lang())\n {\n }\n\n bool CheckString(CatalogItemPtr item, const wxString& source, const wxString& translation) override\n {\n if (u_isupper(source[0]) && u_islower(translation[0]))\n {\n item->SetIssue(CatalogItem::Issue::Warning, _(\"The translation should start as a sentence.\"));\n return true;\n }\n\n if (u_islower(source[0]) && u_isupper(translation[0]))\n {\n if (m_lang != \"de\")\n {\n item->SetIssue(CatalogItem::Issue::Warning, _(\"The translation should start with a lowercase character.\"));\n return true;\n }\n \/\/ else: German nouns start uppercased, this would cause too many false positives\n }\n\n return false;\n }\n\nprivate:\n std::string m_lang;\n};\n\n\nclass WhitespaceMismatch : public QACheck\n{\npublic:\n bool CheckString(CatalogItemPtr item, const wxString& source, const wxString& translation) override\n {\n if (u_isspace(source[0]) && !u_isspace(translation[0]))\n {\n item->SetIssue(CatalogItem::Issue::Warning, _(L\"The translation doesn’t start with a space.\"));\n return true;\n }\n\n if (!u_isspace(source[0]) && u_isspace(translation[0]))\n {\n item->SetIssue(CatalogItem::Issue::Warning, _(L\"The translation starts with a space, but the source text doesn’t.\"));\n return true;\n }\n\n if (source.Last() == '\\n' && translation.Last() != '\\n')\n {\n item->SetIssue(CatalogItem::Issue::Warning, _(L\"The translation is missing a newline at the end.\"));\n return true;\n }\n\n if (source.Last() != '\\n' && translation.Last() == '\\n')\n {\n item->SetIssue(CatalogItem::Issue::Warning, _(L\"The translation ends with a newline, but the source text doesn’t.\"));\n return true;\n }\n\n if (u_isspace(source.Last()) && !u_isspace(translation.Last()))\n {\n item->SetIssue(CatalogItem::Issue::Warning, _(L\"The translation is missing a space at the end.\"));\n return true;\n }\n\n if (!u_isspace(source.Last()) && u_isspace(translation.Last()))\n {\n item->SetIssue(CatalogItem::Issue::Warning, _(L\"The translation ends with a space, but the source text doesn’t.\"));\n return true;\n }\n\n return false;\n }\n};\n\n\nclass PunctuationMismatch : public QACheck\n{\npublic:\n PunctuationMismatch(Language lang) : m_lang(lang.Lang())\n {\n }\n\n bool CheckString(CatalogItemPtr item, const wxString& source, const wxString& translation) override\n {\n if (m_lang == \"th\" || m_lang == \"lo\" || m_lang == \"km\" || m_lang == \"my\")\n {\n \/\/ For Thai, Lao, Khmer and Burmese,\n \/\/ the punctuation rules are so different that these checks don't\n \/\/ apply at all (with the possible exception of quote marks - TODO).\n \/\/ It's better to skip them than to spam the user with bogus warnings\n \/\/ on _everything_.\n \/\/ See https:\/\/www.ccjk.com\/punctuation-rule-for-bahasa-vietnamese-and-thai\/\n return false;\n }\n\n const UChar32 s_last = source.Last();\n const UChar32 t_last = translation.Last();\n const bool s_punct = u_hasBinaryProperty(s_last, UCHAR_TERMINAL_PUNCTUATION) || u_hasBinaryProperty(s_last, UCHAR_QUOTATION_MARK);\n const bool t_punct = u_hasBinaryProperty(t_last, UCHAR_TERMINAL_PUNCTUATION) || u_hasBinaryProperty(t_last, UCHAR_QUOTATION_MARK);\n\n if (u_getIntPropertyValue(s_last, UCHAR_BIDI_PAIRED_BRACKET_TYPE) == U_BPT_CLOSE ||\n u_getIntPropertyValue(t_last, UCHAR_BIDI_PAIRED_BRACKET_TYPE) == U_BPT_CLOSE)\n {\n \/\/ too many reordering related false positives for brackets\n \/\/ e.g. \"your {site} account\" -> \"váš účet na {site}\"\n if ((wchar_t)u_getBidiPairedBracket(s_last) != (wchar_t)source[0])\n {\n return false;\n }\n else\n {\n \/\/ OTOH, it's desirable to check strings fully enclosed in brackets like \"(unsaved)\"\n if (source.find_first_of((wchar_t)s_last, 1) != source.size() - 1)\n {\n \/\/ it's more complicated, possibly something like \"your {foo} on {bar}\"\n return false;\n }\n }\n }\n\n if (u_hasBinaryProperty(s_last, UCHAR_QUOTATION_MARK) || (!s_punct && u_hasBinaryProperty(t_last, UCHAR_QUOTATION_MARK)))\n {\n \/\/ quoted fragments can move around, e.g., so ignore quotes in reporting:\n \/\/ >> Invalid value for ‘{fieldName}’​ field\n \/\/ >> Valor inválido para el campo ‘{fieldName}’\n \/\/ TODO: count quote characters to check if used correctly in translation; don't check position\n return false;\n }\n\n if (s_punct && !t_punct)\n {\n item->SetIssue(CatalogItem::Issue::Warning,\n wxString::Format(_(L\"The translation should end with “%s”.\"), wxString(wxUniChar(s_last))));\n return true;\n }\n else if (!s_punct && t_punct)\n {\n item->SetIssue(CatalogItem::Issue::Warning,\n wxString::Format(_(L\"The translation should not end with “%s”.\"), wxString(wxUniChar(t_last))));\n return true;\n }\n else if (s_punct && t_punct && s_last != t_last)\n {\n if (t_last == L'…' && source.EndsWith(\"...\"))\n {\n \/\/ as a special case, allow translating ... (3 dots) as … (ellipsis)\n }\n else if (u_hasBinaryProperty(s_last, UCHAR_QUOTATION_MARK) && u_hasBinaryProperty(t_last, UCHAR_QUOTATION_MARK))\n {\n \/\/ don't check for correct quotes for now, accept any quotations marks as equal\n }\n else if (IsEquivalent(s_last, t_last))\n {\n \/\/ some characters are mostly equivalent and we shouldn't warn about them\n }\n else\n {\n item->SetIssue(CatalogItem::Issue::Warning,\n wxString::Format(_(L\"The translation ends with “%s”, but the source text ends with “%s”.\"),\n wxString(wxUniChar(t_last)), wxString(wxUniChar(s_last))));\n return true;\n }\n }\n\n return false;\n }\n\nprivate:\n bool IsEquivalent(UChar32 src, UChar32 trans) const\n {\n if (src == trans)\n return true;\n\n if (m_lang == \"zh\" || m_lang == \"ja\")\n {\n \/\/ Chinese uses full-width punctuation.\n \/\/ See https:\/\/en.wikipedia.org\/wiki\/Chinese_punctuation\n switch (src)\n {\n case '.':\n return trans == L'。';\n case ',':\n return trans == L'、';\n case '!':\n return trans == L'!';\n case '?':\n return trans == L'?';\n case ':':\n return trans == L':';\n case '(':\n return trans == L'(';\n case ')':\n return trans == L')';\n default:\n break;\n }\n }\n else if (m_lang == \"ar\" || m_lang == \"fa\")\n {\n \/\/ In Arabic (but not other RTL languages), some punctuation is mirrored.\n switch (src)\n {\n case ';':\n return trans == L'؛';\n case '?':\n return trans == L'؟';\n case ',':\n return trans == L'،';\n default:\n break;\n }\n }\n else if (m_lang == \"el\")\n {\n \/\/ In Greek, questions end with ';' and not '?'.\n if (src == '?')\n return trans == ';';\n }\n\n return false;\n }\n\n std::string m_lang;\n};\n\n\n} \/\/ namespace QA\n\n\n\/\/ -------------------------------------------------------------\n\/\/ QACheck support code\n\/\/ -------------------------------------------------------------\n\nbool QACheck::CheckItem(CatalogItemPtr item)\n{\n if (!item->GetTranslation().empty() && CheckString(item, item->GetString(), item->GetTranslation()))\n return true;\n\n if (item->HasPlural())\n {\n unsigned count = item->GetNumberOfTranslations();\n for (unsigned i = 1; i < count; i++)\n {\n auto t = item->GetTranslation(i);\n if (!t.empty() && CheckString(item, item->GetPluralString(), t))\n return true;\n }\n }\n\n return false;\n}\n\n\nbool QACheck::CheckString(CatalogItemPtr \/*item*\/, const wxString& \/*source*\/, const wxString& \/*translation*\/)\n{\n wxFAIL_MSG(\"not implemented - must override CheckString OR CheckItem\");\n return false;\n}\n\n\n\/\/ -------------------------------------------------------------\n\/\/ QAChecker\n\/\/ -------------------------------------------------------------\n\nint QAChecker::Check(Catalog& catalog)\n{\n \/\/ TODO: parallelize this (make async tasks for chunks of the catalog)\n \/\/ doing it per-checker is MT-unsafe with API that calls SetIssue()!\n\n int issues = 0;\n\n for (auto& i: catalog.items())\n issues += Check(i);\n\n return issues;\n}\n\n\nint QAChecker::Check(CatalogItemPtr item)\n{\n int issues = 0;\n\n for (auto& c: m_checks)\n {\n if (item->GetString().empty() || (item->HasPlural() && item->GetPluralString().empty()))\n continue;\n\n if (c->CheckItem(item))\n issues++;\n }\n\n return issues;\n}\n\n\nstd::shared_ptr QAChecker::GetFor(Catalog& catalog)\n{\n auto lang = catalog.GetLanguage();\n auto c = std::make_shared();\n c->AddCheck();\n c->AddCheck(lang);\n c->AddCheck();\n c->AddCheck(lang);\n return c;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2011 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"reflection.h\"\n\n#include \"class_linker.h\"\n#include \"jni_internal.h\"\n#include \"object.h\"\n#include \"object_utils.h\"\n\n#include \"JniConstants.h\" \/\/ Last to avoid problems with LOG redefinition.\n\nnamespace art {\n\nMethod* gBoolean_valueOf;\nMethod* gByte_valueOf;\nMethod* gCharacter_valueOf;\nMethod* gDouble_valueOf;\nMethod* gFloat_valueOf;\nMethod* gInteger_valueOf;\nMethod* gLong_valueOf;\nMethod* gShort_valueOf;\n\nvoid InitBoxingMethods() {\n ClassLinker* class_linker = Runtime::Current()->GetClassLinker();\n gBoolean_valueOf = class_linker->FindSystemClass(\"Ljava\/lang\/Boolean;\")->FindDeclaredDirectMethod(\"valueOf\", \"(Z)Ljava\/lang\/Boolean;\");\n gByte_valueOf = class_linker->FindSystemClass(\"Ljava\/lang\/Byte;\")->FindDeclaredDirectMethod(\"valueOf\", \"(B)Ljava\/lang\/Byte;\");\n gCharacter_valueOf = class_linker->FindSystemClass(\"Ljava\/lang\/Character;\")->FindDeclaredDirectMethod(\"valueOf\", \"(C)Ljava\/lang\/Character;\");\n gDouble_valueOf = class_linker->FindSystemClass(\"Ljava\/lang\/Double;\")->FindDeclaredDirectMethod(\"valueOf\", \"(D)Ljava\/lang\/Double;\");\n gFloat_valueOf = class_linker->FindSystemClass(\"Ljava\/lang\/Float;\")->FindDeclaredDirectMethod(\"valueOf\", \"(F)Ljava\/lang\/Float;\");\n gInteger_valueOf = class_linker->FindSystemClass(\"Ljava\/lang\/Integer;\")->FindDeclaredDirectMethod(\"valueOf\", \"(I)Ljava\/lang\/Integer;\");\n gLong_valueOf = class_linker->FindSystemClass(\"Ljava\/lang\/Long;\")->FindDeclaredDirectMethod(\"valueOf\", \"(J)Ljava\/lang\/Long;\");\n gShort_valueOf = class_linker->FindSystemClass(\"Ljava\/lang\/Short;\")->FindDeclaredDirectMethod(\"valueOf\", \"(S)Ljava\/lang\/Short;\");\n}\n\njobject InvokeMethod(JNIEnv* env, jobject javaMethod, jobject javaReceiver, jobject javaArgs) {\n Thread* self = Thread::Current();\n ScopedThreadStateChange tsc(self, Thread::kRunnable);\n\n jmethodID mid = env->FromReflectedMethod(javaMethod);\n Method* m = reinterpret_cast(mid);\n\n Class* declaring_class = m->GetDeclaringClass();\n if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(declaring_class, true)) {\n return NULL;\n }\n\n Object* receiver = NULL;\n if (!m->IsStatic()) {\n \/\/ Check that the receiver is non-null and an instance of the field's declaring class.\n receiver = Decode(env, javaReceiver);\n if (!VerifyObjectInClass(env, receiver, declaring_class)) {\n return NULL;\n }\n\n \/\/ Find the actual implementation of the virtual method.\n m = receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(m);\n mid = reinterpret_cast(m);\n }\n\n \/\/ Get our arrays of arguments and their types, and check they're the same size.\n ObjectArray* objects = Decode*>(env, javaArgs);\n MethodHelper mh(m);\n const DexFile::TypeList* classes = mh.GetParameterTypeList();\n uint32_t classes_size = classes == NULL ? 0 : classes->Size();\n uint32_t arg_count = (objects != NULL) ? objects->GetLength() : 0;\n if (arg_count != classes_size) {\n self->ThrowNewExceptionF(\"Ljava\/lang\/IllegalArgumentException;\",\n \"wrong number of arguments; expected %d, got %d\",\n classes_size, arg_count);\n return NULL;\n }\n\n \/\/ Translate javaArgs to a jvalue[].\n UniquePtr args(new jvalue[arg_count]);\n JValue* decoded_args = reinterpret_cast(args.get());\n for (uint32_t i = 0; i < arg_count; ++i) {\n Object* arg = objects->Get(i);\n Class* dst_class = mh.GetClassFromTypeIdx(classes->GetTypeItem(i).type_idx_);\n if (dst_class->IsPrimitive()) {\n std::string what(StringPrintf(\"argument %d\", i + 1)); \/\/ Humans count from 1.\n if (!UnboxPrimitive(env, arg, dst_class, decoded_args[i], what.c_str())) {\n return NULL;\n }\n } else {\n args[i].l = AddLocalReference(env, arg);\n }\n }\n\n \/\/ Invoke the method.\n JValue value = InvokeWithJValues(env, javaReceiver, mid, args.get());\n\n \/\/ Wrap any exception with \"Ljava\/lang\/reflect\/InvocationTargetException;\" and return early.\n if (self->IsExceptionPending()) {\n jthrowable th = env->ExceptionOccurred();\n env->ExceptionClear();\n jclass exception_class = env->FindClass(\"java\/lang\/reflect\/InvocationTargetException\");\n jmethodID mid = env->GetMethodID(exception_class, \"\", \"(Ljava\/lang\/Throwable;)V\");\n jobject exception_instance = env->NewObject(exception_class, mid, th);\n env->Throw(reinterpret_cast(exception_instance));\n return NULL;\n }\n\n \/\/ Box if necessary and return.\n BoxPrimitive(env, mh.GetReturnType()->GetPrimitiveType(), value);\n return AddLocalReference(env, value.l);\n}\n\nbool VerifyObjectInClass(JNIEnv* env, Object* o, Class* c) {\n const char* exception = NULL;\n if (o == NULL) {\n exception = \"java\/lang\/NullPointerException\";\n } else if (!o->InstanceOf(c)) {\n exception = \"java\/lang\/IllegalArgumentException\";\n }\n if (exception != NULL) {\n std::string expected_class_name(PrettyDescriptor(c));\n std::string actual_class_name(PrettyTypeOf(o));\n jniThrowExceptionFmt(env, exception, \"expected receiver of type %s, but got %s\",\n expected_class_name.c_str(), actual_class_name.c_str());\n return false;\n }\n return true;\n}\n\n\/*\n * Convert primitive, boxed data from \"srcPtr\" to \"dstPtr\".\n *\n * Section v2 2.6 lists the various conversions and promotions. We\n * allow the \"widening\" and \"identity\" conversions, but don't allow the\n * \"narrowing\" conversions.\n *\n * Allowed:\n * byte to short, int, long, float, double\n * short to int, long, float double\n * char to int, long, float, double\n * int to long, float, double\n * long to float, double\n * float to double\n * Values of types byte, char, and short are \"internally\" widened to int.\n *\n * Returns the width in 32-bit words of the destination primitive, or\n * -1 if the conversion is not allowed.\n *\/\nbool ConvertPrimitiveValue(Primitive::Type srcType, Primitive::Type dstType,\n const JValue& src, JValue& dst) {\n CHECK(srcType != Primitive::kPrimNot && dstType != Primitive::kPrimNot);\n switch (dstType) {\n case Primitive::kPrimBoolean:\n case Primitive::kPrimChar:\n case Primitive::kPrimByte:\n if (srcType == dstType) {\n dst.i = src.i;\n return true;\n }\n break;\n case Primitive::kPrimShort:\n if (srcType == Primitive::kPrimByte || srcType == Primitive::kPrimShort) {\n dst.i = src.i;\n return true;\n }\n break;\n case Primitive::kPrimInt:\n if (srcType == Primitive::kPrimByte || srcType == Primitive::kPrimChar ||\n srcType == Primitive::kPrimShort || srcType == Primitive::kPrimInt) {\n dst.i = src.i;\n return true;\n }\n break;\n case Primitive::kPrimLong:\n if (srcType == Primitive::kPrimByte || srcType == Primitive::kPrimChar ||\n srcType == Primitive::kPrimShort || srcType == Primitive::kPrimInt) {\n dst.j = src.i;\n return true;\n } else if (srcType == Primitive::kPrimLong) {\n dst.j = src.j;\n return true;\n }\n break;\n case Primitive::kPrimFloat:\n if (srcType == Primitive::kPrimByte || srcType == Primitive::kPrimChar ||\n srcType == Primitive::kPrimShort || srcType == Primitive::kPrimInt) {\n dst.f = src.i;\n return true;\n } else if (srcType == Primitive::kPrimLong) {\n dst.f = src.j;\n return true;\n } else if (srcType == Primitive::kPrimFloat) {\n dst.i = src.i;\n return true;\n }\n break;\n case Primitive::kPrimDouble:\n if (srcType == Primitive::kPrimByte || srcType == Primitive::kPrimChar ||\n srcType == Primitive::kPrimShort || srcType == Primitive::kPrimInt) {\n dst.d = src.i;\n return true;\n } else if (srcType == Primitive::kPrimLong) {\n dst.d = src.j;\n return true;\n } else if (srcType == Primitive::kPrimFloat) {\n dst.d = src.f;\n return true;\n } else if (srcType == Primitive::kPrimDouble) {\n dst.j = src.j;\n return true;\n }\n break;\n default:\n break;\n }\n Thread::Current()->ThrowNewExceptionF(\"Ljava\/lang\/IllegalArgumentException;\",\n \"invalid primitive conversion from %s to %s\",\n PrettyDescriptor(srcType).c_str(),\n PrettyDescriptor(dstType).c_str());\n return false;\n}\n\nvoid BoxPrimitive(JNIEnv*, Primitive::Type src_class, JValue& value) {\n if (src_class == Primitive::kPrimNot) {\n return;\n }\n\n Method* m = NULL;\n switch (src_class) {\n case Primitive::kPrimBoolean:\n m = gBoolean_valueOf;\n break;\n case Primitive::kPrimByte:\n m = gByte_valueOf;\n break;\n case Primitive::kPrimChar:\n m = gCharacter_valueOf;\n break;\n case Primitive::kPrimDouble:\n m = gDouble_valueOf;\n break;\n case Primitive::kPrimFloat:\n m = gFloat_valueOf;\n break;\n case Primitive::kPrimInt:\n m = gInteger_valueOf;\n break;\n case Primitive::kPrimLong:\n m = gLong_valueOf;\n break;\n case Primitive::kPrimShort:\n m = gShort_valueOf;\n break;\n case Primitive::kPrimVoid:\n \/\/ There's no such thing as a void field, and void methods invoked via reflection return null.\n value.l = NULL;\n return;\n default:\n LOG(FATAL) << static_cast(src_class);\n }\n\n Thread* self = Thread::Current();\n ScopedThreadStateChange tsc(self, Thread::kRunnable);\n JValue args[1];\n args[0].j = 0;\n m->Invoke(self, NULL, args, &value);\n}\n\nbool UnboxPrimitive(JNIEnv*, Object* o, Class* dst_class, JValue& unboxed_value, const char* what) {\n if (!dst_class->IsPrimitive()) {\n if (o != NULL && !o->InstanceOf(dst_class)) {\n Thread::Current()->ThrowNewExceptionF(\"Ljava\/lang\/IllegalArgumentException;\",\n \"boxed object for %s should have type %s, but got %s\",\n what,\n PrettyDescriptor(dst_class).c_str(),\n PrettyTypeOf(o).c_str());\n return false;\n }\n unboxed_value.l = o;\n return true;\n } else if (dst_class->GetPrimitiveType() == Primitive::kPrimVoid) {\n Thread::Current()->ThrowNewExceptionF(\"Ljava\/lang\/IllegalArgumentException;\",\n \"can't unbox %s to void\",\n what);\n return false;\n }\n\n if (o == NULL) {\n Thread::Current()->ThrowNewExceptionF(\"Ljava\/lang\/IllegalArgumentException;\",\n \"%s should have type %s, got null\",\n what,\n PrettyDescriptor(dst_class).c_str());\n return false;\n }\n\n JValue boxed_value = { 0 };\n std::string src_descriptor(ClassHelper(o->GetClass()).GetDescriptor());\n Class* src_class = NULL;\n ClassLinker* class_linker = Runtime::Current()->GetClassLinker();\n Field* primitive_field = o->GetClass()->GetIFields()->Get(0);\n if (src_descriptor == \"Ljava\/lang\/Boolean;\") {\n src_class = class_linker->FindPrimitiveClass('Z');\n boxed_value.i = primitive_field->GetBoolean(o); \/\/ and extend read value to 32bits\n } else if (src_descriptor == \"Ljava\/lang\/Byte;\") {\n src_class = class_linker->FindPrimitiveClass('B');\n boxed_value.i = primitive_field->GetByte(o); \/\/ and extend read value to 32bits\n } else if (src_descriptor == \"Ljava\/lang\/Character;\") {\n src_class = class_linker->FindPrimitiveClass('C');\n boxed_value.i = primitive_field->GetChar(o); \/\/ and extend read value to 32bits\n } else if (src_descriptor == \"Ljava\/lang\/Float;\") {\n src_class = class_linker->FindPrimitiveClass('F');\n boxed_value.f = primitive_field->GetFloat(o);\n } else if (src_descriptor == \"Ljava\/lang\/Double;\") {\n src_class = class_linker->FindPrimitiveClass('D');\n boxed_value.d = primitive_field->GetDouble(o);\n } else if (src_descriptor == \"Ljava\/lang\/Integer;\") {\n src_class = class_linker->FindPrimitiveClass('I');\n boxed_value.i = primitive_field->GetInt(o);\n } else if (src_descriptor == \"Ljava\/lang\/Long;\") {\n src_class = class_linker->FindPrimitiveClass('J');\n boxed_value.j = primitive_field->GetLong(o);\n } else if (src_descriptor == \"Ljava\/lang\/Short;\") {\n src_class = class_linker->FindPrimitiveClass('S');\n boxed_value.i = primitive_field->GetShort(o); \/\/ and extend read value to 32bits\n } else {\n Thread::Current()->ThrowNewExceptionF(\"Ljava\/lang\/IllegalArgumentException;\",\n \"%s should have type %s, got %s\",\n what,\n PrettyDescriptor(dst_class).c_str(),\n PrettyDescriptor(src_descriptor.c_str()).c_str());\n return false;\n }\n\n return ConvertPrimitiveValue(src_class->GetPrimitiveType(), dst_class->GetPrimitiveType(),\n boxed_value, unboxed_value);\n}\n\n} \/\/ namespace art\nFix boxing; my invoke stub changes broke this.\/*\n * Copyright (C) 2011 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"reflection.h\"\n\n#include \"class_linker.h\"\n#include \"jni_internal.h\"\n#include \"object.h\"\n#include \"object_utils.h\"\n\n#include \"JniConstants.h\" \/\/ Last to avoid problems with LOG redefinition.\n\nnamespace art {\n\nMethod* gBoolean_valueOf;\nMethod* gByte_valueOf;\nMethod* gCharacter_valueOf;\nMethod* gDouble_valueOf;\nMethod* gFloat_valueOf;\nMethod* gInteger_valueOf;\nMethod* gLong_valueOf;\nMethod* gShort_valueOf;\n\nvoid InitBoxingMethods() {\n ClassLinker* class_linker = Runtime::Current()->GetClassLinker();\n gBoolean_valueOf = class_linker->FindSystemClass(\"Ljava\/lang\/Boolean;\")->FindDeclaredDirectMethod(\"valueOf\", \"(Z)Ljava\/lang\/Boolean;\");\n gByte_valueOf = class_linker->FindSystemClass(\"Ljava\/lang\/Byte;\")->FindDeclaredDirectMethod(\"valueOf\", \"(B)Ljava\/lang\/Byte;\");\n gCharacter_valueOf = class_linker->FindSystemClass(\"Ljava\/lang\/Character;\")->FindDeclaredDirectMethod(\"valueOf\", \"(C)Ljava\/lang\/Character;\");\n gDouble_valueOf = class_linker->FindSystemClass(\"Ljava\/lang\/Double;\")->FindDeclaredDirectMethod(\"valueOf\", \"(D)Ljava\/lang\/Double;\");\n gFloat_valueOf = class_linker->FindSystemClass(\"Ljava\/lang\/Float;\")->FindDeclaredDirectMethod(\"valueOf\", \"(F)Ljava\/lang\/Float;\");\n gInteger_valueOf = class_linker->FindSystemClass(\"Ljava\/lang\/Integer;\")->FindDeclaredDirectMethod(\"valueOf\", \"(I)Ljava\/lang\/Integer;\");\n gLong_valueOf = class_linker->FindSystemClass(\"Ljava\/lang\/Long;\")->FindDeclaredDirectMethod(\"valueOf\", \"(J)Ljava\/lang\/Long;\");\n gShort_valueOf = class_linker->FindSystemClass(\"Ljava\/lang\/Short;\")->FindDeclaredDirectMethod(\"valueOf\", \"(S)Ljava\/lang\/Short;\");\n}\n\njobject InvokeMethod(JNIEnv* env, jobject javaMethod, jobject javaReceiver, jobject javaArgs) {\n Thread* self = Thread::Current();\n ScopedThreadStateChange tsc(self, Thread::kRunnable);\n\n jmethodID mid = env->FromReflectedMethod(javaMethod);\n Method* m = reinterpret_cast(mid);\n\n Class* declaring_class = m->GetDeclaringClass();\n if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(declaring_class, true)) {\n return NULL;\n }\n\n Object* receiver = NULL;\n if (!m->IsStatic()) {\n \/\/ Check that the receiver is non-null and an instance of the field's declaring class.\n receiver = Decode(env, javaReceiver);\n if (!VerifyObjectInClass(env, receiver, declaring_class)) {\n return NULL;\n }\n\n \/\/ Find the actual implementation of the virtual method.\n m = receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(m);\n mid = reinterpret_cast(m);\n }\n\n \/\/ Get our arrays of arguments and their types, and check they're the same size.\n ObjectArray* objects = Decode*>(env, javaArgs);\n MethodHelper mh(m);\n const DexFile::TypeList* classes = mh.GetParameterTypeList();\n uint32_t classes_size = classes == NULL ? 0 : classes->Size();\n uint32_t arg_count = (objects != NULL) ? objects->GetLength() : 0;\n if (arg_count != classes_size) {\n self->ThrowNewExceptionF(\"Ljava\/lang\/IllegalArgumentException;\",\n \"wrong number of arguments; expected %d, got %d\",\n classes_size, arg_count);\n return NULL;\n }\n\n \/\/ Translate javaArgs to a jvalue[].\n UniquePtr args(new jvalue[arg_count]);\n JValue* decoded_args = reinterpret_cast(args.get());\n for (uint32_t i = 0; i < arg_count; ++i) {\n Object* arg = objects->Get(i);\n Class* dst_class = mh.GetClassFromTypeIdx(classes->GetTypeItem(i).type_idx_);\n if (dst_class->IsPrimitive()) {\n std::string what(StringPrintf(\"argument %d\", i + 1)); \/\/ Humans count from 1.\n if (!UnboxPrimitive(env, arg, dst_class, decoded_args[i], what.c_str())) {\n return NULL;\n }\n } else {\n args[i].l = AddLocalReference(env, arg);\n }\n }\n\n \/\/ Invoke the method.\n JValue value = InvokeWithJValues(env, javaReceiver, mid, args.get());\n\n \/\/ Wrap any exception with \"Ljava\/lang\/reflect\/InvocationTargetException;\" and return early.\n if (self->IsExceptionPending()) {\n jthrowable th = env->ExceptionOccurred();\n env->ExceptionClear();\n jclass exception_class = env->FindClass(\"java\/lang\/reflect\/InvocationTargetException\");\n jmethodID mid = env->GetMethodID(exception_class, \"\", \"(Ljava\/lang\/Throwable;)V\");\n jobject exception_instance = env->NewObject(exception_class, mid, th);\n env->Throw(reinterpret_cast(exception_instance));\n return NULL;\n }\n\n \/\/ Box if necessary and return.\n BoxPrimitive(env, mh.GetReturnType()->GetPrimitiveType(), value);\n return AddLocalReference(env, value.l);\n}\n\nbool VerifyObjectInClass(JNIEnv* env, Object* o, Class* c) {\n const char* exception = NULL;\n if (o == NULL) {\n exception = \"java\/lang\/NullPointerException\";\n } else if (!o->InstanceOf(c)) {\n exception = \"java\/lang\/IllegalArgumentException\";\n }\n if (exception != NULL) {\n std::string expected_class_name(PrettyDescriptor(c));\n std::string actual_class_name(PrettyTypeOf(o));\n jniThrowExceptionFmt(env, exception, \"expected receiver of type %s, but got %s\",\n expected_class_name.c_str(), actual_class_name.c_str());\n return false;\n }\n return true;\n}\n\n\/*\n * Convert primitive, boxed data from \"srcPtr\" to \"dstPtr\".\n *\n * Section v2 2.6 lists the various conversions and promotions. We\n * allow the \"widening\" and \"identity\" conversions, but don't allow the\n * \"narrowing\" conversions.\n *\n * Allowed:\n * byte to short, int, long, float, double\n * short to int, long, float double\n * char to int, long, float, double\n * int to long, float, double\n * long to float, double\n * float to double\n * Values of types byte, char, and short are \"internally\" widened to int.\n *\n * Returns the width in 32-bit words of the destination primitive, or\n * -1 if the conversion is not allowed.\n *\/\nbool ConvertPrimitiveValue(Primitive::Type srcType, Primitive::Type dstType,\n const JValue& src, JValue& dst) {\n CHECK(srcType != Primitive::kPrimNot && dstType != Primitive::kPrimNot);\n switch (dstType) {\n case Primitive::kPrimBoolean:\n case Primitive::kPrimChar:\n case Primitive::kPrimByte:\n if (srcType == dstType) {\n dst.i = src.i;\n return true;\n }\n break;\n case Primitive::kPrimShort:\n if (srcType == Primitive::kPrimByte || srcType == Primitive::kPrimShort) {\n dst.i = src.i;\n return true;\n }\n break;\n case Primitive::kPrimInt:\n if (srcType == Primitive::kPrimByte || srcType == Primitive::kPrimChar ||\n srcType == Primitive::kPrimShort || srcType == Primitive::kPrimInt) {\n dst.i = src.i;\n return true;\n }\n break;\n case Primitive::kPrimLong:\n if (srcType == Primitive::kPrimByte || srcType == Primitive::kPrimChar ||\n srcType == Primitive::kPrimShort || srcType == Primitive::kPrimInt) {\n dst.j = src.i;\n return true;\n } else if (srcType == Primitive::kPrimLong) {\n dst.j = src.j;\n return true;\n }\n break;\n case Primitive::kPrimFloat:\n if (srcType == Primitive::kPrimByte || srcType == Primitive::kPrimChar ||\n srcType == Primitive::kPrimShort || srcType == Primitive::kPrimInt) {\n dst.f = src.i;\n return true;\n } else if (srcType == Primitive::kPrimLong) {\n dst.f = src.j;\n return true;\n } else if (srcType == Primitive::kPrimFloat) {\n dst.i = src.i;\n return true;\n }\n break;\n case Primitive::kPrimDouble:\n if (srcType == Primitive::kPrimByte || srcType == Primitive::kPrimChar ||\n srcType == Primitive::kPrimShort || srcType == Primitive::kPrimInt) {\n dst.d = src.i;\n return true;\n } else if (srcType == Primitive::kPrimLong) {\n dst.d = src.j;\n return true;\n } else if (srcType == Primitive::kPrimFloat) {\n dst.d = src.f;\n return true;\n } else if (srcType == Primitive::kPrimDouble) {\n dst.j = src.j;\n return true;\n }\n break;\n default:\n break;\n }\n Thread::Current()->ThrowNewExceptionF(\"Ljava\/lang\/IllegalArgumentException;\",\n \"invalid primitive conversion from %s to %s\",\n PrettyDescriptor(srcType).c_str(),\n PrettyDescriptor(dstType).c_str());\n return false;\n}\n\nvoid BoxPrimitive(JNIEnv*, Primitive::Type src_class, JValue& value) {\n if (src_class == Primitive::kPrimNot) {\n return;\n }\n\n Method* m = NULL;\n switch (src_class) {\n case Primitive::kPrimBoolean:\n m = gBoolean_valueOf;\n break;\n case Primitive::kPrimByte:\n m = gByte_valueOf;\n break;\n case Primitive::kPrimChar:\n m = gCharacter_valueOf;\n break;\n case Primitive::kPrimDouble:\n m = gDouble_valueOf;\n break;\n case Primitive::kPrimFloat:\n m = gFloat_valueOf;\n break;\n case Primitive::kPrimInt:\n m = gInteger_valueOf;\n break;\n case Primitive::kPrimLong:\n m = gLong_valueOf;\n break;\n case Primitive::kPrimShort:\n m = gShort_valueOf;\n break;\n case Primitive::kPrimVoid:\n \/\/ There's no such thing as a void field, and void methods invoked via reflection return null.\n value.l = NULL;\n return;\n default:\n LOG(FATAL) << static_cast(src_class);\n }\n\n Thread* self = Thread::Current();\n ScopedThreadStateChange tsc(self, Thread::kRunnable);\n JValue args[1] = { value };\n m->Invoke(self, NULL, args, &value);\n}\n\nbool UnboxPrimitive(JNIEnv*, Object* o, Class* dst_class, JValue& unboxed_value, const char* what) {\n if (!dst_class->IsPrimitive()) {\n if (o != NULL && !o->InstanceOf(dst_class)) {\n Thread::Current()->ThrowNewExceptionF(\"Ljava\/lang\/IllegalArgumentException;\",\n \"boxed object for %s should have type %s, but got %s\",\n what,\n PrettyDescriptor(dst_class).c_str(),\n PrettyTypeOf(o).c_str());\n return false;\n }\n unboxed_value.l = o;\n return true;\n } else if (dst_class->GetPrimitiveType() == Primitive::kPrimVoid) {\n Thread::Current()->ThrowNewExceptionF(\"Ljava\/lang\/IllegalArgumentException;\",\n \"can't unbox %s to void\",\n what);\n return false;\n }\n\n if (o == NULL) {\n Thread::Current()->ThrowNewExceptionF(\"Ljava\/lang\/IllegalArgumentException;\",\n \"%s should have type %s, got null\",\n what,\n PrettyDescriptor(dst_class).c_str());\n return false;\n }\n\n JValue boxed_value = { 0 };\n std::string src_descriptor(ClassHelper(o->GetClass()).GetDescriptor());\n Class* src_class = NULL;\n ClassLinker* class_linker = Runtime::Current()->GetClassLinker();\n Field* primitive_field = o->GetClass()->GetIFields()->Get(0);\n if (src_descriptor == \"Ljava\/lang\/Boolean;\") {\n src_class = class_linker->FindPrimitiveClass('Z');\n boxed_value.i = primitive_field->GetBoolean(o); \/\/ and extend read value to 32bits\n } else if (src_descriptor == \"Ljava\/lang\/Byte;\") {\n src_class = class_linker->FindPrimitiveClass('B');\n boxed_value.i = primitive_field->GetByte(o); \/\/ and extend read value to 32bits\n } else if (src_descriptor == \"Ljava\/lang\/Character;\") {\n src_class = class_linker->FindPrimitiveClass('C');\n boxed_value.i = primitive_field->GetChar(o); \/\/ and extend read value to 32bits\n } else if (src_descriptor == \"Ljava\/lang\/Float;\") {\n src_class = class_linker->FindPrimitiveClass('F');\n boxed_value.f = primitive_field->GetFloat(o);\n } else if (src_descriptor == \"Ljava\/lang\/Double;\") {\n src_class = class_linker->FindPrimitiveClass('D');\n boxed_value.d = primitive_field->GetDouble(o);\n } else if (src_descriptor == \"Ljava\/lang\/Integer;\") {\n src_class = class_linker->FindPrimitiveClass('I');\n boxed_value.i = primitive_field->GetInt(o);\n } else if (src_descriptor == \"Ljava\/lang\/Long;\") {\n src_class = class_linker->FindPrimitiveClass('J');\n boxed_value.j = primitive_field->GetLong(o);\n } else if (src_descriptor == \"Ljava\/lang\/Short;\") {\n src_class = class_linker->FindPrimitiveClass('S');\n boxed_value.i = primitive_field->GetShort(o); \/\/ and extend read value to 32bits\n } else {\n Thread::Current()->ThrowNewExceptionF(\"Ljava\/lang\/IllegalArgumentException;\",\n \"%s should have type %s, got %s\",\n what,\n PrettyDescriptor(dst_class).c_str(),\n PrettyDescriptor(src_descriptor.c_str()).c_str());\n return false;\n }\n\n return ConvertPrimitiveValue(src_class->GetPrimitiveType(), dst_class->GetPrimitiveType(),\n boxed_value, unboxed_value);\n}\n\n} \/\/ namespace art\n<|endoftext|>"} {"text":"#ifndef regex_impl_hh_INCLUDED\n#define regex_impl_hh_INCLUDED\n\n#include \"exception.hh\"\n#include \"flags.hh\"\n#include \"ref_ptr.hh\"\n#include \"unicode.hh\"\n#include \"utf8.hh\"\n#include \"utf8_iterator.hh\"\n#include \"vector.hh\"\n\n#include \n\nnamespace Kakoune\n{\n\nenum class MatchDirection\n{\n Forward,\n Backward\n};\n\nstruct CompiledRegex : RefCountable\n{\n enum Op : char\n {\n Match,\n Literal,\n LiteralIgnoreCase,\n AnyChar,\n Matcher,\n Jump,\n Split_PrioritizeParent,\n Split_PrioritizeChild,\n Save,\n LineStart,\n LineEnd,\n WordBoundary,\n NotWordBoundary,\n SubjectBegin,\n SubjectEnd,\n LookAhead,\n NegativeLookAhead,\n LookBehind,\n NegativeLookBehind,\n };\n\n struct Instruction\n {\n Op op;\n mutable bool processed;\n mutable bool scheduled;\n uint32_t param;\n };\n static_assert(sizeof(Instruction) == 8, \"\");\n\n explicit operator bool() const { return not instructions.empty(); }\n\n Vector instructions;\n Vector> matchers;\n Vector lookarounds;\n MatchDirection direction;\n size_t save_count;\n\n struct StartChars { bool map[256]; };\n std::unique_ptr start_chars;\n};\n\nCompiledRegex compile_regex(StringView re, MatchDirection direction = MatchDirection::Forward);\n\nenum class RegexExecFlags\n{\n None = 0,\n Search = 1 << 0,\n NotBeginOfLine = 1 << 1,\n NotEndOfLine = 1 << 2,\n NotBeginOfWord = 1 << 3,\n NotEndOfWord = 1 << 4,\n NotBeginOfSubject = 1 << 5,\n NotInitialNull = 1 << 6,\n AnyMatch = 1 << 7,\n NoSaves = 1 << 8,\n PrevAvailable = 1 << 9,\n};\n\nconstexpr bool with_bit_ops(Meta::Type) { return true; }\n\ntemplate\nstruct ChooseUtf8It\n{\n using Type = utf8::iterator;\n};\n\ntemplate\nstruct ChooseUtf8It\n{\n using Type = std::reverse_iterator>;\n};\n\ntemplate\nclass ThreadedRegexVM\n{\npublic:\n ThreadedRegexVM(const CompiledRegex& program)\n : m_program{program}\n {\n kak_assert(m_program);\n if (direction != program.direction)\n throw runtime_error{\"Regex and VM direction mismatch\"};\n }\n\n ThreadedRegexVM(const ThreadedRegexVM&) = delete;\n ThreadedRegexVM& operator=(const ThreadedRegexVM&) = delete;\n\n ~ThreadedRegexVM()\n {\n for (auto* saves : m_saves)\n {\n for (size_t i = m_program.save_count-1; i > 0; --i)\n saves->pos[i].~Iterator();\n saves->~Saves();\n ::operator delete(saves);\n }\n }\n\n bool exec(Iterator begin, Iterator end, RegexExecFlags flags)\n {\n const bool forward = direction == MatchDirection::Forward;\n const bool prev_avail = flags & RegexExecFlags::PrevAvailable;\n m_begin = Utf8It{utf8::iterator{forward ? begin : end,\n prev_avail ? begin-1 : begin, end}};\n m_end = Utf8It{utf8::iterator{forward ? end : begin,\n prev_avail ? begin-1 : begin, end}};\n m_flags = flags;\n\n if (flags & RegexExecFlags::NotInitialNull and m_begin == m_end)\n return false;\n\n Vector current_threads, next_threads;\n\n const bool no_saves = (m_flags & RegexExecFlags::NoSaves);\n Utf8It start{m_begin};\n\n const bool* start_chars = m_program.start_chars ? m_program.start_chars->map : nullptr;\n\n if (flags & RegexExecFlags::Search)\n to_next_start(start, m_end, start_chars);\n\n if (exec_from(start, no_saves ? nullptr : new_saves(nullptr),\n current_threads, next_threads))\n return true;\n\n if (not (flags & RegexExecFlags::Search))\n return false;\n\n do\n {\n to_next_start(++start, m_end, start_chars);\n if (exec_from(start, no_saves ? nullptr : new_saves(nullptr),\n current_threads, next_threads))\n return true;\n }\n while (start != m_end);\n\n return false;\n }\n\n ArrayView captures() const\n {\n if (m_captures)\n return { m_captures->pos, m_program.save_count };\n return {};\n }\n\nprivate:\n struct Saves\n {\n int refcount;\n Iterator pos[1];\n };\n\n template\n Saves* new_saves(Iterator* pos)\n {\n kak_assert(not copy or pos != nullptr);\n const auto count = m_program.save_count;\n if (not m_free_saves.empty())\n {\n Saves* res = m_free_saves.back();\n m_free_saves.pop_back();\n res->refcount = 1;\n if (copy)\n std::copy(pos, pos + count, res->pos);\n else\n std::fill(res->pos, res->pos + count, Iterator{});\n\n return res;\n }\n\n void* ptr = ::operator new (sizeof(Saves) + (count-1) * sizeof(Iterator));\n Saves* saves = new (ptr) Saves{1, {copy ? pos[0] : Iterator{}}};\n for (size_t i = 1; i < count; ++i)\n new (&saves->pos[i]) Iterator{copy ? pos[i] : Iterator{}};\n m_saves.push_back(saves);\n return saves;\n }\n\n void release_saves(Saves* saves)\n {\n if (saves and --saves->refcount == 0)\n m_free_saves.push_back(saves);\n };\n\n struct Thread\n {\n uint32_t inst;\n Saves* saves;\n };\n\n using Utf8It = typename ChooseUtf8It::Type;\n\n enum class StepResult { Consumed, Matched, Failed };\n\n \/\/ Steps a thread until it consumes the current character, matches or fail\n StepResult step(const Utf8It& pos, Thread& thread, Vector& threads)\n {\n while (true)\n {\n auto& inst = m_program.instructions[thread.inst++];\n if (inst.processed)\n return StepResult::Failed;\n inst.processed = true;\n\n switch (inst.op)\n {\n case CompiledRegex::Literal:\n if (pos != m_end and inst.param == *pos)\n return StepResult::Consumed;\n return StepResult::Failed;\n case CompiledRegex::LiteralIgnoreCase:\n if (pos != m_end and inst.param == to_lower(*pos))\n return StepResult::Consumed;\n return StepResult::Failed;\n case CompiledRegex::AnyChar:\n return StepResult::Consumed;\n case CompiledRegex::Jump:\n thread.inst = inst.param;\n break;\n case CompiledRegex::Split_PrioritizeParent:\n {\n if (thread.saves)\n ++thread.saves->refcount;\n threads.push_back({inst.param, thread.saves});\n break;\n }\n case CompiledRegex::Split_PrioritizeChild:\n {\n if (thread.saves)\n ++thread.saves->refcount;\n threads.push_back({thread.inst, thread.saves});\n thread.inst = inst.param;\n break;\n }\n case CompiledRegex::Save:\n {\n if (thread.saves == nullptr)\n break;\n if (thread.saves->refcount > 1)\n {\n --thread.saves->refcount;\n thread.saves = new_saves(thread.saves->pos);\n }\n thread.saves->pos[inst.param] = get_base(pos);\n break;\n }\n case CompiledRegex::Matcher:\n if (pos == m_end)\n return StepResult::Failed;\n return m_program.matchers[inst.param](*pos) ?\n StepResult::Consumed : StepResult::Failed;\n case CompiledRegex::LineStart:\n if (not is_line_start(pos))\n return StepResult::Failed;\n break;\n case CompiledRegex::LineEnd:\n if (not is_line_end(pos))\n return StepResult::Failed;\n break;\n case CompiledRegex::WordBoundary:\n if (not is_word_boundary(pos))\n return StepResult::Failed;\n break;\n case CompiledRegex::NotWordBoundary:\n if (is_word_boundary(pos))\n return StepResult::Failed;\n break;\n case CompiledRegex::SubjectBegin:\n if (pos != m_begin or (m_flags & RegexExecFlags::NotBeginOfSubject))\n return StepResult::Failed;\n break;\n case CompiledRegex::SubjectEnd:\n if (pos != m_end)\n return StepResult::Failed;\n break;\n case CompiledRegex::LookAhead:\n case CompiledRegex::NegativeLookAhead:\n {\n auto ref = m_program.lookarounds.begin() + inst.param;\n for (auto it = pos; *ref != -1 and it != m_end; ++it, ++ref)\n if (*it != *ref)\n break;\n if ((inst.op == CompiledRegex::LookAhead and *ref != -1) or\n (inst.op == CompiledRegex::NegativeLookAhead and *ref == -1))\n return StepResult::Failed;\n break;\n }\n case CompiledRegex::LookBehind:\n case CompiledRegex::NegativeLookBehind:\n {\n auto ref = m_program.lookarounds.begin() + inst.param;\n for (auto it = pos; *ref != -1 and it > m_begin; --it, ++ref)\n if (*(it-1) != *ref)\n break;\n if ((inst.op == CompiledRegex::LookBehind and *ref != -1) or\n (inst.op == CompiledRegex::NegativeLookBehind and *ref == -1))\n return StepResult::Failed;\n break;\n }\n case CompiledRegex::Match:\n return StepResult::Matched;\n }\n }\n return StepResult::Failed;\n }\n\n bool exec_from(Utf8It pos, Saves* initial_saves, Vector& current_threads, Vector& next_threads)\n {\n current_threads.push_back({0, initial_saves});\n next_threads.clear();\n\n bool found_match = false;\n while (true) \/\/ Iterate on all codepoints and once at the end\n {\n for (auto& inst : m_program.instructions)\n {\n inst.processed = false;\n inst.scheduled = false;\n }\n\n while (not current_threads.empty())\n {\n auto thread = current_threads.back();\n current_threads.pop_back();\n switch (step(pos, thread, current_threads))\n {\n case StepResult::Matched:\n if ((pos != m_end and not (m_flags & RegexExecFlags::Search)) or\n (m_flags & RegexExecFlags::NotInitialNull and pos == m_begin))\n {\n release_saves(thread.saves);\n continue;\n }\n\n release_saves(m_captures);\n m_captures = thread.saves;\n if (pos == m_end or (m_flags & RegexExecFlags::AnyMatch))\n return true;\n\n found_match = true;\n current_threads.clear(); \/\/ remove this and lower priority threads\n break;\n case StepResult::Failed:\n release_saves(thread.saves);\n break;\n case StepResult::Consumed:\n if (m_program.instructions[thread.inst].scheduled)\n {\n release_saves(thread.saves);\n continue;\n }\n m_program.instructions[thread.inst].scheduled = true;\n next_threads.push_back(thread);\n break;\n }\n }\n if (pos == m_end or next_threads.empty())\n return found_match;\n\n std::swap(current_threads, next_threads);\n std::reverse(current_threads.begin(), current_threads.end());\n ++pos;\n }\n }\n\n void to_next_start(Utf8It& start, const Utf8It& end, const bool* start_chars)\n {\n if (not start_chars)\n return;\n\n while (start != end and *start >= 0 and *start < 256 and\n not start_chars[*start])\n ++start;\n }\n\n bool is_line_start(const Utf8It& pos) const\n {\n if (not (m_flags & RegexExecFlags::PrevAvailable) and pos == m_begin)\n return not (m_flags & RegexExecFlags::NotBeginOfLine);\n return *(pos-1) == '\\n';\n }\n\n bool is_line_end(const Utf8It& pos) const\n {\n if (pos == m_end)\n return not (m_flags & RegexExecFlags::NotEndOfLine);\n return *pos == '\\n';\n }\n\n bool is_word_boundary(const Utf8It& pos) const\n {\n if (not (m_flags & RegexExecFlags::PrevAvailable) and pos == m_begin)\n return not (m_flags & RegexExecFlags::NotBeginOfWord);\n if (pos == m_end)\n return not (m_flags & RegexExecFlags::NotEndOfWord);\n return is_word(*(pos-1)) != is_word(*pos);\n }\n\n static const Iterator& get_base(const utf8::iterator& it) { return it.base(); }\n static Iterator get_base(const std::reverse_iterator>& it) { return it.base().base(); }\n\n const CompiledRegex& m_program;\n\n Utf8It m_begin;\n Utf8It m_end;\n RegexExecFlags m_flags;\n\n Vector m_saves;\n Vector m_free_saves;\n\n Saves* m_captures = nullptr;\n};\n\ntemplate\nbool regex_match(It begin, It end, const CompiledRegex& re, RegexExecFlags flags = RegexExecFlags::None)\n{\n ThreadedRegexVM vm{re};\n return vm.exec(begin, end, (RegexExecFlags)(flags & ~(RegexExecFlags::Search)) |\n RegexExecFlags::AnyMatch | RegexExecFlags::NoSaves);\n}\n\ntemplate\nbool regex_match(It begin, It end, Vector& captures, const CompiledRegex& re,\n RegexExecFlags flags = RegexExecFlags::None)\n{\n ThreadedRegexVM vm{re};\n if (vm.exec(begin, end, flags & ~(RegexExecFlags::Search)))\n {\n std::copy(vm.captures().begin(), vm.captures().end(), std::back_inserter(captures));\n return true;\n }\n return false;\n}\n\ntemplate\nbool regex_search(It begin, It end, const CompiledRegex& re,\n RegexExecFlags flags = RegexExecFlags::None)\n{\n ThreadedRegexVM vm{re};\n return vm.exec(begin, end, flags | RegexExecFlags::Search | RegexExecFlags::AnyMatch | RegexExecFlags::NoSaves);\n}\n\ntemplate\nbool regex_search(It begin, It end, Vector& captures, const CompiledRegex& re,\n RegexExecFlags flags = RegexExecFlags::None)\n{\n ThreadedRegexVM vm{re};\n if (vm.exec(begin, end, flags | RegexExecFlags::Search))\n {\n std::copy(vm.captures().begin(), vm.captures().end(), std::back_inserter(captures));\n return true;\n }\n return false;\n}\n\n}\n\n#endif \/\/ regex_impl_hh_INCLUDED\nRegex: use std::conditional instead of custom template class to choose Utf8It#ifndef regex_impl_hh_INCLUDED\n#define regex_impl_hh_INCLUDED\n\n#include \"exception.hh\"\n#include \"flags.hh\"\n#include \"ref_ptr.hh\"\n#include \"unicode.hh\"\n#include \"utf8.hh\"\n#include \"utf8_iterator.hh\"\n#include \"vector.hh\"\n\n#include \n\nnamespace Kakoune\n{\n\nenum class MatchDirection\n{\n Forward,\n Backward\n};\n\nstruct CompiledRegex : RefCountable\n{\n enum Op : char\n {\n Match,\n Literal,\n LiteralIgnoreCase,\n AnyChar,\n Matcher,\n Jump,\n Split_PrioritizeParent,\n Split_PrioritizeChild,\n Save,\n LineStart,\n LineEnd,\n WordBoundary,\n NotWordBoundary,\n SubjectBegin,\n SubjectEnd,\n LookAhead,\n NegativeLookAhead,\n LookBehind,\n NegativeLookBehind,\n };\n\n struct Instruction\n {\n Op op;\n mutable bool processed;\n mutable bool scheduled;\n uint32_t param;\n };\n static_assert(sizeof(Instruction) == 8, \"\");\n\n explicit operator bool() const { return not instructions.empty(); }\n\n Vector instructions;\n Vector> matchers;\n Vector lookarounds;\n MatchDirection direction;\n size_t save_count;\n\n struct StartChars { bool map[256]; };\n std::unique_ptr start_chars;\n};\n\nCompiledRegex compile_regex(StringView re, MatchDirection direction = MatchDirection::Forward);\n\nenum class RegexExecFlags\n{\n None = 0,\n Search = 1 << 0,\n NotBeginOfLine = 1 << 1,\n NotEndOfLine = 1 << 2,\n NotBeginOfWord = 1 << 3,\n NotEndOfWord = 1 << 4,\n NotBeginOfSubject = 1 << 5,\n NotInitialNull = 1 << 6,\n AnyMatch = 1 << 7,\n NoSaves = 1 << 8,\n PrevAvailable = 1 << 9,\n};\n\nconstexpr bool with_bit_ops(Meta::Type) { return true; }\n\ntemplate\nclass ThreadedRegexVM\n{\npublic:\n ThreadedRegexVM(const CompiledRegex& program)\n : m_program{program}\n {\n kak_assert(m_program);\n if (direction != program.direction)\n throw runtime_error{\"Regex and VM direction mismatch\"};\n }\n\n ThreadedRegexVM(const ThreadedRegexVM&) = delete;\n ThreadedRegexVM& operator=(const ThreadedRegexVM&) = delete;\n\n ~ThreadedRegexVM()\n {\n for (auto* saves : m_saves)\n {\n for (size_t i = m_program.save_count-1; i > 0; --i)\n saves->pos[i].~Iterator();\n saves->~Saves();\n ::operator delete(saves);\n }\n }\n\n bool exec(Iterator begin, Iterator end, RegexExecFlags flags)\n {\n const bool forward = direction == MatchDirection::Forward;\n const bool prev_avail = flags & RegexExecFlags::PrevAvailable;\n m_begin = Utf8It{utf8::iterator{forward ? begin : end,\n prev_avail ? begin-1 : begin, end}};\n m_end = Utf8It{utf8::iterator{forward ? end : begin,\n prev_avail ? begin-1 : begin, end}};\n m_flags = flags;\n\n if (flags & RegexExecFlags::NotInitialNull and m_begin == m_end)\n return false;\n\n Vector current_threads, next_threads;\n\n const bool no_saves = (m_flags & RegexExecFlags::NoSaves);\n Utf8It start{m_begin};\n\n const bool* start_chars = m_program.start_chars ? m_program.start_chars->map : nullptr;\n\n if (flags & RegexExecFlags::Search)\n to_next_start(start, m_end, start_chars);\n\n if (exec_from(start, no_saves ? nullptr : new_saves(nullptr),\n current_threads, next_threads))\n return true;\n\n if (not (flags & RegexExecFlags::Search))\n return false;\n\n do\n {\n to_next_start(++start, m_end, start_chars);\n if (exec_from(start, no_saves ? nullptr : new_saves(nullptr),\n current_threads, next_threads))\n return true;\n }\n while (start != m_end);\n\n return false;\n }\n\n ArrayView captures() const\n {\n if (m_captures)\n return { m_captures->pos, m_program.save_count };\n return {};\n }\n\nprivate:\n struct Saves\n {\n int refcount;\n Iterator pos[1];\n };\n\n template\n Saves* new_saves(Iterator* pos)\n {\n kak_assert(not copy or pos != nullptr);\n const auto count = m_program.save_count;\n if (not m_free_saves.empty())\n {\n Saves* res = m_free_saves.back();\n m_free_saves.pop_back();\n res->refcount = 1;\n if (copy)\n std::copy(pos, pos + count, res->pos);\n else\n std::fill(res->pos, res->pos + count, Iterator{});\n\n return res;\n }\n\n void* ptr = ::operator new (sizeof(Saves) + (count-1) * sizeof(Iterator));\n Saves* saves = new (ptr) Saves{1, {copy ? pos[0] : Iterator{}}};\n for (size_t i = 1; i < count; ++i)\n new (&saves->pos[i]) Iterator{copy ? pos[i] : Iterator{}};\n m_saves.push_back(saves);\n return saves;\n }\n\n void release_saves(Saves* saves)\n {\n if (saves and --saves->refcount == 0)\n m_free_saves.push_back(saves);\n };\n\n struct Thread\n {\n uint32_t inst;\n Saves* saves;\n };\n\n using Utf8It = std::conditional_t,\n std::reverse_iterator>>;\n\n enum class StepResult { Consumed, Matched, Failed };\n\n \/\/ Steps a thread until it consumes the current character, matches or fail\n StepResult step(const Utf8It& pos, Thread& thread, Vector& threads)\n {\n while (true)\n {\n auto& inst = m_program.instructions[thread.inst++];\n if (inst.processed)\n return StepResult::Failed;\n inst.processed = true;\n\n switch (inst.op)\n {\n case CompiledRegex::Literal:\n if (pos != m_end and inst.param == *pos)\n return StepResult::Consumed;\n return StepResult::Failed;\n case CompiledRegex::LiteralIgnoreCase:\n if (pos != m_end and inst.param == to_lower(*pos))\n return StepResult::Consumed;\n return StepResult::Failed;\n case CompiledRegex::AnyChar:\n return StepResult::Consumed;\n case CompiledRegex::Jump:\n thread.inst = inst.param;\n break;\n case CompiledRegex::Split_PrioritizeParent:\n {\n if (thread.saves)\n ++thread.saves->refcount;\n threads.push_back({inst.param, thread.saves});\n break;\n }\n case CompiledRegex::Split_PrioritizeChild:\n {\n if (thread.saves)\n ++thread.saves->refcount;\n threads.push_back({thread.inst, thread.saves});\n thread.inst = inst.param;\n break;\n }\n case CompiledRegex::Save:\n {\n if (thread.saves == nullptr)\n break;\n if (thread.saves->refcount > 1)\n {\n --thread.saves->refcount;\n thread.saves = new_saves(thread.saves->pos);\n }\n thread.saves->pos[inst.param] = get_base(pos);\n break;\n }\n case CompiledRegex::Matcher:\n if (pos == m_end)\n return StepResult::Failed;\n return m_program.matchers[inst.param](*pos) ?\n StepResult::Consumed : StepResult::Failed;\n case CompiledRegex::LineStart:\n if (not is_line_start(pos))\n return StepResult::Failed;\n break;\n case CompiledRegex::LineEnd:\n if (not is_line_end(pos))\n return StepResult::Failed;\n break;\n case CompiledRegex::WordBoundary:\n if (not is_word_boundary(pos))\n return StepResult::Failed;\n break;\n case CompiledRegex::NotWordBoundary:\n if (is_word_boundary(pos))\n return StepResult::Failed;\n break;\n case CompiledRegex::SubjectBegin:\n if (pos != m_begin or (m_flags & RegexExecFlags::NotBeginOfSubject))\n return StepResult::Failed;\n break;\n case CompiledRegex::SubjectEnd:\n if (pos != m_end)\n return StepResult::Failed;\n break;\n case CompiledRegex::LookAhead:\n case CompiledRegex::NegativeLookAhead:\n {\n auto ref = m_program.lookarounds.begin() + inst.param;\n for (auto it = pos; *ref != -1 and it != m_end; ++it, ++ref)\n if (*it != *ref)\n break;\n if ((inst.op == CompiledRegex::LookAhead and *ref != -1) or\n (inst.op == CompiledRegex::NegativeLookAhead and *ref == -1))\n return StepResult::Failed;\n break;\n }\n case CompiledRegex::LookBehind:\n case CompiledRegex::NegativeLookBehind:\n {\n auto ref = m_program.lookarounds.begin() + inst.param;\n for (auto it = pos; *ref != -1 and it > m_begin; --it, ++ref)\n if (*(it-1) != *ref)\n break;\n if ((inst.op == CompiledRegex::LookBehind and *ref != -1) or\n (inst.op == CompiledRegex::NegativeLookBehind and *ref == -1))\n return StepResult::Failed;\n break;\n }\n case CompiledRegex::Match:\n return StepResult::Matched;\n }\n }\n return StepResult::Failed;\n }\n\n bool exec_from(Utf8It pos, Saves* initial_saves, Vector& current_threads, Vector& next_threads)\n {\n current_threads.push_back({0, initial_saves});\n next_threads.clear();\n\n bool found_match = false;\n while (true) \/\/ Iterate on all codepoints and once at the end\n {\n for (auto& inst : m_program.instructions)\n {\n inst.processed = false;\n inst.scheduled = false;\n }\n\n while (not current_threads.empty())\n {\n auto thread = current_threads.back();\n current_threads.pop_back();\n switch (step(pos, thread, current_threads))\n {\n case StepResult::Matched:\n if ((pos != m_end and not (m_flags & RegexExecFlags::Search)) or\n (m_flags & RegexExecFlags::NotInitialNull and pos == m_begin))\n {\n release_saves(thread.saves);\n continue;\n }\n\n release_saves(m_captures);\n m_captures = thread.saves;\n if (pos == m_end or (m_flags & RegexExecFlags::AnyMatch))\n return true;\n\n found_match = true;\n current_threads.clear(); \/\/ remove this and lower priority threads\n break;\n case StepResult::Failed:\n release_saves(thread.saves);\n break;\n case StepResult::Consumed:\n if (m_program.instructions[thread.inst].scheduled)\n {\n release_saves(thread.saves);\n continue;\n }\n m_program.instructions[thread.inst].scheduled = true;\n next_threads.push_back(thread);\n break;\n }\n }\n if (pos == m_end or next_threads.empty())\n return found_match;\n\n std::swap(current_threads, next_threads);\n std::reverse(current_threads.begin(), current_threads.end());\n ++pos;\n }\n }\n\n void to_next_start(Utf8It& start, const Utf8It& end, const bool* start_chars)\n {\n if (not start_chars)\n return;\n\n while (start != end and *start >= 0 and *start < 256 and\n not start_chars[*start])\n ++start;\n }\n\n bool is_line_start(const Utf8It& pos) const\n {\n if (not (m_flags & RegexExecFlags::PrevAvailable) and pos == m_begin)\n return not (m_flags & RegexExecFlags::NotBeginOfLine);\n return *(pos-1) == '\\n';\n }\n\n bool is_line_end(const Utf8It& pos) const\n {\n if (pos == m_end)\n return not (m_flags & RegexExecFlags::NotEndOfLine);\n return *pos == '\\n';\n }\n\n bool is_word_boundary(const Utf8It& pos) const\n {\n if (not (m_flags & RegexExecFlags::PrevAvailable) and pos == m_begin)\n return not (m_flags & RegexExecFlags::NotBeginOfWord);\n if (pos == m_end)\n return not (m_flags & RegexExecFlags::NotEndOfWord);\n return is_word(*(pos-1)) != is_word(*pos);\n }\n\n static const Iterator& get_base(const utf8::iterator& it) { return it.base(); }\n static Iterator get_base(const std::reverse_iterator>& it) { return it.base().base(); }\n\n const CompiledRegex& m_program;\n\n Utf8It m_begin;\n Utf8It m_end;\n RegexExecFlags m_flags;\n\n Vector m_saves;\n Vector m_free_saves;\n\n Saves* m_captures = nullptr;\n};\n\ntemplate\nbool regex_match(It begin, It end, const CompiledRegex& re, RegexExecFlags flags = RegexExecFlags::None)\n{\n ThreadedRegexVM vm{re};\n return vm.exec(begin, end, (RegexExecFlags)(flags & ~(RegexExecFlags::Search)) |\n RegexExecFlags::AnyMatch | RegexExecFlags::NoSaves);\n}\n\ntemplate\nbool regex_match(It begin, It end, Vector& captures, const CompiledRegex& re,\n RegexExecFlags flags = RegexExecFlags::None)\n{\n ThreadedRegexVM vm{re};\n if (vm.exec(begin, end, flags & ~(RegexExecFlags::Search)))\n {\n std::copy(vm.captures().begin(), vm.captures().end(), std::back_inserter(captures));\n return true;\n }\n return false;\n}\n\ntemplate\nbool regex_search(It begin, It end, const CompiledRegex& re,\n RegexExecFlags flags = RegexExecFlags::None)\n{\n ThreadedRegexVM vm{re};\n return vm.exec(begin, end, flags | RegexExecFlags::Search | RegexExecFlags::AnyMatch | RegexExecFlags::NoSaves);\n}\n\ntemplate\nbool regex_search(It begin, It end, Vector& captures, const CompiledRegex& re,\n RegexExecFlags flags = RegexExecFlags::None)\n{\n ThreadedRegexVM vm{re};\n if (vm.exec(begin, end, flags | RegexExecFlags::Search))\n {\n std::copy(vm.captures().begin(), vm.captures().end(), std::back_inserter(captures));\n return true;\n }\n return false;\n}\n\n}\n\n#endif \/\/ regex_impl_hh_INCLUDED\n<|endoftext|>"} {"text":"#define BOOST_COMPUTE_DEBUG_KERNEL_COMPILATION\n#include \"boost\/compute.hpp\"\n\n#include \"Canvas.h\"\n#include \"Triangle.h\"\n#include \"draw_triangle.h\"\n\n#include \n#include \n#include \n#include \n\nusing namespace std;\nnamespace bc = boost::compute;\n\nbc::kernel make_kernel(const bc::context& ctx, const char* source, std::string name);\n\nint main(int argc, char** argv)\n{\n bc::device device = bc::system::default_device();\n bc::context context(device);\n bc::command_queue queue(context, device);\n bc::kernel kernel;\n\n try\n {\n kernel = make_kernel(context, garth_kernels::draw_triangles.c_str(), \"draw_triangles\");\n }\n catch (bc::opencl_error& ex)\n {\n cout << \"Boost.Compute error: \" << ex.error_string() << endl;\n cout << \"Boost.Compute error_code: \" << ex.error_code() << endl;\n return 1;\n }\n catch (exception& ex)\n {\n cout << \"WTF HAPPENED?!?!~?! - \" << ex.what() << endl;\n return 1;\n }\n\n cout << \"Default device: \" << device.name() << endl;\n\n \/\/ Settings:\n uint32_t num_triangles = 10,\n canvas_width = 100,\n canvas_height = 100;\n\n \/\/ Create RNG\n std::default_random_engine rng;\n std::uniform_int_distribution random_color(0,255);\n \n \/\/ Create Triangle buffer:\n vector triangles(num_triangles);\n for(auto& t : triangles)\n {\n t.c.Red = random_color(rng);\n t.c.Green = random_color(rng);\n t.c.Blue = random_color(rng);\n }\n Canvas canvas(canvas_width, canvas_height);\n\n \/\/ Create memory buffers for the input and output:\n bc::buffer buffer_triangles(context, sizeof(triangles));\n bc::buffer buffer_canvas(context, sizeof(canvas));\n\n \/\/ Set the kernel arguments:\n kernel.set_arg(0, buffer_triangles);\n kernel.set_arg(1, num_triangles);\n kernel.set_arg(2, buffer_canvas);\n kernel.set_arg(3, canvas_width);\n kernel.set_arg(4, canvas_height);\n \n\n \/\/ Write the data to the device:\n queue.enqueue_write_buffer(buffer_triangles, 0, sizeof(triangles.data()), triangles.data());\n queue.enqueue_write_buffer(buffer_canvas, 0, sizeof(canvas.getCanvas().data()), canvas.getCanvas().data());\n\n \/\/ Calculate local\/global group sizes:\n bc::extents<2> offsetRange(0);\n bc::extents<2> globalRange = { 10, 10 };\n bc::extents<2> localRange = { 10, 10 };\n\n \/\/ Run kernel:\n queue.enqueue_nd_range_kernel(kernel, offsetRange, globalRange, localRange);\n\n \/\/ transfer results back to the host\n queue.enqueue_read_buffer(buffer_canvas, 0, sizeof(canvas.getCanvas().data()), canvas.getCanvas().data());\n\n canvas.save(\"triangles.png\");\n return 0;\n}\n\nbc::kernel make_kernel(const bc::context& context, const char* source, std::string name)\n{\n \/\/ setup compilation flags for the program\n std::string options;\n\n \/\/ create and build the program\n bc::program program =\n bc::program::build_with_source(source, context, options.c_str());\n\n \/\/ create and return the kernel\n return program.create_kernel(name);\n}\nClang support#define BOOST_COMPUTE_DEBUG_KERNEL_COMPILATION\n#include \"boost\/compute.hpp\"\n\n#include \"Canvas.h\"\n#include \"Triangle.h\"\n#include \"draw_triangle.h\"\n\n#include \n#include \n#include \n#include \n\nusing namespace std;\nnamespace bc = boost::compute;\n\nbc::kernel make_kernel(const bc::context& ctx, const char* source, std::string name);\n\nint main(int argc, char** argv)\n{\n bc::device device = bc::system::default_device();\n bc::context context(device);\n bc::command_queue queue(context, device);\n bc::kernel kernel;\n\n try\n {\n kernel = make_kernel(context, garth_kernels::draw_triangles.c_str(), \"draw_triangles\");\n }\n catch (bc::opencl_error& ex)\n {\n cout << \"Boost.Compute error: \" << ex.error_string() << endl;\n cout << \"Boost.Compute error_code: \" << ex.error_code() << endl;\n return 1;\n }\n catch (exception& ex)\n {\n cout << \"WTF HAPPENED?!?!~?! - \" << ex.what() << endl;\n return 1;\n }\n\n cout << \"Default device: \" << device.name() << endl;\n\n \/\/ Settings:\n uint32_t num_triangles = 10,\n canvas_width = 100,\n canvas_height = 100;\n\n \/\/ Create RNG\n std::default_random_engine rng;\n std::uniform_int_distribution random_color(0,255);\n \n \/\/ Create Triangle buffer:\n vector triangles(num_triangles);\n for(auto& t : triangles)\n {\n t.c.Red = random_color(rng);\n t.c.Green = random_color(rng);\n t.c.Blue = random_color(rng);\n }\n Canvas canvas(canvas_width, canvas_height);\n\n \/\/ Create memory buffers for the input and output:\n bc::buffer buffer_triangles(context, sizeof(triangles));\n bc::buffer buffer_canvas(context, sizeof(canvas));\n\n \/\/ Set the kernel arguments:\n kernel.set_arg(0, buffer_triangles);\n kernel.set_arg(1, num_triangles);\n kernel.set_arg(2, buffer_canvas);\n kernel.set_arg(3, canvas_width);\n kernel.set_arg(4, canvas_height);\n \n\n \/\/ Write the data to the device:\n queue.enqueue_write_buffer(buffer_triangles, 0, sizeof(triangles.data()), triangles.data());\n queue.enqueue_write_buffer(buffer_canvas, 0, sizeof(canvas.getCanvas().data()), canvas.getCanvas().data());\n\n \/\/ Calculate local\/global group sizes:\n bc::extents<2> offsetRange(0);\n bc::extents<2> globalRange;\n globalRange[0] = 10;\n globalRange[1] = 10;\n\n bc::extents<2> localRange;\n localRange[0] = 10;\n localRange[1] = 10;\n\n \/\/ Run kernel:\n queue.enqueue_nd_range_kernel(kernel, offsetRange, globalRange, localRange);\n\n \/\/ transfer results back to the host\n queue.enqueue_read_buffer(buffer_canvas, 0, sizeof(canvas.getCanvas().data()), canvas.getCanvas().data());\n\n canvas.save(\"triangles.png\");\n return 0;\n}\n\nbc::kernel make_kernel(const bc::context& context, const char* source, std::string name)\n{\n \/\/ setup compilation flags for the program\n std::string options;\n\n \/\/ create and build the program\n bc::program program =\n bc::program::build_with_source(source, context, options.c_str());\n\n \/\/ create and return the kernel\n return program.create_kernel(name);\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2016 The Zcash developers\n\/\/ Original code from: https:\/\/gist.github.com\/laanwj\/0e689cfa37b52bcbbb44\n\n\/*\n\nTo set up a new alert system\n----------------------------\n\nCreate a new alert key pair:\nopenssl ecparam -name secp256k1 -genkey -param_enc explicit -outform PEM -out data.pem\n\nGet the private key in hex:\nopenssl ec -in data.pem -outform DER | tail -c 279 | xxd -p -c 279\n\nGet the public key in hex:\nopenssl ec -in data.pem -pubout -outform DER | tail -c 65 | xxd -p -c 65\n\nUpdate the public keys found in chainparams.cpp.\n\n\nTo send an alert message\n------------------------\n\nCopy the private keys into alertkeys.h.\n\nModify the alert parameters, id and message found in this file.\n\nBuild and run with -sendalert or -printalert.\n\n.\/zcashd -printtoconsole -sendalert\n\nOne minute after starting up, the alert will be broadcast. It is then\nflooded through the network until the nRelayUntil time, and will be\nactive until nExpiration OR the alert is cancelled.\n\nIf you make a mistake, send another alert with nCancel set to cancel\nthe bad alert.\n\n*\/\n\n#include \"main.h\"\n#include \"net.h\"\n#include \"alert.h\"\n#include \"init.h\"\n\n#include \"util.h\"\n#include \"utiltime.h\"\n#include \"key.h\"\n#include \"clientversion.h\"\n#include \"chainparams.h\"\n\n#include \"alertkeys.h\"\n\n\nstatic const int64_t DAYS = 24 * 60 * 60;\n\nvoid ThreadSendAlert()\n{\n if (!mapArgs.count(\"-sendalert\") && !mapArgs.count(\"-printalert\"))\n return;\n\n MilliSleep(60*1000); \/\/ Wait a minute so we get connected\n\n \/\/\n \/\/ Alerts are relayed around the network until nRelayUntil, flood\n \/\/ filling to every node.\n \/\/ After the relay time is past, new nodes are told about alerts\n \/\/ when they connect to peers, until either nExpiration or\n \/\/ the alert is cancelled by a newer alert.\n \/\/ Nodes never save alerts to disk, they are in-memory-only.\n \/\/\n CAlert alert;\n alert.nRelayUntil = GetTime() + 15 * 60;\n alert.nExpiration = GetTime() + 365 * 60 * 60;\n alert.nID = 1000; \/\/ use https:\/\/z.cash to keep track of alert IDs\n alert.nCancel = 0; \/\/ cancels previous messages up to this ID number\n\n \/\/ These versions are protocol versions\n \/\/ 60002 : 0.7.*\n \/\/ 70001 : 0.8.*\n \/\/ 70002 : 0.9.*\n alert.nMinVer = 70002;\n alert.nMaxVer = 70002;\n\n \/\/\n \/\/ main.cpp: \n \/\/ 1000 for Misc warnings like out of disk space and clock is wrong\n \/\/ 2000 for longer invalid proof-of-work chain \n \/\/ Higher numbers mean higher priority\n alert.nPriority = 5000;\n alert.strComment = \"\";\n alert.strStatusBar = \"URGENT: Upgrade required: see https:\/\/z.cash\";\n\n \/\/ Set specific client version\/versions here. If setSubVer is empty, no filtering on subver is done:\n \/\/ alert.setSubVer.insert(std::string(\"\/Satoshi:0.7.2\/\"));\n\n \/\/ Sign\n const CChainParams& chainparams = Params();\n std::string networkID = chainparams.NetworkIDString();\n bool fIsTestNet = networkID.compare(\"test\") == 0;\n std::vector vchTmp(ParseHex(fIsTestNet ? pszTestNetPrivKey : pszPrivKey));\n CPrivKey vchPrivKey(vchTmp.begin(), vchTmp.end());\n\n CDataStream sMsg(SER_NETWORK, CLIENT_VERSION);\n sMsg << *(CUnsignedAlert*)&alert;\n alert.vchMsg = std::vector(sMsg.begin(), sMsg.end());\n CKey key;\n if (!key.SetPrivKey(vchPrivKey, false))\n {\n printf(\"ThreadSendAlert() : key.SetPrivKey failed\\n\");\n return;\n }\n if (!key.Sign(Hash(alert.vchMsg.begin(), alert.vchMsg.end()), alert.vchSig))\n {\n printf(\"ThreadSendAlert() : key.Sign failed\\n\");\n return;\n }\n\n \/\/ Test\n CDataStream sBuffer(SER_NETWORK, CLIENT_VERSION);\n sBuffer << alert;\n CAlert alert2;\n sBuffer >> alert2;\n if (!alert2.CheckSignature(chainparams.AlertKey()))\n {\n printf(\"ThreadSendAlert() : CheckSignature failed\\n\");\n return;\n }\n assert(alert2.vchMsg == alert.vchMsg);\n assert(alert2.vchSig == alert.vchSig);\n alert.SetNull();\n printf(\"\\nThreadSendAlert:\\n\");\n printf(\"hash=%s\\n\", alert2.GetHash().ToString().c_str());\n printf(\"%s\\n\", alert2.ToString().c_str());\n printf(\"vchMsg=%s\\n\", HexStr(alert2.vchMsg).c_str());\n printf(\"vchSig=%s\\n\", HexStr(alert2.vchSig).c_str());\n\n \/\/ Confirm\n if (!mapArgs.count(\"-sendalert\"))\n return;\n while (vNodes.size() < 1 && !ShutdownRequested())\n MilliSleep(500);\n if (ShutdownRequested())\n return;\n#if 0\n#ifdef QT_GUI\n if (ThreadSafeMessageBox(\"Send alert?\", \"ThreadSendAlert\", wxYES_NO | wxNO_DEFAULT) != wxYES)\n return;\n if (ThreadSafeMessageBox(\"Send alert, are you sure?\", \"ThreadSendAlert\", wxYES_NO | wxNO_DEFAULT) != wxYES)\n {\n ThreadSafeMessageBox(\"Nothing sent\", \"ThreadSendAlert\", wxOK);\n return;\n }\n#endif\n#endif\n \/\/ Send\n printf(\"ThreadSendAlert() : Sending alert\\n\");\n int nSent = 0;\n {\n LOCK(cs_vNodes);\n BOOST_FOREACH(CNode* pnode, vNodes)\n {\n if (alert2.RelayTo(pnode))\n {\n printf(\"ThreadSendAlert() : Sent alert to %s\\n\", pnode->addr.ToString().c_str());\n nSent++;\n }\n }\n }\n printf(\"ThreadSendAlert() : Alert sent to %d nodes\\n\", nSent);\n}\nUpdate alert protocol version comment.\/\/ Copyright (c) 2016 The Zcash developers\n\/\/ Original code from: https:\/\/gist.github.com\/laanwj\/0e689cfa37b52bcbbb44\n\n\/*\n\nTo set up a new alert system\n----------------------------\n\nCreate a new alert key pair:\nopenssl ecparam -name secp256k1 -genkey -param_enc explicit -outform PEM -out data.pem\n\nGet the private key in hex:\nopenssl ec -in data.pem -outform DER | tail -c 279 | xxd -p -c 279\n\nGet the public key in hex:\nopenssl ec -in data.pem -pubout -outform DER | tail -c 65 | xxd -p -c 65\n\nUpdate the public keys found in chainparams.cpp.\n\n\nTo send an alert message\n------------------------\n\nCopy the private keys into alertkeys.h.\n\nModify the alert parameters, id and message found in this file.\n\nBuild and run with -sendalert or -printalert.\n\n.\/zcashd -printtoconsole -sendalert\n\nOne minute after starting up, the alert will be broadcast. It is then\nflooded through the network until the nRelayUntil time, and will be\nactive until nExpiration OR the alert is cancelled.\n\nIf you make a mistake, send another alert with nCancel set to cancel\nthe bad alert.\n\n*\/\n\n#include \"main.h\"\n#include \"net.h\"\n#include \"alert.h\"\n#include \"init.h\"\n\n#include \"util.h\"\n#include \"utiltime.h\"\n#include \"key.h\"\n#include \"clientversion.h\"\n#include \"chainparams.h\"\n\n#include \"alertkeys.h\"\n\n\nstatic const int64_t DAYS = 24 * 60 * 60;\n\nvoid ThreadSendAlert()\n{\n if (!mapArgs.count(\"-sendalert\") && !mapArgs.count(\"-printalert\"))\n return;\n\n MilliSleep(60*1000); \/\/ Wait a minute so we get connected\n\n \/\/\n \/\/ Alerts are relayed around the network until nRelayUntil, flood\n \/\/ filling to every node.\n \/\/ After the relay time is past, new nodes are told about alerts\n \/\/ when they connect to peers, until either nExpiration or\n \/\/ the alert is cancelled by a newer alert.\n \/\/ Nodes never save alerts to disk, they are in-memory-only.\n \/\/\n CAlert alert;\n alert.nRelayUntil = GetTime() + 15 * 60;\n alert.nExpiration = GetTime() + 365 * 60 * 60;\n alert.nID = 1000; \/\/ use https:\/\/z.cash to keep track of alert IDs\n alert.nCancel = 0; \/\/ cancels previous messages up to this ID number\n\n \/\/ These versions are protocol versions\n \/\/ 70002 : 0.11.2.*\n alert.nMinVer = 70002;\n alert.nMaxVer = 70002;\n\n \/\/\n \/\/ main.cpp: \n \/\/ 1000 for Misc warnings like out of disk space and clock is wrong\n \/\/ 2000 for longer invalid proof-of-work chain \n \/\/ Higher numbers mean higher priority\n alert.nPriority = 5000;\n alert.strComment = \"\";\n alert.strStatusBar = \"URGENT: Upgrade required: see https:\/\/z.cash\";\n\n \/\/ Set specific client version\/versions here. If setSubVer is empty, no filtering on subver is done:\n \/\/ alert.setSubVer.insert(std::string(\"\/Satoshi:0.7.2\/\"));\n\n \/\/ Sign\n const CChainParams& chainparams = Params();\n std::string networkID = chainparams.NetworkIDString();\n bool fIsTestNet = networkID.compare(\"test\") == 0;\n std::vector vchTmp(ParseHex(fIsTestNet ? pszTestNetPrivKey : pszPrivKey));\n CPrivKey vchPrivKey(vchTmp.begin(), vchTmp.end());\n\n CDataStream sMsg(SER_NETWORK, CLIENT_VERSION);\n sMsg << *(CUnsignedAlert*)&alert;\n alert.vchMsg = std::vector(sMsg.begin(), sMsg.end());\n CKey key;\n if (!key.SetPrivKey(vchPrivKey, false))\n {\n printf(\"ThreadSendAlert() : key.SetPrivKey failed\\n\");\n return;\n }\n if (!key.Sign(Hash(alert.vchMsg.begin(), alert.vchMsg.end()), alert.vchSig))\n {\n printf(\"ThreadSendAlert() : key.Sign failed\\n\");\n return;\n }\n\n \/\/ Test\n CDataStream sBuffer(SER_NETWORK, CLIENT_VERSION);\n sBuffer << alert;\n CAlert alert2;\n sBuffer >> alert2;\n if (!alert2.CheckSignature(chainparams.AlertKey()))\n {\n printf(\"ThreadSendAlert() : CheckSignature failed\\n\");\n return;\n }\n assert(alert2.vchMsg == alert.vchMsg);\n assert(alert2.vchSig == alert.vchSig);\n alert.SetNull();\n printf(\"\\nThreadSendAlert:\\n\");\n printf(\"hash=%s\\n\", alert2.GetHash().ToString().c_str());\n printf(\"%s\\n\", alert2.ToString().c_str());\n printf(\"vchMsg=%s\\n\", HexStr(alert2.vchMsg).c_str());\n printf(\"vchSig=%s\\n\", HexStr(alert2.vchSig).c_str());\n\n \/\/ Confirm\n if (!mapArgs.count(\"-sendalert\"))\n return;\n while (vNodes.size() < 1 && !ShutdownRequested())\n MilliSleep(500);\n if (ShutdownRequested())\n return;\n#if 0\n#ifdef QT_GUI\n if (ThreadSafeMessageBox(\"Send alert?\", \"ThreadSendAlert\", wxYES_NO | wxNO_DEFAULT) != wxYES)\n return;\n if (ThreadSafeMessageBox(\"Send alert, are you sure?\", \"ThreadSendAlert\", wxYES_NO | wxNO_DEFAULT) != wxYES)\n {\n ThreadSafeMessageBox(\"Nothing sent\", \"ThreadSendAlert\", wxOK);\n return;\n }\n#endif\n#endif\n \/\/ Send\n printf(\"ThreadSendAlert() : Sending alert\\n\");\n int nSent = 0;\n {\n LOCK(cs_vNodes);\n BOOST_FOREACH(CNode* pnode, vNodes)\n {\n if (alert2.RelayTo(pnode))\n {\n printf(\"ThreadSendAlert() : Sent alert to %s\\n\", pnode->addr.ToString().c_str());\n nSent++;\n }\n }\n }\n printf(\"ThreadSendAlert() : Alert sent to %d nodes\\n\", nSent);\n}\n<|endoftext|>"} {"text":"#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\"server_io.h\"\n\nint respondValidating(int submission_id)\n{\n ostringstream sout;\n sout << \"respond_validating.py \" << submission_id;\n system(sout.str().c_str());\n return 0;\n}\n\nint fetchSubmission(submission &sub)\n{\n FILE *Pipe = popen(\"fetch_submission.py\", \"r\");\n fscanf(Pipe, \"%d\", &sub.submission_id);\n if(sub.submission_id < 0){\n pclose(Pipe);\n return sub.submission_id;\n }\n fscanf(Pipe, \"%d\", &sub.problem_id);\n fscanf(Pipe, \"%d\", &sub.problem_type);\n fscanf(Pipe, \"%d\", &sub.submitter_id);\n char buff[30];\n fscanf(Pipe, \"%s\", buff);\n pclose(Pipe);\n if(string(buff) == \"c++11\"){\n sub.lang = \"c++\";\n sub.std = \"c++11\";\n }else if(string(buff) == \"c++\"){\n sub.lang = \"c++\";\n sub.std = \"\";\n }else if(string(buff) == \"c\"){\n sub.lang = \"c\";\n sub.std = \"\";\n }else{\n sub.lang = \"c++\";\n sub.std = \"c++11\";\n }\n return 0;\n}\n\nint downloadTestdata(submission &sub)\n{\n ostringstream sout;\n sout << \".\/testdata\/\" << setfill('0') << setw(4) << sub.problem_id;\n sout << \"\/input\";\n string dir(sout.str());\n\n sout.str(\"\");\n sout << \"fetch_testdata_meta.py \" << sub.problem_id;\n FILE *Pipe = popen(sout.str().c_str(), \"r\");\n fscanf(Pipe, \"%d\", &sub.testdata_count);\n for(int i = 0; i < sub.testdata_count; ++i){\n int testdata_id;\n long long timestamp;\n fscanf(Pipe, \"%d %lld\", &testdata_id, ×tamp);\n bool flag = true;\n sout.str(\"\");\n sout << dir << setfill('0') << setw(3) << i;\n string td(sout.str());\n ifstream fin(td + \".meta\");\n long long ts;\n if(fin >> ts){\n if(ts == timestamp){\n flag = false;\n }\n }\n fin.close();\n if(flag){\n \/\/need to renew td\n sout.str(\"\");\n sout << testdata_id << ' ' << sub.problem_id << ' ' << i;\n system((\"fetch_testdata.py \" + sout.str()).c_str());\n ofstream fout(td + \".meta\");\n fout << timestamp << endl;\n }\n }\n pclose(Pipe);\n return 0;\n}\n\nint fetchProblem(submission &sub)\n{\n \/\/get submission code\n char *buff = new char[5*1024*1024];\n ostringstream sout;\n sout << \"fetch_code.py \" << sub.submission_id;\n FILE* Pipe = popen(sout.str().c_str(), \"r\");\n sout.str(\"\");\n while(fgets(buff, 5*1024*1024, Pipe) != NULL)\n sout << buff;\n sub.code = sout.str();\n pclose(Pipe);\n \n \/\/get sjcode\n sout.str(\"\");\n sout << \"fetch_sjcode.py \" << sub.problem_id;\n Pipe = popen(sout.str().c_str(), \"r\");\n sout.str(\"\");\n while(fgets(buff, 5*1024*1024, Pipe) != NULL)\n sout << buff;\n sub.sjcode = sout.str();\n pclose(Pipe);\n \n \/\/get interlib\n sout.str(\"\");\n sout << \"fetch_interlib.py \" << sub.problem_id;\n Pipe = popen(sout.str().c_str(), \"r\");\n sout.str(\"\");\n while(fgets(buff, 5*1024*1024, Pipe) != NULL)\n sout << buff;\n sub.interlib = sout.str();\n pclose(Pipe);\n \n delete [] buff;\n \/\/check if testdata dir exists\n sout.str(\"\");\n sout << \".\/testdata\/\";\n sout << setfill('0') << setw(4) << sub.problem_id;\n string testdata_dir(sout.str());\n if(access(testdata_dir.c_str(), F_OK)){\n system((\"mkdir \" + testdata_dir + \" 2>\/dev\/null\").c_str());\n }\n\n \/\/download testdata\n if(downloadTestdata(sub) == -1){\n return -1;\n }\n \n \/\/get memlimit, timelimit\n sout.str(\"\");\n sout << \"fetch_limits.py \" << sub.problem_id;\n Pipe = popen(sout.str().c_str(), \"r\");\n for(int i = 0; i < sub.testdata_count; ++i){\n fscanf(Pipe, \"%d %d\", &sub.time_limit[i], &sub.mem_limit[i]);\n }\n pclose(Pipe);\n\n\n \/\/Only have Batch judge now, haven't done anything for `special`\n \/\/`interactive`, `output only` yet\n\n\n return 0;\n}\n\nint sendResult(submission &sub, int verdict, bool done)\n{\n ostringstream sout;\n sout << \"update_verdict.py \" << sub.submission_id << ' ';\n if(verdict == CE){\n sout << \"CE\";\n }else if(verdict == ER){\n sout << \"ER\";\n }else{\n for(int i = 0; i < sub.testdata_count; ++i){\n sout << fromVerdict(sub.verdict[i]).toAbr() << '\/';\n sout << sub.time[i] << '\/';\n sout << sub.mem[i] << '\/';\n \n cerr << \"td\" << i << \" : time \" << sub.time[i];\n cerr << \" mem \" << sub.mem[i];\n cerr << \" verdict \" << fromVerdict(sub.verdict[i]).toStr();\n cerr << endl;\n }\n }\n if(done){\n sout << \" OK\";\n }else{\n sout << \" NO\";\n }\n system(sout.str().c_str());\n return 0;\n \/*\n if(verdict != CE){\n for(int i = 0; i < sub.testdata_count; ++i){\n verdict = max(verdict, sub.verdict[i]);\n cerr << \"td\" << i << \" : time \" << sub.time[i];\n cerr << \" mem \" << sub.mem[i];\n cerr << \" verdict \" << fromVerdict(sub.verdict[i]).toStr();\n cerr << endl;\n }\n }\n ostringstream sout;\n sout << \"update_verdict.py\" << ' ' << sub.submission_id << ' ';\n \/\/sout << \"'\"<< fromVerdict(verdict).toStr() << \"'\";\n sout << \"'\"<< fromVerdict(verdict).toAbr() << \"'\";\n system(sout.str().c_str());\n return 0;\n *\/\n}\n\nwont halt if no td#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\"server_io.h\"\n\nint respondValidating(int submission_id)\n{\n ostringstream sout;\n sout << \"respond_validating.py \" << submission_id;\n system(sout.str().c_str());\n return 0;\n}\n\nint fetchSubmission(submission &sub)\n{\n FILE *Pipe = popen(\"fetch_submission.py\", \"r\");\n fscanf(Pipe, \"%d\", &sub.submission_id);\n if(sub.submission_id < 0){\n pclose(Pipe);\n return sub.submission_id;\n }\n fscanf(Pipe, \"%d\", &sub.problem_id);\n fscanf(Pipe, \"%d\", &sub.problem_type);\n fscanf(Pipe, \"%d\", &sub.submitter_id);\n char buff[30];\n fscanf(Pipe, \"%s\", buff);\n pclose(Pipe);\n if(string(buff) == \"c++11\"){\n sub.lang = \"c++\";\n sub.std = \"c++11\";\n }else if(string(buff) == \"c++\"){\n sub.lang = \"c++\";\n sub.std = \"\";\n }else if(string(buff) == \"c\"){\n sub.lang = \"c\";\n sub.std = \"\";\n }else{\n sub.lang = \"c++\";\n sub.std = \"c++11\";\n }\n return 0;\n}\n\nint downloadTestdata(submission &sub)\n{\n ostringstream sout;\n sout << \".\/testdata\/\" << setfill('0') << setw(4) << sub.problem_id;\n sout << \"\/input\";\n string dir(sout.str());\n\n sout.str(\"\");\n sout << \"fetch_testdata_meta.py \" << sub.problem_id;\n FILE *Pipe = popen(sout.str().c_str(), \"r\");\n fscanf(Pipe, \"%d\", &sub.testdata_count);\n for(int i = 0; i < sub.testdata_count; ++i){\n int testdata_id;\n long long timestamp;\n fscanf(Pipe, \"%d %lld\", &testdata_id, ×tamp);\n bool flag = true;\n sout.str(\"\");\n sout << dir << setfill('0') << setw(3) << i;\n string td(sout.str());\n ifstream fin(td + \".meta\");\n long long ts;\n if(fin >> ts){\n if(ts == timestamp){\n flag = false;\n }\n }\n fin.close();\n if(flag){\n \/\/need to renew td\n sout.str(\"\");\n sout << testdata_id << ' ' << sub.problem_id << ' ' << i;\n system((\"fetch_testdata.py \" + sout.str()).c_str());\n ofstream fout(td + \".meta\");\n fout << timestamp << endl;\n }\n }\n pclose(Pipe);\n return 0;\n}\n\nint fetchProblem(submission &sub)\n{\n \/\/get submission code\n char *buff = new char[5*1024*1024];\n ostringstream sout;\n sout << \"fetch_code.py \" << sub.submission_id;\n FILE* Pipe = popen(sout.str().c_str(), \"r\");\n sout.str(\"\");\n while(fgets(buff, 5*1024*1024, Pipe) != NULL)\n sout << buff;\n sub.code = sout.str();\n pclose(Pipe);\n \n \/\/get sjcode\n sout.str(\"\");\n sout << \"fetch_sjcode.py \" << sub.problem_id;\n Pipe = popen(sout.str().c_str(), \"r\");\n sout.str(\"\");\n while(fgets(buff, 5*1024*1024, Pipe) != NULL)\n sout << buff;\n sub.sjcode = sout.str();\n pclose(Pipe);\n \n \/\/get interlib\n sout.str(\"\");\n sout << \"fetch_interlib.py \" << sub.problem_id;\n Pipe = popen(sout.str().c_str(), \"r\");\n sout.str(\"\");\n while(fgets(buff, 5*1024*1024, Pipe) != NULL)\n sout << buff;\n sub.interlib = sout.str();\n pclose(Pipe);\n \n delete [] buff;\n \/\/check if testdata dir exists\n sout.str(\"\");\n sout << \".\/testdata\/\";\n sout << setfill('0') << setw(4) << sub.problem_id;\n string testdata_dir(sout.str());\n if(access(testdata_dir.c_str(), F_OK)){\n system((\"mkdir \" + testdata_dir + \" 2>\/dev\/null\").c_str());\n }\n\n \/\/download testdata\n if(downloadTestdata(sub) == -1){\n return -1;\n }\n \n \/\/get memlimit, timelimit\n sout.str(\"\");\n sout << \"fetch_limits.py \" << sub.problem_id;\n Pipe = popen(sout.str().c_str(), \"r\");\n for(int i = 0; i < sub.testdata_count; ++i){\n fscanf(Pipe, \"%d %d\", &sub.time_limit[i], &sub.mem_limit[i]);\n }\n pclose(Pipe);\n\n\n \/\/Only have Batch judge now, haven't done anything for `special`\n \/\/`interactive`, `output only` yet\n\n\n return 0;\n}\n\nint sendResult(submission &sub, int verdict, bool done)\n{\n ostringstream sout;\n sout << \"update_verdict.py \" << sub.submission_id << ' ';\n if(verdict == CE){\n sout << \"CE\";\n }else if(verdict == ER){\n sout << \"ER\";\n }else{\n for(int i = 0; i < sub.testdata_count; ++i){\n sout << fromVerdict(sub.verdict[i]).toAbr() << '\/';\n sout << sub.time[i] << '\/';\n sout << sub.mem[i] << '\/';\n \n cerr << \"td\" << i << \" : time \" << sub.time[i];\n cerr << \" mem \" << sub.mem[i];\n cerr << \" verdict \" << fromVerdict(sub.verdict[i]).toStr();\n cerr << endl;\n }\n }\n if(done){\n sout << \" OK OK\";\n }else{\n sout << \" NO NO\";\n }\n system(sout.str().c_str());\n return 0;\n \/*\n if(verdict != CE){\n for(int i = 0; i < sub.testdata_count; ++i){\n verdict = max(verdict, sub.verdict[i]);\n cerr << \"td\" << i << \" : time \" << sub.time[i];\n cerr << \" mem \" << sub.mem[i];\n cerr << \" verdict \" << fromVerdict(sub.verdict[i]).toStr();\n cerr << endl;\n }\n }\n ostringstream sout;\n sout << \"update_verdict.py\" << ' ' << sub.submission_id << ' ';\n \/\/sout << \"'\"<< fromVerdict(verdict).toStr() << \"'\";\n sout << \"'\"<< fromVerdict(verdict).toAbr() << \"'\";\n system(sout.str().c_str());\n return 0;\n *\/\n}\n\n<|endoftext|>"} {"text":"Inspector: optimize Probe's window-temperature<|endoftext|>"} {"text":"\/*\n* hooks.cpp\n* StatusSpec project\n*\n* Copyright (c) 2014 thesupremecommander\n* BSD 2-Clause License\n* http:\/\/opensource.org\/licenses\/BSD-2-Clause\n*\n*\/\n\n#include \"hooks.h\"\n\nvoid StatusSpecUnloader::ReadyToUnload(SourceHook::Plugin plug) {};\n\nSourceHook::Impl::CSourceHookImpl g_SourceHook;\nSourceHook::ISourceHook *g_SHPtr = &g_SourceHook;\nint g_PLID = 0;\n\nSH_DECL_MANUALHOOK5_void(C_TFPlayer_CalcView, OFFSET_CALCVIEW, 0, 0, Vector &, QAngle &, float &, float &, float &);\nSH_DECL_MANUALHOOK3_void(C_TFPlayer_GetGlowEffectColor, OFFSET_GETGLOWEFFECTCOLOR, 0, 0, float *, float *, float *);\nSH_DECL_MANUALHOOK0(C_TFPlayer_GetObserverMode, OFFSET_GETOBSERVERMODE, 0, 0, int);\nSH_DECL_MANUALHOOK0(C_TFPlayer_GetObserverTarget, OFFSET_GETOBSERVERTARGET, 0, 0, C_BaseEntity *);\nSH_DECL_MANUALHOOK0_void(C_TFPlayer_UpdateGlowEffect, OFFSET_UPDATEGLOWEFFECT, 0, 0);\nSH_DECL_HOOK1_void(IBaseClientDLL, FrameStageNotify, SH_NOATTRIB, 0, ClientFrameStage_t);\nSH_DECL_HOOK2(IGameEventManager2, FireEvent, SH_NOATTRIB, 0, bool, IGameEvent *, bool);\nSH_DECL_HOOK1(IGameEventManager2, FireEventClientSide, SH_NOATTRIB, 0, bool, IGameEvent *);\nSH_DECL_HOOK1(IGameResources, GetPlayerName, SH_NOATTRIB, 0, const char *, int);\nSH_DECL_HOOK3_void(IPanel, PaintTraverse, SH_NOATTRIB, 0, VPANEL, bool, bool);\nSH_DECL_HOOK3_void(IPanel, SendMessage, SH_NOATTRIB, 0, VPANEL, KeyValues *, VPANEL);\nSH_DECL_HOOK2(IVEngineClient, GetPlayerInfo, SH_NOATTRIB, 0, bool, int, player_info_t *);\n\nint Hooks::AddHook_C_TFPlayer_GetGlowEffectColor(C_TFPlayer *instance, void(*hook)(float *, float *, float *)) {\n\treturn SH_ADD_MANUALVPHOOK(C_TFPlayer_GetGlowEffectColor, instance, hook, false);\n}\n\nint Hooks::AddHook_IBaseClientDLL_FrameStageNotify(IBaseClientDLL *instance, void(*hook)(ClientFrameStage_t)) {\n\treturn SH_ADD_HOOK(IBaseClientDLL, FrameStageNotify, instance, hook, false);\n}\n\nint Hooks::AddHook_IGameEventManager2_FireEvent(IGameEventManager2 *instance, bool(*hook)(IGameEvent *, bool)) {\n\treturn SH_ADD_HOOK(IGameEventManager2, FireEvent, instance, hook, false);\n}\n\nint Hooks::AddHook_IGameEventManager2_FireEventClientSide(IGameEventManager2 *instance, bool(*hook)(IGameEvent *)) {\n\treturn SH_ADD_HOOK(IGameEventManager2, FireEventClientSide, instance, hook, false);\n}\n\nint Hooks::AddHook_IGameResources_GetPlayerName(IGameResources *instance, const char *(*hook)(int)) {\n\treturn SH_ADD_HOOK(IGameResources, GetPlayerName, instance, hook, false);\n}\n\nint Hooks::AddHook_IPanel_PaintTraverse(vgui::IPanel *instance, void(*hook)(vgui::VPANEL, bool, bool)) {\n\treturn SH_ADD_HOOK(IPanel, PaintTraverse, instance, hook, false);\n}\n\nint Hooks::AddHook_IPanel_SendMessage(vgui::IPanel *instance, void(*hook)(vgui::VPANEL, KeyValues *, vgui::VPANEL)) {\n\treturn SH_ADD_HOOK(IPanel, SendMessage, instance, hook, false);\n}\n\nint Hooks::AddHook_IVEngineClient_GetPlayerInfo(IVEngineClient *instance, bool(*hook)(int, player_info_t *)) {\n\treturn SH_ADD_HOOK(IVEngineClient, GetPlayerInfo, instance, hook, false);\n}\n\nvoid Hooks::CallFunc_C_TFPlayer_CalcView(C_TFPlayer *instance, Vector &eyeOrigin, QAngle &eyeAngles, float &zNear, float &zFar, float &fov) {\n\tSH_MCALL(instance, C_TFPlayer_CalcView)(eyeOrigin, eyeAngles, zNear, zFar, fov);\n}\n\nint Hooks::CallFunc_C_TFPlayer_GetObserverMode(C_TFPlayer *instance) {\n\treturn SH_MCALL(instance, C_TFPlayer_GetObserverMode)();\n}\n\nC_BaseEntity *Hooks::CallFunc_C_TFPlayer_GetObserverTarget(C_TFPlayer *instance) {\n\treturn SH_MCALL(instance, C_TFPlayer_GetObserverTarget)();\n}\n\nvoid Hooks::CallFunc_C_TFPlayer_UpdateGlowEffect(C_TFPlayer *instance) {\n\tSH_MCALL(instance, C_TFPlayer_UpdateGlowEffect)();\n}\n\nvoid Hooks::Pause() {\n\tg_SourceHook.PausePlugin(g_PLID);\n}\n\nbool Hooks::RemoveHook(int hookID) {\n\treturn SH_REMOVE_HOOK_ID(hookID);\n}\n\nvoid Hooks::Unload() {\n\tg_SourceHook.UnloadPlugin(g_PLID, new StatusSpecUnloader());\n}\n\nvoid Hooks::Unpause() {\n\tg_SourceHook.UnpausePlugin(g_PLID);\n}Make sure to use SH_STATIC macros for hooking functions.\/*\n* hooks.cpp\n* StatusSpec project\n*\n* Copyright (c) 2014 thesupremecommander\n* BSD 2-Clause License\n* http:\/\/opensource.org\/licenses\/BSD-2-Clause\n*\n*\/\n\n#include \"hooks.h\"\n\nvoid StatusSpecUnloader::ReadyToUnload(SourceHook::Plugin plug) {};\n\nSourceHook::Impl::CSourceHookImpl g_SourceHook;\nSourceHook::ISourceHook *g_SHPtr = &g_SourceHook;\nint g_PLID = 0;\n\nSH_DECL_MANUALHOOK5_void(C_TFPlayer_CalcView, OFFSET_CALCVIEW, 0, 0, Vector &, QAngle &, float &, float &, float &);\nSH_DECL_MANUALHOOK3_void(C_TFPlayer_GetGlowEffectColor, OFFSET_GETGLOWEFFECTCOLOR, 0, 0, float *, float *, float *);\nSH_DECL_MANUALHOOK0(C_TFPlayer_GetObserverMode, OFFSET_GETOBSERVERMODE, 0, 0, int);\nSH_DECL_MANUALHOOK0(C_TFPlayer_GetObserverTarget, OFFSET_GETOBSERVERTARGET, 0, 0, C_BaseEntity *);\nSH_DECL_MANUALHOOK0_void(C_TFPlayer_UpdateGlowEffect, OFFSET_UPDATEGLOWEFFECT, 0, 0);\nSH_DECL_HOOK1_void(IBaseClientDLL, FrameStageNotify, SH_NOATTRIB, 0, ClientFrameStage_t);\nSH_DECL_HOOK2(IGameEventManager2, FireEvent, SH_NOATTRIB, 0, bool, IGameEvent *, bool);\nSH_DECL_HOOK1(IGameEventManager2, FireEventClientSide, SH_NOATTRIB, 0, bool, IGameEvent *);\nSH_DECL_HOOK1(IGameResources, GetPlayerName, SH_NOATTRIB, 0, const char *, int);\nSH_DECL_HOOK3_void(IPanel, PaintTraverse, SH_NOATTRIB, 0, VPANEL, bool, bool);\nSH_DECL_HOOK3_void(IPanel, SendMessage, SH_NOATTRIB, 0, VPANEL, KeyValues *, VPANEL);\nSH_DECL_HOOK2(IVEngineClient, GetPlayerInfo, SH_NOATTRIB, 0, bool, int, player_info_t *);\n\nint Hooks::AddHook_C_TFPlayer_GetGlowEffectColor(C_TFPlayer *instance, void(*hook)(float *, float *, float *)) {\n\treturn SH_ADD_MANUALVPHOOK(C_TFPlayer_GetGlowEffectColor, instance, SH_STATIC(hook), false);\n}\n\nint Hooks::AddHook_IBaseClientDLL_FrameStageNotify(IBaseClientDLL *instance, void(*hook)(ClientFrameStage_t)) {\n\treturn SH_ADD_HOOK(IBaseClientDLL, FrameStageNotify, instance, SH_STATIC(hook), false);\n}\n\nint Hooks::AddHook_IGameEventManager2_FireEvent(IGameEventManager2 *instance, bool(*hook)(IGameEvent *, bool)) {\n\treturn SH_ADD_HOOK(IGameEventManager2, FireEvent, instance, SH_STATIC(hook), false);\n}\n\nint Hooks::AddHook_IGameEventManager2_FireEventClientSide(IGameEventManager2 *instance, bool(*hook)(IGameEvent *)) {\n\treturn SH_ADD_HOOK(IGameEventManager2, FireEventClientSide, instance, SH_STATIC(hook), false);\n}\n\nint Hooks::AddHook_IGameResources_GetPlayerName(IGameResources *instance, const char *(*hook)(int)) {\n\treturn SH_ADD_HOOK(IGameResources, GetPlayerName, instance, SH_STATIC(hook), false);\n}\n\nint Hooks::AddHook_IPanel_PaintTraverse(vgui::IPanel *instance, void(*hook)(vgui::VPANEL, bool, bool)) {\n\treturn SH_ADD_HOOK(IPanel, PaintTraverse, instance, SH_STATIC(hook), false);\n}\n\nint Hooks::AddHook_IPanel_SendMessage(vgui::IPanel *instance, void(*hook)(vgui::VPANEL, KeyValues *, vgui::VPANEL)) {\n\treturn SH_ADD_HOOK(IPanel, SendMessage, instance, SH_STATIC(hook), false);\n}\n\nint Hooks::AddHook_IVEngineClient_GetPlayerInfo(IVEngineClient *instance, bool(*hook)(int, player_info_t *)) {\n\treturn SH_ADD_HOOK(IVEngineClient, GetPlayerInfo, instance, SH_STATIC(hook), false);\n}\n\nvoid Hooks::CallFunc_C_TFPlayer_CalcView(C_TFPlayer *instance, Vector &eyeOrigin, QAngle &eyeAngles, float &zNear, float &zFar, float &fov) {\n\tSH_MCALL(instance, C_TFPlayer_CalcView)(eyeOrigin, eyeAngles, zNear, zFar, fov);\n}\n\nint Hooks::CallFunc_C_TFPlayer_GetObserverMode(C_TFPlayer *instance) {\n\treturn SH_MCALL(instance, C_TFPlayer_GetObserverMode)();\n}\n\nC_BaseEntity *Hooks::CallFunc_C_TFPlayer_GetObserverTarget(C_TFPlayer *instance) {\n\treturn SH_MCALL(instance, C_TFPlayer_GetObserverTarget)();\n}\n\nvoid Hooks::CallFunc_C_TFPlayer_UpdateGlowEffect(C_TFPlayer *instance) {\n\tSH_MCALL(instance, C_TFPlayer_UpdateGlowEffect)();\n}\n\nvoid Hooks::Pause() {\n\tg_SourceHook.PausePlugin(g_PLID);\n}\n\nbool Hooks::RemoveHook(int hookID) {\n\treturn SH_REMOVE_HOOK_ID(hookID);\n}\n\nvoid Hooks::Unload() {\n\tg_SourceHook.UnloadPlugin(g_PLID, new StatusSpecUnloader());\n}\n\nvoid Hooks::Unpause() {\n\tg_SourceHook.UnpausePlugin(g_PLID);\n}<|endoftext|>"} {"text":"\/\/== BasicStore.cpp - Basic map from Locations to Values --------*- C++ -*--==\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file defined the BasicStore and BasicStoreManager classes.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/Analysis\/Analyses\/LiveVariables.h\"\n#include \"clang\/Analysis\/PathSensitive\/GRState.h\"\n#include \"llvm\/ADT\/ImmutableMap.h\"\n#include \"llvm\/Support\/Compiler.h\"\n#include \"llvm\/Support\/Streams.h\"\n\nusing namespace clang;\n\ntypedef llvm::ImmutableMap VarBindingsTy; \n\nnamespace {\n \nclass VISIBILITY_HIDDEN BasicStoreManager : public StoreManager {\n VarBindingsTy::Factory VBFactory;\n GRStateManager& StateMgr;\n MemRegionManager MRMgr;\n \npublic:\n BasicStoreManager(GRStateManager& mgr)\n : StateMgr(mgr), MRMgr(StateMgr.getAllocator()) {}\n \n virtual ~BasicStoreManager() {}\n\n virtual RVal GetRVal(Store St, LVal LV, QualType T); \n virtual Store SetRVal(Store St, LVal LV, RVal V); \n virtual Store Remove(Store St, LVal LV);\n\n virtual Store getInitialStore();\n\n virtual MemRegionManager& getRegionManager() { return MRMgr; }\n\n \/\/ FIXME: Investigate what is using this. This method should be removed.\n virtual LVal getLVal(const VarDecl* VD) {\n return lval::MemRegionVal(MRMgr.getVarRegion(VD));\n }\n \n RVal getLValueVar(const GRState* St, const VarDecl* VD);\n RVal getLValueIvar(const GRState* St, const ObjCIvarDecl* D, RVal Base); \n RVal getLValueField(const GRState* St, const FieldDecl* D, RVal Base); \n RVal getLValueElement(const GRState* St, RVal Base, RVal Offset);\n \n virtual Store\n RemoveDeadBindings(Store store, Stmt* Loc, const LiveVariables& Live,\n llvm::SmallVectorImpl& RegionRoots,\n LiveSymbolsTy& LSymbols, DeadSymbolsTy& DSymbols);\n\n virtual void iterBindings(Store store, BindingsHandler& f);\n\n virtual Store AddDecl(Store store,\n const VarDecl* VD, Expr* Ex, \n RVal InitVal = UndefinedVal(), unsigned Count = 0);\n\n static inline VarBindingsTy GetVarBindings(Store store) {\n return VarBindingsTy(static_cast(store));\n }\n\n virtual void print(Store store, std::ostream& Out,\n const char* nl, const char *sep);\n\n};\n \n} \/\/ end anonymous namespace\n\n\nStoreManager* clang::CreateBasicStoreManager(GRStateManager& StMgr) {\n return new BasicStoreManager(StMgr);\n}\nRVal BasicStoreManager::getLValueVar(const GRState* St, const VarDecl* VD) {\n QualType T = VD->getType();\n assert(!T->isArrayType() && \"Array and struct variable have no lvalue.\");\n return lval::MemRegionVal(MRMgr.getVarRegion(VD));\n}\n \nRVal BasicStoreManager::getLValueIvar(const GRState* St, const ObjCIvarDecl* D,\n RVal Base) {\n return UnknownVal();\n}\n \n \nRVal BasicStoreManager::getLValueField(const GRState* St, const FieldDecl* D,\n RVal Base) {\n return UnknownVal();\n}\n\nRVal BasicStoreManager::getLValueElement(const GRState* St, RVal Base,\n RVal Offset) {\n return UnknownVal();\n}\n\nRVal BasicStoreManager::GetRVal(Store St, LVal LV, QualType T) {\n \n if (isa(LV))\n return UnknownVal();\n \n assert (!isa(LV));\n \n switch (LV.getSubKind()) {\n\n case lval::MemRegionKind: {\n VarRegion* R =\n dyn_cast(cast(LV).getRegion());\n \n if (!R)\n return UnknownVal();\n \n VarBindingsTy B(static_cast(St)); \n VarBindingsTy::data_type* T = B.lookup(R->getDecl()); \n return T ? *T : UnknownVal();\n }\n \n case lval::SymbolValKind:\n return UnknownVal();\n \n case lval::ConcreteIntKind:\n \/\/ Some clients may call GetRVal with such an option simply because\n \/\/ they are doing a quick scan through their LVals (potentially to\n \/\/ invalidate their bindings). Just return Undefined.\n return UndefinedVal(); \n case lval::FuncValKind:\n return LV;\n \n case lval::StringLiteralValKind:\n \/\/ FIXME: Implement better support for fetching characters from strings.\n return UnknownVal();\n \n default:\n assert (false && \"Invalid LVal.\");\n break;\n }\n \n return UnknownVal();\n}\n \nStore BasicStoreManager::SetRVal(Store store, LVal LV, RVal V) { \n switch (LV.getSubKind()) { \n case lval::MemRegionKind: {\n VarRegion* R =\n dyn_cast(cast(LV).getRegion());\n \n if (!R)\n return store;\n \n VarBindingsTy B = GetVarBindings(store);\n return V.isUnknown()\n ? VBFactory.Remove(B, R->getDecl()).getRoot()\n : VBFactory.Add(B, R->getDecl(), V).getRoot();\n }\n default:\n assert (\"SetRVal for given LVal type not yet implemented.\");\n return store;\n }\n}\n\nStore BasicStoreManager::Remove(Store store, LVal LV) {\n switch (LV.getSubKind()) {\n case lval::MemRegionKind: {\n VarRegion* R =\n dyn_cast(cast(LV).getRegion());\n \n if (!R)\n return store;\n \n VarBindingsTy B = GetVarBindings(store);\n return VBFactory.Remove(B,R->getDecl()).getRoot();\n }\n default:\n assert (\"Remove for given LVal type not yet implemented.\");\n return store;\n }\n}\n\nStore\nBasicStoreManager::RemoveDeadBindings(Store store, Stmt* Loc,\n const LiveVariables& Liveness,\n llvm::SmallVectorImpl& RegionRoots,\n LiveSymbolsTy& LSymbols, DeadSymbolsTy& DSymbols) {\n \n VarBindingsTy B = GetVarBindings(store);\n typedef RVal::symbol_iterator symbol_iterator;\n \n \/\/ Iterate over the variable bindings.\n for (VarBindingsTy::iterator I=B.begin(), E=B.end(); I!=E ; ++I)\n if (Liveness.isLive(Loc, I.getKey())) {\n RegionRoots.push_back(MRMgr.getVarRegion(I.getKey())); \n RVal X = I.getData();\n \n for (symbol_iterator SI=X.symbol_begin(), SE=X.symbol_end(); SI!=SE; ++SI)\n LSymbols.insert(*SI);\n }\n \n \/\/ Scan for live variables and live symbols.\n llvm::SmallPtrSet Marked;\n \n while (!RegionRoots.empty()) {\n const VarRegion* R = cast(RegionRoots.back());\n RegionRoots.pop_back();\n \n if (Marked.count(R))\n continue;\n \n Marked.insert(R); \n \/\/ FIXME: Do we need the QualType here, since regions are partially\n \/\/ typed?\n RVal X = GetRVal(store, lval::MemRegionVal(R), QualType()); \n \n for (symbol_iterator SI=X.symbol_begin(), SE=X.symbol_end(); SI!=SE; ++SI)\n LSymbols.insert(*SI);\n \n if (!isa(X))\n continue;\n \n const lval::MemRegionVal& LVD = cast(X);\n RegionRoots.push_back(cast(LVD.getRegion()));\n }\n \n \/\/ Remove dead variable bindings. \n for (VarBindingsTy::iterator I=B.begin(), E=B.end(); I!=E ; ++I) {\n const VarRegion* R = cast(MRMgr.getVarRegion(I.getKey()));\n \n if (!Marked.count(R)) {\n store = Remove(store, lval::MemRegionVal(R));\n RVal X = I.getData();\n \n for (symbol_iterator SI=X.symbol_begin(), SE=X.symbol_end(); SI!=SE; ++SI)\n if (!LSymbols.count(*SI)) DSymbols.insert(*SI);\n }\n }\n \n return store;\n}\n\nStore BasicStoreManager::getInitialStore() {\n \/\/ The LiveVariables information already has a compilation of all VarDecls\n \/\/ used in the function. Iterate through this set, and \"symbolicate\"\n \/\/ any VarDecl whose value originally comes from outside the function.\n\n typedef LiveVariables::AnalysisDataTy LVDataTy;\n LVDataTy& D = StateMgr.getLiveVariables().getAnalysisData();\n\n Store St = VBFactory.GetEmptyMap().getRoot();\n\n for (LVDataTy::decl_iterator I=D.begin_decl(), E=D.end_decl(); I != E; ++I) {\n ScopedDecl* SD = const_cast(I->first);\n\n if (VarDecl* VD = dyn_cast(SD)) {\n \/\/ Punt on static variables for now.\n if (VD->getStorageClass() == VarDecl::Static)\n continue;\n\n \/\/ Only handle pointers and integers for now.\n QualType T = VD->getType();\n if (LVal::IsLValType(T) || T->isIntegerType()) {\n \/\/ Initialize globals and parameters to symbolic values.\n \/\/ Initialize local variables to undefined.\n RVal X = (VD->hasGlobalStorage() || isa(VD) ||\n isa(VD))\n ? RVal::GetSymbolValue(StateMgr.getSymbolManager(), VD)\n : UndefinedVal();\n\n St = SetRVal(St, lval::MemRegionVal(MRMgr.getVarRegion(VD)), X);\n }\n }\n }\n return St;\n}\n\nStore BasicStoreManager::AddDecl(Store store,\n const VarDecl* VD, Expr* Ex,\n RVal InitVal, unsigned Count) {\n \n BasicValueFactory& BasicVals = StateMgr.getBasicVals();\n SymbolManager& SymMgr = StateMgr.getSymbolManager();\n \n \/\/ BasicStore does not model arrays and structs.\n if (VD->getType()->isArrayType() || VD->getType()->isStructureType())\n return store;\n\n if (VD->hasGlobalStorage()) {\n \/\/ Handle variables with global storage: extern, static, PrivateExtern.\n\n \/\/ FIXME:: static variables may have an initializer, but the second time a\n \/\/ function is called those values may not be current. Currently, a function\n \/\/ will not be called more than once.\n\n \/\/ Static global variables should not be visited here.\n assert(!(VD->getStorageClass() == VarDecl::Static &&\n VD->isFileVarDecl()));\n \n \/\/ Process static variables.\n if (VD->getStorageClass() == VarDecl::Static) {\n \/\/ C99: 6.7.8 Initialization\n \/\/ If an object that has static storage duration is not initialized\n \/\/ explicitly, then: \n \/\/ —if it has pointer type, it is initialized to a null pointer; \n \/\/ —if it has arithmetic type, it is initialized to (positive or \n \/\/ unsigned) zero;\n if (!Ex) {\n QualType T = VD->getType();\n if (LVal::IsLValType(T))\n store = SetRVal(store, getLVal(VD),\n lval::ConcreteInt(BasicVals.getValue(0, T)));\n else if (T->isIntegerType())\n store = SetRVal(store, getLVal(VD),\n nonlval::ConcreteInt(BasicVals.getValue(0, T)));\n else {\n \/\/ assert(0 && \"ignore other types of variables\");\n }\n } else {\n store = SetRVal(store, getLVal(VD), InitVal);\n }\n }\n } else {\n \/\/ Process local scalar variables.\n QualType T = VD->getType();\n if (LVal::IsLValType(T) || T->isIntegerType()) {\n RVal V = Ex ? InitVal : UndefinedVal();\n\n if (Ex && InitVal.isUnknown()) {\n \/\/ EXPERIMENTAL: \"Conjured\" symbols.\n SymbolID Sym = SymMgr.getConjuredSymbol(Ex, Count);\n\n V = LVal::IsLValType(Ex->getType())\n ? cast(lval::SymbolVal(Sym))\n : cast(nonlval::SymbolVal(Sym));\n }\n\n store = SetRVal(store, getLVal(VD), V);\n }\n }\n\n return store;\n}\n\nvoid BasicStoreManager::print(Store store, std::ostream& Out,\n const char* nl, const char *sep) {\n \n VarBindingsTy B = GetVarBindings(store);\n Out << \"Variables:\" << nl;\n \n bool isFirst = true;\n \n for (VarBindingsTy::iterator I=B.begin(), E=B.end(); I != E; ++I) {\n if (isFirst) isFirst = false;\n else Out << nl;\n \n Out << ' ' << I.getKey()->getName() << \" : \";\n I.getData().print(Out);\n }\n}\n\n\nvoid BasicStoreManager::iterBindings(Store store, BindingsHandler& f) {\n VarBindingsTy B = GetVarBindings(store);\n \n for (VarBindingsTy::iterator I=B.begin(), E=B.end(); I != E; ++I) {\n\n f.HandleBinding(*this, store, MRMgr.getVarRegion(I.getKey()),I.getData());\n }\n}\n\nStoreManager::BindingsHandler::~BindingsHandler() {}\nArray and struct variables do have lvalue. For example, struct s {}; void f() { int a[10]; int (*p)[10]; p = &a; (*p)[3] =1;\/\/== BasicStore.cpp - Basic map from Locations to Values --------*- C++ -*--==\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file defined the BasicStore and BasicStoreManager classes.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/Analysis\/Analyses\/LiveVariables.h\"\n#include \"clang\/Analysis\/PathSensitive\/GRState.h\"\n#include \"llvm\/ADT\/ImmutableMap.h\"\n#include \"llvm\/Support\/Compiler.h\"\n#include \"llvm\/Support\/Streams.h\"\n\nusing namespace clang;\n\ntypedef llvm::ImmutableMap VarBindingsTy; \n\nnamespace {\n \nclass VISIBILITY_HIDDEN BasicStoreManager : public StoreManager {\n VarBindingsTy::Factory VBFactory;\n GRStateManager& StateMgr;\n MemRegionManager MRMgr;\n \npublic:\n BasicStoreManager(GRStateManager& mgr)\n : StateMgr(mgr), MRMgr(StateMgr.getAllocator()) {}\n \n virtual ~BasicStoreManager() {}\n\n virtual RVal GetRVal(Store St, LVal LV, QualType T); \n virtual Store SetRVal(Store St, LVal LV, RVal V); \n virtual Store Remove(Store St, LVal LV);\n\n virtual Store getInitialStore();\n\n virtual MemRegionManager& getRegionManager() { return MRMgr; }\n\n \/\/ FIXME: Investigate what is using this. This method should be removed.\n virtual LVal getLVal(const VarDecl* VD) {\n return lval::MemRegionVal(MRMgr.getVarRegion(VD));\n }\n \n RVal getLValueVar(const GRState* St, const VarDecl* VD);\n RVal getLValueIvar(const GRState* St, const ObjCIvarDecl* D, RVal Base); \n RVal getLValueField(const GRState* St, const FieldDecl* D, RVal Base); \n RVal getLValueElement(const GRState* St, RVal Base, RVal Offset);\n \n virtual Store\n RemoveDeadBindings(Store store, Stmt* Loc, const LiveVariables& Live,\n llvm::SmallVectorImpl& RegionRoots,\n LiveSymbolsTy& LSymbols, DeadSymbolsTy& DSymbols);\n\n virtual void iterBindings(Store store, BindingsHandler& f);\n\n virtual Store AddDecl(Store store,\n const VarDecl* VD, Expr* Ex, \n RVal InitVal = UndefinedVal(), unsigned Count = 0);\n\n static inline VarBindingsTy GetVarBindings(Store store) {\n return VarBindingsTy(static_cast(store));\n }\n\n virtual void print(Store store, std::ostream& Out,\n const char* nl, const char *sep);\n\n};\n \n} \/\/ end anonymous namespace\n\n\nStoreManager* clang::CreateBasicStoreManager(GRStateManager& StMgr) {\n return new BasicStoreManager(StMgr);\n}\nRVal BasicStoreManager::getLValueVar(const GRState* St, const VarDecl* VD) {\n return lval::MemRegionVal(MRMgr.getVarRegion(VD));\n}\n \nRVal BasicStoreManager::getLValueIvar(const GRState* St, const ObjCIvarDecl* D,\n RVal Base) {\n return UnknownVal();\n}\n \n \nRVal BasicStoreManager::getLValueField(const GRState* St, const FieldDecl* D,\n RVal Base) {\n return UnknownVal();\n}\n\nRVal BasicStoreManager::getLValueElement(const GRState* St, RVal Base,\n RVal Offset) {\n return UnknownVal();\n}\n\nRVal BasicStoreManager::GetRVal(Store St, LVal LV, QualType T) {\n \n if (isa(LV))\n return UnknownVal();\n \n assert (!isa(LV));\n \n switch (LV.getSubKind()) {\n\n case lval::MemRegionKind: {\n VarRegion* R =\n dyn_cast(cast(LV).getRegion());\n \n if (!R)\n return UnknownVal();\n \n VarBindingsTy B(static_cast(St)); \n VarBindingsTy::data_type* T = B.lookup(R->getDecl()); \n return T ? *T : UnknownVal();\n }\n \n case lval::SymbolValKind:\n return UnknownVal();\n \n case lval::ConcreteIntKind:\n \/\/ Some clients may call GetRVal with such an option simply because\n \/\/ they are doing a quick scan through their LVals (potentially to\n \/\/ invalidate their bindings). Just return Undefined.\n return UndefinedVal(); \n case lval::FuncValKind:\n return LV;\n \n case lval::StringLiteralValKind:\n \/\/ FIXME: Implement better support for fetching characters from strings.\n return UnknownVal();\n \n default:\n assert (false && \"Invalid LVal.\");\n break;\n }\n \n return UnknownVal();\n}\n \nStore BasicStoreManager::SetRVal(Store store, LVal LV, RVal V) { \n switch (LV.getSubKind()) { \n case lval::MemRegionKind: {\n VarRegion* R =\n dyn_cast(cast(LV).getRegion());\n \n if (!R)\n return store;\n \n VarBindingsTy B = GetVarBindings(store);\n return V.isUnknown()\n ? VBFactory.Remove(B, R->getDecl()).getRoot()\n : VBFactory.Add(B, R->getDecl(), V).getRoot();\n }\n default:\n assert (\"SetRVal for given LVal type not yet implemented.\");\n return store;\n }\n}\n\nStore BasicStoreManager::Remove(Store store, LVal LV) {\n switch (LV.getSubKind()) {\n case lval::MemRegionKind: {\n VarRegion* R =\n dyn_cast(cast(LV).getRegion());\n \n if (!R)\n return store;\n \n VarBindingsTy B = GetVarBindings(store);\n return VBFactory.Remove(B,R->getDecl()).getRoot();\n }\n default:\n assert (\"Remove for given LVal type not yet implemented.\");\n return store;\n }\n}\n\nStore\nBasicStoreManager::RemoveDeadBindings(Store store, Stmt* Loc,\n const LiveVariables& Liveness,\n llvm::SmallVectorImpl& RegionRoots,\n LiveSymbolsTy& LSymbols, DeadSymbolsTy& DSymbols) {\n \n VarBindingsTy B = GetVarBindings(store);\n typedef RVal::symbol_iterator symbol_iterator;\n \n \/\/ Iterate over the variable bindings.\n for (VarBindingsTy::iterator I=B.begin(), E=B.end(); I!=E ; ++I)\n if (Liveness.isLive(Loc, I.getKey())) {\n RegionRoots.push_back(MRMgr.getVarRegion(I.getKey())); \n RVal X = I.getData();\n \n for (symbol_iterator SI=X.symbol_begin(), SE=X.symbol_end(); SI!=SE; ++SI)\n LSymbols.insert(*SI);\n }\n \n \/\/ Scan for live variables and live symbols.\n llvm::SmallPtrSet Marked;\n \n while (!RegionRoots.empty()) {\n const VarRegion* R = cast(RegionRoots.back());\n RegionRoots.pop_back();\n \n if (Marked.count(R))\n continue;\n \n Marked.insert(R); \n \/\/ FIXME: Do we need the QualType here, since regions are partially\n \/\/ typed?\n RVal X = GetRVal(store, lval::MemRegionVal(R), QualType()); \n \n for (symbol_iterator SI=X.symbol_begin(), SE=X.symbol_end(); SI!=SE; ++SI)\n LSymbols.insert(*SI);\n \n if (!isa(X))\n continue;\n \n const lval::MemRegionVal& LVD = cast(X);\n RegionRoots.push_back(cast(LVD.getRegion()));\n }\n \n \/\/ Remove dead variable bindings. \n for (VarBindingsTy::iterator I=B.begin(), E=B.end(); I!=E ; ++I) {\n const VarRegion* R = cast(MRMgr.getVarRegion(I.getKey()));\n \n if (!Marked.count(R)) {\n store = Remove(store, lval::MemRegionVal(R));\n RVal X = I.getData();\n \n for (symbol_iterator SI=X.symbol_begin(), SE=X.symbol_end(); SI!=SE; ++SI)\n if (!LSymbols.count(*SI)) DSymbols.insert(*SI);\n }\n }\n \n return store;\n}\n\nStore BasicStoreManager::getInitialStore() {\n \/\/ The LiveVariables information already has a compilation of all VarDecls\n \/\/ used in the function. Iterate through this set, and \"symbolicate\"\n \/\/ any VarDecl whose value originally comes from outside the function.\n\n typedef LiveVariables::AnalysisDataTy LVDataTy;\n LVDataTy& D = StateMgr.getLiveVariables().getAnalysisData();\n\n Store St = VBFactory.GetEmptyMap().getRoot();\n\n for (LVDataTy::decl_iterator I=D.begin_decl(), E=D.end_decl(); I != E; ++I) {\n ScopedDecl* SD = const_cast(I->first);\n\n if (VarDecl* VD = dyn_cast(SD)) {\n \/\/ Punt on static variables for now.\n if (VD->getStorageClass() == VarDecl::Static)\n continue;\n\n \/\/ Only handle pointers and integers for now.\n QualType T = VD->getType();\n if (LVal::IsLValType(T) || T->isIntegerType()) {\n \/\/ Initialize globals and parameters to symbolic values.\n \/\/ Initialize local variables to undefined.\n RVal X = (VD->hasGlobalStorage() || isa(VD) ||\n isa(VD))\n ? RVal::GetSymbolValue(StateMgr.getSymbolManager(), VD)\n : UndefinedVal();\n\n St = SetRVal(St, lval::MemRegionVal(MRMgr.getVarRegion(VD)), X);\n }\n }\n }\n return St;\n}\n\nStore BasicStoreManager::AddDecl(Store store,\n const VarDecl* VD, Expr* Ex,\n RVal InitVal, unsigned Count) {\n \n BasicValueFactory& BasicVals = StateMgr.getBasicVals();\n SymbolManager& SymMgr = StateMgr.getSymbolManager();\n \n \/\/ BasicStore does not model arrays and structs.\n if (VD->getType()->isArrayType() || VD->getType()->isStructureType())\n return store;\n\n if (VD->hasGlobalStorage()) {\n \/\/ Handle variables with global storage: extern, static, PrivateExtern.\n\n \/\/ FIXME:: static variables may have an initializer, but the second time a\n \/\/ function is called those values may not be current. Currently, a function\n \/\/ will not be called more than once.\n\n \/\/ Static global variables should not be visited here.\n assert(!(VD->getStorageClass() == VarDecl::Static &&\n VD->isFileVarDecl()));\n \n \/\/ Process static variables.\n if (VD->getStorageClass() == VarDecl::Static) {\n \/\/ C99: 6.7.8 Initialization\n \/\/ If an object that has static storage duration is not initialized\n \/\/ explicitly, then: \n \/\/ —if it has pointer type, it is initialized to a null pointer; \n \/\/ —if it has arithmetic type, it is initialized to (positive or \n \/\/ unsigned) zero;\n if (!Ex) {\n QualType T = VD->getType();\n if (LVal::IsLValType(T))\n store = SetRVal(store, getLVal(VD),\n lval::ConcreteInt(BasicVals.getValue(0, T)));\n else if (T->isIntegerType())\n store = SetRVal(store, getLVal(VD),\n nonlval::ConcreteInt(BasicVals.getValue(0, T)));\n else {\n \/\/ assert(0 && \"ignore other types of variables\");\n }\n } else {\n store = SetRVal(store, getLVal(VD), InitVal);\n }\n }\n } else {\n \/\/ Process local scalar variables.\n QualType T = VD->getType();\n if (LVal::IsLValType(T) || T->isIntegerType()) {\n RVal V = Ex ? InitVal : UndefinedVal();\n\n if (Ex && InitVal.isUnknown()) {\n \/\/ EXPERIMENTAL: \"Conjured\" symbols.\n SymbolID Sym = SymMgr.getConjuredSymbol(Ex, Count);\n\n V = LVal::IsLValType(Ex->getType())\n ? cast(lval::SymbolVal(Sym))\n : cast(nonlval::SymbolVal(Sym));\n }\n\n store = SetRVal(store, getLVal(VD), V);\n }\n }\n\n return store;\n}\n\nvoid BasicStoreManager::print(Store store, std::ostream& Out,\n const char* nl, const char *sep) {\n \n VarBindingsTy B = GetVarBindings(store);\n Out << \"Variables:\" << nl;\n \n bool isFirst = true;\n \n for (VarBindingsTy::iterator I=B.begin(), E=B.end(); I != E; ++I) {\n if (isFirst) isFirst = false;\n else Out << nl;\n \n Out << ' ' << I.getKey()->getName() << \" : \";\n I.getData().print(Out);\n }\n}\n\n\nvoid BasicStoreManager::iterBindings(Store store, BindingsHandler& f) {\n VarBindingsTy B = GetVarBindings(store);\n \n for (VarBindingsTy::iterator I=B.begin(), E=B.end(); I != E; ++I) {\n\n f.HandleBinding(*this, store, MRMgr.getVarRegion(I.getKey()),I.getData());\n }\n}\n\nStoreManager::BindingsHandler::~BindingsHandler() {}\n<|endoftext|>"} {"text":"\/**\n * @file classify-test.cpp\n *\/\n\n#include \n#include \n#include \n#include \n\n#include \"index\/document.h\"\n#include \"io\/config_reader.h\"\n#include \"tokenizers\/tokenizers.h\"\n#include \"util\/invertible_map.h\"\n#include \"classify\/classifier\/all.h\"\n\nusing std::vector;\nusing std::unordered_map;\nusing std::pair;\nusing std::cout;\nusing std::cerr;\nusing std::endl;\nusing std::string;\n\nusing namespace meta;\nusing namespace meta::index;\nusing namespace meta::util;\nusing namespace meta::tokenizers;\n\n\/**\n * Tokenizes testing and training docs.\n *\/\nvoid tokenize(vector & docs, const cpptoml::toml_group & config)\n{\n std::shared_ptr tok = io::config_reader::create_tokenizer(config);\n\n size_t i = 0;\n for(auto & d: docs)\n {\n common::show_progress(i++, docs.size(), 20, \" tokenizing \");\n tok->tokenize(d, nullptr);\n }\n common::end_progress(\" tokenizing \");\n}\n\nclassify::confusion_matrix cv( classify::classifier & c, const vector & train_docs ) {\n classify::confusion_matrix matrix = c.cross_validate(train_docs, 5);\n matrix.print();\n matrix.print_stats();\n return matrix;\n}\n\n\/**\n *\n *\/\nint main(int argc, char* argv[])\n{\n if(argc != 2)\n {\n cerr << \"Usage:\\t\" << argv[0] << \" config.ini\" << endl;\n return 1;\n }\n\n auto config = io::config_reader::read(argv[1]);\n string prefix = *cpptoml::get_as( config, \"prefix\" ) \n + *cpptoml::get_as( config, \"dataset\" );;\n string corpus_file = prefix \n + \"\/\" \n + *cpptoml::get_as( config, \"list\" ) \n + \"-full-corpus.txt\";\n vector train_docs = document::load_docs(corpus_file, prefix);\n \/\/vector test_docs = document::loadDocs(prefix + \"\/test.txt\", prefix);\n\n tokenize(train_docs, config);\n \/\/tokenize(test_docs, config);\n \n classify::liblinear_svm svm{ *cpptoml::get_as( config, \"liblinear\" ) };\n classify::linear_svm l2svm;\n classify::linear_svm l1svm{ classify::linear_svm::loss_function::L1 };\n classify::perceptron p;\n classify::naive_bayes nb;\n auto m1 = cv( svm, train_docs );\n auto m2 = cv( l2svm, train_docs );\n std::cout << \"(liblinear) Significant? \" << std::boolalpha << classify::confusion_matrix::mcnemar_significant( m1, m2 ) << std::endl;\n auto m3 = cv( l1svm, train_docs );\n std::cout << \"(liblinear) Significant? \" << std::boolalpha << classify::confusion_matrix::mcnemar_significant( m1, m3 ) << std::endl;\n auto m4 = cv( p, train_docs );\n std::cout << \"(liblinear) Significant? \" << std::boolalpha << classify::confusion_matrix::mcnemar_significant( m1, m4 ) << std::endl;\n std::cout << \"(lsvm) Significant? \" << std::boolalpha << classify::confusion_matrix::mcnemar_significant( m2, m4 ) << std::endl;\n cv( nb, train_docs );\n \/\/svm.train(train_docs);\n \n return 0;\n}\nfix few small typos\/**\n * @file classify-test.cpp\n *\/\n\n#include \n#include \n#include \n#include \n\n#include \"index\/document.h\"\n#include \"io\/config_reader.h\"\n#include \"tokenizers\/tokenizers.h\"\n#include \"util\/invertible_map.h\"\n#include \"classify\/classifier\/all.h\"\n\nusing std::vector;\nusing std::unordered_map;\nusing std::pair;\nusing std::cout;\nusing std::cerr;\nusing std::endl;\nusing std::string;\n\nusing namespace meta;\nusing namespace meta::index;\nusing namespace meta::util;\nusing namespace meta::tokenizers;\n\n\/**\n * Tokenizes testing and training docs.\n *\/\nvoid tokenize(vector & docs, const cpptoml::toml_group & config)\n{\n std::shared_ptr tok = io::config_reader::create_tokenizer(config);\n\n size_t i = 0;\n for(auto & d: docs)\n {\n common::show_progress(i++, docs.size(), 20, \" tokenizing \");\n tok->tokenize(d, nullptr);\n }\n common::end_progress(\" tokenizing \");\n}\n\nclassify::confusion_matrix cv( classify::classifier & c, const vector & train_docs ) {\n classify::confusion_matrix matrix = c.cross_validate(train_docs, 5);\n matrix.print();\n matrix.print_stats();\n return matrix;\n}\n\n\/**\n *\n *\/\nint main(int argc, char* argv[])\n{\n if(argc != 2)\n {\n cerr << \"Usage:\\t\" << argv[0] << \" config.toml\" << endl;\n return 1;\n }\n\n auto config = io::config_reader::read(argv[1]);\n string prefix = *cpptoml::get_as( config, \"prefix\" ) \n + *cpptoml::get_as( config, \"dataset\" );\n string corpus_file = prefix \n + \"\/\" \n + *cpptoml::get_as( config, \"list\" ) \n + \"-full-corpus.txt\";\n vector train_docs = document::load_docs(corpus_file, prefix);\n \/\/vector test_docs = document::loadDocs(prefix + \"\/test.txt\", prefix);\n\n tokenize(train_docs, config);\n \/\/tokenize(test_docs, config);\n \n classify::liblinear_svm svm{ *cpptoml::get_as( config, \"liblinear\" ) };\n classify::linear_svm l2svm;\n classify::linear_svm l1svm{ classify::linear_svm::loss_function::L1 };\n classify::perceptron p;\n classify::naive_bayes nb;\n auto m1 = cv( svm, train_docs );\n auto m2 = cv( l2svm, train_docs );\n std::cout << \"(liblinear) Significant? \" << std::boolalpha << classify::confusion_matrix::mcnemar_significant( m1, m2 ) << std::endl;\n auto m3 = cv( l1svm, train_docs );\n std::cout << \"(liblinear) Significant? \" << std::boolalpha << classify::confusion_matrix::mcnemar_significant( m1, m3 ) << std::endl;\n auto m4 = cv( p, train_docs );\n std::cout << \"(liblinear) Significant? \" << std::boolalpha << classify::confusion_matrix::mcnemar_significant( m1, m4 ) << std::endl;\n std::cout << \"(lsvm) Significant? \" << std::boolalpha << classify::confusion_matrix::mcnemar_significant( m2, m4 ) << std::endl;\n cv( nb, train_docs );\n \/\/svm.train(train_docs);\n \n return 0;\n}\n<|endoftext|>"} {"text":"fix text of commands to create B-spline curves<|endoftext|>"} {"text":"#ifndef KARM_UTILITY_H\n#define KARM_UTILITY_H\n\n#include \"karmutility.h\"\n\nQString formatTime( long minutes )\n{\n QString time;\n time.sprintf(\"%ld:%02ld\", minutes \/ 60, labs(minutes % 60));\n return time;\n}\n\n#endif \/\/ KARM_UTILITY_H\n#ifndef KARM_UTILITY_H\n#define KARM_UTILITY_H\n\n#include \n\n#include \"karmutility.h\"\n\nQString formatTime( long minutes )\n{\n QString time;\n time.sprintf(\"%ld:%02ld\", minutes \/ 60, labs(minutes % 60));\n return time;\n}\n\n#endif \/\/ KARM_UTILITY_H\n<|endoftext|>"} {"text":"\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2013-2016.\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/www.opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#include \n\n#include \"drivers\/keyboard.hpp\"\n\n#include \"stdio.hpp\"\n#include \"terminal.hpp\"\n#include \"terminal_driver.hpp\"\n#include \"console.hpp\"\n#include \"assert.hpp\"\n#include \"logging.hpp\"\n#include \"scheduler.hpp\"\n\nnamespace {\n\nstdio::terminal_driver terminal_driver_impl;\nstdio::terminal_driver* tty_driver = &terminal_driver_impl;\n\nconstexpr const size_t MAX_TERMINALS = 3;\nsize_t active_terminal;\n\nstd::array terminals;\n\nvoid input_thread(void* data) {\n auto& terminal = *reinterpret_cast(data);\n\n auto pid = scheduler::get_pid();\n\n logging::logf(logging::log_level::TRACE, \"stdio: Input Thread for terminal %u started (pid:%u)\\n\", terminal.id, pid);\n\n bool shift = false;\n bool alt = false;\n\n while (true) {\n \/\/ Wait for some input\n scheduler::block_process(pid);\n\n \/\/ Handle keyboard input\n while (!terminal.keyboard_buffer.empty()) {\n auto key = terminal.keyboard_buffer.pop();\n\n if (terminal.canonical) {\n \/\/Key released\n if (key & 0x80) {\n key &= ~(0x80);\n\n if (alt && key == keyboard::KEY_F1) {\n stdio::switch_terminal(0);\n } else if (alt && key == keyboard::KEY_F2) {\n stdio::switch_terminal(1);\n } else if (alt && key == keyboard::KEY_F3) {\n stdio::switch_terminal(2);\n }\n\n if (key == keyboard::KEY_LEFT_SHIFT || key == keyboard::KEY_RIGHT_SHIFT) {\n shift = false;\n }\n\n if (key == keyboard::KEY_ALT) {\n alt = false;\n }\n }\n \/\/Key pressed\n else {\n if (key == keyboard::KEY_LEFT_SHIFT || key == keyboard::KEY_RIGHT_SHIFT) {\n shift = true;\n } else if (key == keyboard::KEY_ALT) {\n alt = true;\n } else if (key == keyboard::KEY_BACKSPACE) {\n if (!terminal.input_buffer.empty()) {\n terminal.input_buffer.pop_last();\n terminal.print('\\b');\n }\n } else {\n auto qwertz_key =\n shift\n ? keyboard::shift_key_to_ascii(key)\n : keyboard::key_to_ascii(key);\n\n if (qwertz_key) {\n terminal.input_buffer.push(qwertz_key);\n\n terminal.print(qwertz_key);\n\n if (qwertz_key == '\\n') {\n \/\/ Transfer current line to the canonical buffer\n while (!terminal.input_buffer.empty()) {\n terminal.canonical_buffer.push(terminal.input_buffer.pop());\n }\n\n terminal.input_queue.notify_one();\n }\n }\n }\n }\n } else {\n \/\/ The complete processing of the key will be done by the\n \/\/ userspace program\n auto code = keyboard::raw_key_to_keycode(key);\n terminal.raw_buffer.push(static_cast(code));\n\n terminal.input_queue.notify_one();\n\n thor_assert(!terminal.raw_buffer.full(), \"raw buffer is full!\");\n }\n }\n\n \/\/ Handle mouse input\n while (!terminal.mouse_buffer.empty()) {\n auto key = terminal.mouse_buffer.pop();\n\n if (!terminal.canonical && terminal.is_mouse()) {\n terminal.raw_buffer.push(key);\n\n terminal.input_queue.notify_one();\n\n thor_assert(!terminal.raw_buffer.full(), \"raw buffer is full!\");\n }\n }\n }\n}\n\n} \/\/end of anonymous namespace\n\nvoid stdio::init_terminals() {\n size_t id = 0;\n\n for (auto& terminal : terminals) {\n terminal.id = id++;\n terminal.active = false;\n terminal.canonical = true;\n terminal.mouse = false;\n }\n\n \/\/ Initialize the active terminal\n\n active_terminal = 0;\n terminals[active_terminal].active = true;\n terminals[active_terminal].get_console().set_active(true);\n}\n\nvoid stdio::register_devices() {\n for (auto& terminal : terminals) {\n std::string name = std::string(\"tty\") + std::to_string(terminal.id);\n\n devfs::register_device(\"\/dev\/\", name, devfs::device_type::CHAR_DEVICE, tty_driver, &terminal);\n }\n}\n\nvoid stdio::finalize() {\n for (auto& terminal : terminals) {\n auto* user_stack = new char[scheduler::user_stack_size];\n auto* kernel_stack = new char[scheduler::kernel_stack_size];\n\n auto& input_process = scheduler::create_kernel_task_args(\"tty_input\", user_stack, kernel_stack, &input_thread, &terminal);\n input_process.ppid = 1;\n input_process.priority = scheduler::DEFAULT_PRIORITY;\n\n scheduler::queue_system_process(input_process.pid);\n\n terminal.input_thread_pid = input_process.pid;\n\n \/\/ Save the initial image of the terminal\n terminal.get_console().init();\n terminal.get_console().save();\n }\n}\n\nsize_t stdio::terminals_count() {\n return MAX_TERMINALS;\n}\n\nstdio::virtual_terminal& stdio::get_active_terminal() {\n return terminals[active_terminal];\n}\n\nstdio::virtual_terminal& stdio::get_terminal(size_t id) {\n thor_assert(id < MAX_TERMINALS, \"Out of bound tty\");\n\n return terminals[id];\n}\n\nvoid stdio::switch_terminal(size_t id) {\n if (active_terminal != id) {\n logging::logf(logging::log_level::TRACE, \"stdio: Switch activate virtual terminal %u\\n\", id);\n\n \/\/ Effectively switch the terminal\n terminals[active_terminal].set_active(false);\n terminals[id].set_active(true);\n\n active_terminal = id;\n }\n}\nLower number of terminals in low memory systems\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2013-2016.\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/www.opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#include \n\n#include \"drivers\/keyboard.hpp\"\n\n#include \"stdio.hpp\"\n#include \"terminal.hpp\"\n#include \"terminal_driver.hpp\"\n#include \"console.hpp\"\n#include \"assert.hpp\"\n#include \"logging.hpp\"\n#include \"scheduler.hpp\"\n#include \"physical_allocator.hpp\"\n\nnamespace {\n\nstdio::terminal_driver terminal_driver_impl;\nstdio::terminal_driver* tty_driver = &terminal_driver_impl;\n\nconstexpr const size_t MAX_TERMINALS = 3;\n\nsize_t _terminals_count;\nsize_t active_terminal;\n\nstd::array terminals;\n\nvoid input_thread(void* data) {\n auto& terminal = *reinterpret_cast(data);\n\n auto pid = scheduler::get_pid();\n\n logging::logf(logging::log_level::TRACE, \"stdio: Input Thread for terminal %u started (pid:%u)\\n\", terminal.id, pid);\n\n bool shift = false;\n bool alt = false;\n\n while (true) {\n \/\/ Wait for some input\n scheduler::block_process(pid);\n\n \/\/ Handle keyboard input\n while (!terminal.keyboard_buffer.empty()) {\n auto key = terminal.keyboard_buffer.pop();\n\n if (terminal.canonical) {\n \/\/Key released\n if (key & 0x80) {\n key &= ~(0x80);\n\n if (alt && key == keyboard::KEY_F1) {\n stdio::switch_terminal(0);\n } else if (alt && key == keyboard::KEY_F2) {\n stdio::switch_terminal(1);\n } else if (alt && key == keyboard::KEY_F3) {\n stdio::switch_terminal(2);\n }\n\n if (key == keyboard::KEY_LEFT_SHIFT || key == keyboard::KEY_RIGHT_SHIFT) {\n shift = false;\n }\n\n if (key == keyboard::KEY_ALT) {\n alt = false;\n }\n }\n \/\/Key pressed\n else {\n if (key == keyboard::KEY_LEFT_SHIFT || key == keyboard::KEY_RIGHT_SHIFT) {\n shift = true;\n } else if (key == keyboard::KEY_ALT) {\n alt = true;\n } else if (key == keyboard::KEY_BACKSPACE) {\n if (!terminal.input_buffer.empty()) {\n terminal.input_buffer.pop_last();\n terminal.print('\\b');\n }\n } else {\n auto qwertz_key =\n shift\n ? keyboard::shift_key_to_ascii(key)\n : keyboard::key_to_ascii(key);\n\n if (qwertz_key) {\n terminal.input_buffer.push(qwertz_key);\n\n terminal.print(qwertz_key);\n\n if (qwertz_key == '\\n') {\n \/\/ Transfer current line to the canonical buffer\n while (!terminal.input_buffer.empty()) {\n terminal.canonical_buffer.push(terminal.input_buffer.pop());\n }\n\n terminal.input_queue.notify_one();\n }\n }\n }\n }\n } else {\n \/\/ The complete processing of the key will be done by the\n \/\/ userspace program\n auto code = keyboard::raw_key_to_keycode(key);\n terminal.raw_buffer.push(static_cast(code));\n\n terminal.input_queue.notify_one();\n\n thor_assert(!terminal.raw_buffer.full(), \"raw buffer is full!\");\n }\n }\n\n \/\/ Handle mouse input\n while (!terminal.mouse_buffer.empty()) {\n auto key = terminal.mouse_buffer.pop();\n\n if (!terminal.canonical && terminal.is_mouse()) {\n terminal.raw_buffer.push(key);\n\n terminal.input_queue.notify_one();\n\n thor_assert(!terminal.raw_buffer.full(), \"raw buffer is full!\");\n }\n }\n }\n}\n\n} \/\/end of anonymous namespace\n\nvoid stdio::init_terminals() {\n size_t id = 0;\n\n if(physical_allocator::available() < 64 * 1024 * 1024){\n _terminals_count = 1;\n } else {\n _terminals_count = MAX_TERMINALS;\n }\n\n logging::logf(logging::log_level::DEBUG, \"stdio: using %u terminals\\n\", _terminals_count);\n\n for (size_t i = 0; i < _terminals_count; ++i){\n auto& terminal = terminals[i];\n\n terminal.id = id++;\n terminal.active = false;\n terminal.canonical = true;\n terminal.mouse = false;\n }\n\n \/\/ Initialize the active terminal\n\n active_terminal = 0;\n terminals[active_terminal].active = true;\n terminals[active_terminal].get_console().set_active(true);\n}\n\nvoid stdio::register_devices() {\n for (size_t i = 0; i < _terminals_count; ++i){\n auto& terminal = terminals[i];\n\n std::string name = std::string(\"tty\") + std::to_string(terminal.id);\n\n devfs::register_device(\"\/dev\/\", name, devfs::device_type::CHAR_DEVICE, tty_driver, &terminal);\n }\n}\n\nvoid stdio::finalize() {\n for (size_t i = 0; i < _terminals_count; ++i){\n auto& terminal = terminals[i];\n\n auto* user_stack = new char[scheduler::user_stack_size];\n auto* kernel_stack = new char[scheduler::kernel_stack_size];\n\n auto& input_process = scheduler::create_kernel_task_args(\"tty_input\", user_stack, kernel_stack, &input_thread, &terminal);\n input_process.ppid = 1;\n input_process.priority = scheduler::DEFAULT_PRIORITY;\n\n scheduler::queue_system_process(input_process.pid);\n\n terminal.input_thread_pid = input_process.pid;\n\n \/\/ Save the initial image of the terminal\n terminal.get_console().init();\n terminal.get_console().save();\n }\n}\n\nsize_t stdio::terminals_count() {\n return _terminals_count;\n}\n\nstdio::virtual_terminal& stdio::get_active_terminal() {\n return terminals[active_terminal];\n}\n\nstdio::virtual_terminal& stdio::get_terminal(size_t id) {\n thor_assert(id < _terminals_count, \"Out of bound tty\");\n\n return terminals[id];\n}\n\nvoid stdio::switch_terminal(size_t id) {\n if (active_terminal != id) {\n logging::logf(logging::log_level::TRACE, \"stdio: Switch activate virtual terminal %u\\n\", id);\n\n \/\/ Effectively switch the terminal\n terminals[active_terminal].set_active(false);\n terminals[id].set_active(true);\n\n active_terminal = id;\n }\n}\n<|endoftext|>"} {"text":"[REF] Simpler symbol_set::enough_terminals method<|endoftext|>"} {"text":"\/\/ @(#)root\/base:$Name: $:$Id: TStorage.cxx,v 1.5 2000\/09\/14 17:41:44 rdm Exp $\n\/\/ Author: Fons Rademakers 29\/07\/95\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TStorage \/\/\n\/\/ \/\/\n\/\/ Storage manager. The storage manager works best in conjunction with \/\/\n\/\/ the custom ROOT new and delete operators defined in the file \/\/\n\/\/ NewDelete.cxx (libNew.so). Only when using the custom allocation \/\/\n\/\/ operators will memory usage statistics be gathered using the \/\/\n\/\/ TStorage EnterStat(), RemoveStat(), etc. functions. \/\/\n\/\/ Memory checking is by default enabled (when using libNew.so) and \/\/\n\/\/ usage statistics is gathered. Using the resource (in .rootrc): \/\/\n\/\/ Root.MemStat one can toggle statistics gathering on or off. More \/\/\n\/\/ specifically on can trap the allocation of a block of memory of a \/\/\n\/\/ certain size. This can be specified using the resource: \/\/\n\/\/ Root.MemStat.size, using the resource Root.MemStat.cnt one can \/\/\n\/\/ specify after how many allocations of this size the trap should \/\/\n\/\/ occur. \/\/\n\/\/ Set the compile option R__NOSTATS to de-activate all memory checking \/\/\n\/\/ and statistics gathering in the system. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \n\n#include \"TObjectTable.h\"\n#include \"TError.h\"\n#include \"TMath.h\"\n#include \"TString.h\"\n\n#if !defined(R__NOSTATS)\n# define MEM_DEBUG\n# define MEM_STAT\n# define MEM_CHECKOBJECTPOINTERS\n#endif\n\n#if defined(MEM_STAT) && !defined(MEM_DEBUG)\n# define MEM_DEBUG\n#endif\n\n#ifdef MEM_DEBUG\n# ifdef R__B64\n# define storage_size(p) ((size_t)(((size_t*)p)[-1]))\n# else\n# define storage_size(p) ((size_t)(((int*)p)[-2]))\n# endif\n#else\n# define storage_size(p) ((size_t)0)\n#endif\n\n#ifndef NOCINT\n#define G__PVOID (-1)\n#ifndef WIN32\nextern long G__globalvarpointer;\n#else\n#include \"G__ci.h\"\n#endif\n#endif\n\nULong_t TStorage::fgHeapBegin = (ULong_t)-1L;\nULong_t TStorage::fgHeapEnd;\nsize_t TStorage::fgMaxBlockSize;\nFreeHookFun_t TStorage::fgFreeHook;\nvoid *TStorage::fgFreeHookData;\nReAllocFun_t TStorage::fgReAllocHook;\nReAllocCFun_t TStorage::fgReAllocCHook;\nBool_t TStorage::fgHasCustomNewDelete;\n\n\nClassImp(TStorage)\n\n\/\/------------------------------------------------------------------------------\n\nstatic const char *spaceErr = \"storage exhausted\";\n\nconst size_t kObjMaxSize = 10024;\n\nstatic Bool_t memStatistics;\nstatic Int_t allocated[kObjMaxSize], freed[kObjMaxSize];\nstatic Int_t allocatedTotal, freedTotal;\nstatic void **traceArray = 0;\nstatic Int_t traceCapacity = 10, traceIndex = 0, memSize = -1, memIndex = -1;\n\n\n\/\/______________________________________________________________________________\nvoid TStorage::EnterStat(size_t size, void *p)\n{\n \/\/ Register a memory allocation operation. If desired one can trap an\n \/\/ allocation of a certain size in case one tries to find a memory\n \/\/ leak of that particular size. This function is only called via\n \/\/ the ROOT custom new operators.\n\n TStorage::SetMaxBlockSize(TMath::Max(TStorage::GetMaxBlockSize(), size));\n\n if (!memStatistics) return;\n\n if ((Int_t)size == memSize) {\n if (traceIndex == memIndex)\n Fatal(\"EnterStat\", \"trapped allocation %d\", memIndex);\n\n if (!traceArray) traceArray = (void**) malloc(sizeof(void*)*traceCapacity);\n\n if (traceIndex >= traceCapacity) {\n traceCapacity = traceCapacity*2;\n traceArray = (void**) realloc(traceArray, sizeof(void*)*traceCapacity);\n }\n traceArray[traceIndex++] = p;\n }\n if (size >= kObjMaxSize)\n allocated[kObjMaxSize-1]++;\n else\n allocated[size]++;\n allocatedTotal += size;\n}\n\n\/\/______________________________________________________________________________\nvoid TStorage::RemoveStat(void *vp)\n{\n \/\/ Register a memory free operation. This function is only called via\n \/\/ the custom ROOT delete operator.\n\n if (!memStatistics) return;\n\n size_t size = storage_size(vp);\n if ((Int_t)size == memSize) {\n for (int i = 0; i < traceIndex; i++)\n if (traceArray[i] == vp) {\n traceArray[i] = 0;\n break;\n }\n }\n if (size >= kObjMaxSize)\n freed[kObjMaxSize-1]++;\n else\n freed[size]++;\n freedTotal += size;\n}\n\n\/\/______________________________________________________________________________\nvoid *TStorage::ReAlloc(void *ovp, size_t size)\n{\n \/\/ Reallocate (i.e. resize) block of memory.\n\n if (fgReAllocHook && fgHasCustomNewDelete)\n return (*fgReAllocHook)(ovp, size);\n\n static const char *where = \"TStorage::ReAlloc\";\n\n void *vp;\n if (ovp == 0) {\n vp = ::operator new(size);\n if (vp == 0)\n Fatal(where, spaceErr);\n return vp;\n }\n\n vp = ::operator new(size);\n if (vp == 0)\n Fatal(where, spaceErr);\n memmove(vp, ovp, size);\n ::operator delete(ovp);\n return vp;\n}\n\n\/\/______________________________________________________________________________\nvoid *TStorage::ReAlloc(void *ovp, size_t size, size_t oldsize)\n{\n \/\/ Reallocate (i.e. resize) block of memory. Checks if current size is\n \/\/ equal to oldsize. If not memory was overwritten.\n\n if (fgReAllocCHook && fgHasCustomNewDelete)\n return (*fgReAllocCHook)(ovp, size, oldsize);\n\n static const char *where = \"TStorage::ReAlloc\";\n\n void *vp;\n if (ovp == 0) {\n vp = ::operator new(size);\n if (vp == 0)\n Fatal(where, spaceErr);\n return vp;\n }\n if (oldsize == size)\n return ovp;\n\n vp = ::operator new(size);\n if (vp == 0)\n Fatal(where, spaceErr);\n if (size > oldsize) {\n memcpy(vp, ovp, oldsize);\n memset((char*)vp+oldsize, 0, size-oldsize);\n } else\n memcpy(vp, ovp, size);\n ::operator delete(ovp);\n return vp;\n}\n\n\/\/______________________________________________________________________________\nvoid *TStorage::ObjectAlloc(size_t sz)\n{\n \/\/ Used to allocate a TObject on the heap (via TObject::operator new()).\n \/\/ Directly after this routine one can call (in the TObject ctor)\n \/\/ TStorage::IsOnHeap() to find out if the just created object is on\n \/\/ the heap.\n\n ULong_t space;\n\n#ifndef NOCINT\n \/\/ to handle new with placement called via CINT\n#ifndef WIN32\n if (G__globalvarpointer != G__PVOID) {\n space = G__globalvarpointer;\n G__globalvarpointer = G__PVOID;\n } else\n#else\n space = G__getgvp();\n if ((long)space != G__PVOID) {\n G__setgvp(G__PVOID);\n } else\n#endif\n#endif\n space = (ULong_t) ::operator new(sz);\n AddToHeap(space, space+sz);\n return (void*) space;\n}\n\n\/\/______________________________________________________________________________\nvoid *TStorage::ObjectAlloc(size_t , void *vp)\n{\n \/\/ Used to allocate a TObject on the heap (via TObject::operator new(size_t,void*))\n \/\/ in position vp. vp is already allocated (maybe on heap, maybe on\n \/\/ stack) so just return.\n\n return vp;\n}\n\n\/\/______________________________________________________________________________\nvoid TStorage::ObjectDealloc(void *vp)\n{\n \/\/ Used to deallocate a TObject on the heap (via TObject::operator delete()).\n\n#ifndef NOCINT\n \/\/ to handle delete with placement called via CINT\n#ifndef WIN32\n if ((long)vp == G__globalvarpointer && G__globalvarpointer != G__PVOID)\n return;\n#else\n long gvp = G__getgvp();\n if ((long)vp == gvp && gvp != G__PVOID)\n return;\n#endif\n#endif\n ::operator delete(vp);\n}\n\n\/\/______________________________________________________________________________\nvoid TStorage::ObjectDealloc(void *vp, void *ptr)\n{\n \/\/ Used to deallocate a TObject on the heap (via TObject::operator delete(void*,void*)).\n\n if (vp && ptr) { }\n}\n\n\/\/______________________________________________________________________________\nvoid TStorage::SetFreeHook(FreeHookFun_t fh, void *data)\n{\n \/\/ Set a free handler.\n\n fgFreeHook = fh;\n fgFreeHookData = data;\n}\n\n\/\/______________________________________________________________________________\nvoid TStorage::SetReAllocHooks(ReAllocFun_t rh1, ReAllocCFun_t rh2)\n{\n \/\/ Set a custom ReAlloc handlers. This function is typically\n \/\/ called via a static object in the ROOT libNew.so shared library.\n\n fgReAllocHook = rh1;\n fgReAllocCHook = rh2;\n}\n\n\/\/______________________________________________________________________________\nvoid TStorage::PrintStatistics()\n{\n \/\/ Print memory usage statistics.\n\n#if defined(MEM_DEBUG) && defined(MEM_STAT)\n\n if (!memStatistics || !HasCustomNewDelete())\n return;\n\n \/\/Printf(\"\");\n Printf(\"Heap statistics\");\n Printf(\"%12s%12s%12s%12s\", \"size\", \"alloc\", \"free\", \"diff\");\n Printf(\"================================================\");\n\n int i;\n for (i = 0; i < (int)kObjMaxSize; i++)\n if (allocated[i] != freed[i])\n \/\/if (allocated[i])\n Printf(\"%12d%12d%12d%12d\", i, allocated[i], freed[i],\n allocated[i]-freed[i]);\n\n if (allocatedTotal != freedTotal) {\n Printf(\"------------------------------------------------\");\n Printf(\"Total: %12d%12d%12d\", allocatedTotal, freedTotal,\n allocatedTotal-freedTotal);\n }\n\n if (memSize != -1) {\n Printf(\"------------------------------------------------\");\n for (i= 0; i < traceIndex; i++)\n if (traceArray[i])\n Printf(\"block %d of size %d not freed\", i, memSize);\n }\n Printf(\"================================================\");\n Printf(\"\");\n#endif\n}\n\n\/\/______________________________________________________________________________\nvoid TStorage::EnableStatistics(int size, int ix)\n{\n \/\/ Enable memory usage statistics gathering. Size is the size of the memory\n \/\/ block that should be trapped and ix is after how many such allocations\n \/\/ the trap should happen.\n\n#ifdef MEM_STAT\n memSize = size;\n memIndex = ix;\n memStatistics = kTRUE;\n#else\n int idum = size; int iidum = ix;\n#endif\n}\n\n\/\/______________________________________________________________________________\nULong_t TStorage::GetHeapBegin()\n{\n return fgHeapBegin;\n}\n\n\/\/______________________________________________________________________________\nULong_t TStorage::GetHeapEnd()\n{\n return fgHeapEnd;\n}\n\n\/\/______________________________________________________________________________\nvoid *TStorage::GetFreeHookData()\n{\n return fgFreeHookData;\n}\n\n\/\/______________________________________________________________________________\nBool_t TStorage::HasCustomNewDelete()\n{\n return fgHasCustomNewDelete;\n}\n\n\/\/______________________________________________________________________________\nvoid TStorage::SetCustomNewDelete()\n{\n fgHasCustomNewDelete = kTRUE;\n}\n\n#ifdef WIN32\n\n\/\/______________________________________________________________________________\nvoid TStorage::AddToHeap(ULong_t begin, ULong_t end)\n{\n if (begin < fgHeapBegin) fgHeapBegin = begin;\n if (end > fgHeapEnd) fgHeapEnd = end;\n}\n\n\/\/______________________________________________________________________________\nBool_t TStorage::IsOnHeap(void *p)\n{\n return (ULong_t)p >= fgHeapBegin && (ULong_t)p < fgHeapEnd;\n}\n\n\/\/______________________________________________________________________________\nsize_t TStorage::GetMaxBlockSize()\n{\n return fgMaxBlockSize;\n}\n\n\/\/______________________________________________________________________________\nvoid TStorage::SetMaxBlockSize(size_t size)\n{\n fgMaxBlockSize = size;\n}\n\n\/\/______________________________________________________________________________\nFreeHookFun_t TStorage::GetFreeHook()\n{\n return fgFreeHook;\n}\n\n#endif\nadd case for new memory checker.\/\/ @(#)root\/base:$Name: $:$Id: TStorage.cxx,v 1.6 2000\/10\/13 18:57:45 rdm Exp $\n\/\/ Author: Fons Rademakers 29\/07\/95\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TStorage \/\/\n\/\/ \/\/\n\/\/ Storage manager. The storage manager works best in conjunction with \/\/\n\/\/ the custom ROOT new and delete operators defined in the file \/\/\n\/\/ NewDelete.cxx (libNew.so). Only when using the custom allocation \/\/\n\/\/ operators will memory usage statistics be gathered using the \/\/\n\/\/ TStorage EnterStat(), RemoveStat(), etc. functions. \/\/\n\/\/ Memory checking is by default enabled (when using libNew.so) and \/\/\n\/\/ usage statistics is gathered. Using the resource (in .rootrc): \/\/\n\/\/ Root.MemStat one can toggle statistics gathering on or off. More \/\/\n\/\/ specifically on can trap the allocation of a block of memory of a \/\/\n\/\/ certain size. This can be specified using the resource: \/\/\n\/\/ Root.MemStat.size, using the resource Root.MemStat.cnt one can \/\/\n\/\/ specify after how many allocations of this size the trap should \/\/\n\/\/ occur. \/\/\n\/\/ Set the compile option R__NOSTATS to de-activate all memory checking \/\/\n\/\/ and statistics gathering in the system. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \n\n#include \"TROOT.h\"\n#include \"TObjectTable.h\"\n#include \"TError.h\"\n#include \"TMath.h\"\n#include \"TString.h\"\n\n#if !defined(R__NOSTATS)\n# define MEM_DEBUG\n# define MEM_STAT\n# define MEM_CHECKOBJECTPOINTERS\n#endif\n\n#if defined(MEM_STAT) && !defined(MEM_DEBUG)\n# define MEM_DEBUG\n#endif\n\n#ifdef MEM_DEBUG\n# ifdef R__B64\n# define storage_size(p) ((size_t)(((size_t*)p)[-1]))\n# else\n# define storage_size(p) ((size_t)(((int*)p)[-2]))\n# endif\n#else\n# define storage_size(p) ((size_t)0)\n#endif\n\n#ifndef NOCINT\n#define G__PVOID (-1)\n#ifndef WIN32\nextern long G__globalvarpointer;\n#else\n#include \"G__ci.h\"\n#endif\n#endif\n\nULong_t TStorage::fgHeapBegin = (ULong_t)-1L;\nULong_t TStorage::fgHeapEnd;\nsize_t TStorage::fgMaxBlockSize;\nFreeHookFun_t TStorage::fgFreeHook;\nvoid *TStorage::fgFreeHookData;\nReAllocFun_t TStorage::fgReAllocHook;\nReAllocCFun_t TStorage::fgReAllocCHook;\nBool_t TStorage::fgHasCustomNewDelete;\n\n\nClassImp(TStorage)\n\n\/\/------------------------------------------------------------------------------\n\nstatic const char *spaceErr = \"storage exhausted\";\n\nconst size_t kObjMaxSize = 10024;\n\nstatic Bool_t memStatistics;\nstatic Int_t allocated[kObjMaxSize], freed[kObjMaxSize];\nstatic Int_t allocatedTotal, freedTotal;\nstatic void **traceArray = 0;\nstatic Int_t traceCapacity = 10, traceIndex = 0, memSize = -1, memIndex = -1;\n\n\n\/\/______________________________________________________________________________\nvoid TStorage::EnterStat(size_t size, void *p)\n{\n \/\/ Register a memory allocation operation. If desired one can trap an\n \/\/ allocation of a certain size in case one tries to find a memory\n \/\/ leak of that particular size. This function is only called via\n \/\/ the ROOT custom new operators.\n\n TStorage::SetMaxBlockSize(TMath::Max(TStorage::GetMaxBlockSize(), size));\n\n if (!memStatistics) return;\n\n if ((Int_t)size == memSize) {\n if (traceIndex == memIndex)\n Fatal(\"EnterStat\", \"trapped allocation %d\", memIndex);\n\n if (!traceArray) traceArray = (void**) malloc(sizeof(void*)*traceCapacity);\n\n if (traceIndex >= traceCapacity) {\n traceCapacity = traceCapacity*2;\n traceArray = (void**) realloc(traceArray, sizeof(void*)*traceCapacity);\n }\n traceArray[traceIndex++] = p;\n }\n if (size >= kObjMaxSize)\n allocated[kObjMaxSize-1]++;\n else\n allocated[size]++;\n allocatedTotal += size;\n}\n\n\/\/______________________________________________________________________________\nvoid TStorage::RemoveStat(void *vp)\n{\n \/\/ Register a memory free operation. This function is only called via\n \/\/ the custom ROOT delete operator.\n\n if (!memStatistics) return;\n\n size_t size = storage_size(vp);\n if ((Int_t)size == memSize) {\n for (int i = 0; i < traceIndex; i++)\n if (traceArray[i] == vp) {\n traceArray[i] = 0;\n break;\n }\n }\n if (size >= kObjMaxSize)\n freed[kObjMaxSize-1]++;\n else\n freed[size]++;\n freedTotal += size;\n}\n\n\/\/______________________________________________________________________________\nvoid *TStorage::ReAlloc(void *ovp, size_t size)\n{\n \/\/ Reallocate (i.e. resize) block of memory.\n\n if (fgReAllocHook && fgHasCustomNewDelete && !TROOT::MemCheck())\n return (*fgReAllocHook)(ovp, size);\n\n static const char *where = \"TStorage::ReAlloc\";\n\n void *vp;\n if (ovp == 0) {\n vp = ::operator new(size);\n if (vp == 0)\n Fatal(where, spaceErr);\n return vp;\n }\n\n vp = ::operator new(size);\n if (vp == 0)\n Fatal(where, spaceErr);\n memmove(vp, ovp, size);\n ::operator delete(ovp);\n return vp;\n}\n\n\/\/______________________________________________________________________________\nvoid *TStorage::ReAlloc(void *ovp, size_t size, size_t oldsize)\n{\n \/\/ Reallocate (i.e. resize) block of memory. Checks if current size is\n \/\/ equal to oldsize. If not memory was overwritten.\n\n if (fgReAllocCHook && fgHasCustomNewDelete && !TROOT::MemCheck())\n return (*fgReAllocCHook)(ovp, size, oldsize);\n\n static const char *where = \"TStorage::ReAlloc\";\n\n void *vp;\n if (ovp == 0) {\n vp = ::operator new(size);\n if (vp == 0)\n Fatal(where, spaceErr);\n return vp;\n }\n if (oldsize == size)\n return ovp;\n\n vp = ::operator new(size);\n if (vp == 0)\n Fatal(where, spaceErr);\n if (size > oldsize) {\n memcpy(vp, ovp, oldsize);\n memset((char*)vp+oldsize, 0, size-oldsize);\n } else\n memcpy(vp, ovp, size);\n ::operator delete(ovp);\n return vp;\n}\n\n\/\/______________________________________________________________________________\nvoid *TStorage::ObjectAlloc(size_t sz)\n{\n \/\/ Used to allocate a TObject on the heap (via TObject::operator new()).\n \/\/ Directly after this routine one can call (in the TObject ctor)\n \/\/ TStorage::IsOnHeap() to find out if the just created object is on\n \/\/ the heap.\n\n ULong_t space;\n\n#ifndef NOCINT\n \/\/ to handle new with placement called via CINT\n#ifndef WIN32\n if (G__globalvarpointer != G__PVOID) {\n space = G__globalvarpointer;\n G__globalvarpointer = G__PVOID;\n } else\n#else\n space = G__getgvp();\n if ((long)space != G__PVOID) {\n G__setgvp(G__PVOID);\n } else\n#endif\n#endif\n space = (ULong_t) ::operator new(sz);\n AddToHeap(space, space+sz);\n return (void*) space;\n}\n\n\/\/______________________________________________________________________________\nvoid *TStorage::ObjectAlloc(size_t , void *vp)\n{\n \/\/ Used to allocate a TObject on the heap (via TObject::operator new(size_t,void*))\n \/\/ in position vp. vp is already allocated (maybe on heap, maybe on\n \/\/ stack) so just return.\n\n return vp;\n}\n\n\/\/______________________________________________________________________________\nvoid TStorage::ObjectDealloc(void *vp)\n{\n \/\/ Used to deallocate a TObject on the heap (via TObject::operator delete()).\n\n#ifndef NOCINT\n \/\/ to handle delete with placement called via CINT\n#ifndef WIN32\n if ((long)vp == G__globalvarpointer && G__globalvarpointer != G__PVOID)\n return;\n#else\n long gvp = G__getgvp();\n if ((long)vp == gvp && gvp != G__PVOID)\n return;\n#endif\n#endif\n ::operator delete(vp);\n}\n\n\/\/______________________________________________________________________________\nvoid TStorage::ObjectDealloc(void *vp, void *ptr)\n{\n \/\/ Used to deallocate a TObject on the heap (via TObject::operator delete(void*,void*)).\n\n if (vp && ptr) { }\n}\n\n\/\/______________________________________________________________________________\nvoid TStorage::SetFreeHook(FreeHookFun_t fh, void *data)\n{\n \/\/ Set a free handler.\n\n fgFreeHook = fh;\n fgFreeHookData = data;\n}\n\n\/\/______________________________________________________________________________\nvoid TStorage::SetReAllocHooks(ReAllocFun_t rh1, ReAllocCFun_t rh2)\n{\n \/\/ Set a custom ReAlloc handlers. This function is typically\n \/\/ called via a static object in the ROOT libNew.so shared library.\n\n fgReAllocHook = rh1;\n fgReAllocCHook = rh2;\n}\n\n\/\/______________________________________________________________________________\nvoid TStorage::PrintStatistics()\n{\n \/\/ Print memory usage statistics.\n\n#if defined(MEM_DEBUG) && defined(MEM_STAT)\n\n if (!memStatistics || !HasCustomNewDelete())\n return;\n\n \/\/Printf(\"\");\n Printf(\"Heap statistics\");\n Printf(\"%12s%12s%12s%12s\", \"size\", \"alloc\", \"free\", \"diff\");\n Printf(\"================================================\");\n\n int i;\n for (i = 0; i < (int)kObjMaxSize; i++)\n if (allocated[i] != freed[i])\n \/\/if (allocated[i])\n Printf(\"%12d%12d%12d%12d\", i, allocated[i], freed[i],\n allocated[i]-freed[i]);\n\n if (allocatedTotal != freedTotal) {\n Printf(\"------------------------------------------------\");\n Printf(\"Total: %12d%12d%12d\", allocatedTotal, freedTotal,\n allocatedTotal-freedTotal);\n }\n\n if (memSize != -1) {\n Printf(\"------------------------------------------------\");\n for (i= 0; i < traceIndex; i++)\n if (traceArray[i])\n Printf(\"block %d of size %d not freed\", i, memSize);\n }\n Printf(\"================================================\");\n Printf(\"\");\n#endif\n}\n\n\/\/______________________________________________________________________________\nvoid TStorage::EnableStatistics(int size, int ix)\n{\n \/\/ Enable memory usage statistics gathering. Size is the size of the memory\n \/\/ block that should be trapped and ix is after how many such allocations\n \/\/ the trap should happen.\n\n#ifdef MEM_STAT\n memSize = size;\n memIndex = ix;\n memStatistics = kTRUE;\n#else\n int idum = size; int iidum = ix;\n#endif\n}\n\n\/\/______________________________________________________________________________\nULong_t TStorage::GetHeapBegin()\n{\n return fgHeapBegin;\n}\n\n\/\/______________________________________________________________________________\nULong_t TStorage::GetHeapEnd()\n{\n return fgHeapEnd;\n}\n\n\/\/______________________________________________________________________________\nvoid *TStorage::GetFreeHookData()\n{\n return fgFreeHookData;\n}\n\n\/\/______________________________________________________________________________\nBool_t TStorage::HasCustomNewDelete()\n{\n return fgHasCustomNewDelete;\n}\n\n\/\/______________________________________________________________________________\nvoid TStorage::SetCustomNewDelete()\n{\n fgHasCustomNewDelete = kTRUE;\n}\n\n#ifdef WIN32\n\n\/\/______________________________________________________________________________\nvoid TStorage::AddToHeap(ULong_t begin, ULong_t end)\n{\n if (begin < fgHeapBegin) fgHeapBegin = begin;\n if (end > fgHeapEnd) fgHeapEnd = end;\n}\n\n\/\/______________________________________________________________________________\nBool_t TStorage::IsOnHeap(void *p)\n{\n return (ULong_t)p >= fgHeapBegin && (ULong_t)p < fgHeapEnd;\n}\n\n\/\/______________________________________________________________________________\nsize_t TStorage::GetMaxBlockSize()\n{\n return fgMaxBlockSize;\n}\n\n\/\/______________________________________________________________________________\nvoid TStorage::SetMaxBlockSize(size_t size)\n{\n fgMaxBlockSize = size;\n}\n\n\/\/______________________________________________________________________________\nFreeHookFun_t TStorage::GetFreeHook()\n{\n return fgFreeHook;\n}\n\n#endif\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\nnamespace test {\n\nusing ::testing::_;\nusing ::testing::Return;\nusing ::testing::AtLeast;\n\nstruct ChannelTestSuite : public ::testing::Test{\n using Events = Transformer::Events;\n using EventTypes = Transformer::EventTypes;\n using TransPtr = Transformation::TransPtr;\n\n struct TestTransformer : public SimpleTransformer {\n TestTransformer() : SimpleTransformer(EventType(), EventType()) {}\n MOCK_CONST_METHOD1(check, bool(const MetaEvent&));\n MOCK_CONST_METHOD1(execute, MetaEvent(const MetaEvent&));\n MOCK_CONST_METHOD1(print, void(std::ostream&));\n };\n\n struct TestChannel : public Channel {\n TestChannel() : Channel(TransPtr(new TestTransformer())) { }\n\n MOCK_CONST_METHOD1(publishEvent, void(const MetaEvent& e));\n void handleEvent() { Channel::handleEvent(MetaEvent()); }\n Transformer* trans() { return mTrans.get(); }\n } c;\n};\n\nTEST_F(ChannelTestSuite, failedSingleTransformTest) {\n ASSERT_TRUE(c.trans());\n\tEXPECT_CALL(dynamic_cast(*c.trans()), execute(_))\n\t\t.Times(0);\n EXPECT_CALL(dynamic_cast(*c.trans()), check(_))\n .Times(AtLeast(1))\n .WillRepeatedly(Return(false));\n EXPECT_CALL(c, publishEvent(_))\n .Times(0);\n c.handleEvent();\n}\n\nTEST_F(ChannelTestSuite, succededTransformTest) {\n\tMetaEvent e;\n\tMetaAttribute a;\n\te.add(a);\n ASSERT_TRUE(c.trans());\n\tEXPECT_CALL(dynamic_cast(*c.trans()), execute(_))\n\t\t.Times(1)\n\t\t.WillRepeatedly(Return(e));\n EXPECT_CALL(dynamic_cast(*c.trans()), check(_))\n .Times(AtLeast(1))\n .WillRepeatedly(Return(true));\n EXPECT_CALL(c, publishEvent(_))\n .Times(1);\n c.handleEvent();\n}\n\n}\nUnitTest: fix channel test to fulfil new checks#include \n#include \n#include \n#include \n\nnamespace test {\n\nusing ::testing::_;\nusing ::testing::Return;\nusing ::testing::AtLeast;\n\nstruct ChannelTestSuite : public ::testing::Test{\n using Events = Transformer::Events;\n using EventTypes = Transformer::EventTypes;\n using TransPtr = Transformation::TransPtr;\n\n struct TestTransformer : public SimpleTransformer {\n TestTransformer() : SimpleTransformer(EventType(), EventType()) {}\n MOCK_CONST_METHOD1(check, bool(const MetaEvent&));\n MOCK_CONST_METHOD1(execute, MetaEvent(const MetaEvent&));\n MOCK_CONST_METHOD1(print, void(std::ostream&));\n };\n\n struct TestChannel : public Channel {\n TestChannel() : Channel(TransPtr(new TestTransformer())) { }\n\n MOCK_CONST_METHOD1(publishEvent, void(const MetaEvent& e));\n MOCK_CONST_METHOD2(error, void(Errors, const MetaEvent&));\n void handleEvent() { Channel::handleEvent(MetaEvent()); }\n Transformer* trans() { return mTrans.get(); }\n } c;\n};\n\nTEST_F(ChannelTestSuite, failedSingleTransformTest) {\n ASSERT_TRUE(c.trans());\n\tEXPECT_CALL(c, error(_,_)).Times(0);\n\tEXPECT_CALL(dynamic_cast(*c.trans()), execute(_))\n\t\t.Times(0);\n EXPECT_CALL(dynamic_cast(*c.trans()), check(_))\n .Times(AtLeast(1))\n .WillRepeatedly(Return(false));\n EXPECT_CALL(c, publishEvent(_))\n .Times(0);\n c.handleEvent();\n}\n\nTEST_F(ChannelTestSuite, succededTransformTest) {\n\tMetaEvent e((EventType)BaseEvent<>());\n ASSERT_TRUE(c.trans());\n\tEXPECT_CALL(c, error(_,_)).Times(0);\n\tEXPECT_CALL(dynamic_cast(*c.trans()), execute(_))\n\t\t.Times(1)\n\t\t.WillRepeatedly(Return(e));\n EXPECT_CALL(dynamic_cast(*c.trans()), check(_))\n .Times(AtLeast(1))\n .WillRepeatedly(Return(true));\n EXPECT_CALL(c, publishEvent(_))\n .Times(1);\n c.handleEvent();\n}\n\n}\n<|endoftext|>"} {"text":"Fix for osx Lanzcos scale test.<|endoftext|>"} {"text":"#include \n\n#include \"siteeditor.h\"\nusing namespace AhoViewer;\nusing namespace AhoViewer::Booru;\n\n#include \"settings.h\"\n\n\/\/ Fixes issue with winnt.h\n#ifdef DELETE\n#undef DELETE\n#endif\n\nSiteEditor::SiteEditor(BaseObjectType *cobj, const Glib::RefPtr &bldr)\n : Gtk::TreeView(cobj),\n m_Model(Gtk::ListStore::create(m_Columns)),\n m_NameColumn(Gtk::manage(new Gtk::TreeView::Column(_(\"Name\"), m_Columns.name))),\n m_UrlColumn(Gtk::manage(new Gtk::TreeView::Column(_(\"Url\"), m_Columns.url))),\n m_Sites(Settings.get_sites()),\n m_ErrorPixbuf(Gtk::Invisible().render_icon(Gtk::Stock::DELETE, Gtk::ICON_SIZE_MENU)),\n m_SiteCheckEdit(false),\n m_SiteCheckEditSuccess(false)\n{\n bldr->get_widget(\"BooruRegisterLinkButton\", m_RegisterButton);\n bldr->get_widget(\"BooruUsernameEntry\", m_UsernameEntry);\n bldr->get_widget(\"BooruPasswordEntry\", m_PasswordEntry);\n bldr->get_widget(\"BooruPasswordLabel\", m_PasswordLabel);\n\n m_SignalSiteChecked.connect(sigc::mem_fun(*this, &SiteEditor::on_site_checked));\n\n for (const std::shared_ptr &s : m_Sites)\n {\n Gtk::TreeIter iter = m_Model->append();\n iter->set_value(m_Columns.icon, s->get_icon_pixbuf());\n s->signal_icon_downloaded().connect([ this, iter, s ]()\n { iter->set_value(m_Columns.icon, s->get_icon_pixbuf()); });\n iter->set_value(m_Columns.name, s->get_name());\n iter->set_value(m_Columns.url, s->get_url());\n iter->set_value(m_Columns.site, s);\n }\n\n CellRendererIcon *iconRenderer = Gtk::manage(new CellRendererIcon(this));\n iconRenderer->property_xpad() = 2;\n iconRenderer->property_ypad() = 2;\n append_column(\"\", *iconRenderer);\n get_column(0)->add_attribute(iconRenderer->property_loading(), m_Columns.loading);\n get_column(0)->add_attribute(iconRenderer->property_pulse(), m_Columns.pulse);\n get_column(0)->add_attribute(iconRenderer->property_pixbuf(), m_Columns.icon);\n\n Gtk::CellRendererText *textRenderer = nullptr;\n\n textRenderer = static_cast(m_NameColumn->get_first_cell());\n textRenderer->property_editable() = true;\n textRenderer->signal_edited().connect(sigc::mem_fun(*this, &SiteEditor::on_name_edited));\n append_column(*m_NameColumn);\n\n textRenderer = static_cast(m_UrlColumn->get_first_cell());\n textRenderer->property_editable() = true;\n textRenderer->signal_edited().connect(sigc::mem_fun(*this, &SiteEditor::on_url_edited));\n append_column(*m_UrlColumn);\n\n set_model(m_Model);\n get_selection()->select(m_Model->get_iter(\"0\"));\n\n Gtk::ToolButton *toolButton = nullptr;\n bldr->get_widget(\"DeleteSiteButton\", toolButton);\n toolButton->signal_clicked().connect(sigc::mem_fun(*this, &SiteEditor::delete_site));\n\n bldr->get_widget(\"AddSiteButton\", toolButton);\n toolButton->signal_clicked().connect(sigc::mem_fun(*this, &SiteEditor::add_row));\n\n m_UsernameConn = m_UsernameEntry->signal_changed().connect(\n sigc::mem_fun(*this, &SiteEditor::on_username_edited));\n m_PasswordConn = m_PasswordEntry->signal_changed().connect(\n sigc::mem_fun(*this, &SiteEditor::on_password_edited));\n\n#ifdef HAVE_LIBSECRET\n \/\/ Make sure the initially selected site's password gets set in the entry once it's loaded\n const std::shared_ptr &s = get_selection()->get_selected()->get_value(m_Columns.site);\n if (s)\n s->signal_password_lookup().connect([ this, s ]() { m_PasswordEntry->set_text(s->get_password()); });\n\n m_PasswordEntry->set_visibility(false);\n#endif \/\/ HAVE_LIBSECRET\n\n \/\/ Set initial values for entries and linkbutton\n on_cursor_changed();\n}\n\nSiteEditor::~SiteEditor()\n{\n if (m_SiteCheckThread.joinable())\n m_SiteCheckThread.join();\n}\n\nbool SiteEditor::on_key_release_event(GdkEventKey *e)\n{\n if (e->keyval == GDK_Return || e->keyval == GDK_ISO_Enter\n || e->keyval == GDK_KP_Enter || e->keyval == GDK_Tab)\n {\n Gtk::TreeIter iter = get_selection()->get_selected();\n Gtk::TreePath p(iter);\n\n if (iter->get_value(m_Columns.url).empty())\n set_cursor(p, *m_UrlColumn, true);\n else if (iter->get_value(m_Columns.name).empty())\n set_cursor(p, *m_NameColumn, true);\n }\n\n return false;\n}\n\nvoid SiteEditor::on_cursor_changed()\n{\n Gtk::TreeView::on_cursor_changed();\n\n const std::shared_ptr &s = get_selection()->get_selected()->get_value(m_Columns.site);\n\n m_UsernameConn.block();\n m_PasswordConn.block();\n\n if (s)\n {\n m_RegisterButton->set_label(_(\"Register account on \") + s->get_name());\n m_RegisterButton->set_uri(s->get_register_uri());\n\n m_UsernameEntry->set_text(s->get_username());\n m_PasswordEntry->set_text(s->get_password());\n }\n else\n {\n m_RegisterButton->set_label(_(\"Register account\"));\n\n m_UsernameEntry->set_text(\"\");\n m_PasswordEntry->set_text(\"\");\n }\n\n m_UsernameConn.unblock();\n m_PasswordConn.unblock();\n\n m_RegisterButton->set_sensitive(!!s);\n m_UsernameEntry->set_sensitive(!!s);\n m_PasswordEntry->set_sensitive(!!s);\n\n if (!s || s->get_type() == Site::Type::GELBOORU)\n m_PasswordLabel->set_text(_(\"Password:\"));\n else\n m_PasswordLabel->set_text(_(\"API Key:\"));\n}\n\nvoid SiteEditor::add_row()\n{\n Gtk::TreePath path(m_Model->append());\n set_cursor(path, *m_NameColumn, true);\n scroll_to_row(path);\n}\n\nvoid SiteEditor::delete_site()\n{\n Gtk::TreeIter o = get_selection()->get_selected();\n\n if (o)\n {\n m_Sites.erase(std::remove(m_Sites.begin(), m_Sites.end(), o->get_value(m_Columns.site)), m_Sites.end());\n m_SignalEdited();\n\n Gtk::TreeIter n = m_Model->erase(o);\n if (m_Model->children().size())\n {\n get_selection()->select(n ? n : --n);\n on_cursor_changed();\n }\n }\n}\n\nvoid SiteEditor::on_name_edited(const std::string &p, const std::string &text)\n{\n Gtk::TreePath path(p);\n Gtk::TreeIter iter = m_Model->get_iter(path);\n std::string name = text;\n\n \/\/ make sure the site name is unique\n for (size_t i = 1; !is_name_unique(iter, name); ++i)\n name = text + std::to_string(i);\n\n iter->set_value(m_Columns.name, name);\n\n if (!iter->get_value(m_Columns.url).empty())\n add_edit_site(iter);\n}\n\nvoid SiteEditor::on_url_edited(const std::string &p, const std::string &text)\n{\n Gtk::TreePath path(p);\n Gtk::TreeIter iter = m_Model->get_iter(path);\n std::string url = text;\n\n if (url.back() == '\/')\n url = text.substr(0, text.size() - 1);\n\n iter->set_value(m_Columns.url, url);\n add_edit_site(iter);\n}\n\nbool SiteEditor::is_name_unique(const Gtk::TreeIter &iter, const std::string &name) const\n{\n for (const Gtk::TreeIter &i : m_Model->children())\n if (i->get_value(m_Columns.name) == name && iter != i)\n return false;\n\n return true;\n}\n\nvoid SiteEditor::add_edit_site(const Gtk::TreeIter &iter)\n{\n std::string name = iter->get_value(m_Columns.name),\n url(iter->get_value(m_Columns.url));\n\n if (name.empty() || url.empty())\n {\n iter->set_value(m_Columns.icon, m_ErrorPixbuf);\n return;\n }\n\n if (m_SiteCheckThread.joinable())\n m_SiteCheckThread.join();\n\n m_SiteCheckIter = iter;\n\n std::vector>::iterator i =\n std::find(m_Sites.begin(), m_Sites.end(), iter->get_value(m_Columns.site));\n std::shared_ptr site = i != m_Sites.end() ? *i : nullptr;\n\n \/\/ editting\n if (site)\n {\n if (name == site->get_name() && url == site->get_url())\n {\n if (iter->get_value(m_Columns.icon) == m_ErrorPixbuf)\n iter->set_value(m_Columns.icon, site->get_icon_pixbuf());\n\n return;\n }\n\n m_SiteCheckEdit = true;\n m_SiteCheckSite = site;\n m_SiteCheckIter->set_value(m_Columns.loading, true);\n m_SiteCheckThread = std::thread([ this, name, url ]()\n {\n m_SiteCheckSite->set_name(name);\n m_SiteCheckEditSuccess = m_SiteCheckSite->set_url(url);\n\n if (m_SiteCheckEditSuccess)\n update_edited_site_icon();\n\n m_SignalSiteChecked();\n });\n }\n else\n {\n m_SiteCheckEdit = false;\n m_SiteCheckIter->set_value(m_Columns.loading, true);\n m_SiteCheckThread = std::thread([ this, name, url ]()\n {\n m_SiteCheckSite = Site::create(name, url);\n\n if (m_SiteCheckSite)\n update_edited_site_icon();\n\n m_SignalSiteChecked();\n });\n }\n}\n\nvoid SiteEditor::update_edited_site_icon()\n{\n m_SiteCheckIter->set_value(m_Columns.icon, m_SiteCheckSite->get_icon_pixbuf(true));\n m_SiteCheckIter->set_value(m_Columns.loading, false);\n}\n\nvoid SiteEditor::on_site_checked()\n{\n if ((m_SiteCheckEdit && !m_SiteCheckEditSuccess) || (!m_SiteCheckEdit && !m_SiteCheckSite))\n {\n m_SiteCheckIter->set_value(m_Columns.icon, m_ErrorPixbuf);\n m_SiteCheckIter->set_value(m_Columns.loading, false);\n }\n else if (m_SiteCheckSite && !m_SiteCheckEdit)\n {\n m_Sites.push_back(m_SiteCheckSite);\n m_SiteCheckIter->set_value(m_Columns.site, m_SiteCheckSite);\n on_cursor_changed();\n }\n\n if (m_SiteCheckEdit || m_SiteCheckSite)\n m_SignalEdited();\n\n if (m_SiteCheckThread.joinable())\n m_SiteCheckThread.join();\n}\n\nvoid SiteEditor::on_username_edited()\n{\n const std::shared_ptr &s = get_selection()->get_selected()->get_value(m_Columns.site);\n if (s) s->set_username(m_UsernameEntry->get_text());\n}\n\nvoid SiteEditor::on_password_edited()\n{\n const std::shared_ptr &s = get_selection()->get_selected()->get_value(m_Columns.site);\n if (s) s->set_password(m_PasswordEntry->get_text());\n}\nsiteeditor: Handle deleting all sites better#include \n\n#include \"siteeditor.h\"\nusing namespace AhoViewer;\nusing namespace AhoViewer::Booru;\n\n#include \"settings.h\"\n\n\/\/ Fixes issue with winnt.h\n#ifdef DELETE\n#undef DELETE\n#endif\n\nSiteEditor::SiteEditor(BaseObjectType *cobj, const Glib::RefPtr &bldr)\n : Gtk::TreeView(cobj),\n m_Model(Gtk::ListStore::create(m_Columns)),\n m_NameColumn(Gtk::manage(new Gtk::TreeView::Column(_(\"Name\"), m_Columns.name))),\n m_UrlColumn(Gtk::manage(new Gtk::TreeView::Column(_(\"Url\"), m_Columns.url))),\n m_Sites(Settings.get_sites()),\n m_ErrorPixbuf(Gtk::Invisible().render_icon(Gtk::Stock::DELETE, Gtk::ICON_SIZE_MENU)),\n m_SiteCheckEdit(false),\n m_SiteCheckEditSuccess(false)\n{\n bldr->get_widget(\"BooruRegisterLinkButton\", m_RegisterButton);\n bldr->get_widget(\"BooruUsernameEntry\", m_UsernameEntry);\n bldr->get_widget(\"BooruPasswordEntry\", m_PasswordEntry);\n bldr->get_widget(\"BooruPasswordLabel\", m_PasswordLabel);\n\n m_SignalSiteChecked.connect(sigc::mem_fun(*this, &SiteEditor::on_site_checked));\n\n for (const std::shared_ptr &s : m_Sites)\n {\n Gtk::TreeIter iter = m_Model->append();\n iter->set_value(m_Columns.icon, s->get_icon_pixbuf());\n s->signal_icon_downloaded().connect([ this, iter, s ]()\n { iter->set_value(m_Columns.icon, s->get_icon_pixbuf()); });\n iter->set_value(m_Columns.name, s->get_name());\n iter->set_value(m_Columns.url, s->get_url());\n iter->set_value(m_Columns.site, s);\n }\n\n CellRendererIcon *iconRenderer = Gtk::manage(new CellRendererIcon(this));\n iconRenderer->property_xpad() = 2;\n iconRenderer->property_ypad() = 2;\n append_column(\"\", *iconRenderer);\n get_column(0)->add_attribute(iconRenderer->property_loading(), m_Columns.loading);\n get_column(0)->add_attribute(iconRenderer->property_pulse(), m_Columns.pulse);\n get_column(0)->add_attribute(iconRenderer->property_pixbuf(), m_Columns.icon);\n\n Gtk::CellRendererText *textRenderer = nullptr;\n\n textRenderer = static_cast(m_NameColumn->get_first_cell());\n textRenderer->property_editable() = true;\n textRenderer->signal_edited().connect(sigc::mem_fun(*this, &SiteEditor::on_name_edited));\n append_column(*m_NameColumn);\n\n textRenderer = static_cast(m_UrlColumn->get_first_cell());\n textRenderer->property_editable() = true;\n textRenderer->signal_edited().connect(sigc::mem_fun(*this, &SiteEditor::on_url_edited));\n append_column(*m_UrlColumn);\n\n set_model(m_Model);\n get_selection()->select(m_Model->get_iter(\"0\"));\n\n Gtk::ToolButton *toolButton = nullptr;\n bldr->get_widget(\"DeleteSiteButton\", toolButton);\n toolButton->signal_clicked().connect(sigc::mem_fun(*this, &SiteEditor::delete_site));\n\n bldr->get_widget(\"AddSiteButton\", toolButton);\n toolButton->signal_clicked().connect(sigc::mem_fun(*this, &SiteEditor::add_row));\n\n m_UsernameConn = m_UsernameEntry->signal_changed().connect(\n sigc::mem_fun(*this, &SiteEditor::on_username_edited));\n m_PasswordConn = m_PasswordEntry->signal_changed().connect(\n sigc::mem_fun(*this, &SiteEditor::on_password_edited));\n\n#ifdef HAVE_LIBSECRET\n \/\/ Make sure the initially selected site's password gets set in the entry once it's loaded\n const std::shared_ptr &s = get_selection()->get_selected()->get_value(m_Columns.site);\n if (s)\n s->signal_password_lookup().connect([ this, s ]() { m_PasswordEntry->set_text(s->get_password()); });\n\n m_PasswordEntry->set_visibility(false);\n#endif \/\/ HAVE_LIBSECRET\n\n \/\/ Set initial values for entries and linkbutton\n on_cursor_changed();\n}\n\nSiteEditor::~SiteEditor()\n{\n if (m_SiteCheckThread.joinable())\n m_SiteCheckThread.join();\n}\n\nbool SiteEditor::on_key_release_event(GdkEventKey *e)\n{\n if (e->keyval == GDK_Return || e->keyval == GDK_ISO_Enter\n || e->keyval == GDK_KP_Enter || e->keyval == GDK_Tab)\n {\n Gtk::TreeIter iter = get_selection()->get_selected();\n Gtk::TreePath p(iter);\n\n if (iter->get_value(m_Columns.url).empty())\n set_cursor(p, *m_UrlColumn, true);\n else if (iter->get_value(m_Columns.name).empty())\n set_cursor(p, *m_NameColumn, true);\n }\n\n return false;\n}\n\nvoid SiteEditor::on_cursor_changed()\n{\n Gtk::TreeView::on_cursor_changed();\n std::shared_ptr s = nullptr;\n\n if (get_selection()->get_selected())\n s = get_selection()->get_selected()->get_value(m_Columns.site);\n\n m_UsernameConn.block();\n m_PasswordConn.block();\n\n if (s)\n {\n m_RegisterButton->set_label(_(\"Register account on \") + s->get_name());\n m_RegisterButton->set_uri(s->get_register_uri());\n\n m_UsernameEntry->set_text(s->get_username());\n m_PasswordEntry->set_text(s->get_password());\n }\n else\n {\n m_RegisterButton->set_label(_(\"Register account\"));\n\n m_UsernameEntry->set_text(\"\");\n m_PasswordEntry->set_text(\"\");\n }\n\n m_UsernameConn.unblock();\n m_PasswordConn.unblock();\n\n m_RegisterButton->set_sensitive(!!s);\n m_UsernameEntry->set_sensitive(!!s);\n m_PasswordEntry->set_sensitive(!!s);\n\n if (!s || s->get_type() == Site::Type::GELBOORU)\n m_PasswordLabel->set_text(_(\"Password:\"));\n else\n m_PasswordLabel->set_text(_(\"API Key:\"));\n}\n\nvoid SiteEditor::add_row()\n{\n Gtk::TreePath path(m_Model->append());\n set_cursor(path, *m_NameColumn, true);\n scroll_to_row(path);\n}\n\nvoid SiteEditor::delete_site()\n{\n Gtk::TreeIter o = get_selection()->get_selected();\n\n if (o)\n {\n m_Sites.erase(std::remove(m_Sites.begin(), m_Sites.end(), o->get_value(m_Columns.site)), m_Sites.end());\n m_SignalEdited();\n\n Gtk::TreeIter n = m_Model->erase(o);\n if (m_Model->children().size())\n get_selection()->select(n ? n : --n);\n on_cursor_changed();\n }\n}\n\nvoid SiteEditor::on_name_edited(const std::string &p, const std::string &text)\n{\n Gtk::TreePath path(p);\n Gtk::TreeIter iter = m_Model->get_iter(path);\n std::string name = text;\n\n \/\/ make sure the site name is unique\n for (size_t i = 1; !is_name_unique(iter, name); ++i)\n name = text + std::to_string(i);\n\n iter->set_value(m_Columns.name, name);\n\n if (!iter->get_value(m_Columns.url).empty())\n add_edit_site(iter);\n}\n\nvoid SiteEditor::on_url_edited(const std::string &p, const std::string &text)\n{\n Gtk::TreePath path(p);\n Gtk::TreeIter iter = m_Model->get_iter(path);\n std::string url = text;\n\n if (url.back() == '\/')\n url = text.substr(0, text.size() - 1);\n\n iter->set_value(m_Columns.url, url);\n add_edit_site(iter);\n}\n\nbool SiteEditor::is_name_unique(const Gtk::TreeIter &iter, const std::string &name) const\n{\n for (const Gtk::TreeIter &i : m_Model->children())\n if (i->get_value(m_Columns.name) == name && iter != i)\n return false;\n\n return true;\n}\n\nvoid SiteEditor::add_edit_site(const Gtk::TreeIter &iter)\n{\n std::string name = iter->get_value(m_Columns.name),\n url(iter->get_value(m_Columns.url));\n\n if (name.empty() || url.empty())\n {\n iter->set_value(m_Columns.icon, m_ErrorPixbuf);\n return;\n }\n\n if (m_SiteCheckThread.joinable())\n m_SiteCheckThread.join();\n\n m_SiteCheckIter = iter;\n\n std::vector>::iterator i =\n std::find(m_Sites.begin(), m_Sites.end(), iter->get_value(m_Columns.site));\n std::shared_ptr site = i != m_Sites.end() ? *i : nullptr;\n\n \/\/ editting\n if (site)\n {\n if (name == site->get_name() && url == site->get_url())\n {\n if (iter->get_value(m_Columns.icon) == m_ErrorPixbuf)\n iter->set_value(m_Columns.icon, site->get_icon_pixbuf());\n\n return;\n }\n\n m_SiteCheckEdit = true;\n m_SiteCheckSite = site;\n m_SiteCheckIter->set_value(m_Columns.loading, true);\n m_SiteCheckThread = std::thread([ this, name, url ]()\n {\n m_SiteCheckSite->set_name(name);\n m_SiteCheckEditSuccess = m_SiteCheckSite->set_url(url);\n\n if (m_SiteCheckEditSuccess)\n update_edited_site_icon();\n\n m_SignalSiteChecked();\n });\n }\n else\n {\n m_SiteCheckEdit = false;\n m_SiteCheckIter->set_value(m_Columns.loading, true);\n m_SiteCheckThread = std::thread([ this, name, url ]()\n {\n m_SiteCheckSite = Site::create(name, url);\n\n if (m_SiteCheckSite)\n update_edited_site_icon();\n\n m_SignalSiteChecked();\n });\n }\n}\n\nvoid SiteEditor::update_edited_site_icon()\n{\n m_SiteCheckIter->set_value(m_Columns.icon, m_SiteCheckSite->get_icon_pixbuf(true));\n m_SiteCheckIter->set_value(m_Columns.loading, false);\n}\n\nvoid SiteEditor::on_site_checked()\n{\n if ((m_SiteCheckEdit && !m_SiteCheckEditSuccess) || (!m_SiteCheckEdit && !m_SiteCheckSite))\n {\n m_SiteCheckIter->set_value(m_Columns.icon, m_ErrorPixbuf);\n m_SiteCheckIter->set_value(m_Columns.loading, false);\n }\n else if (m_SiteCheckSite && !m_SiteCheckEdit)\n {\n m_Sites.push_back(m_SiteCheckSite);\n m_SiteCheckIter->set_value(m_Columns.site, m_SiteCheckSite);\n on_cursor_changed();\n }\n\n if (m_SiteCheckEdit || m_SiteCheckSite)\n m_SignalEdited();\n\n if (m_SiteCheckThread.joinable())\n m_SiteCheckThread.join();\n}\n\nvoid SiteEditor::on_username_edited()\n{\n const std::shared_ptr &s = get_selection()->get_selected()->get_value(m_Columns.site);\n if (s) s->set_username(m_UsernameEntry->get_text());\n}\n\nvoid SiteEditor::on_password_edited()\n{\n const std::shared_ptr &s = get_selection()->get_selected()->get_value(m_Columns.site);\n if (s) s->set_password(m_PasswordEntry->get_text());\n}\n<|endoftext|>"} {"text":"#pragma once\n#include \n#include \n\nnamespace archie\n{\n template \n auto filter(Range&, Pred);\n\n namespace detail\n {\n template \n class filter_impl {\n class filter_iterator {\n friend class filter_impl;\n ForwardIt first_;\n ForwardIt last_;\n Pred pred_;\n\n explicit filter_iterator(ForwardIt first, ForwardIt last, Pred pred)\n : first_(first), last_(last), pred_(pred)\n {\n }\n\n public:\n auto& operator*() const { return *first_; }\n filter_iterator& operator++()\n {\n first_ = std::find_if(++first_, last_, pred_);\n return *this;\n }\n bool operator==(filter_iterator const& rhs) const { return first_ == rhs.first_; }\n bool operator!=(filter_iterator const& rhs) const { return !(*this == rhs); }\n };\n\n ForwardIt first_;\n ForwardIt last_;\n Pred pred_;\n\n template \n friend auto archie::filter(Range&, P);\n\n explicit filter_impl(ForwardIt first, ForwardIt last, Pred pred)\n : first_(std::find_if(first, last, pred)), last_(last), pred_(pred)\n {\n }\n\n public:\n filter_iterator begin() const { return filter_iterator(first_, last_, pred_); }\n filter_iterator end() const { return filter_iterator(last_, last_, pred_); }\n };\n }\n\n template \n auto filter(Range& r, Pred pred)\n {\n return detail::filter_impl(std::begin(r), std::end(r), pred);\n }\n}\nclang compilation fix to lazy filter#pragma once\n#include \n#include \n\nnamespace archie\n{\n namespace detail\n {\n template \n class filter_impl;\n }\n template \n auto filter(Range& r, Pred) -> detail::filter_impl;\n\n namespace detail\n {\n template \n class filter_impl {\n class filter_iterator {\n friend class filter_impl;\n ForwardIt first_;\n ForwardIt last_;\n Pred pred_;\n\n explicit filter_iterator(ForwardIt first, ForwardIt last, Pred pred)\n : first_(first), last_(last), pred_(pred)\n {\n }\n\n public:\n auto& operator*() const { return *first_; }\n filter_iterator& operator++()\n {\n first_ = std::find_if(++first_, last_, pred_);\n return *this;\n }\n bool operator==(filter_iterator const& rhs) const { return first_ == rhs.first_; }\n bool operator!=(filter_iterator const& rhs) const { return !(*this == rhs); }\n };\n\n ForwardIt first_;\n ForwardIt last_;\n Pred pred_;\n\n template \n friend auto archie::filter(Range& r, P) -> filter_impl;\n\n explicit filter_impl(ForwardIt first, ForwardIt last, Pred pred)\n : first_(std::find_if(first, last, pred)), last_(last), pred_(pred)\n {\n }\n\n public:\n filter_iterator begin() const { return filter_iterator(first_, last_, pred_); }\n filter_iterator end() const { return filter_iterator(last_, last_, pred_); }\n };\n }\n\n template \n auto filter(Range& r, Pred pred) -> detail::filter_impl\n {\n return detail::filter_impl(std::begin(r), std::end(r), pred);\n }\n}\n<|endoftext|>"} {"text":"#pragma once\n\n#if defined(__x86_64__)\n#include \n#endif\n\nnamespace pthash::util {\n\ntemplate \ninline void prefetch(T const* ptr) {\n#if defined(__x86_64__)\n _mm_prefetch(reinterpret_cast(ptr), _MM_HINT_T0);\n#endif\n}\n\ninline uint8_t msb(uint64_t x) {\n assert(x);\n unsigned long ret = -1U;\n if (x) { ret = (unsigned long)(63 - __builtin_clzll(x)); }\n return (uint8_t)ret;\n}\n\ninline bool bsr64(unsigned long* const index, const uint64_t mask) {\n if (mask) {\n *index = (unsigned long)(63 - __builtin_clzll(mask));\n return true;\n } else {\n return false;\n }\n}\n\ninline uint8_t msb(uint64_t x, unsigned long& ret) {\n return bsr64(&ret, x);\n}\n\ninline uint8_t lsb(uint64_t x, unsigned long& ret) {\n if (x) {\n ret = (unsigned long)__builtin_ctzll(x);\n return true;\n }\n return false;\n}\n\ninline uint8_t lsb(uint64_t x) {\n assert(x);\n unsigned long ret = -1U;\n lsb(x, ret);\n return (uint8_t)ret;\n}\n\ninline uint64_t popcount(uint64_t x) {\n#ifdef __SSE4_2__\n return static_cast(_mm_popcnt_u64(x));\n#else\n return std::popcount(x);\n#endif\n}\n\ninline uint64_t select64(uint64_t x, uint64_t k) {\n#ifndef __BMI2__\n \/\/ Modified from: Bit Twiddling Hacks\n \/\/ https:\/\/graphics.stanford.edu\/~seander\/bithacks.html#SelectPosFromMSBRank\n unsigned int s; \/\/ Output: Resulting position of bit with rank r [1-64]\n uint64_t a, b, c, d; \/\/ Intermediate temporaries for bit count.\n unsigned int t; \/\/ Bit count temporary.\n k = popcount(x) - k;\n\n a = x - ((x >> 1) & ~0UL\/3);\n b = (a & ~0UL\/5) + ((a >> 2) & ~0UL\/5);\n c = (b + (b >> 4)) & ~0UL\/0x11;\n d = (c + (c >> 8)) & ~0UL\/0x101;\n t = (d >> 32) + (d >> 48);\n s = 64;\n s -= ((t - k) & 256) >> 3; k -= (t & ((t - k) >> 8));\n t = (d >> (s - 16)) & 0xff;\n s -= ((t - k) & 256) >> 4; k -= (t & ((t - k) >> 8));\n t = (c >> (s - 8)) & 0xf;\n s -= ((t - k) & 256) >> 5; k -= (t & ((t - k) >> 8));\n t = (b >> (s - 4)) & 0x7;\n s -= ((t - k) & 256) >> 6; k -= (t & ((t - k) >> 8));\n t = (a >> (s - 2)) & 0x3;\n s -= ((t - k) & 256) >> 7; k -= (t & ((t - k) >> 8));\n t = (x >> (s - 1)) & 0x1;\n s -= ((t - k) & 256) >> 8;\n return s - 1;\n#else\n uint64_t i = 1ULL << k;\n asm(\"pdep %[x], %[mask], %[x]\" : [x] \"+r\"(x) : [mask] \"r\"(i));\n asm(\"tzcnt %[bit], %[index]\" : [index] \"=r\"(i) : [bit] \"g\"(x) : \"cc\");\n return i;\n#endif\n}\n\ninline uint64_t select_in_word(const uint64_t x, const uint64_t k) {\n assert(k < popcount(x));\n return select64(x, k);\n}\n\n} \/\/ namespace pthash::utilpopcount defaults to __builtin_popcountll for ARM processors without c++ 2020#pragma once\n\n#if defined(__x86_64__)\n#include \n#endif\n\nnamespace pthash::util {\n\ntemplate \ninline void prefetch(T const* ptr) {\n#if defined(__x86_64__)\n _mm_prefetch(reinterpret_cast(ptr), _MM_HINT_T0);\n#endif\n}\n\ninline uint8_t msb(uint64_t x) {\n assert(x);\n unsigned long ret = -1U;\n if (x) { ret = (unsigned long)(63 - __builtin_clzll(x)); }\n return (uint8_t)ret;\n}\n\ninline bool bsr64(unsigned long* const index, const uint64_t mask) {\n if (mask) {\n *index = (unsigned long)(63 - __builtin_clzll(mask));\n return true;\n } else {\n return false;\n }\n}\n\ninline uint8_t msb(uint64_t x, unsigned long& ret) {\n return bsr64(&ret, x);\n}\n\ninline uint8_t lsb(uint64_t x, unsigned long& ret) {\n if (x) {\n ret = (unsigned long)__builtin_ctzll(x);\n return true;\n }\n return false;\n}\n\ninline uint8_t lsb(uint64_t x) {\n assert(x);\n unsigned long ret = -1U;\n lsb(x, ret);\n return (uint8_t)ret;\n}\n\ninline uint64_t popcount(uint64_t x) {\n#ifdef __SSE4_2__\n return static_cast(_mm_popcnt_u64(x));\n#elif __cplusplus >= 202002L\n return std::popcount(x);\n#else\n return static_cast(__builtin_popcountll(x));\n#endif\n}\n\ninline uint64_t select64(uint64_t x, uint64_t k) {\n#ifndef __BMI2__\n \/\/ Modified from: Bit Twiddling Hacks\n \/\/ https:\/\/graphics.stanford.edu\/~seander\/bithacks.html#SelectPosFromMSBRank\n unsigned int s; \/\/ Output: Resulting position of bit with rank r [1-64]\n uint64_t a, b, c, d; \/\/ Intermediate temporaries for bit count.\n unsigned int t; \/\/ Bit count temporary.\n k = popcount(x) - k;\n\n a = x - ((x >> 1) & ~0UL \/ 3);\n b = (a & ~0UL \/ 5) + ((a >> 2) & ~0UL \/ 5);\n c = (b + (b >> 4)) & ~0UL \/ 0x11;\n d = (c + (c >> 8)) & ~0UL \/ 0x101;\n t = (d >> 32) + (d >> 48);\n s = 64;\n s -= ((t - k) & 256) >> 3;\n k -= (t & ((t - k) >> 8));\n t = (d >> (s - 16)) & 0xff;\n s -= ((t - k) & 256) >> 4;\n k -= (t & ((t - k) >> 8));\n t = (c >> (s - 8)) & 0xf;\n s -= ((t - k) & 256) >> 5;\n k -= (t & ((t - k) >> 8));\n t = (b >> (s - 4)) & 0x7;\n s -= ((t - k) & 256) >> 6;\n k -= (t & ((t - k) >> 8));\n t = (a >> (s - 2)) & 0x3;\n s -= ((t - k) & 256) >> 7;\n k -= (t & ((t - k) >> 8));\n t = (x >> (s - 1)) & 0x1;\n s -= ((t - k) & 256) >> 8;\n return s - 1;\n#else\n uint64_t i = 1ULL << k;\n asm(\"pdep %[x], %[mask], %[x]\" : [ x ] \"+r\"(x) : [ mask ] \"r\"(i));\n asm(\"tzcnt %[bit], %[index]\" : [ index ] \"=r\"(i) : [ bit ] \"g\"(x) : \"cc\");\n return i;\n#endif\n}\n\ninline uint64_t select_in_word(const uint64_t x, const uint64_t k) {\n assert(k < popcount(x));\n return select64(x, k);\n}\n\n} \/\/ namespace pthash::util<|endoftext|>"} {"text":"\/*\n * This is part of the FL library, a C++ Bayesian filtering library\n * (https:\/\/github.com\/filtering-library)\n *\n * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)\n * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)\n *\n * Max-Planck Institute for Intelligent Systems, AMD Lab\n * University of Southern California, CLMC Lab\n *\n * This Source Code Form is subject to the terms of the MIT License (MIT).\n * A copy of the license can be found in the LICENSE file distributed with this\n * source code.\n *\/\n\n\/**\n * \\file types.hpp\n * \\date June 2015\n * \\author Jan Issac (jan.issac@gmail.com)\n *\/\n\n#ifndef FL__UTIL__TYPES_HPP\n#define FL__UTIL__TYPES_HPP\n\n#include \n\nnamespace fl\n{\n\n#if defined(fl_USE_FLOAT)\n typedef float FloatingPoint;\n#elif defined(fl_USE_DOUBLE)\n typedef double FloatingPoint;\n#elif defined(fl_USE_LONG_DOUBLE)\n typedef long double FloatingPoint;\n#else\n typedef double FloatingPoint;\n#endif\n\n\/**\n * \\ingroup types\n * \\brief Common floating point type. The default type of Real is \\c double.\n * This type is used throughout the entire ::fl library.\n *\n * In order or use other basic floating point types please compile with one of\n * the following defines:\n *\n * - \\c FL_USE_FLOAT: defines fl::Real as \\c float\n * - \\c FL_USE_DOUBLE: defines fl::Real as \\c double (default)\n * - \\c FL_USE_LONG_DOUBLE: defines fl::Real as \\c long double\n *\/\ntypedef FloatingPoint Real;\n\n\/**\n * \\ingroup types\n *\/\ntemplate struct Additive\n{\n typedef Model_ Model;\n};\n\n\/**\n * \\ingroup types\n *\/\ntemplate struct AdditiveUncorrelated\n{\n typedef Model_ Model;\n};\n\n\/**\n * \\ingroup types\n *\/\ntemplate struct NonAdditive\n{\n typedef Model_ Model;\n};\n\n\/**\n * \\internal\n *\/\nnamespace internal\n{\n\n\/**\n * \\internal\n * \\ingroup types\n *\n * \\brief Observation model type identifier\n *\/\nstruct ObsrvModelType { };\n\n\/**\n * \\internal\n * \\ingroup types\n *\n * \\brief Process model type identifier\n *\/\nstruct ProcessModelType { };\n\n\/**\n * \\internal\n * \\ingroup types\n *\n * \\brief Adaptive model type identifier\n *\/\nstruct AdaptiveModelType { };\n\n\/**\n * \\internal\n * \\ingroup types\n *\n * \\brief Represents the base type of any model with additive noise term\n * \\f$ x_{t+1} = f(x_t) + v_t\\f$ while \\f$v_t\\f$ is the additive noise.\n *\/\nstruct AdditiveModelType { };\n\n\/**\n * \\internal\n * \\ingroup types\n *\n * \\brief Represents the base type of any model with additive uncorrelated\n * Gaussian white noise term in \\f$ x_{t+1} = f(x_t) + v_t\\f$ while \\f$v_t\\f$ is\n * the additive noise with \\f$v_t \\sim {\\cal N}(v_t; 0, Q_t)\\f$. Here, the\n * covariance matrix has a diagonal form \\f$Q_t = \\text{diag}(q_1, q_2, \\ldots,\n * q_n)\\f$ and \\f$n\\f$ is the dimension of \\f$v_t \\in \\mathbb{R}^n\\f$.\n *\/\nstruct AdditiveUncorrelatedModelType { };\n\n\/**\n * \\internal\n * \\ingroup types\n *\n * \\brief Represents the base type of any model with non-additive noise term\n * \\f$ x_{t+1} = f(x_t, v_t) \\f$ while \\f$v_t\\f$ is the additive noise.\n *\/\nstruct NonAdditiveModelType { };\n\n}\n\n}\n\n#endif\nAdded LinearModel type identifier\/*\n * This is part of the FL library, a C++ Bayesian filtering library\n * (https:\/\/github.com\/filtering-library)\n *\n * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)\n * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)\n *\n * Max-Planck Institute for Intelligent Systems, AMD Lab\n * University of Southern California, CLMC Lab\n *\n * This Source Code Form is subject to the terms of the MIT License (MIT).\n * A copy of the license can be found in the LICENSE file distributed with this\n * source code.\n *\/\n\n\/**\n * \\file types.hpp\n * \\date June 2015\n * \\author Jan Issac (jan.issac@gmail.com)\n *\/\n\n#ifndef FL__UTIL__TYPES_HPP\n#define FL__UTIL__TYPES_HPP\n\n#include \n\nnamespace fl\n{\n\n#if defined(fl_USE_FLOAT)\n typedef float FloatingPoint;\n#elif defined(fl_USE_DOUBLE)\n typedef double FloatingPoint;\n#elif defined(fl_USE_LONG_DOUBLE)\n typedef long double FloatingPoint;\n#else\n typedef double FloatingPoint;\n#endif\n\n\/**\n * \\ingroup types\n * \\brief Common floating point type. The default type of Real is \\c double.\n * This type is used throughout the entire ::fl library.\n *\n * In order or use other basic floating point types please compile with one of\n * the following defines:\n *\n * - \\c FL_USE_FLOAT: defines fl::Real as \\c float\n * - \\c FL_USE_DOUBLE: defines fl::Real as \\c double (default)\n * - \\c FL_USE_LONG_DOUBLE: defines fl::Real as \\c long double\n *\/\ntypedef FloatingPoint Real;\n\n\/**\n * \\ingroup types\n *\/\ntemplate struct Additive\n{\n typedef Model_ Model;\n};\n\n\/**\n * \\ingroup types\n *\/\ntemplate struct AdditiveUncorrelated\n{\n typedef Model_ Model;\n};\n\n\/**\n * \\ingroup types\n *\/\ntemplate struct NonAdditive\n{\n typedef Model_ Model;\n};\n\n\/**\n * \\internal\n *\/\nnamespace internal\n{\n\n\/**\n * \\internal\n * \\ingroup types\n *\n * \\brief Linear model type identifier\n *\/\nstruct LinearModelType { };\n\n\/**\n * \\internal\n * \\ingroup types\n *\n * \\brief Observation model type identifier\n *\/\nstruct ObsrvModelType { };\n\n\/**\n * \\internal\n * \\ingroup types\n *\n * \\brief Process model type identifier\n *\/\nstruct ProcessModelType { };\n\n\/**\n * \\internal\n * \\ingroup types\n *\n * \\brief Adaptive model type identifier\n *\/\nstruct AdaptiveModelType { };\n\n\/**\n * \\internal\n * \\ingroup types\n *\n * \\brief Represents the base type of any model with additive noise term\n * \\f$ x_{t+1} = f(x_t) + v_t\\f$ while \\f$v_t\\f$ is the additive noise.\n *\/\nstruct AdditiveNoiseModelType { };\n\n\/**\n * \\internal\n * \\ingroup types\n *\n * \\brief Represents the base type of any model with additive uncorrelated\n * Gaussian white noise term in \\f$ x_{t+1} = f(x_t) + v_t\\f$ while \\f$v_t\\f$ is\n * the additive noise with \\f$v_t \\sim {\\cal N}(v_t; 0, Q_t)\\f$. Here, the\n * covariance matrix has a diagonal form \\f$Q_t = \\text{diag}(q_1, q_2, \\ldots,\n * q_n)\\f$ and \\f$n\\f$ is the dimension of \\f$v_t \\in \\mathbb{R}^n\\f$.\n *\/\nstruct AdditiveUncorrelatedNoiseModelType { };\n\n\/**\n * \\internal\n * \\ingroup types\n *\n * \\brief Represents the base type of any model with non-additive noise term\n * \\f$ x_{t+1} = f(x_t, v_t) \\f$ while \\f$v_t\\f$ is the additive noise.\n *\/\nstruct NonAdditiveNoiseModelType { };\n\n}\n\n}\n\n#endif\n<|endoftext|>"} {"text":"\/*\n===============================================================================\n\n FILE: laszip.hpp\n \n CONTENTS:\n \n Contains LASitem and LASchunk structs as well as the IDs of the currently\r\n supported entropy coding scheme\n\n PROGRAMMERS:\r\n \r\n martin.isenburg@gmail.com\r\n \r\n COPYRIGHT:\r\n\r\n (c) 2007-2011, Martin Isenburg, LASSO - tools to catch reality\r\n\r\n This is free software; you can redistribute and\/or modify it under the\r\n terms of the GNU Lesser General Licence as published by the Free Software\r\n Foundation. See the COPYING file for more information.\r\n\r\n This software is distributed WITHOUT ANY WARRANTY and without even the\r\n implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\r\n \r\n CHANGE HISTORY:\r\n \r\n 6 October 2011 -- large file support, ability to read with missing chunk table\r\n 23 June 2011 -- turned on LASzip version 2.0 compressor with chunking \r\n 8 May 2011 -- added an option for variable chunking via chunk()\r\n 23 April 2011 -- changed interface for simplicity and chunking support\r\n 20 March 2011 -- incrementing LASZIP_VERSION to 1.2 for improved compression\r\n 10 January 2011 -- licensing change for LGPL release and liblas integration\r\n 12 December 2010 -- refactored from lasdefinitions after movies with silke\r\n \n===============================================================================\n*\/\n#ifndef LASZIP_HPP\n#define LASZIP_HPP\n\r\n#if defined(_MSC_VER) && (_MSC_VER < 1300)\r\n#define LZ_WIN32_VC6\r\ntypedef __int64 SIGNED_INT64;\r\n#else\r\ntypedef long long SIGNED_INT64;\r\n#endif\r\n\r\n#if defined(_MSC_VER) && \\\r\n (_MSC_FULL_VER >= 150000000)\r\n#define LASCopyString _strdup\r\n#else\r\n#define LASCopyString strdup\r\n#endif\r\n\r\n#define LASZIP_VERSION_MAJOR 2\r\n#define LASZIP_VERSION_MINOR 0\r\n#define LASZIP_VERSION_REVISION 2\r\n\r\n#define LASZIP_COMPRESSOR_NONE 0\r\n#define LASZIP_COMPRESSOR_POINTWISE 1\r\n#define LASZIP_COMPRESSOR_POINTWISE_CHUNKED 2\r\n#define LASZIP_COMPRESSOR_TOTAL_NUMBER_OF 3\r\n\r\n#define LASZIP_COMPRESSOR_CHUNKED LASZIP_COMPRESSOR_POINTWISE_CHUNKED\r\n#define LASZIP_COMPRESSOR_NOT_CHUNKED LASZIP_COMPRESSOR_POINTWISE\r\n\r\n#define LASZIP_COMPRESSOR_DEFAULT LASZIP_COMPRESSOR_CHUNKED\r\n\r\n#define LASZIP_CODER_ARITHMETIC 0\r\n#define LASZIP_CODER_TOTAL_NUMBER_OF 1\r\n\r\n#define LASZIP_CHUNK_SIZE_DEFAULT 50000\r\n\r\n#include \"laszipexport.hpp\"\r\n\r\nclass LASitem\r\n{\r\npublic:\r\n enum Type { BYTE = 0, SHORT, INT, LONG, FLOAT, DOUBLE, POINT10, GPSTIME11, RGB12, WAVEPACKET13 } type;\r\n unsigned short size;\r\n unsigned short version;\r\n bool is_type(LASitem::Type t) const;\r\n const char* get_name() const;\r\n};\r\n\r\nclass LASZIP_DLL LASzip\r\n{\r\npublic:\r\n\r\n \/\/ supported version control\r\n bool check_compressor(const unsigned short compressor);\r\n bool check_coder(const unsigned short coder);\r\n bool check_item(const LASitem* item);\r\n bool check_items(const unsigned short num_items, const LASitem* items);\r\n bool check();\r\n\r\n \/\/ go back and forth between item array and point type & size\r\n bool setup(unsigned short* num_items, LASitem** items, const unsigned char point_type, const unsigned short point_size, const unsigned short compressor=LASZIP_COMPRESSOR_NONE);\r\n bool is_standard(const unsigned short num_items, const LASitem* items, unsigned char* point_type=0, unsigned short* record_length=0);\r\n bool is_standard(unsigned char* point_type=0, unsigned short* record_length=0);\r\n\r\n \/\/ pack to and unpack from VLR\r\n unsigned char* bytes;\r\n bool unpack(const unsigned char* bytes, const int num);\r\n bool pack(unsigned char*& bytes, int& num);\r\n\r\n \/\/ setup\r\n bool setup(const unsigned char point_type, const unsigned short point_size, const unsigned short compressor=LASZIP_COMPRESSOR_DEFAULT);\r\n bool setup(const unsigned short num_items, const LASitem* items, const unsigned short compressor);\r\n bool set_chunk_size(const unsigned int chunk_size); \/* for compressor only *\/\r\n bool request_version(const unsigned short requested_version); \/* for compressor only *\/\r\n\r\n \/\/ in case a function returns false this string describes the problem\r\n const char* get_error() const;\r\n\r\n \/\/ stored in LASzip VLR data section\r\n unsigned short compressor;\r\n unsigned short coder;\r\n unsigned char version_major;\r\n unsigned char version_minor;\r\n unsigned short version_revision;\r\n unsigned int options;\r\n unsigned int chunk_size; \r\n SIGNED_INT64 num_points; \/* not mandatory ... -1 if unknown *\/\r\n SIGNED_INT64 num_bytes; \/* not mandatory ... -1 if unknown *\/\r\n unsigned short num_items;\r\n LASitem* items;\r\n\r\n LASzip();\r\n ~LASzip();\r\n\r\nprivate:\r\n bool return_error(const char* err);\r\n char* error_string;\r\n};\r\n\r\n#endif\nwin32 dll fix\/*\n===============================================================================\n\n FILE: laszip.hpp\n \n CONTENTS:\n \n Contains LASitem and LASchunk structs as well as the IDs of the currently\r\n supported entropy coding scheme\n\n PROGRAMMERS:\r\n \r\n martin.isenburg@gmail.com\r\n \r\n COPYRIGHT:\r\n\r\n (c) 2007-2011, Martin Isenburg, LASSO - tools to catch reality\r\n\r\n This is free software; you can redistribute and\/or modify it under the\r\n terms of the GNU Lesser General Licence as published by the Free Software\r\n Foundation. See the COPYING file for more information.\r\n\r\n This software is distributed WITHOUT ANY WARRANTY and without even the\r\n implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\r\n \r\n CHANGE HISTORY:\r\n \r\n 6 October 2011 -- large file support, ability to read with missing chunk table\r\n 23 June 2011 -- turned on LASzip version 2.0 compressor with chunking \r\n 8 May 2011 -- added an option for variable chunking via chunk()\r\n 23 April 2011 -- changed interface for simplicity and chunking support\r\n 20 March 2011 -- incrementing LASZIP_VERSION to 1.2 for improved compression\r\n 10 January 2011 -- licensing change for LGPL release and liblas integration\r\n 12 December 2010 -- refactored from lasdefinitions after movies with silke\r\n \n===============================================================================\n*\/\n#ifndef LASZIP_HPP\n#define LASZIP_HPP\n\r\n#if defined(_MSC_VER) && (_MSC_VER < 1300)\r\n#define LZ_WIN32_VC6\r\ntypedef __int64 SIGNED_INT64;\r\n#else\r\ntypedef long long SIGNED_INT64;\r\n#endif\r\n\r\n#if defined(_MSC_VER) && \\\r\n (_MSC_FULL_VER >= 150000000)\r\n#define LASCopyString _strdup\r\n#else\r\n#define LASCopyString strdup\r\n#endif\r\n\r\n#define LASZIP_VERSION_MAJOR 2\r\n#define LASZIP_VERSION_MINOR 0\r\n#define LASZIP_VERSION_REVISION 2\r\n\r\n#define LASZIP_COMPRESSOR_NONE 0\r\n#define LASZIP_COMPRESSOR_POINTWISE 1\r\n#define LASZIP_COMPRESSOR_POINTWISE_CHUNKED 2\r\n#define LASZIP_COMPRESSOR_TOTAL_NUMBER_OF 3\r\n\r\n#define LASZIP_COMPRESSOR_CHUNKED LASZIP_COMPRESSOR_POINTWISE_CHUNKED\r\n#define LASZIP_COMPRESSOR_NOT_CHUNKED LASZIP_COMPRESSOR_POINTWISE\r\n\r\n#define LASZIP_COMPRESSOR_DEFAULT LASZIP_COMPRESSOR_CHUNKED\r\n\r\n#define LASZIP_CODER_ARITHMETIC 0\r\n#define LASZIP_CODER_TOTAL_NUMBER_OF 1\r\n\r\n#define LASZIP_CHUNK_SIZE_DEFAULT 50000\r\n\r\n#include \"laszipexport.hpp\"\r\n\r\nclass LASZIP_DLL LASitem\r\n{\r\npublic:\r\n enum Type { BYTE = 0, SHORT, INT, LONG, FLOAT, DOUBLE, POINT10, GPSTIME11, RGB12, WAVEPACKET13 } type;\r\n unsigned short size;\r\n unsigned short version;\r\n bool is_type(LASitem::Type t) const;\r\n const char* get_name() const;\r\n};\r\n\r\nclass LASZIP_DLL LASzip\r\n{\r\npublic:\r\n\r\n \/\/ supported version control\r\n bool check_compressor(const unsigned short compressor);\r\n bool check_coder(const unsigned short coder);\r\n bool check_item(const LASitem* item);\r\n bool check_items(const unsigned short num_items, const LASitem* items);\r\n bool check();\r\n\r\n \/\/ go back and forth between item array and point type & size\r\n bool setup(unsigned short* num_items, LASitem** items, const unsigned char point_type, const unsigned short point_size, const unsigned short compressor=LASZIP_COMPRESSOR_NONE);\r\n bool is_standard(const unsigned short num_items, const LASitem* items, unsigned char* point_type=0, unsigned short* record_length=0);\r\n bool is_standard(unsigned char* point_type=0, unsigned short* record_length=0);\r\n\r\n \/\/ pack to and unpack from VLR\r\n unsigned char* bytes;\r\n bool unpack(const unsigned char* bytes, const int num);\r\n bool pack(unsigned char*& bytes, int& num);\r\n\r\n \/\/ setup\r\n bool setup(const unsigned char point_type, const unsigned short point_size, const unsigned short compressor=LASZIP_COMPRESSOR_DEFAULT);\r\n bool setup(const unsigned short num_items, const LASitem* items, const unsigned short compressor);\r\n bool set_chunk_size(const unsigned int chunk_size); \/* for compressor only *\/\r\n bool request_version(const unsigned short requested_version); \/* for compressor only *\/\r\n\r\n \/\/ in case a function returns false this string describes the problem\r\n const char* get_error() const;\r\n\r\n \/\/ stored in LASzip VLR data section\r\n unsigned short compressor;\r\n unsigned short coder;\r\n unsigned char version_major;\r\n unsigned char version_minor;\r\n unsigned short version_revision;\r\n unsigned int options;\r\n unsigned int chunk_size; \r\n SIGNED_INT64 num_points; \/* not mandatory ... -1 if unknown *\/\r\n SIGNED_INT64 num_bytes; \/* not mandatory ... -1 if unknown *\/\r\n unsigned short num_items;\r\n LASitem* items;\r\n\r\n LASzip();\r\n ~LASzip();\r\n\r\nprivate:\r\n bool return_error(const char* err);\r\n char* error_string;\r\n};\r\n\r\n#endif\n<|endoftext|>"} {"text":"#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"SDL.h\"\n#include \"proxy_sqrat.hpp\"\n#include \"types.hpp\"\n\nnamespace Oddlib\n{\n class IStream\n {\n public:\n static inline void RegisterScriptBindings();\n\n enum class ReadMode\n {\n ReadOnly,\n ReadWrite\n };\n\n static std::vector ReadAll(IStream& stream)\n {\n const auto oldPos = stream.Pos();\n stream.Seek(0);\n const auto size = stream.Size();\n\n std::vector allStreamBytes(size);\n stream.ReadBytes(allStreamBytes.data(), allStreamBytes.size());\n stream.Seek(oldPos);\n return allStreamBytes;\n }\n\n \/\/ Read any fundamental type\n template\n void Read(T& type)\n {\n static_assert(std::is_fundamental::value, \"Can only read fundamental types\");\n ReadBytes(reinterpret_cast(&type), sizeof(type));\n }\n\n \/\/ Read a string\n void Read(std::string& type)\n {\n ReadBytes(reinterpret_cast(&type[0]), type.size());\n }\n\n \/\/ Read any vector of fundamental type\n template\n void Read(std::vector& type)\n {\n static_assert(std::is_fundamental::value, \"Can only read vectors of fundamental types\");\n ReadBytes(reinterpret_cast(type.data()), sizeof(T)*type.size());\n }\n\n \/\/ Read any std::array of fundamental type\n template\n void Read(std::array& type)\n {\n static_assert(std::is_fundamental::value, \"Can only read vectors of fundamental types\");\n ReadBytes(reinterpret_cast(type.data()), sizeof(T)*type.size());\n }\n\n \/\/ Read any fixed array of fundamental type\n template\n void Read(T(&value)[count])\n {\n static_assert(std::is_fundamental::value, \"Can only read fundamental types\");\n ReadBytes(reinterpret_cast(&value[0]), sizeof(T)* count);\n }\n\n \/\/ Write any fundamental type\n template\n void Write(const T& type)\n {\n static_assert(std::is_fundamental::value, \"Can only write fundamental types\");\n WriteBytes(reinterpret_cast(&type), sizeof(type));\n }\n\n \/\/ Write vector of any fundamental type\n template\n void Write(std::vector& type)\n {\n static_assert(std::is_fundamental::value, \"Can only write vectors of fundamental types\");\n WriteBytes(reinterpret_cast(type.data()), sizeof(T)*type.size());\n }\n\n \/\/ Write a string\n void Write(const std::string& type)\n {\n WriteBytes(reinterpret_cast(&type[0]), type.size());\n }\n\n virtual ~IStream() = default;\n virtual IStream* Clone() = 0;\n virtual IStream* Clone(u32 start, u32 size) = 0;\n virtual void ReadBytes(u8* pDest, size_t destSize) = 0;\n virtual void WriteBytes(const u8* pSrc, size_t srcSize) = 0;\n virtual void Seek(size_t pos) = 0;\n virtual size_t Pos() const = 0;\n virtual size_t Size() const = 0;\n virtual bool AtEnd() const = 0;\n virtual const std::string& Name() const = 0;\n virtual std::string LoadAllToString() = 0;\n \n \/\/ Debug helper to write all of the stream to a file as a binary blob\n bool BinaryDump(const std::string& fileName)\n {\n std::ofstream s;\n s.open(fileName.c_str(), std::ios::binary);\n if (!s.is_open())\n {\n return false;\n }\n \n auto allStreamBytes = ReadAll(*this);\n s.write(reinterpret_cast(allStreamBytes.data()), allStreamBytes.size());\n return true;\n }\n };\n\n\n inline u16 ReadU16(IStream& stream)\n {\n u16 ret = 0;\n stream.Read(ret);\n return ret;\n }\n\n inline u32 ReadU32(IStream& stream)\n {\n u32 ret = 0;\n stream.Read(ret);\n return ret;\n }\n\n inline u8 ReadU8(IStream& stream)\n {\n u8 ret = 0;\n stream.Read(ret);\n return ret;\n }\n\n \/*static*\/ inline void IStream::RegisterScriptBindings()\n {\n Sqrat::Class> c(Sqrat::DefaultVM::Get(), \"IStream\");\n c.StaticFunc(\"ReadU32\", &ReadU32);\n c.StaticFunc(\"ReadU16\", &ReadU16);\n Sqrat::RootTable().Bind(\"IStream\", c);\n }\n\n\n template\n class Stream : public IStream\n {\n public:\n virtual IStream* Clone(u32 start, u32 size) override;\n virtual void ReadBytes(u8* pDest, size_t destSize) override;\n virtual void WriteBytes(const u8* pDest, size_t destSize) override;\n virtual void Seek(size_t pos) override;\n virtual size_t Pos() const override;\n virtual size_t Size() const override;\n virtual bool AtEnd() const override;\n virtual const std::string& Name() const override { return mName; }\n virtual std::string LoadAllToString() override;\n protected:\n Stream() = default;\n mutable std::unique_ptr mStream;\n size_t mSize = 0;\n std::string mName;\n };\n\n class MemoryStream : public Stream\n {\n public:\n explicit MemoryStream(std::vector&& data);\n virtual IStream* Clone() override;\n virtual IStream* Clone(u32 start, u32 size) override { return Stream::Clone(start, size); }\n };\n\n class FileStream :public Stream\n {\n public:\n explicit FileStream(const std::string& fileName, ReadMode mode);\n virtual IStream* Clone() override;\n virtual IStream* Clone(u32 start, u32 size) override { return Stream::Clone(start, size); }\n private:\n ReadMode mMode = IStream::ReadMode::ReadOnly;\n };\n}\nallow scripts to call ReadU8#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"SDL.h\"\n#include \"proxy_sqrat.hpp\"\n#include \"types.hpp\"\n\nnamespace Oddlib\n{\n class IStream\n {\n public:\n static inline void RegisterScriptBindings();\n\n enum class ReadMode\n {\n ReadOnly,\n ReadWrite\n };\n\n static std::vector ReadAll(IStream& stream)\n {\n const auto oldPos = stream.Pos();\n stream.Seek(0);\n const auto size = stream.Size();\n\n std::vector allStreamBytes(size);\n stream.ReadBytes(allStreamBytes.data(), allStreamBytes.size());\n stream.Seek(oldPos);\n return allStreamBytes;\n }\n\n \/\/ Read any fundamental type\n template\n void Read(T& type)\n {\n static_assert(std::is_fundamental::value, \"Can only read fundamental types\");\n ReadBytes(reinterpret_cast(&type), sizeof(type));\n }\n\n \/\/ Read a string\n void Read(std::string& type)\n {\n ReadBytes(reinterpret_cast(&type[0]), type.size());\n }\n\n \/\/ Read any vector of fundamental type\n template\n void Read(std::vector& type)\n {\n static_assert(std::is_fundamental::value, \"Can only read vectors of fundamental types\");\n ReadBytes(reinterpret_cast(type.data()), sizeof(T)*type.size());\n }\n\n \/\/ Read any std::array of fundamental type\n template\n void Read(std::array& type)\n {\n static_assert(std::is_fundamental::value, \"Can only read vectors of fundamental types\");\n ReadBytes(reinterpret_cast(type.data()), sizeof(T)*type.size());\n }\n\n \/\/ Read any fixed array of fundamental type\n template\n void Read(T(&value)[count])\n {\n static_assert(std::is_fundamental::value, \"Can only read fundamental types\");\n ReadBytes(reinterpret_cast(&value[0]), sizeof(T)* count);\n }\n\n \/\/ Write any fundamental type\n template\n void Write(const T& type)\n {\n static_assert(std::is_fundamental::value, \"Can only write fundamental types\");\n WriteBytes(reinterpret_cast(&type), sizeof(type));\n }\n\n \/\/ Write vector of any fundamental type\n template\n void Write(std::vector& type)\n {\n static_assert(std::is_fundamental::value, \"Can only write vectors of fundamental types\");\n WriteBytes(reinterpret_cast(type.data()), sizeof(T)*type.size());\n }\n\n \/\/ Write a string\n void Write(const std::string& type)\n {\n WriteBytes(reinterpret_cast(&type[0]), type.size());\n }\n\n virtual ~IStream() = default;\n virtual IStream* Clone() = 0;\n virtual IStream* Clone(u32 start, u32 size) = 0;\n virtual void ReadBytes(u8* pDest, size_t destSize) = 0;\n virtual void WriteBytes(const u8* pSrc, size_t srcSize) = 0;\n virtual void Seek(size_t pos) = 0;\n virtual size_t Pos() const = 0;\n virtual size_t Size() const = 0;\n virtual bool AtEnd() const = 0;\n virtual const std::string& Name() const = 0;\n virtual std::string LoadAllToString() = 0;\n \n \/\/ Debug helper to write all of the stream to a file as a binary blob\n bool BinaryDump(const std::string& fileName)\n {\n std::ofstream s;\n s.open(fileName.c_str(), std::ios::binary);\n if (!s.is_open())\n {\n return false;\n }\n \n auto allStreamBytes = ReadAll(*this);\n s.write(reinterpret_cast(allStreamBytes.data()), allStreamBytes.size());\n return true;\n }\n };\n\n inline u8 ReadU8(IStream& stream)\n {\n u8 ret = 0;\n stream.Read(ret);\n return ret;\n }\n\n inline u16 ReadU16(IStream& stream)\n {\n u16 ret = 0;\n stream.Read(ret);\n return ret;\n }\n\n inline u32 ReadU32(IStream& stream)\n {\n u32 ret = 0;\n stream.Read(ret);\n return ret;\n }\n\n \/*static*\/ inline void IStream::RegisterScriptBindings()\n {\n Sqrat::Class> c(Sqrat::DefaultVM::Get(), \"IStream\");\n c.StaticFunc(\"ReadU8\", &ReadU8);\n c.StaticFunc(\"ReadU16\", &ReadU16);\n c.StaticFunc(\"ReadU32\", &ReadU32);\n Sqrat::RootTable().Bind(\"IStream\", c);\n }\n\n\n template\n class Stream : public IStream\n {\n public:\n virtual IStream* Clone(u32 start, u32 size) override;\n virtual void ReadBytes(u8* pDest, size_t destSize) override;\n virtual void WriteBytes(const u8* pDest, size_t destSize) override;\n virtual void Seek(size_t pos) override;\n virtual size_t Pos() const override;\n virtual size_t Size() const override;\n virtual bool AtEnd() const override;\n virtual const std::string& Name() const override { return mName; }\n virtual std::string LoadAllToString() override;\n protected:\n Stream() = default;\n mutable std::unique_ptr mStream;\n size_t mSize = 0;\n std::string mName;\n };\n\n class MemoryStream : public Stream\n {\n public:\n explicit MemoryStream(std::vector&& data);\n virtual IStream* Clone() override;\n virtual IStream* Clone(u32 start, u32 size) override { return Stream::Clone(start, size); }\n };\n\n class FileStream :public Stream\n {\n public:\n explicit FileStream(const std::string& fileName, ReadMode mode);\n virtual IStream* Clone() override;\n virtual IStream* Clone(u32 start, u32 size) override { return Stream::Clone(start, size); }\n private:\n ReadMode mMode = IStream::ReadMode::ReadOnly;\n };\n}\n<|endoftext|>"} {"text":"#include \"stdsneezy.h\"\n#include \"games.h\"\n\nHiLoGame gHiLo;\n\nconst float WIN_INIT=0.05;\nbool HiLoGame::enter(const TBeing *ch)\n{\n if(inuse){\n ch->sendTo(\"This table is already in use.\\n\\r\");\n return false;\n }\n\n inuse = true;\n hilo_shuffle(ch);\n bet = 0;\n name=ch->name;\n\n return true;\n}\n\nvoid HiLoGame::hilo_shuffle(const TBeing *ch)\n{\n act(\"The dealer shuffles the deck.\",FALSE, ch, 0, 0, TO_CHAR);\n act(\"The dealer shuffles the deck.\",FALSE, ch, 0, 0, TO_ROOM);\n\n shuffle();\n deck_inx = 0;\n}\n\nbool TBeing::checkHiLo(bool inGame = false) const\n{\n if (in_room == ROOM_HILO && (inGame || (gHiLo.index(this) > -1)))\n return true;\n else\n return false;\n}\n\nvoid HiLoGame::BetHi(TBeing *ch, int new_card)\n{\n sstring buf;\n\n if(CARD_NUM_ACEHI(new_card) > CARD_NUM_ACEHI(card)){\n win_perc*=2;\n ch->sendTo(\"You win! Your winnings are now at %i talens.\\n\\r\",\n\t (int)((float)bet * (1.0 + win_perc)));\n ssprintf(buf, \"$n wins! $n's winnings are now at %i talens.\",\n\t (int)((float)bet * (1.0 + win_perc)));\n act(buf.c_str(), TRUE, ch, 0, 0, TO_ROOM); \n observerReaction(ch, GAMBLER_HILO_BET);\n } else {\n ch->sendTo(\"You lose!\\n\\r\");\n act(\"$n loses!\", TRUE, ch, 0, 0, TO_ROOM);\n observerReaction(ch, GAMBLER_LOST);\n bet = 0;\n card = 0;\n }\n}\n\nvoid HiLoGame::BetLo(TBeing *ch, int new_card)\n{\n sstring buf;\n\n if(CARD_NUM_ACEHI(new_card) < CARD_NUM_ACEHI(card)){\n win_perc*=2;\n ch->sendTo(\"You win! Your winnings are now at %i talens.\\n\\r\",\n\t (int)((float)bet * (1.0 + win_perc)));\n ssprintf(buf, \"$n wins! $n's winnings are now at %i talens.\",\n\t (int)((float)bet * (1.0 + win_perc)));\n act(buf.c_str(), TRUE, ch, 0, 0, TO_ROOM); \n observerReaction(ch, GAMBLER_HILO_BET);\n } else {\n ch->sendTo(\"You lose!\\n\\r\");\n act(\"$n loses!\", TRUE, ch, 0, 0, TO_ROOM);\n observerReaction(ch, GAMBLER_LOST);\n bet = 0;\n card = 0;\n }\n}\n\nvoid HiLoGame::stay(TBeing *ch)\n{\n if(win_perc==WIN_INIT){\n ch->sendTo(\"You just started, you can't quit now!\\n\\r\");\n return;\n }\n\n ch->sendTo(\"You give up and cash out your winnings.\\n\\r\");\n act(\"$n gives up and cashes out $s winnings.\",\n TRUE, ch, 0, 0, TO_ROOM);\n\n int next_card=deck[deck_inx++];\n sstring buf;\n ch->sendTo(COLOR_BASIC, \"The next card was the %s.\\n\\r\", pretty_card_printout(ch, next_card).c_str());\n ssprintf(buf, \"The next card was the %s.\", pretty_card_printout(ch, next_card).c_str());\n act(buf.c_str(), TRUE, ch, 0, 0, TO_ROOM);\n\n payout(ch, (int)((double)bet * (1.0 + win_perc)));\n bet = 0;\n card = 0;\n observerReaction(ch, GAMBLER_WON);\n}\n\n\nvoid HiLoGame::Bet(TBeing *ch, const sstring &arg)\n{\n int inx, new_card;\n sstring coin_str;\n sstring log_msg;\n sstring buf;\n TObj *chip;\n\n if (ch->checkHiLo()) {\n inx = index(ch);\n if (inx < 0) {\n ch->sendTo(\"You are not sitting at the table yet.\\n\\r\");\n return;\n }\n if (bet > 0) {\n if(arg==\"hi\" || arg==\"lo\"){\n\tif (deck_inx > 10)\n\t hilo_shuffle(ch);\n\t\n\tnew_card=deck[deck_inx++];\n\t\n\tssprintf(buf, \"$n bets %s.\", arg.c_str());\n\tact(buf.c_str(), TRUE, ch, 0, 0, TO_ROOM);\n\t\n\tssprintf(log_msg, \"You are dealt:\\n\\r%s\\n\\r\", pretty_card_printout(ch, new_card).c_str());\n\tch->sendTo(COLOR_BASIC, log_msg.c_str());\n\t\n\tssprintf(log_msg, \"$n is dealt:\\n\\r%s\", pretty_card_printout(ch, new_card).c_str());\n\tact(log_msg.c_str(), TRUE, ch, 0, 0, TO_ROOM);\n\t\n\tif(arg==\"hi\"){\n\t BetHi(ch, new_card);\n\t} else if(arg==\"lo\"){\n\t BetLo(ch, new_card);\n\t}\n\tcard=new_card;\n\treturn;\n } else {\n\tch->sendTo(\"You can't change your bet now.\\n\\r\");\n\tch->sendTo(\"You must either bet 'hi' or 'lo' for the next card.\\n\\r\");\n\treturn;\n }\n }\n argument_parser(arg, coin_str);\n if (coin_str.empty()){\n ch->sendTo(\"Bet which chip?\\n\\r\");\n return;\n }\n\n if(!(chip=find_chip(ch, coin_str))){\n ch->sendTo(\"You don't have that chip!\\n\\r\");\n return;\n }\n\n bet = chip->obj_flags.cost;\n ch->doSave(SILENT_YES);\n\n sstring buf;\n ssprintf(buf, \"$n bets %s.\", chip->getName());\n act(buf.c_str(), TRUE, ch, 0, 0, TO_ROOM);\n ssprintf(buf, \"You bet %s.\", chip->getName());\n act(buf.c_str(), TRUE, ch, 0, 0, TO_CHAR);\n\n (*chip)--;\n delete chip;\n\n win_perc=WIN_INIT;\n card=0;\n if (deck_inx > 10)\n hilo_shuffle(ch);\n\n card = deck[deck_inx++];\n\n ssprintf(log_msg, \"You are dealt:\\n\\r%s\\n\\r\", pretty_card_printout(ch, card).c_str());\n ch->sendTo(COLOR_BASIC, log_msg.c_str());\n\n ssprintf(log_msg, \"$n is dealt:\\n\\r%s\\n\\r\", pretty_card_printout(ch, card).c_str());\n act(log_msg.c_str(), TRUE, ch, 0, 0, TO_ROOM);\n\n observerReaction(ch, GAMBLER_HILO_BET);\n }\n}\n\n\nvoid HiLoGame::peek(const TBeing *ch) const\n{\n sstring log_msg;\n\n if (index(ch) < 0) {\n ch->sendTo(\"You are not sitting at the table yet.\\n\\r\");\n return;\n }\n if (!bet) {\n ch->sendTo(\"You are not playing a game.\\n\\r\");\n return;\n }\n ssprintf(log_msg, \"You peek at your hand:\\n\\r%s\\n\\r\", pretty_card_printout(ch, card).c_str());\n ch->sendTo(COLOR_BASIC, log_msg.c_str());\n}\n\n\nint HiLoGame::exitGame(const TBeing *ch)\n{\n int inx;\n\n if ((inx = index(ch)) < 0) {\n forceCrash(\"%s left a table he was not at!\", ch->name);\n return FALSE;\n }\n inuse = FALSE;\n name=\"\";\n deck_inx = 0;\n bet = 0;\n card = 0;\n win_perc=0;\n setup_deck();\n ch->sendTo(\"You leave the hi-lo table.\\n\\r\");\n return TRUE;\n}\n\n\nint HiLoGame::index(const TBeing *ch) const\n{\n if(ch->name == name)\n return 0;\n\n return -1;\n}\nlimited winnings on hi-lo#include \"stdsneezy.h\"\n#include \"games.h\"\n\nHiLoGame gHiLo;\n\nconst float WIN_INIT=0.05;\nbool HiLoGame::enter(const TBeing *ch)\n{\n if(inuse){\n ch->sendTo(\"This table is already in use.\\n\\r\");\n return false;\n }\n\n inuse = true;\n hilo_shuffle(ch);\n bet = 0;\n name=ch->name;\n\n return true;\n}\n\nvoid HiLoGame::hilo_shuffle(const TBeing *ch)\n{\n act(\"The dealer shuffles the deck.\",FALSE, ch, 0, 0, TO_CHAR);\n act(\"The dealer shuffles the deck.\",FALSE, ch, 0, 0, TO_ROOM);\n\n shuffle();\n deck_inx = 0;\n}\n\nbool TBeing::checkHiLo(bool inGame = false) const\n{\n if (in_room == ROOM_HILO && (inGame || (gHiLo.index(this) > -1)))\n return true;\n else\n return false;\n}\n\nvoid HiLoGame::BetHi(TBeing *ch, int new_card)\n{\n sstring buf;\n\n if(CARD_NUM_ACEHI(new_card) > CARD_NUM_ACEHI(card)){\n win_perc*=2;\n ch->sendTo(\"You win! Your winnings are now at %i talens.\\n\\r\",\n\t (int)((float)bet * (1.0 + win_perc)));\n ssprintf(buf, \"$n wins! $n's winnings are now at %i talens.\",\n\t (int)((float)bet * (1.0 + win_perc)));\n act(buf.c_str(), TRUE, ch, 0, 0, TO_ROOM); \n observerReaction(ch, GAMBLER_HILO_BET);\n\n if(win_perc > 10){\n ch->sendTo(\"You've reach the win limit.\\n\\r\");\n stay(ch);\n }\n\n } else {\n ch->sendTo(\"You lose!\\n\\r\");\n act(\"$n loses!\", TRUE, ch, 0, 0, TO_ROOM);\n observerReaction(ch, GAMBLER_LOST);\n bet = 0;\n card = 0;\n }\n}\n\nvoid HiLoGame::BetLo(TBeing *ch, int new_card)\n{\n sstring buf;\n\n if(CARD_NUM_ACEHI(new_card) < CARD_NUM_ACEHI(card)){\n win_perc*=2;\n ch->sendTo(\"You win! Your winnings are now at %i talens.\\n\\r\",\n\t (int)((float)bet * (1.0 + win_perc)));\n ssprintf(buf, \"$n wins! $n's winnings are now at %i talens.\",\n\t (int)((float)bet * (1.0 + win_perc)));\n act(buf.c_str(), TRUE, ch, 0, 0, TO_ROOM); \n observerReaction(ch, GAMBLER_HILO_BET);\n\n if(win_perc > 10){\n ch->sendTo(\"You've reach the win limit.\\n\\r\");\n stay(ch);\n }\n\n } else {\n ch->sendTo(\"You lose!\\n\\r\");\n act(\"$n loses!\", TRUE, ch, 0, 0, TO_ROOM);\n observerReaction(ch, GAMBLER_LOST);\n bet = 0;\n card = 0;\n }\n}\n\nvoid HiLoGame::stay(TBeing *ch)\n{\n if(win_perc==WIN_INIT){\n ch->sendTo(\"You just started, you can't quit now!\\n\\r\");\n return;\n }\n\n ch->sendTo(\"You give up and cash out your winnings.\\n\\r\");\n act(\"$n gives up and cashes out $s winnings.\",\n TRUE, ch, 0, 0, TO_ROOM);\n\n int next_card=deck[deck_inx++];\n sstring buf;\n ch->sendTo(COLOR_BASIC, \"The next card was the %s.\\n\\r\", pretty_card_printout(ch, next_card).c_str());\n ssprintf(buf, \"The next card was the %s.\", pretty_card_printout(ch, next_card).c_str());\n act(buf.c_str(), TRUE, ch, 0, 0, TO_ROOM);\n\n payout(ch, (int)((double)bet * (1.0 + win_perc)));\n bet = 0;\n card = 0;\n observerReaction(ch, GAMBLER_WON);\n}\n\n\nvoid HiLoGame::Bet(TBeing *ch, const sstring &arg)\n{\n int inx, new_card;\n sstring coin_str;\n sstring log_msg;\n sstring buf;\n TObj *chip;\n\n if (ch->checkHiLo()) {\n inx = index(ch);\n if (inx < 0) {\n ch->sendTo(\"You are not sitting at the table yet.\\n\\r\");\n return;\n }\n if (bet > 0) {\n if(arg==\"hi\" || arg==\"lo\"){\n\tif (deck_inx > 10)\n\t hilo_shuffle(ch);\n\t\n\tnew_card=deck[deck_inx++];\n\t\n\tssprintf(buf, \"$n bets %s.\", arg.c_str());\n\tact(buf.c_str(), TRUE, ch, 0, 0, TO_ROOM);\n\t\n\tssprintf(log_msg, \"You are dealt:\\n\\r%s\\n\\r\", pretty_card_printout(ch, new_card).c_str());\n\tch->sendTo(COLOR_BASIC, log_msg.c_str());\n\t\n\tssprintf(log_msg, \"$n is dealt:\\n\\r%s\", pretty_card_printout(ch, new_card).c_str());\n\tact(log_msg.c_str(), TRUE, ch, 0, 0, TO_ROOM);\n\t\n\tif(arg==\"hi\"){\n\t BetHi(ch, new_card);\n\t} else if(arg==\"lo\"){\n\t BetLo(ch, new_card);\n\t}\n\tcard=new_card;\n\treturn;\n } else {\n\tch->sendTo(\"You can't change your bet now.\\n\\r\");\n\tch->sendTo(\"You must either bet 'hi' or 'lo' for the next card.\\n\\r\");\n\treturn;\n }\n }\n argument_parser(arg, coin_str);\n if (coin_str.empty()){\n ch->sendTo(\"Bet which chip?\\n\\r\");\n return;\n }\n\n if(!(chip=find_chip(ch, coin_str))){\n ch->sendTo(\"You don't have that chip!\\n\\r\");\n return;\n }\n\n bet = chip->obj_flags.cost;\n ch->doSave(SILENT_YES);\n\n sstring buf;\n ssprintf(buf, \"$n bets %s.\", chip->getName());\n act(buf.c_str(), TRUE, ch, 0, 0, TO_ROOM);\n ssprintf(buf, \"You bet %s.\", chip->getName());\n act(buf.c_str(), TRUE, ch, 0, 0, TO_CHAR);\n\n (*chip)--;\n delete chip;\n\n win_perc=WIN_INIT;\n card=0;\n if (deck_inx > 10)\n hilo_shuffle(ch);\n\n card = deck[deck_inx++];\n\n ssprintf(log_msg, \"You are dealt:\\n\\r%s\\n\\r\", pretty_card_printout(ch, card).c_str());\n ch->sendTo(COLOR_BASIC, log_msg.c_str());\n\n ssprintf(log_msg, \"$n is dealt:\\n\\r%s\\n\\r\", pretty_card_printout(ch, card).c_str());\n act(log_msg.c_str(), TRUE, ch, 0, 0, TO_ROOM);\n\n observerReaction(ch, GAMBLER_HILO_BET);\n }\n}\n\n\nvoid HiLoGame::peek(const TBeing *ch) const\n{\n sstring log_msg;\n\n if (index(ch) < 0) {\n ch->sendTo(\"You are not sitting at the table yet.\\n\\r\");\n return;\n }\n if (!bet) {\n ch->sendTo(\"You are not playing a game.\\n\\r\");\n return;\n }\n ssprintf(log_msg, \"You peek at your hand:\\n\\r%s\\n\\r\", pretty_card_printout(ch, card).c_str());\n ch->sendTo(COLOR_BASIC, log_msg.c_str());\n}\n\n\nint HiLoGame::exitGame(const TBeing *ch)\n{\n int inx;\n\n if ((inx = index(ch)) < 0) {\n forceCrash(\"%s left a table he was not at!\", ch->name);\n return FALSE;\n }\n inuse = FALSE;\n name=\"\";\n deck_inx = 0;\n bet = 0;\n card = 0;\n win_perc=0;\n setup_deck();\n ch->sendTo(\"You leave the hi-lo table.\\n\\r\");\n return TRUE;\n}\n\n\nint HiLoGame::index(const TBeing *ch) const\n{\n if(ch->name == name)\n return 0;\n\n return -1;\n}\n<|endoftext|>"} {"text":"\/\/ RUN: clang-cc -fsyntax-only -verify %s\n\ntemplate class A;\n\nextern \"C++\" {\n template class B;\n}\n\nnamespace N {\n template class C;\n}\n\nextern \"C\" {\n template class D; \/\/ expected-error{{templates must have C++ linkage}}\n}\n\ntemplate class A; \/\/ expected-note{{previous template declaration is here}}\n\ntemplate class A; \/\/ expected-error{{template parameter has a different kind in template redeclaration}}\n\ntemplate class NonTypeTemplateParm;\n\ntypedef int INT;\n\ntemplate class NonTypeTemplateParm; \/\/ expected-note{{previous non-type template parameter with type 'INT' (aka 'int') is here}}\n\ntemplate class NonTypeTemplateParm; \/\/ expected-error{{template non-type parameter has a different type 'long' in template redeclaration}}\n\ntemplate class X> class TemplateTemplateParm;\n\ntemplate class Y> class TemplateTemplateParm; \/\/ expected-note{{previous template declaration is here}} \\\n \/\/ expected-note{{previous template template parameter is here}}\n\ntemplate class TemplateTemplateParm; \/\/ expected-error{{template parameter has a different kind in template redeclaration}}\n\ntemplate class X> class TemplateTemplateParm; \/\/ expected-error{{too many template parameters in template template parameter redeclaration}}\n\ntemplate\nstruct test {}; \/\/ expected-note{{previous definition}}\n\ntemplate\nstruct test : T {}; \/\/ expected-error{{redefinition}}\n\n#if 0\n\/\/ FIXME: parse template declarations in these scopes, so that we can\n\/\/ complain about the one at function scope.\nclass X {\npublic:\n template class C;\n};\n\nvoid f() {\n template class X;\n}\n#endif\nDe-FIXME a test\/\/ RUN: clang-cc -fsyntax-only -verify %s\n\ntemplate class A;\n\nextern \"C++\" {\n template class B;\n}\n\nnamespace N {\n template class C;\n}\n\nextern \"C\" {\n template class D; \/\/ expected-error{{templates must have C++ linkage}}\n}\n\ntemplate class A; \/\/ expected-note{{previous template declaration is here}}\n\ntemplate class A; \/\/ expected-error{{template parameter has a different kind in template redeclaration}}\n\ntemplate class NonTypeTemplateParm;\n\ntypedef int INT;\n\ntemplate class NonTypeTemplateParm; \/\/ expected-note{{previous non-type template parameter with type 'INT' (aka 'int') is here}}\n\ntemplate class NonTypeTemplateParm; \/\/ expected-error{{template non-type parameter has a different type 'long' in template redeclaration}}\n\ntemplate class X> class TemplateTemplateParm;\n\ntemplate class Y> class TemplateTemplateParm; \/\/ expected-note{{previous template declaration is here}} \\\n \/\/ expected-note{{previous template template parameter is here}}\n\ntemplate class TemplateTemplateParm; \/\/ expected-error{{template parameter has a different kind in template redeclaration}}\n\ntemplate class X> class TemplateTemplateParm; \/\/ expected-error{{too many template parameters in template template parameter redeclaration}}\n\ntemplate\nstruct test {}; \/\/ expected-note{{previous definition}}\n\ntemplate\nstruct test : T {}; \/\/ expected-error{{redefinition}}\n\nclass X {\npublic:\n template class C;\n};\n\nvoid f() {\n template class X; \/\/ expected-error{{expression}}\n}\n<|endoftext|>"} {"text":"#define OROCOS_TARGET gnulinux\n#include \n#include \n#include \"Types.hpp\"\n#include \"Plugin.hpp\"\n#include \"opaque.h\"\n\n#ifdef WITH_CORBA\n#include \n#include \n#include \n#include \"build\/.orogen\/typekit\/transports\/corba\/opaqueTypesC.h\"\n#include \".orogen\/typekit\/transports\/corba\/TransportPlugin.hpp\"\n#endif\n\n#ifdef WITH_TYPELIB\n#include \"transports\/typelib\/TransportPlugin.hpp\"\n#include \".orogen\/typekit\/transports\/typelib\/TypelibMarshallerBase.hpp\"\n#endif\n\n#include \".orogen\/typekit\/OpaqueConvertions.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace RTT;\nusing namespace RTT::types;\nusing namespace RTT::internal;\nusing namespace RTT::marsh;\nusing namespace opaque;\nusing std::cerr;\nusing std::endl;\n\nnamespace TestOpaque {\n inline std::ostream& operator << (std::ostream& io, Position_m const& data) {\n io << \"{ .timestamp = \" << data.timestamp << \", .p.x\" << data.p.x << \", .p.y\" << data.p.y << \"}\";\n return io;\n }\n}\nnamespace std {\n extern std::ostream& operator << (std::ostream& io, std::vector const& data);\n extern std::ostream& operator << (std::ostream& io, std::vector const& data);\n}\ntemplate\nT identity(T const& value) { return value; }\n\n#ifdef WITH_TYPELIB\ntemplate\nvoid from_intermediate(OrocosType& orocos_value, TypelibType& typelib_value)\n{\n ValueDataSource* data_source\n = new ValueDataSource();\n data_source->ref();\n\n TypeInfo const* type = data_source->getTypeInfo();\n orogen_transports::TypelibMarshallerBase* transport =\n dynamic_cast(type->getProtocol(orogen_transports::TYPELIB_MARSHALLER_ID));\n\n orogen_transports::TypelibMarshallerBase::Handle* handle =\n transport->createSample();\n transport->setTypelibSample(handle, reinterpret_cast(&typelib_value));\n transport->writeDataSource(*data_source, handle);\n orocos_value = data_source->get();\n\n transport->deleteHandle(handle);\n data_source->deref();\n}\n\ntemplate\nbool generic_typelib_test(T const& testValue, TypeInfo const& ti, Getter get_test_value)\n{\n cerr << \"- testing Typelib marshalling\/unmarshalling ...\" << endl;\n ConstantDataSource* source\n = new ConstantDataSource(testValue);\n source->ref();\n\n orogen_transports::TypelibMarshallerBase* transport =\n dynamic_cast(ti.getProtocol(orogen_transports::TYPELIB_MARSHALLER_ID));\n\n std::vector buffer;\n orogen_transports::TypelibMarshallerBase::Handle* handle =\n transport->createSample();\n transport->readDataSource(*source, handle);\n transport->marshal(buffer, handle);\n transport->deleteHandle(handle);\n source->deref();\n\n handle = transport->createSample();\n transport->unmarshal(buffer, handle);\n ValueDataSource unmarshalled;\n transport->writeDataSource(unmarshalled, handle);\n transport->deleteHandle(handle);\n\n if (!(get_test_value(unmarshalled.get()) == get_test_value(testValue)))\n {\n cerr << \"unmarshalled Typelib data does not match original data\" << endl;\n return false;\n }\n return true;\n}\n#endif\n\n\/* This is a generic test of type handling.\n * - it marshals the type into a XML file. This file can then be compared\n * with an expected content by the Ruby test case.\n * - it does the same with a CPF file\n * - it unmarshals the CPF file and checks that both values are equal\n * - if the test is done with CORBA, it also converts to\/from any and compares\n * the two values.\n *\/\ntemplate\nbool generic_type_handling_test(std::string const& name, T const& testValue, TypeInfo const& ti,\n Getter get_test_value)\n{\n ConstantDataSource* source\n = new ConstantDataSource(testValue);\n source->ref();\n\n std::cerr << \"disabled XML decomposition\/recomposition test\" << std::endl;\n\n \/\/PropertyBag bag;\n \/\/ti.decomposeType(source, bag);\n\n \/\/\/\/ First, save it into XML. The Ruby test case will compare that to an\n \/\/\/\/ expected XML document\n \/\/std::ofstream xml_file((name + \".xml\").c_str());\n \/\/XMLMarshaller xml_output(xml_file);\n \/\/xml_output.serialize(bag);\n\n \/\/\/\/ Now, marshal it to the standard Orocos format, reload it and compare\n \/\/\/\/ the result\n \/\/PropertyMarshaller cpf_output(name + \".cpf\");\n \/\/cpf_output.serialize(bag);\n \/\/cpf_output.flush();\n\n \/\/PropertyBag input_bag;\n \/\/PropertyDemarshaller cpf_input(name + \".cpf\");\n \/\/cpf_input.deserialize(input_bag);\n\n \/\/cerr << \"Testing PropertyBag composition\" << endl;\n \/\/{ ValueDataSource* reader = new ValueDataSource();\n \/\/ reader->ref();\n \/\/ Property bag(\"\", \"\", input_bag);\n \/\/ if (!ti.composeType(bag.getDataSource(), reader))\n \/\/ {\n \/\/ cerr << \"cannot recompose type\" << endl;\n \/\/ return false;\n \/\/ }\n\n \/\/ T value = reader->get();\n \/\/ if (!(get_test_value(value) == get_test_value(testValue)))\n \/\/ {\n \/\/ cerr << \"error. Expected\\n\\n\" << get_test_value(testValue) <<\n \/\/ \"\\n\\nand got\\n\\n\" << get_test_value(value) << endl;\n \/\/ }\n \/\/ reader->deref();\n \/\/}\n\n#ifdef WITH_CORBA\n std::cerr << \"Testing CORBA marshalling\/unmarshalling ...\" << std::endl;\n { RTT::corba::CorbaTypeTransporter* transport =\n dynamic_cast(ti.getProtocol(ORO_CORBA_PROTOCOL_ID));\n\n CORBA::Any* result = transport->createAny(source);\n\n ValueDataSource* reader = new ValueDataSource();\n reader->ref();\n transport->updateFromAny(result, reader);\n\n T value = reader->get();\n if (!(get_test_value(value) == get_test_value(testValue)))\n {\n cerr << \"error in CORBA marshalling\/demarshalling\" << endl;\n return false;\n }\n delete result;\n reader->deref();\n }\n#endif\n\n#ifdef WITH_TYPELIB\n if (!generic_typelib_test(testValue, ti, get_test_value))\n return false;\n#endif\n\n source->deref();\n return true;\n}\n\nbool test_plain_opaque()\n{\n cerr << \"\\n======== Testing plain opaque handling ========\" << endl;\n\n TypeInfoRepository::shared_ptr ti = TypeInfoRepository::Instance();\n TypeInfo* type = ti->type(\"\/NotOrogenCompatible\/Point2D\");\n if (! type)\n {\n\tcerr << \"cannot find \/NotOrogenCompatible\/Point2D in the type info repository\" << endl;\n\treturn false;\n }\n\n std::cerr << \"Testing the initialization of the types from an intermediate...\" << std::endl;\n {\n TestOpaque::Point2D testValue = { 100, 20, 30 };\n NotOrogenCompatible::Point2D p(0, 0);\n from_intermediate(p, testValue);\n\n if (testValue.x != p.x() || testValue.y != p.y())\n {\n cerr << \"error in Typelib marshalling\" << endl;\n return false;\n }\n }\n\n\n NotOrogenCompatible::Point2D testValue(10, 20);\n if (!generic_type_handling_test(\"opaque\", testValue, *type, &::identity ))\n return false;\n\n return true;\n}\n\nbool test_composed_opaque()\n{\n cerr << \"\\n======== Testing opaque field in struct ========\" << endl;\n\n TypeInfoRepository::shared_ptr ti = TypeInfoRepository::Instance();\n TypeInfo* type = ti->type(\"\/TestOpaque\/Position\");\n if (! type)\n {\n\tcerr << \"cannot find \/TestOpaque\/Position in the type info repository\" << endl;\n\treturn 1;\n }\n\n TestOpaque::Position testValue;\n testValue.timestamp = 10;\n testValue.p.x() = 20;\n testValue.p.y() = 30;\n\n generic_type_handling_test(\"composed_opaque\", testValue, *type, &::identity );\n\n std::cerr << \"Testing the initialization of the types from an intermediate...\" << std::endl;\n {\n TestOpaque::Position_m testValue = { 100, 20, 30 };\n TestOpaque::Position p;\n memset(&p, 0, sizeof(p));\n from_intermediate(p, testValue);\n\n if (testValue.timestamp != p.timestamp || testValue.p.x != p.p.x() || testValue.p.y != p.p.y())\n {\n cerr << \"error in Typelib marshalling\" << endl;\n return false;\n }\n }\n\n return true;\n}\n\ntemplate\nT get_ptr_content(boost::shared_ptr const& left)\n{ return *left; }\n\ntemplate\nT get_ro_ptr_content(RTT::extras::ReadOnlyPointer const& left)\n{ return *left; }\n\nbool test_shared_pointer()\n{\n cerr << \"\\n======== Testing shared pointer ========\" << endl;\n\n TypeInfoRepository::shared_ptr ti = TypeInfoRepository::Instance();\n TypeInfo* type = ti->type(\"\/boost\/shared_ptr<\/std\/vector<\/float>>\");\n if (! type)\n {\n\tcerr << \"cannot find \/boost\/shared_ptr<\/std\/vector<\/float>> in the type info repository\" << endl;\n\treturn 1;\n }\n\n boost::shared_ptr< std::vector > testValue( new std::vector );\n std::vector& data = *testValue;\n\n for (int i = 0; i < 10; ++i)\n data.push_back(i);\n\n generic_type_handling_test(\"shared_ptr__opaque_type\", testValue, *type, &get_ptr_content< std::vector >);\n\n std::cerr << \"Testing the initialization of the types from an intermediate...\" << std::endl;\n {\n boost::shared_ptr< std::vector > result;\n from_intermediate(result, *testValue);\n\n for (int i = 0; i < data.size(); ++i)\n if ((*result)[i] != (*testValue)[i])\n {\n cerr << \"error in type initialization from an intermediate\" << endl;\n return false;\n }\n }\n\n return true;\n}\n\nbool test_shared_ptr_shortcut()\n{\n cerr << \"\\n======== Testing shared pointer (from #shared_ptr) ========\" << endl;\n\n TypeInfoRepository::shared_ptr ti = TypeInfoRepository::Instance();\n TypeInfo* type = ti->type(\"\/boost\/shared_ptr<\/std\/vector<\/int>>\");\n if (! type)\n {\n\tcerr << \"cannot find \/boost\/shared_ptr<\/std\/vector<\/int>> in the type info repository\" << endl;\n\treturn 1;\n }\n\n boost::shared_ptr< std::vector > testValue( new std::vector );\n std::vector& data = *testValue;\n\n for (int i = 0; i < 10; ++i)\n data.push_back(i);\n\n\n generic_type_handling_test(\"shared_ptr__shared_ptr\", testValue, *type, &get_ptr_content< std::vector >);\n\n std::cerr << \"Testing the initialization of the types from an intermediate...\" << std::endl;\n {\n boost::shared_ptr< std::vector > result;\n from_intermediate(result, data);\n\n for (int i = 0; i < data.size(); ++i)\n if ((*result)[i] != (*testValue)[i])\n {\n cerr << \"error in type initialization from an intermediate\" << endl;\n return false;\n }\n }\n\n return true;\n}\n\nbool test_ro_ptr()\n{\n cerr << \"\\n======== Testing ReadOnlyPointer (from #ro_ptr) ========\" << endl;\n\n TypeInfoRepository::shared_ptr ti = TypeInfoRepository::Instance();\n TypeInfo* type = ti->type(\"\/RTT\/extras\/ReadOnlyPointer<\/std\/vector<\/int>>\");\n if (! type)\n {\n\tcerr << \"cannot find \/RTT\/extras\/ReadOnlyPointer<\/std\/vector<\/int>> in the type info repository\" << endl;\n\treturn 1;\n }\n\n std::vector* data = new std::vector();\n for (int i = 0; i < 10; ++i)\n data->push_back(i);\n\n RTT::extras::ReadOnlyPointer< std::vector > testValue(data);\n\n\n generic_type_handling_test(\"readonlypointer\", testValue, *type, &get_ro_ptr_content< std::vector >);\n\n std::cerr << \"Testing the initialization of the types from an intermediate...\" << std::endl;\n {\n RTT::extras::ReadOnlyPointer< std::vector > result;\n from_intermediate(result, *data);\n\n for (int i = 0; i < data->size(); ++i)\n if ((*result)[i] != (*testValue)[i])\n {\n cerr << \"error in type initialization from an intermediate\" << endl;\n return false;\n }\n }\n\n return true;\n}\n\n\nint ORO_main(int argc, char** argv)\n{\n log().setLogLevel( Logger::Debug );\n RTT::types::TypekitRepository::Import( new RTT::types::RealTimeTypekitPlugin );\n RTT::types::TypekitRepository::Import( new orogen_typekits::opaqueTypekitPlugin );\n#ifdef WITH_CORBA\n RTT::types::TypekitRepository::Import( new orogen_typekits::opaqueCorbaTransportPlugin );\n#endif\n#ifdef WITH_TYPELIB\n RTT::types::TypekitRepository::Import( new orogen_typekits::opaqueTypelibTransportPlugin );\n#endif\n\n if (!test_plain_opaque())\n {\n cerr << \"plain_opaque failed\" << endl;\n return 1;\n }\n if (!test_composed_opaque())\n {\n cerr << \"composed_opaque failed\" << endl;\n return 1;\n }\n if (!test_shared_pointer())\n {\n cerr << \"shared_ptr failed\" << endl;\n return 1;\n }\n if (!test_shared_ptr_shortcut())\n {\n cerr << \"shared_ptr (from #shared_ptr) failed\" << endl;\n return 1;\n }\n if (!test_ro_ptr())\n {\n cerr << \"ReadOnlyPointer failed\" << endl;\n return 1;\n }\n\n return 0;\n}\n\nopaque.h does not exist anymore#define OROCOS_TARGET gnulinux\n#include \n#include \n#include \"Types.hpp\"\n#include \"Plugin.hpp\"\n\n#ifdef WITH_CORBA\n#include \n#include \n#include \n#include \"build\/.orogen\/typekit\/transports\/corba\/opaqueTypesC.h\"\n#include \".orogen\/typekit\/transports\/corba\/TransportPlugin.hpp\"\n#endif\n\n#ifdef WITH_TYPELIB\n#include \"transports\/typelib\/TransportPlugin.hpp\"\n#include \".orogen\/typekit\/transports\/typelib\/TypelibMarshallerBase.hpp\"\n#endif\n\n#include \".orogen\/typekit\/OpaqueConvertions.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace RTT;\nusing namespace RTT::types;\nusing namespace RTT::internal;\nusing namespace RTT::marsh;\nusing namespace opaque;\nusing std::cerr;\nusing std::endl;\n\nnamespace TestOpaque {\n inline std::ostream& operator << (std::ostream& io, Position_m const& data) {\n io << \"{ .timestamp = \" << data.timestamp << \", .p.x\" << data.p.x << \", .p.y\" << data.p.y << \"}\";\n return io;\n }\n}\nnamespace std {\n extern std::ostream& operator << (std::ostream& io, std::vector const& data);\n extern std::ostream& operator << (std::ostream& io, std::vector const& data);\n}\ntemplate\nT identity(T const& value) { return value; }\n\n#ifdef WITH_TYPELIB\ntemplate\nvoid from_intermediate(OrocosType& orocos_value, TypelibType& typelib_value)\n{\n ValueDataSource* data_source\n = new ValueDataSource();\n data_source->ref();\n\n TypeInfo const* type = data_source->getTypeInfo();\n orogen_transports::TypelibMarshallerBase* transport =\n dynamic_cast(type->getProtocol(orogen_transports::TYPELIB_MARSHALLER_ID));\n\n orogen_transports::TypelibMarshallerBase::Handle* handle =\n transport->createSample();\n transport->setTypelibSample(handle, reinterpret_cast(&typelib_value));\n transport->writeDataSource(*data_source, handle);\n orocos_value = data_source->get();\n\n transport->deleteHandle(handle);\n data_source->deref();\n}\n\ntemplate\nbool generic_typelib_test(T const& testValue, TypeInfo const& ti, Getter get_test_value)\n{\n cerr << \"- testing Typelib marshalling\/unmarshalling ...\" << endl;\n ConstantDataSource* source\n = new ConstantDataSource(testValue);\n source->ref();\n\n orogen_transports::TypelibMarshallerBase* transport =\n dynamic_cast(ti.getProtocol(orogen_transports::TYPELIB_MARSHALLER_ID));\n\n std::vector buffer;\n orogen_transports::TypelibMarshallerBase::Handle* handle =\n transport->createSample();\n transport->readDataSource(*source, handle);\n transport->marshal(buffer, handle);\n transport->deleteHandle(handle);\n source->deref();\n\n handle = transport->createSample();\n transport->unmarshal(buffer, handle);\n ValueDataSource unmarshalled;\n transport->writeDataSource(unmarshalled, handle);\n transport->deleteHandle(handle);\n\n if (!(get_test_value(unmarshalled.get()) == get_test_value(testValue)))\n {\n cerr << \"unmarshalled Typelib data does not match original data\" << endl;\n return false;\n }\n return true;\n}\n#endif\n\n\/* This is a generic test of type handling.\n * - it marshals the type into a XML file. This file can then be compared\n * with an expected content by the Ruby test case.\n * - it does the same with a CPF file\n * - it unmarshals the CPF file and checks that both values are equal\n * - if the test is done with CORBA, it also converts to\/from any and compares\n * the two values.\n *\/\ntemplate\nbool generic_type_handling_test(std::string const& name, T const& testValue, TypeInfo const& ti,\n Getter get_test_value)\n{\n ConstantDataSource* source\n = new ConstantDataSource(testValue);\n source->ref();\n\n std::cerr << \"disabled XML decomposition\/recomposition test\" << std::endl;\n\n \/\/PropertyBag bag;\n \/\/ti.decomposeType(source, bag);\n\n \/\/\/\/ First, save it into XML. The Ruby test case will compare that to an\n \/\/\/\/ expected XML document\n \/\/std::ofstream xml_file((name + \".xml\").c_str());\n \/\/XMLMarshaller xml_output(xml_file);\n \/\/xml_output.serialize(bag);\n\n \/\/\/\/ Now, marshal it to the standard Orocos format, reload it and compare\n \/\/\/\/ the result\n \/\/PropertyMarshaller cpf_output(name + \".cpf\");\n \/\/cpf_output.serialize(bag);\n \/\/cpf_output.flush();\n\n \/\/PropertyBag input_bag;\n \/\/PropertyDemarshaller cpf_input(name + \".cpf\");\n \/\/cpf_input.deserialize(input_bag);\n\n \/\/cerr << \"Testing PropertyBag composition\" << endl;\n \/\/{ ValueDataSource* reader = new ValueDataSource();\n \/\/ reader->ref();\n \/\/ Property bag(\"\", \"\", input_bag);\n \/\/ if (!ti.composeType(bag.getDataSource(), reader))\n \/\/ {\n \/\/ cerr << \"cannot recompose type\" << endl;\n \/\/ return false;\n \/\/ }\n\n \/\/ T value = reader->get();\n \/\/ if (!(get_test_value(value) == get_test_value(testValue)))\n \/\/ {\n \/\/ cerr << \"error. Expected\\n\\n\" << get_test_value(testValue) <<\n \/\/ \"\\n\\nand got\\n\\n\" << get_test_value(value) << endl;\n \/\/ }\n \/\/ reader->deref();\n \/\/}\n\n#ifdef WITH_CORBA\n std::cerr << \"Testing CORBA marshalling\/unmarshalling ...\" << std::endl;\n { RTT::corba::CorbaTypeTransporter* transport =\n dynamic_cast(ti.getProtocol(ORO_CORBA_PROTOCOL_ID));\n\n CORBA::Any* result = transport->createAny(source);\n\n ValueDataSource* reader = new ValueDataSource();\n reader->ref();\n transport->updateFromAny(result, reader);\n\n T value = reader->get();\n if (!(get_test_value(value) == get_test_value(testValue)))\n {\n cerr << \"error in CORBA marshalling\/demarshalling\" << endl;\n return false;\n }\n delete result;\n reader->deref();\n }\n#endif\n\n#ifdef WITH_TYPELIB\n if (!generic_typelib_test(testValue, ti, get_test_value))\n return false;\n#endif\n\n source->deref();\n return true;\n}\n\nbool test_plain_opaque()\n{\n cerr << \"\\n======== Testing plain opaque handling ========\" << endl;\n\n TypeInfoRepository::shared_ptr ti = TypeInfoRepository::Instance();\n TypeInfo* type = ti->type(\"\/NotOrogenCompatible\/Point2D\");\n if (! type)\n {\n\tcerr << \"cannot find \/NotOrogenCompatible\/Point2D in the type info repository\" << endl;\n\treturn false;\n }\n\n std::cerr << \"Testing the initialization of the types from an intermediate...\" << std::endl;\n {\n TestOpaque::Point2D testValue = { 100, 20, 30 };\n NotOrogenCompatible::Point2D p(0, 0);\n from_intermediate(p, testValue);\n\n if (testValue.x != p.x() || testValue.y != p.y())\n {\n cerr << \"error in Typelib marshalling\" << endl;\n return false;\n }\n }\n\n\n NotOrogenCompatible::Point2D testValue(10, 20);\n if (!generic_type_handling_test(\"opaque\", testValue, *type, &::identity ))\n return false;\n\n return true;\n}\n\nbool test_composed_opaque()\n{\n cerr << \"\\n======== Testing opaque field in struct ========\" << endl;\n\n TypeInfoRepository::shared_ptr ti = TypeInfoRepository::Instance();\n TypeInfo* type = ti->type(\"\/TestOpaque\/Position\");\n if (! type)\n {\n\tcerr << \"cannot find \/TestOpaque\/Position in the type info repository\" << endl;\n\treturn 1;\n }\n\n TestOpaque::Position testValue;\n testValue.timestamp = 10;\n testValue.p.x() = 20;\n testValue.p.y() = 30;\n\n generic_type_handling_test(\"composed_opaque\", testValue, *type, &::identity );\n\n std::cerr << \"Testing the initialization of the types from an intermediate...\" << std::endl;\n {\n TestOpaque::Position_m testValue = { 100, 20, 30 };\n TestOpaque::Position p;\n memset(&p, 0, sizeof(p));\n from_intermediate(p, testValue);\n\n if (testValue.timestamp != p.timestamp || testValue.p.x != p.p.x() || testValue.p.y != p.p.y())\n {\n cerr << \"error in Typelib marshalling\" << endl;\n return false;\n }\n }\n\n return true;\n}\n\ntemplate\nT get_ptr_content(boost::shared_ptr const& left)\n{ return *left; }\n\ntemplate\nT get_ro_ptr_content(RTT::extras::ReadOnlyPointer const& left)\n{ return *left; }\n\nbool test_shared_pointer()\n{\n cerr << \"\\n======== Testing shared pointer ========\" << endl;\n\n TypeInfoRepository::shared_ptr ti = TypeInfoRepository::Instance();\n TypeInfo* type = ti->type(\"\/boost\/shared_ptr<\/std\/vector<\/float>>\");\n if (! type)\n {\n\tcerr << \"cannot find \/boost\/shared_ptr<\/std\/vector<\/float>> in the type info repository\" << endl;\n\treturn 1;\n }\n\n boost::shared_ptr< std::vector > testValue( new std::vector );\n std::vector& data = *testValue;\n\n for (int i = 0; i < 10; ++i)\n data.push_back(i);\n\n generic_type_handling_test(\"shared_ptr__opaque_type\", testValue, *type, &get_ptr_content< std::vector >);\n\n std::cerr << \"Testing the initialization of the types from an intermediate...\" << std::endl;\n {\n boost::shared_ptr< std::vector > result;\n from_intermediate(result, *testValue);\n\n for (int i = 0; i < data.size(); ++i)\n if ((*result)[i] != (*testValue)[i])\n {\n cerr << \"error in type initialization from an intermediate\" << endl;\n return false;\n }\n }\n\n return true;\n}\n\nbool test_shared_ptr_shortcut()\n{\n cerr << \"\\n======== Testing shared pointer (from #shared_ptr) ========\" << endl;\n\n TypeInfoRepository::shared_ptr ti = TypeInfoRepository::Instance();\n TypeInfo* type = ti->type(\"\/boost\/shared_ptr<\/std\/vector<\/int>>\");\n if (! type)\n {\n\tcerr << \"cannot find \/boost\/shared_ptr<\/std\/vector<\/int>> in the type info repository\" << endl;\n\treturn 1;\n }\n\n boost::shared_ptr< std::vector > testValue( new std::vector );\n std::vector& data = *testValue;\n\n for (int i = 0; i < 10; ++i)\n data.push_back(i);\n\n\n generic_type_handling_test(\"shared_ptr__shared_ptr\", testValue, *type, &get_ptr_content< std::vector >);\n\n std::cerr << \"Testing the initialization of the types from an intermediate...\" << std::endl;\n {\n boost::shared_ptr< std::vector > result;\n from_intermediate(result, data);\n\n for (int i = 0; i < data.size(); ++i)\n if ((*result)[i] != (*testValue)[i])\n {\n cerr << \"error in type initialization from an intermediate\" << endl;\n return false;\n }\n }\n\n return true;\n}\n\nbool test_ro_ptr()\n{\n cerr << \"\\n======== Testing ReadOnlyPointer (from #ro_ptr) ========\" << endl;\n\n TypeInfoRepository::shared_ptr ti = TypeInfoRepository::Instance();\n TypeInfo* type = ti->type(\"\/RTT\/extras\/ReadOnlyPointer<\/std\/vector<\/int>>\");\n if (! type)\n {\n\tcerr << \"cannot find \/RTT\/extras\/ReadOnlyPointer<\/std\/vector<\/int>> in the type info repository\" << endl;\n\treturn 1;\n }\n\n std::vector* data = new std::vector();\n for (int i = 0; i < 10; ++i)\n data->push_back(i);\n\n RTT::extras::ReadOnlyPointer< std::vector > testValue(data);\n\n\n generic_type_handling_test(\"readonlypointer\", testValue, *type, &get_ro_ptr_content< std::vector >);\n\n std::cerr << \"Testing the initialization of the types from an intermediate...\" << std::endl;\n {\n RTT::extras::ReadOnlyPointer< std::vector > result;\n from_intermediate(result, *data);\n\n for (int i = 0; i < data->size(); ++i)\n if ((*result)[i] != (*testValue)[i])\n {\n cerr << \"error in type initialization from an intermediate\" << endl;\n return false;\n }\n }\n\n return true;\n}\n\n\nint ORO_main(int argc, char** argv)\n{\n log().setLogLevel( Logger::Debug );\n RTT::types::TypekitRepository::Import( new RTT::types::RealTimeTypekitPlugin );\n RTT::types::TypekitRepository::Import( new orogen_typekits::opaqueTypekitPlugin );\n#ifdef WITH_CORBA\n RTT::types::TypekitRepository::Import( new orogen_typekits::opaqueCorbaTransportPlugin );\n#endif\n#ifdef WITH_TYPELIB\n RTT::types::TypekitRepository::Import( new orogen_typekits::opaqueTypelibTransportPlugin );\n#endif\n\n if (!test_plain_opaque())\n {\n cerr << \"plain_opaque failed\" << endl;\n return 1;\n }\n if (!test_composed_opaque())\n {\n cerr << \"composed_opaque failed\" << endl;\n return 1;\n }\n if (!test_shared_pointer())\n {\n cerr << \"shared_ptr failed\" << endl;\n return 1;\n }\n if (!test_shared_ptr_shortcut())\n {\n cerr << \"shared_ptr (from #shared_ptr) failed\" << endl;\n return 1;\n }\n if (!test_ro_ptr())\n {\n cerr << \"ReadOnlyPointer failed\" << endl;\n return 1;\n }\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"\/\/ Copyright (C) 2017 Elviss Strazdins\n\/\/ This file is part of the Ouzel engine.\n\n#include \n#include \"TextureResource.h\"\n#include \"Renderer.h\"\n#include \"core\/Engine.h\"\n#include \"math\/MathUtils.h\"\n\nnamespace ouzel\n{\n namespace graphics\n {\n TextureResource::TextureResource()\n {\n }\n\n TextureResource::~TextureResource()\n {\n }\n\n bool TextureResource::init(const Size2& newSize,\n bool newDynamic,\n bool newMipmaps,\n bool newRenderTarget,\n uint32_t newSampleCount,\n bool newDepth,\n PixelFormat newPixelFormat)\n {\n std::lock_guard lock(uploadMutex);\n\n dynamic = newDynamic;\n mipmaps = newMipmaps;\n renderTarget = newRenderTarget;\n sampleCount = newSampleCount;\n depth = newDepth;\n pixelFormat = newPixelFormat;\n\n if (!calculateSizes(newSize))\n {\n return false;\n }\n\n dirty |= DIRTY_DATA | DIRTY_PARAMETERS;\n\n return true;\n }\n\n bool TextureResource::initFromBuffer(const std::vector& newData,\n const Size2& newSize,\n bool newDynamic,\n bool newMipmaps,\n PixelFormat newPixelFormat)\n {\n std::lock_guard lock(uploadMutex);\n\n dynamic = newDynamic;\n mipmaps = newMipmaps;\n renderTarget = false;\n sampleCount = 1;\n depth = false;\n pixelFormat = newPixelFormat;\n\n if (!calculateData(newData, newSize))\n {\n return false;\n }\n\n dirty |= DIRTY_DATA | DIRTY_PARAMETERS;\n\n return true;\n }\n\n bool TextureResource::setSize(const Size2& newSize)\n {\n std::lock_guard lock(uploadMutex);\n\n if (!dynamic)\n {\n return false;\n }\n\n if (newSize.v[0] <= 0.0f || newSize.v[1] <= 0.0f)\n {\n return false;\n }\n\n if (!calculateSizes(newSize))\n {\n return false;\n }\n\n dirty |= DIRTY_DATA;\n\n return true;\n }\n\n bool TextureResource::setData(const std::vector& newData, const Size2& newSize)\n {\n std::lock_guard lock(uploadMutex);\n\n if (!dynamic)\n {\n return false;\n }\n\n if (newSize.v[0] <= 0.0f || newSize.v[1] <= 0.0f)\n {\n return false;\n }\n\n if (!calculateData(newData, newSize))\n {\n return false;\n }\n\n dirty |= DIRTY_DATA;\n\n return true;\n }\n\n bool TextureResource::calculateSizes(const Size2& newSize)\n {\n levels.clear();\n size = newSize;\n\n uint32_t newWidth = static_cast(newSize.v[0]);\n uint32_t newHeight = static_cast(newSize.v[1]);\n\n uint32_t pixelSize = getPixelSize(pixelFormat);\n uint32_t pitch = newWidth * pixelSize;\n levels.push_back({newSize, pitch, std::vector()});\n\n if (mipmaps && !renderTarget && (sharedEngine->getRenderer()->isNPOTTexturesSupported() || (isPOT(newWidth) && isPOT(newHeight))))\n {\n uint32_t bufferSize = newWidth * newHeight * pixelSize;\n\n if (newWidth == 1)\n {\n bufferSize *= 2;\n }\n if (newHeight == 1)\n {\n bufferSize *= 2;\n }\n\n while (newWidth >= 2 && newHeight >= 2)\n {\n newWidth >>= 1;\n newHeight >>= 1;\n\n Size2 mipMapSize = Size2(static_cast(newWidth), static_cast(newHeight));\n pitch = newWidth * pixelSize;\n\n levels.push_back({mipMapSize, pitch, std::vector()});\n }\n\n if (newWidth > newHeight)\n {\n for (; newWidth >= 2;)\n {\n newWidth >>= 1;\n\n Size2 mipMapSize = Size2(static_cast(newWidth), static_cast(newHeight));\n pitch = newWidth * pixelSize;\n\n levels.push_back({mipMapSize, pitch, std::vector()});\n }\n }\n else\n {\n for (; newHeight >= 2;)\n {\n newHeight >>= 1;\n\n Size2 mipMapSize = Size2(static_cast(newWidth), static_cast(newHeight));\n levels.push_back({mipMapSize, pitch, std::vector()});\n }\n }\n }\n\n return true;\n }\n\n static void imageRGB8Downsample2x2(uint32_t width, uint32_t height, uint32_t pitch, const uint8_t* src, uint8_t* dst)\n {\n const uint32_t dstWidth = width \/ 2;\n const uint32_t dstHeight = height \/ 2;\n\n if (dstWidth == 0 || dstHeight == 0)\n {\n return;\n }\n\n for (uint32_t y = 0, ystep = pitch * 2; y < dstHeight; ++y, src += ystep)\n {\n const uint8_t* rgb = src;\n for (uint32_t x = 0; x < dstWidth; ++x, rgb += 6, dst += 3)\n {\n float pixels = 0.0f;\n float r = 0, g = 0, b = 0.0;\n\n r += powf(rgb[0], 2.2f);\n g += powf(rgb[1], 2.2f);\n b += powf(rgb[2], 2.2f);\n pixels += 1.0f;\n\n r += powf(rgb[3], 2.2f);\n g += powf(rgb[4], 2.2f);\n b += powf(rgb[5], 2.2f);\n pixels += 1.0f;\n\n r += powf(rgb[pitch + 0], 2.2f);\n g += powf(rgb[pitch + 1], 2.2f);\n b += powf(rgb[pitch + 2], 2.2f);\n pixels += 1.0f;\n\n r += powf(rgb[pitch + 3], 2.2f);\n g += powf(rgb[pitch + 4], 2.2f);\n b += powf(rgb[pitch + 5], 2.2f);\n pixels += 1.0f;\n\n if (pixels > 0.0f)\n {\n r \/= pixels;\n g \/= pixels;\n b \/= pixels;\n }\n else\n {\n r = g = b = 0.0f;\n }\n\n r = powf(r, 1.0f \/ 2.2f);\n g = powf(g, 1.0f \/ 2.2f);\n b = powf(b, 1.0f \/ 2.2f);\n dst[0] = static_cast(r);\n dst[1] = static_cast(g);\n dst[2] = static_cast(b);\n }\n }\n }\n\n static void imageRGBA8Downsample2x2(uint32_t width, uint32_t height, uint32_t pitch, const uint8_t* src, uint8_t* dst)\n {\n const uint32_t dstWidth = width \/ 2;\n const uint32_t dstHeight = height \/ 2;\n\n if (dstWidth == 0 || dstHeight == 0)\n {\n return;\n }\n\n for (uint32_t y = 0, ystep = pitch * 2; y < dstHeight; ++y, src += ystep)\n {\n const uint8_t* rgba = src;\n for (uint32_t x = 0; x < dstWidth; ++x, rgba += 8, dst += 4)\n {\n float pixels = 0.0f;\n float r = 0, g = 0, b = 0, a = 0.0f;\n\n if (rgba[3] > 0)\n {\n r += powf(rgba[0], 2.2f);\n g += powf(rgba[1], 2.2f);\n b += powf(rgba[2], 2.2f);\n pixels += 1.0f;\n }\n a = rgba[3];\n\n if (rgba[7] > 0)\n {\n r += powf(rgba[4], 2.2f);\n g += powf(rgba[5], 2.2f);\n b += powf(rgba[6], 2.2f);\n pixels += 1.0f;\n }\n a += rgba[7];\n\n if (rgba[pitch + 3] > 0)\n {\n r += powf(rgba[pitch + 0], 2.2f);\n g += powf(rgba[pitch + 1], 2.2f);\n b += powf(rgba[pitch + 2], 2.2f);\n pixels += 1.0f;\n }\n a += rgba[pitch + 3];\n\n if (rgba[pitch + 7] > 0)\n {\n r += powf(rgba[pitch + 4], 2.2f);\n g += powf(rgba[pitch + 5], 2.2f);\n b += powf(rgba[pitch + 6], 2.2f);\n pixels += 1.0f;\n }\n a += rgba[pitch + 7];\n\n if (pixels > 0.0f)\n {\n r \/= pixels;\n g \/= pixels;\n b \/= pixels;\n }\n else\n {\n r = g = b = 0.0f;\n }\n\n r = powf(r, 1.0f \/ 2.2f);\n g = powf(g, 1.0f \/ 2.2f);\n b = powf(b, 1.0f \/ 2.2f);\n a *= 0.25f;\n dst[0] = static_cast(r);\n dst[1] = static_cast(g);\n dst[2] = static_cast(b);\n dst[3] = static_cast(a);\n }\n }\n }\n\n bool TextureResource::calculateData(const std::vector& newData, const Size2& newSize)\n {\n levels.clear();\n size = newSize;\n\n uint32_t newWidth = static_cast(newSize.v[0]);\n uint32_t newHeight = static_cast(newSize.v[1]);\n\n uint32_t pixelSize = getPixelSize(pixelFormat);\n uint32_t pitch = newWidth * pixelSize;\n levels.push_back({newSize, pitch, newData});\n\n if (mipmaps && !renderTarget && (sharedEngine->getRenderer()->isNPOTTexturesSupported() || (isPOT(newWidth) && isPOT(newHeight))))\n {\n uint32_t bufferSize = newWidth * newHeight * pixelSize;\n\n if (newWidth == 1)\n {\n bufferSize *= 2;\n }\n if (newHeight == 1)\n {\n bufferSize *= 2;\n }\n\n std::vector mipMapData(bufferSize);\n std::copy(newData.begin(),\n newData.begin() + static_cast::difference_type>(newWidth * newHeight * pixelSize),\n mipMapData.begin());\n\n while (newWidth >= 2 && newHeight >= 2)\n {\n if (pixelFormat == PixelFormat::RGBA8_UINT)\n {\n imageRGBA8Downsample2x2(newWidth, newHeight, pitch, mipMapData.data(), mipMapData.data());\n }\n else if (pixelFormat == PixelFormat::RGB8_UINT)\n {\n imageRGBA8Downsample2x2(newWidth, 2, pitch, mipMapData.data(), mipMapData.data());\n }\n else\n {\n \/\/ TODO: implement downsampling of other pixel formats\n }\n\n newWidth >>= 1;\n newHeight >>= 1;\n\n Size2 mipMapSize = Size2(static_cast(newWidth), static_cast(newHeight));\n pitch = newWidth * pixelSize;\n\n levels.push_back({mipMapSize, pitch, mipMapData});\n }\n\n if (newWidth > newHeight) \/\/ height is 2\n {\n for (; newWidth >= 2;)\n {\n std::copy(mipMapData.begin(),\n mipMapData.begin() + newWidth * pixelSize,\n mipMapData.begin() + newWidth * pixelSize);\n\n if (pixelFormat == PixelFormat::RGBA8_UINT)\n {\n imageRGBA8Downsample2x2(newWidth, 2, pitch, mipMapData.data(), mipMapData.data());\n }\n else if (pixelFormat == PixelFormat::RGB8_UINT)\n {\n imageRGBA8Downsample2x2(newWidth, 2, pitch, mipMapData.data(), mipMapData.data());\n }\n else\n {\n \/\/ TODO: implement downsampling of other pixel formats\n }\n\n newWidth >>= 1;\n\n Size2 mipMapSize = Size2(static_cast(newWidth), static_cast(newHeight));\n pitch = newWidth * pixelSize;\n\n levels.push_back({mipMapSize, pitch, mipMapData});\n }\n }\n else \/\/ width is 2\n {\n for (; newHeight >= 2;)\n {\n for (int32_t i = static_cast(newHeight) - 1; i >= 0; --i)\n {\n std::copy(mipMapData.begin() + static_cast(i * 2) * pixelSize,\n mipMapData.begin() + static_cast(i * 2) * pixelSize + pixelSize,\n mipMapData.begin() + static_cast(i) * pixelSize);\n\n std::copy(mipMapData.begin() + static_cast(i * 2 + 1) * pixelSize,\n mipMapData.begin() + static_cast(i * 2 + 1) * pixelSize + pixelSize,\n mipMapData.begin() + static_cast(i) * pixelSize);\n }\n\n if (pixelFormat == PixelFormat::RGBA8_UINT)\n {\n imageRGBA8Downsample2x2(2, newHeight, 8, mipMapData.data(), mipMapData.data());\n }\n else if (pixelFormat == PixelFormat::RGB8_UINT)\n {\n imageRGB8Downsample2x2(2, newHeight, 8, mipMapData.data(), mipMapData.data());\n }\n else\n {\n \/\/ TODO: implement downsampling of other pixel formats\n }\n\n newHeight >>= 1;\n\n Size2 mipMapSize = Size2(static_cast(newWidth), static_cast(newHeight));\n levels.push_back({mipMapSize, pitch, mipMapData});\n }\n }\n }\n\n return true;\n }\n\n bool TextureResource::setFilter(Texture::Filter newFilter)\n {\n std::lock_guard lock(uploadMutex);\n\n filter = newFilter;\n dirty |= DIRTY_PARAMETERS;\n\n return true;\n }\n\n bool TextureResource::setAddressX(Texture::Address newAddressX)\n {\n std::lock_guard lock(uploadMutex);\n\n addressX = newAddressX;\n dirty |= DIRTY_PARAMETERS;\n\n return true;\n }\n\n bool TextureResource::setAddressY(Texture::Address newAddressY)\n {\n std::lock_guard lock(uploadMutex);\n\n addressY = newAddressY;\n dirty |= DIRTY_PARAMETERS;\n\n return true;\n }\n\n bool TextureResource::setMaxAnisotropy(uint32_t newMaxAnisotropy)\n {\n std::lock_guard lock(uploadMutex);\n\n maxAnisotropy = newMaxAnisotropy;\n dirty |= DIRTY_PARAMETERS;\n\n return true;\n }\n\n void TextureResource::setClearColorBuffer(bool clear)\n {\n std::lock_guard lock(uploadMutex);\n\n clearColorBuffer = clear;\n dirty |= DIRTY_PARAMETERS;\n }\n\n void TextureResource::setClearDepthBuffer(bool clear)\n {\n std::lock_guard lock(uploadMutex);\n\n clearColorBuffer = clear;\n dirty |= DIRTY_PARAMETERS;\n }\n\n void TextureResource::setClearColor(Color color)\n {\n std::lock_guard lock(uploadMutex);\n\n clearColor = color;\n dirty |= DIRTY_PARAMETERS;\n }\n } \/\/ namespace graphics\n} \/\/ namespace ouzel\nReduce RGB resample code\/\/ Copyright (C) 2017 Elviss Strazdins\n\/\/ This file is part of the Ouzel engine.\n\n#include \n#include \"TextureResource.h\"\n#include \"Renderer.h\"\n#include \"core\/Engine.h\"\n#include \"math\/MathUtils.h\"\n\nnamespace ouzel\n{\n namespace graphics\n {\n TextureResource::TextureResource()\n {\n }\n\n TextureResource::~TextureResource()\n {\n }\n\n bool TextureResource::init(const Size2& newSize,\n bool newDynamic,\n bool newMipmaps,\n bool newRenderTarget,\n uint32_t newSampleCount,\n bool newDepth,\n PixelFormat newPixelFormat)\n {\n std::lock_guard lock(uploadMutex);\n\n dynamic = newDynamic;\n mipmaps = newMipmaps;\n renderTarget = newRenderTarget;\n sampleCount = newSampleCount;\n depth = newDepth;\n pixelFormat = newPixelFormat;\n\n if (!calculateSizes(newSize))\n {\n return false;\n }\n\n dirty |= DIRTY_DATA | DIRTY_PARAMETERS;\n\n return true;\n }\n\n bool TextureResource::initFromBuffer(const std::vector& newData,\n const Size2& newSize,\n bool newDynamic,\n bool newMipmaps,\n PixelFormat newPixelFormat)\n {\n std::lock_guard lock(uploadMutex);\n\n dynamic = newDynamic;\n mipmaps = newMipmaps;\n renderTarget = false;\n sampleCount = 1;\n depth = false;\n pixelFormat = newPixelFormat;\n\n if (!calculateData(newData, newSize))\n {\n return false;\n }\n\n dirty |= DIRTY_DATA | DIRTY_PARAMETERS;\n\n return true;\n }\n\n bool TextureResource::setSize(const Size2& newSize)\n {\n std::lock_guard lock(uploadMutex);\n\n if (!dynamic)\n {\n return false;\n }\n\n if (newSize.v[0] <= 0.0f || newSize.v[1] <= 0.0f)\n {\n return false;\n }\n\n if (!calculateSizes(newSize))\n {\n return false;\n }\n\n dirty |= DIRTY_DATA;\n\n return true;\n }\n\n bool TextureResource::setData(const std::vector& newData, const Size2& newSize)\n {\n std::lock_guard lock(uploadMutex);\n\n if (!dynamic)\n {\n return false;\n }\n\n if (newSize.v[0] <= 0.0f || newSize.v[1] <= 0.0f)\n {\n return false;\n }\n\n if (!calculateData(newData, newSize))\n {\n return false;\n }\n\n dirty |= DIRTY_DATA;\n\n return true;\n }\n\n bool TextureResource::calculateSizes(const Size2& newSize)\n {\n levels.clear();\n size = newSize;\n\n uint32_t newWidth = static_cast(newSize.v[0]);\n uint32_t newHeight = static_cast(newSize.v[1]);\n\n uint32_t pixelSize = getPixelSize(pixelFormat);\n uint32_t pitch = newWidth * pixelSize;\n levels.push_back({newSize, pitch, std::vector()});\n\n if (mipmaps && !renderTarget && (sharedEngine->getRenderer()->isNPOTTexturesSupported() || (isPOT(newWidth) && isPOT(newHeight))))\n {\n uint32_t bufferSize = newWidth * newHeight * pixelSize;\n\n if (newWidth == 1)\n {\n bufferSize *= 2;\n }\n if (newHeight == 1)\n {\n bufferSize *= 2;\n }\n\n while (newWidth >= 2 && newHeight >= 2)\n {\n newWidth >>= 1;\n newHeight >>= 1;\n\n Size2 mipMapSize = Size2(static_cast(newWidth), static_cast(newHeight));\n pitch = newWidth * pixelSize;\n\n levels.push_back({mipMapSize, pitch, std::vector()});\n }\n\n if (newWidth > newHeight)\n {\n for (; newWidth >= 2;)\n {\n newWidth >>= 1;\n\n Size2 mipMapSize = Size2(static_cast(newWidth), static_cast(newHeight));\n pitch = newWidth * pixelSize;\n\n levels.push_back({mipMapSize, pitch, std::vector()});\n }\n }\n else\n {\n for (; newHeight >= 2;)\n {\n newHeight >>= 1;\n\n Size2 mipMapSize = Size2(static_cast(newWidth), static_cast(newHeight));\n levels.push_back({mipMapSize, pitch, std::vector()});\n }\n }\n }\n\n return true;\n }\n\n static void imageRGB8Downsample2x2(uint32_t width, uint32_t height, uint32_t pitch, const uint8_t* src, uint8_t* dst)\n {\n const uint32_t dstWidth = width \/ 2;\n const uint32_t dstHeight = height \/ 2;\n\n if (dstWidth == 0 || dstHeight == 0)\n {\n return;\n }\n\n for (uint32_t y = 0, ystep = pitch * 2; y < dstHeight; ++y, src += ystep)\n {\n const uint8_t* rgb = src;\n for (uint32_t x = 0; x < dstWidth; ++x, rgb += 6, dst += 3)\n {\n float r = 0.0f, g = 0.0f, b = 0.0f;\n\n r += powf(rgb[0], 2.2f);\n g += powf(rgb[1], 2.2f);\n b += powf(rgb[2], 2.2f);\n\n r += powf(rgb[3], 2.2f);\n g += powf(rgb[4], 2.2f);\n b += powf(rgb[5], 2.2f);\n\n r += powf(rgb[pitch + 0], 2.2f);\n g += powf(rgb[pitch + 1], 2.2f);\n b += powf(rgb[pitch + 2], 2.2f);\n\n r += powf(rgb[pitch + 3], 2.2f);\n g += powf(rgb[pitch + 4], 2.2f);\n b += powf(rgb[pitch + 5], 2.2f);\n\n r \/= 4.0f;\n g \/= 4.0f;\n b \/= 4.0f;\n\n r = powf(r, 1.0f \/ 2.2f);\n g = powf(g, 1.0f \/ 2.2f);\n b = powf(b, 1.0f \/ 2.2f);\n dst[0] = static_cast(r);\n dst[1] = static_cast(g);\n dst[2] = static_cast(b);\n }\n }\n }\n\n static void imageRGBA8Downsample2x2(uint32_t width, uint32_t height, uint32_t pitch, const uint8_t* src, uint8_t* dst)\n {\n const uint32_t dstWidth = width \/ 2;\n const uint32_t dstHeight = height \/ 2;\n\n if (dstWidth == 0 || dstHeight == 0)\n {\n return;\n }\n\n for (uint32_t y = 0, ystep = pitch * 2; y < dstHeight; ++y, src += ystep)\n {\n const uint8_t* rgba = src;\n for (uint32_t x = 0; x < dstWidth; ++x, rgba += 8, dst += 4)\n {\n float pixels = 0.0f;\n float r = 0.0f, g = 0.0f, b = 0.0f, a = 0.0f;\n\n if (rgba[3] > 0)\n {\n r += powf(rgba[0], 2.2f);\n g += powf(rgba[1], 2.2f);\n b += powf(rgba[2], 2.2f);\n pixels += 1.0f;\n }\n a = rgba[3];\n\n if (rgba[7] > 0)\n {\n r += powf(rgba[4], 2.2f);\n g += powf(rgba[5], 2.2f);\n b += powf(rgba[6], 2.2f);\n pixels += 1.0f;\n }\n a += rgba[7];\n\n if (rgba[pitch + 3] > 0)\n {\n r += powf(rgba[pitch + 0], 2.2f);\n g += powf(rgba[pitch + 1], 2.2f);\n b += powf(rgba[pitch + 2], 2.2f);\n pixels += 1.0f;\n }\n a += rgba[pitch + 3];\n\n if (rgba[pitch + 7] > 0)\n {\n r += powf(rgba[pitch + 4], 2.2f);\n g += powf(rgba[pitch + 5], 2.2f);\n b += powf(rgba[pitch + 6], 2.2f);\n pixels += 1.0f;\n }\n a += rgba[pitch + 7];\n\n if (pixels > 0.0f)\n {\n r \/= pixels;\n g \/= pixels;\n b \/= pixels;\n }\n else\n {\n r = g = b = 0.0f;\n }\n\n r = powf(r, 1.0f \/ 2.2f);\n g = powf(g, 1.0f \/ 2.2f);\n b = powf(b, 1.0f \/ 2.2f);\n a *= 0.25f;\n dst[0] = static_cast(r);\n dst[1] = static_cast(g);\n dst[2] = static_cast(b);\n dst[3] = static_cast(a);\n }\n }\n }\n\n bool TextureResource::calculateData(const std::vector& newData, const Size2& newSize)\n {\n levels.clear();\n size = newSize;\n\n uint32_t newWidth = static_cast(newSize.v[0]);\n uint32_t newHeight = static_cast(newSize.v[1]);\n\n uint32_t pixelSize = getPixelSize(pixelFormat);\n uint32_t pitch = newWidth * pixelSize;\n levels.push_back({newSize, pitch, newData});\n\n if (mipmaps && !renderTarget && (sharedEngine->getRenderer()->isNPOTTexturesSupported() || (isPOT(newWidth) && isPOT(newHeight))))\n {\n uint32_t bufferSize = newWidth * newHeight * pixelSize;\n\n if (newWidth == 1)\n {\n bufferSize *= 2;\n }\n if (newHeight == 1)\n {\n bufferSize *= 2;\n }\n\n std::vector mipMapData(bufferSize);\n std::copy(newData.begin(),\n newData.begin() + static_cast::difference_type>(newWidth * newHeight * pixelSize),\n mipMapData.begin());\n\n while (newWidth >= 2 && newHeight >= 2)\n {\n if (pixelFormat == PixelFormat::RGBA8_UINT)\n {\n imageRGBA8Downsample2x2(newWidth, newHeight, pitch, mipMapData.data(), mipMapData.data());\n }\n else if (pixelFormat == PixelFormat::RGB8_UINT)\n {\n imageRGBA8Downsample2x2(newWidth, 2, pitch, mipMapData.data(), mipMapData.data());\n }\n else\n {\n \/\/ TODO: implement downsampling of other pixel formats\n }\n\n newWidth >>= 1;\n newHeight >>= 1;\n\n Size2 mipMapSize = Size2(static_cast(newWidth), static_cast(newHeight));\n pitch = newWidth * pixelSize;\n\n levels.push_back({mipMapSize, pitch, mipMapData});\n }\n\n if (newWidth > newHeight) \/\/ height is 2\n {\n for (; newWidth >= 2;)\n {\n std::copy(mipMapData.begin(),\n mipMapData.begin() + newWidth * pixelSize,\n mipMapData.begin() + newWidth * pixelSize);\n\n if (pixelFormat == PixelFormat::RGBA8_UINT)\n {\n imageRGBA8Downsample2x2(newWidth, 2, pitch, mipMapData.data(), mipMapData.data());\n }\n else if (pixelFormat == PixelFormat::RGB8_UINT)\n {\n imageRGBA8Downsample2x2(newWidth, 2, pitch, mipMapData.data(), mipMapData.data());\n }\n else\n {\n \/\/ TODO: implement downsampling of other pixel formats\n }\n\n newWidth >>= 1;\n\n Size2 mipMapSize = Size2(static_cast(newWidth), static_cast(newHeight));\n pitch = newWidth * pixelSize;\n\n levels.push_back({mipMapSize, pitch, mipMapData});\n }\n }\n else \/\/ width is 2\n {\n for (; newHeight >= 2;)\n {\n for (int32_t i = static_cast(newHeight) - 1; i >= 0; --i)\n {\n std::copy(mipMapData.begin() + static_cast(i * 2) * pixelSize,\n mipMapData.begin() + static_cast(i * 2) * pixelSize + pixelSize,\n mipMapData.begin() + static_cast(i) * pixelSize);\n\n std::copy(mipMapData.begin() + static_cast(i * 2 + 1) * pixelSize,\n mipMapData.begin() + static_cast(i * 2 + 1) * pixelSize + pixelSize,\n mipMapData.begin() + static_cast(i) * pixelSize);\n }\n\n if (pixelFormat == PixelFormat::RGBA8_UINT)\n {\n imageRGBA8Downsample2x2(2, newHeight, 8, mipMapData.data(), mipMapData.data());\n }\n else if (pixelFormat == PixelFormat::RGB8_UINT)\n {\n imageRGB8Downsample2x2(2, newHeight, 8, mipMapData.data(), mipMapData.data());\n }\n else\n {\n \/\/ TODO: implement downsampling of other pixel formats\n }\n\n newHeight >>= 1;\n\n Size2 mipMapSize = Size2(static_cast(newWidth), static_cast(newHeight));\n levels.push_back({mipMapSize, pitch, mipMapData});\n }\n }\n }\n\n return true;\n }\n\n bool TextureResource::setFilter(Texture::Filter newFilter)\n {\n std::lock_guard lock(uploadMutex);\n\n filter = newFilter;\n dirty |= DIRTY_PARAMETERS;\n\n return true;\n }\n\n bool TextureResource::setAddressX(Texture::Address newAddressX)\n {\n std::lock_guard lock(uploadMutex);\n\n addressX = newAddressX;\n dirty |= DIRTY_PARAMETERS;\n\n return true;\n }\n\n bool TextureResource::setAddressY(Texture::Address newAddressY)\n {\n std::lock_guard lock(uploadMutex);\n\n addressY = newAddressY;\n dirty |= DIRTY_PARAMETERS;\n\n return true;\n }\n\n bool TextureResource::setMaxAnisotropy(uint32_t newMaxAnisotropy)\n {\n std::lock_guard lock(uploadMutex);\n\n maxAnisotropy = newMaxAnisotropy;\n dirty |= DIRTY_PARAMETERS;\n\n return true;\n }\n\n void TextureResource::setClearColorBuffer(bool clear)\n {\n std::lock_guard lock(uploadMutex);\n\n clearColorBuffer = clear;\n dirty |= DIRTY_PARAMETERS;\n }\n\n void TextureResource::setClearDepthBuffer(bool clear)\n {\n std::lock_guard lock(uploadMutex);\n\n clearColorBuffer = clear;\n dirty |= DIRTY_PARAMETERS;\n }\n\n void TextureResource::setClearColor(Color color)\n {\n std::lock_guard lock(uploadMutex);\n\n clearColor = color;\n dirty |= DIRTY_PARAMETERS;\n }\n } \/\/ namespace graphics\n} \/\/ namespace ouzel\n<|endoftext|>"} {"text":"#include \"envoy\/api\/v2\/discovery.pb.h\"\n#include \"envoy\/api\/v2\/rds.pb.h\"\n#include \"envoy\/grpc\/status.h\"\n#include \"envoy\/stats\/scope.h\"\n\n#include \"common\/config\/protobuf_link_hacks.h\"\n#include \"common\/config\/resources.h\"\n#include \"common\/protobuf\/protobuf.h\"\n#include \"common\/protobuf\/utility.h\"\n\n#include \"test\/common\/grpc\/grpc_client_integration.h\"\n#include \"test\/integration\/http_integration.h\"\n#include \"test\/integration\/utility.h\"\n#include \"test\/mocks\/server\/mocks.h\"\n#include \"test\/test_common\/network_utility.h\"\n#include \"test\/test_common\/simulated_time_system.h\"\n#include \"test\/test_common\/utility.h\"\n\n#include \"absl\/synchronization\/notification.h\"\n#include \"gtest\/gtest.h\"\n\nusing testing::AssertionFailure;\nusing testing::AssertionResult;\nusing testing::AssertionSuccess;\nusing testing::IsSubstring;\n\nnamespace Envoy {\nnamespace {\n\nconst char Config[] = R\"EOF(\nadmin:\n access_log_path: \/dev\/null\n address:\n socket_address:\n address: 127.0.0.1\n port_value: 0\nstatic_resources:\n clusters:\n - name: xds_cluster\n type: STATIC\n http2_protocol_options: {}\n hosts:\n socket_address:\n address: 127.0.0.1\n port_value: 0\n - name: my_service\n type: STATIC\n http2_protocol_options: {}\n hosts:\n socket_address:\n address: 127.0.0.1\n port_value: 0\n listeners:\n - name: http\n address:\n socket_address:\n address: 127.0.0.1\n port_value: 0\n filter_chains:\n - filters:\n - name: envoy.http_connection_manager\n config:\n stat_prefix: config_test\n http_filters:\n - name: envoy.router\n codec_type: HTTP2\n rds:\n route_config_name: my_route\n config_source:\n api_config_source:\n api_type: GRPC\n grpc_services:\n envoy_grpc:\n cluster_name: xds_cluster\n)EOF\";\n\nconst char RdsConfig[] = R\"EOF(\nname: my_route\nvhds:\n config_source:\n api_config_source:\n api_type: DELTA_GRPC\n grpc_services:\n envoy_grpc:\n cluster_name: xds_cluster\n)EOF\";\n\nconst char RdsConfigWithVhosts[] = R\"EOF(\nname: my_route\nvirtual_hosts:\n- name: vhost_rds1\n domains: [\"vhost.rds.first\"]\n routes:\n - match: { prefix: \"\/rdsone\" }\n route: { cluster: my_service }\nvhds:\n config_source:\n api_config_source:\n api_type: DELTA_GRPC\n grpc_services:\n envoy_grpc:\n cluster_name: xds_cluster\n)EOF\";\n\nclass VhdsIntegrationTest : public HttpIntegrationTest,\n public Grpc::GrpcClientIntegrationParamTest {\npublic:\n VhdsIntegrationTest()\n : HttpIntegrationTest(Http::CodecClient::Type::HTTP2, ipVersion(), realTime(), Config) {}\n\n void TearDown() override {\n cleanUpXdsConnection();\n test_server_.reset();\n fake_upstreams_.clear();\n }\n\n std::string virtualHostYaml(const std::string& name, const std::string& domain) {\n return fmt::format(R\"EOF(\n name: {}\n domains: [{}]\n routes:\n - match: {{ prefix: \"\/\" }}\n route: {{ cluster: \"my_service\" }}\n )EOF\",\n name, domain);\n }\n\n envoy::api::v2::route::VirtualHost buildVirtualHost() {\n return TestUtility::parseYaml(\n virtualHostYaml(\"vhost_0\", \"host\"));\n }\n\n std::vector buildVirtualHost1() {\n return {TestUtility::parseYaml(\n virtualHostYaml(\"vhost_1\", \"vhost.first\")),\n TestUtility::parseYaml(\n virtualHostYaml(\"vhost_2\", \"vhost.second\"))};\n }\n\n envoy::api::v2::route::VirtualHost buildVirtualHost2() {\n return TestUtility::parseYaml(\n virtualHostYaml(\"vhost_1\", \"vhost.first\"));\n }\n\n \/\/ Overridden to insert this stuff into the initialize() at the very beginning of\n \/\/ HttpIntegrationTest::testRouterRequestAndResponseWithBody().\n void initialize() override {\n \/\/ Controls how many fake_upstreams_.emplace_back(new FakeUpstream) will happen in\n \/\/ BaseIntegrationTest::createUpstreams() (which is part of initialize()).\n \/\/ Make sure this number matches the size of the 'clusters' repeated field in the bootstrap\n \/\/ config that you use!\n setUpstreamCount(2); \/\/ the CDS cluster\n setUpstreamProtocol(FakeHttpConnection::Type::HTTP2); \/\/ CDS uses gRPC uses HTTP2.\n\n \/\/ BaseIntegrationTest::initialize() does many things:\n \/\/ 1) It appends to fake_upstreams_ as many as you asked for via setUpstreamCount().\n \/\/ 2) It updates your bootstrap config with the ports your fake upstreams are actually listening\n \/\/ on (since you're supposed to leave them as 0).\n \/\/ 3) It creates and starts an IntegrationTestServer - the thing that wraps the almost-actual\n \/\/ Envoy used in the tests.\n \/\/ 4) Bringing up the server usually entails waiting to ensure that any listeners specified in\n \/\/ the bootstrap config have come up, and registering them in a port map (see lookupPort()).\n \/\/ However, this test needs to defer all of that to later.\n defer_listener_finalization_ = true;\n HttpIntegrationTest::initialize();\n\n \/\/ Now that the upstream has been created, process Envoy's request to discover it.\n \/\/ (First, we have to let Envoy establish its connection to the RDS server.)\n AssertionResult result = \/\/ xds_connection_ is filled with the new FakeHttpConnection.\n fake_upstreams_[0]->waitForHttpConnection(*dispatcher_, xds_connection_);\n RELEASE_ASSERT(result, result.message());\n result = xds_connection_->waitForNewStream(*dispatcher_, xds_stream_);\n RELEASE_ASSERT(result, result.message());\n xds_stream_->startGrpcStream();\n fake_upstreams_[0]->set_allow_unexpected_disconnects(true);\n\n EXPECT_TRUE(\n compareDiscoveryRequest(Config::TypeUrl::get().RouteConfiguration, \"\", {\"my_route\"}));\n sendDiscoveryResponse(\n Config::TypeUrl::get().RouteConfiguration, {rdsConfig()}, \"1\");\n\n result = xds_connection_->waitForNewStream(*dispatcher_, vhds_stream_, true);\n RELEASE_ASSERT(result, result.message());\n vhds_stream_->startGrpcStream();\n\n EXPECT_TRUE(\n compareDeltaDiscoveryRequest(Config::TypeUrl::get().VirtualHost, {}, {}, vhds_stream_));\n sendDeltaDiscoveryResponse({buildVirtualHost()}, {}, \"1\",\n vhds_stream_);\n\n \/\/ Wait for our statically specified listener to become ready, and register its port in the\n \/\/ test framework's downstream listener port map.\n test_server_->waitUntilListenersReady();\n registerTestServerPorts({\"http\"});\n }\n\n void useRdsWithVhosts() { use_rds_with_vhosts = true; }\n const envoy::api::v2::RouteConfiguration rdsConfig() const {\n return TestUtility::parseYaml(\n use_rds_with_vhosts ? RdsConfigWithVhosts : RdsConfig);\n }\n\n FakeStreamPtr vhds_stream_;\n bool use_rds_with_vhosts{false};\n};\n\nINSTANTIATE_TEST_CASE_P(IpVersionsClientType, VhdsIntegrationTest, GRPC_CLIENT_INTEGRATION_PARAMS);\n\n\/\/ tests a scenario when:\n\/\/ - a spontaneous VHDS DiscoveryResponse adds two virtual hosts\n\/\/ - the next spontaneous VHDS DiscoveryResponse removes newly added virtual hosts\n\/\/ - Upstream makes a request to an (now) unknown domain, which fails\nTEST_P(VhdsIntegrationTest, VhdsVirtualHostAddUpdateRemove) {\n \/\/ Calls our initialize(), which includes establishing a listener, route, and cluster.\n testRouterHeaderOnlyRequestAndResponse(nullptr, 1);\n cleanupUpstreamAndDownstream();\n codec_client_->waitForDisconnect();\n\n \/\/ A spontaneous VHDS DiscoveryResponse adds two virtual hosts\n sendDeltaDiscoveryResponse(buildVirtualHost1(), {}, \"2\",\n vhds_stream_);\n EXPECT_TRUE(\n compareDeltaDiscoveryRequest(Config::TypeUrl::get().VirtualHost, {}, {}, vhds_stream_));\n\n testRouterHeaderOnlyRequestAndResponse(nullptr, 1, \"\/one\", \"vhost.first\");\n cleanupUpstreamAndDownstream();\n codec_client_->waitForDisconnect();\n testRouterHeaderOnlyRequestAndResponse(nullptr, 1, \"\/two\", \"vhost.second\");\n cleanupUpstreamAndDownstream();\n codec_client_->waitForDisconnect();\n\n \/\/ A spontaneous VHDS DiscoveryResponse removes newly added virtual hosts\n sendDeltaDiscoveryResponse({}, {\"vhost_1\", \"vhost_2\"}, \"3\",\n vhds_stream_);\n EXPECT_TRUE(\n compareDeltaDiscoveryRequest(Config::TypeUrl::get().VirtualHost, {}, {}, vhds_stream_));\n\n \/\/ an upstream request to an (now) unknown domain\n codec_client_ = makeHttpConnection(makeClientConnection((lookupPort(\"http\"))));\n Http::TestHeaderMapImpl request_headers{{\":method\", \"GET\"},\n {\":path\", \"\/one\"},\n {\":scheme\", \"http\"},\n {\":authority\", \"vhost.first\"},\n {\"x-lyft-user-id\", \"123\"}};\n IntegrationStreamDecoderPtr response = codec_client_->makeHeaderOnlyRequest(request_headers);\n response->waitForHeaders();\n EXPECT_EQ(\"404\", response->headers().Status()->value().getStringView());\n\n cleanupUpstreamAndDownstream();\n}\n\n\/\/ tests a scenario when:\n\/\/ - an RDS exchange contains a non-empty virtual_hosts array\n\/\/ - a spontaneous VHDS DiscoveryResponse adds two virtual hosts\n\/\/ - the next spontaneous VHDS DiscoveryResponse removes newly added virtual hosts\n\/\/ - Upstream makes a request to an (now) unknown domain, which fails\nTEST_P(VhdsIntegrationTest, RdsWithVirtualHostsVhdsVirtualHostAddUpdateRemove) {\n \/\/ RDS exchange with a non-empty virtual_hosts field\n useRdsWithVhosts();\n\n testRouterHeaderOnlyRequestAndResponse(nullptr, 1);\n cleanupUpstreamAndDownstream();\n codec_client_->waitForDisconnect();\n\n \/\/ A spontaneous VHDS DiscoveryResponse adds two virtual hosts\n sendDeltaDiscoveryResponse(buildVirtualHost1(), {}, \"2\",\n vhds_stream_);\n EXPECT_TRUE(\n compareDeltaDiscoveryRequest(Config::TypeUrl::get().VirtualHost, {}, {}, vhds_stream_));\n\n \/\/ verify that rds-based virtual host can be resolved\n testRouterHeaderOnlyRequestAndResponse(nullptr, 1, \"\/rdsone\", \"vhost.rds.first\");\n cleanupUpstreamAndDownstream();\n codec_client_->waitForDisconnect();\n testRouterHeaderOnlyRequestAndResponse(nullptr, 1, \"\/one\", \"vhost.first\");\n cleanupUpstreamAndDownstream();\n codec_client_->waitForDisconnect();\n testRouterHeaderOnlyRequestAndResponse(nullptr, 1, \"\/two\", \"vhost.second\");\n cleanupUpstreamAndDownstream();\n codec_client_->waitForDisconnect();\n\n \/\/ A spontaneous VHDS DiscoveryResponse removes virtual hosts added via vhds\n sendDeltaDiscoveryResponse({}, {\"vhost_1\", \"vhost_2\"}, \"3\",\n vhds_stream_);\n EXPECT_TRUE(\n compareDeltaDiscoveryRequest(Config::TypeUrl::get().VirtualHost, {}, {}, vhds_stream_));\n\n \/\/ verify rds-based virtual host is still present\n testRouterHeaderOnlyRequestAndResponse(nullptr, 1, \"\/rdsone\", \"vhost.rds.first\");\n cleanupUpstreamAndDownstream();\n codec_client_->waitForDisconnect();\n\n codec_client_ = makeHttpConnection(makeClientConnection((lookupPort(\"http\"))));\n Http::TestHeaderMapImpl request_headers{{\":method\", \"GET\"},\n {\":path\", \"\/one\"},\n {\":scheme\", \"http\"},\n {\":authority\", \"vhost.first\"},\n {\"x-lyft-user-id\", \"123\"}};\n IntegrationStreamDecoderPtr response = codec_client_->makeHeaderOnlyRequest(request_headers);\n response->waitForHeaders();\n EXPECT_EQ(\"404\", response->headers().Status()->value().getStringView());\n\n cleanupUpstreamAndDownstream();\n}\n\n} \/\/ namespace\n} \/\/ namespace Envoy\nFix for an intermittently failing integration test (#6978)#include \"envoy\/api\/v2\/discovery.pb.h\"\n#include \"envoy\/api\/v2\/rds.pb.h\"\n#include \"envoy\/grpc\/status.h\"\n#include \"envoy\/stats\/scope.h\"\n\n#include \"common\/config\/protobuf_link_hacks.h\"\n#include \"common\/config\/resources.h\"\n#include \"common\/protobuf\/protobuf.h\"\n#include \"common\/protobuf\/utility.h\"\n\n#include \"test\/common\/grpc\/grpc_client_integration.h\"\n#include \"test\/integration\/http_integration.h\"\n#include \"test\/integration\/utility.h\"\n#include \"test\/mocks\/server\/mocks.h\"\n#include \"test\/test_common\/network_utility.h\"\n#include \"test\/test_common\/simulated_time_system.h\"\n#include \"test\/test_common\/utility.h\"\n\n#include \"absl\/synchronization\/notification.h\"\n#include \"gtest\/gtest.h\"\n\nusing testing::AssertionFailure;\nusing testing::AssertionResult;\nusing testing::AssertionSuccess;\nusing testing::IsSubstring;\n\nnamespace Envoy {\nnamespace {\n\nconst char Config[] = R\"EOF(\nadmin:\n access_log_path: \/dev\/null\n address:\n socket_address:\n address: 127.0.0.1\n port_value: 0\nstatic_resources:\n clusters:\n - name: xds_cluster\n type: STATIC\n http2_protocol_options: {}\n hosts:\n socket_address:\n address: 127.0.0.1\n port_value: 0\n - name: my_service\n type: STATIC\n http2_protocol_options: {}\n hosts:\n socket_address:\n address: 127.0.0.1\n port_value: 0\n listeners:\n - name: http\n address:\n socket_address:\n address: 127.0.0.1\n port_value: 0\n filter_chains:\n - filters:\n - name: envoy.http_connection_manager\n config:\n stat_prefix: config_test\n http_filters:\n - name: envoy.router\n codec_type: HTTP2\n rds:\n route_config_name: my_route\n config_source:\n api_config_source:\n api_type: GRPC\n grpc_services:\n envoy_grpc:\n cluster_name: xds_cluster\n)EOF\";\n\nconst char RdsConfig[] = R\"EOF(\nname: my_route\nvhds:\n config_source:\n api_config_source:\n api_type: DELTA_GRPC\n grpc_services:\n envoy_grpc:\n cluster_name: xds_cluster\n)EOF\";\n\nconst char RdsConfigWithVhosts[] = R\"EOF(\nname: my_route\nvirtual_hosts:\n- name: vhost_rds1\n domains: [\"vhost.rds.first\"]\n routes:\n - match: { prefix: \"\/rdsone\" }\n route: { cluster: my_service }\nvhds:\n config_source:\n api_config_source:\n api_type: DELTA_GRPC\n grpc_services:\n envoy_grpc:\n cluster_name: xds_cluster\n)EOF\";\n\nclass VhdsIntegrationTest : public HttpIntegrationTest,\n public Grpc::GrpcClientIntegrationParamTest {\npublic:\n VhdsIntegrationTest()\n : HttpIntegrationTest(Http::CodecClient::Type::HTTP2, ipVersion(), realTime(), Config) {}\n\n void TearDown() override {\n cleanUpXdsConnection();\n test_server_.reset();\n fake_upstreams_.clear();\n }\n\n std::string virtualHostYaml(const std::string& name, const std::string& domain) {\n return fmt::format(R\"EOF(\n name: {}\n domains: [{}]\n routes:\n - match: {{ prefix: \"\/\" }}\n route: {{ cluster: \"my_service\" }}\n )EOF\",\n name, domain);\n }\n\n envoy::api::v2::route::VirtualHost buildVirtualHost() {\n return TestUtility::parseYaml(\n virtualHostYaml(\"vhost_0\", \"host\"));\n }\n\n std::vector buildVirtualHost1() {\n return {TestUtility::parseYaml(\n virtualHostYaml(\"vhost_1\", \"vhost.first\")),\n TestUtility::parseYaml(\n virtualHostYaml(\"vhost_2\", \"vhost.second\"))};\n }\n\n envoy::api::v2::route::VirtualHost buildVirtualHost2() {\n return TestUtility::parseYaml(\n virtualHostYaml(\"vhost_1\", \"vhost.first\"));\n }\n\n \/\/ Overridden to insert this stuff into the initialize() at the very beginning of\n \/\/ HttpIntegrationTest::testRouterRequestAndResponseWithBody().\n void initialize() override {\n \/\/ Controls how many fake_upstreams_.emplace_back(new FakeUpstream) will happen in\n \/\/ BaseIntegrationTest::createUpstreams() (which is part of initialize()).\n \/\/ Make sure this number matches the size of the 'clusters' repeated field in the bootstrap\n \/\/ config that you use!\n setUpstreamCount(2); \/\/ the CDS cluster\n setUpstreamProtocol(FakeHttpConnection::Type::HTTP2); \/\/ CDS uses gRPC uses HTTP2.\n\n \/\/ BaseIntegrationTest::initialize() does many things:\n \/\/ 1) It appends to fake_upstreams_ as many as you asked for via setUpstreamCount().\n \/\/ 2) It updates your bootstrap config with the ports your fake upstreams are actually listening\n \/\/ on (since you're supposed to leave them as 0).\n \/\/ 3) It creates and starts an IntegrationTestServer - the thing that wraps the almost-actual\n \/\/ Envoy used in the tests.\n \/\/ 4) Bringing up the server usually entails waiting to ensure that any listeners specified in\n \/\/ the bootstrap config have come up, and registering them in a port map (see lookupPort()).\n \/\/ However, this test needs to defer all of that to later.\n defer_listener_finalization_ = true;\n HttpIntegrationTest::initialize();\n\n \/\/ Now that the upstream has been created, process Envoy's request to discover it.\n \/\/ (First, we have to let Envoy establish its connection to the RDS server.)\n AssertionResult result = \/\/ xds_connection_ is filled with the new FakeHttpConnection.\n fake_upstreams_[0]->waitForHttpConnection(*dispatcher_, xds_connection_);\n RELEASE_ASSERT(result, result.message());\n result = xds_connection_->waitForNewStream(*dispatcher_, xds_stream_);\n RELEASE_ASSERT(result, result.message());\n xds_stream_->startGrpcStream();\n fake_upstreams_[0]->set_allow_unexpected_disconnects(true);\n\n EXPECT_TRUE(\n compareDiscoveryRequest(Config::TypeUrl::get().RouteConfiguration, \"\", {\"my_route\"}));\n sendDiscoveryResponse(\n Config::TypeUrl::get().RouteConfiguration, {rdsConfig()}, \"1\");\n\n result = xds_connection_->waitForNewStream(*dispatcher_, vhds_stream_, true);\n RELEASE_ASSERT(result, result.message());\n vhds_stream_->startGrpcStream();\n\n EXPECT_TRUE(\n compareDeltaDiscoveryRequest(Config::TypeUrl::get().VirtualHost, {}, {}, vhds_stream_));\n sendDeltaDiscoveryResponse({buildVirtualHost()}, {}, \"1\",\n vhds_stream_);\n EXPECT_TRUE(\n compareDeltaDiscoveryRequest(Config::TypeUrl::get().VirtualHost, {}, {}, vhds_stream_));\n\n \/\/ Wait for our statically specified listener to become ready, and register its port in the\n \/\/ test framework's downstream listener port map.\n test_server_->waitUntilListenersReady();\n registerTestServerPorts({\"http\"});\n }\n\n void useRdsWithVhosts() { use_rds_with_vhosts = true; }\n const envoy::api::v2::RouteConfiguration rdsConfig() const {\n return TestUtility::parseYaml(\n use_rds_with_vhosts ? RdsConfigWithVhosts : RdsConfig);\n }\n\n FakeStreamPtr vhds_stream_;\n bool use_rds_with_vhosts{false};\n};\n\nINSTANTIATE_TEST_CASE_P(IpVersionsClientType, VhdsIntegrationTest, GRPC_CLIENT_INTEGRATION_PARAMS);\n\n\/\/ tests a scenario when:\n\/\/ - a spontaneous VHDS DiscoveryResponse adds two virtual hosts\n\/\/ - the next spontaneous VHDS DiscoveryResponse removes newly added virtual hosts\n\/\/ - Upstream makes a request to an (now) unknown domain, which fails\nTEST_P(VhdsIntegrationTest, VhdsVirtualHostAddUpdateRemove) {\n \/\/ Calls our initialize(), which includes establishing a listener, route, and cluster.\n testRouterHeaderOnlyRequestAndResponse(nullptr, 1);\n cleanupUpstreamAndDownstream();\n codec_client_->waitForDisconnect();\n\n \/\/ A spontaneous VHDS DiscoveryResponse adds two virtual hosts\n sendDeltaDiscoveryResponse(buildVirtualHost1(), {}, \"2\",\n vhds_stream_);\n EXPECT_TRUE(\n compareDeltaDiscoveryRequest(Config::TypeUrl::get().VirtualHost, {}, {}, vhds_stream_));\n\n testRouterHeaderOnlyRequestAndResponse(nullptr, 1, \"\/one\", \"vhost.first\");\n cleanupUpstreamAndDownstream();\n codec_client_->waitForDisconnect();\n testRouterHeaderOnlyRequestAndResponse(nullptr, 1, \"\/two\", \"vhost.second\");\n cleanupUpstreamAndDownstream();\n codec_client_->waitForDisconnect();\n\n \/\/ A spontaneous VHDS DiscoveryResponse removes newly added virtual hosts\n sendDeltaDiscoveryResponse({}, {\"vhost_1\", \"vhost_2\"}, \"3\",\n vhds_stream_);\n EXPECT_TRUE(\n compareDeltaDiscoveryRequest(Config::TypeUrl::get().VirtualHost, {}, {}, vhds_stream_));\n\n \/\/ an upstream request to an (now) unknown domain\n codec_client_ = makeHttpConnection(makeClientConnection((lookupPort(\"http\"))));\n Http::TestHeaderMapImpl request_headers{{\":method\", \"GET\"},\n {\":path\", \"\/one\"},\n {\":scheme\", \"http\"},\n {\":authority\", \"vhost.first\"},\n {\"x-lyft-user-id\", \"123\"}};\n IntegrationStreamDecoderPtr response = codec_client_->makeHeaderOnlyRequest(request_headers);\n response->waitForHeaders();\n EXPECT_EQ(\"404\", response->headers().Status()->value().getStringView());\n\n cleanupUpstreamAndDownstream();\n}\n\n\/\/ tests a scenario when:\n\/\/ - an RDS exchange contains a non-empty virtual_hosts array\n\/\/ - a spontaneous VHDS DiscoveryResponse adds two virtual hosts\n\/\/ - the next spontaneous VHDS DiscoveryResponse removes newly added virtual hosts\n\/\/ - Upstream makes a request to an (now) unknown domain, which fails\nTEST_P(VhdsIntegrationTest, RdsWithVirtualHostsVhdsVirtualHostAddUpdateRemove) {\n \/\/ RDS exchange with a non-empty virtual_hosts field\n useRdsWithVhosts();\n\n testRouterHeaderOnlyRequestAndResponse(nullptr, 1);\n cleanupUpstreamAndDownstream();\n codec_client_->waitForDisconnect();\n\n \/\/ A spontaneous VHDS DiscoveryResponse adds two virtual hosts\n sendDeltaDiscoveryResponse(buildVirtualHost1(), {}, \"2\",\n vhds_stream_);\n EXPECT_TRUE(\n compareDeltaDiscoveryRequest(Config::TypeUrl::get().VirtualHost, {}, {}, vhds_stream_));\n\n \/\/ verify that rds-based virtual host can be resolved\n testRouterHeaderOnlyRequestAndResponse(nullptr, 1, \"\/rdsone\", \"vhost.rds.first\");\n cleanupUpstreamAndDownstream();\n codec_client_->waitForDisconnect();\n testRouterHeaderOnlyRequestAndResponse(nullptr, 1, \"\/one\", \"vhost.first\");\n cleanupUpstreamAndDownstream();\n codec_client_->waitForDisconnect();\n testRouterHeaderOnlyRequestAndResponse(nullptr, 1, \"\/two\", \"vhost.second\");\n cleanupUpstreamAndDownstream();\n codec_client_->waitForDisconnect();\n\n \/\/ A spontaneous VHDS DiscoveryResponse removes virtual hosts added via vhds\n sendDeltaDiscoveryResponse({}, {\"vhost_1\", \"vhost_2\"}, \"3\",\n vhds_stream_);\n EXPECT_TRUE(\n compareDeltaDiscoveryRequest(Config::TypeUrl::get().VirtualHost, {}, {}, vhds_stream_));\n\n \/\/ verify rds-based virtual host is still present\n testRouterHeaderOnlyRequestAndResponse(nullptr, 1, \"\/rdsone\", \"vhost.rds.first\");\n cleanupUpstreamAndDownstream();\n codec_client_->waitForDisconnect();\n\n codec_client_ = makeHttpConnection(makeClientConnection((lookupPort(\"http\"))));\n Http::TestHeaderMapImpl request_headers{{\":method\", \"GET\"},\n {\":path\", \"\/one\"},\n {\":scheme\", \"http\"},\n {\":authority\", \"vhost.first\"},\n {\"x-lyft-user-id\", \"123\"}};\n IntegrationStreamDecoderPtr response = codec_client_->makeHeaderOnlyRequest(request_headers);\n response->waitForHeaders();\n EXPECT_EQ(\"404\", response->headers().Status()->value().getStringView());\n\n cleanupUpstreamAndDownstream();\n}\n\n} \/\/ namespace\n} \/\/ namespace Envoy\n<|endoftext|>"} {"text":"\/**\n* Copyright (C) 2015 3D Repo Ltd\n*\n* This program is free software: you can redistribute it and\/or modify\n* it under the terms of the GNU Affero General Public License as\n* published by the Free Software Foundation, either version 3 of the\n* License, or (at your option) any later version.\n*\n* This program is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU Affero General Public License for more details.\n*\n* You should have received a copy of the GNU Affero General Public License\n* along with this program. If not, see .\n*\/\n\n#include \n#include \n#include \n#include \n#include \"..\/repo_test_database_info.h\"\n#include \"..\/repo_test_fileservice_info.h\"\n#include \"..\/repo_test_utils.h\"\n\nusing namespace repo;\n\nstatic std::shared_ptr getController()\n{\n\tstatic std::shared_ptr controller =\n\t\tstd::make_shared();\n\n\treturn controller;\n}\n\nTEST(RepoControllerTest, CommitScene) {\n\tauto controller = getController();\n\tauto token = initController(controller.get());\n\t\/\/Try to commit a scene without setting db\/project name\n\tuint8_t errCode;\n\tauto scene = controller->loadSceneFromFile(getDataPath(simpleModel), errCode);\n\tEXPECT_EQ(REPOERR_OK, errCode);\n\tEXPECT_EQ(REPOERR_UNKNOWN_ERR, controller->commitScene(token, scene));\n\tEXPECT_FALSE(scene->isRevisioned());\n\n\t\/\/Trying to commit a scene with empty db and project name should also fail\n\tscene->setDatabaseAndProjectName(\"\", \"\");\n\tEXPECT_EQ(REPOERR_UNKNOWN_ERR, controller->commitScene(token, scene));\n\tEXPECT_FALSE(scene->isRevisioned());\n\n\tscene->setDatabaseAndProjectName(\"balh\", \"\");\n\tEXPECT_EQ(REPOERR_UNKNOWN_ERR, controller->commitScene(token, scene));\n\tEXPECT_FALSE(scene->isRevisioned());\n\n\tscene->setDatabaseAndProjectName(\"\", \"blah\");\n\tEXPECT_EQ(REPOERR_UNKNOWN_ERR, controller->commitScene(token, scene));\n\tEXPECT_FALSE(scene->isRevisioned());\n\n\t\/\/Setting the db name and project name should allow commit successfully\n\tscene->setDatabaseAndProjectName(\"commitSceneTest\", \"commitCube\");\n\tEXPECT_EQ(REPOERR_OK, controller->commitScene(initController(controller.get()), scene));\n\tEXPECT_TRUE(scene->isRevisioned());\n\tEXPECT_TRUE(projectExists(\"commitSceneTest\", \"commitCube\"));\n\tEXPECT_EQ(scene->getOwner(), REPO_GTEST_DBUSER);\n\n\tauto scene2 = controller->loadSceneFromFile(getDataPath(simpleModel), errCode);\n\tstd::string owner = \"dog\";\n\tEXPECT_EQ(errCode, 0);\n\tscene2->setDatabaseAndProjectName(\"commitSceneTest\", \"commitCube2\");\n\tEXPECT_EQ(REPOERR_OK, controller->commitScene(initController(controller.get()), scene2, owner));\n\tEXPECT_TRUE(scene2->isRevisioned());\n\tEXPECT_TRUE(projectExists(\"commitSceneTest\", \"commitCube2\"));\n\tEXPECT_EQ(scene2->getOwner(), owner);\n\n\t\/\/null pointer checks\n\tEXPECT_EQ(REPOERR_UNKNOWN_ERR, controller->commitScene(token, nullptr));\n\tEXPECT_EQ(REPOERR_UNKNOWN_ERR, controller->commitScene(nullptr, scene));\n}\n\nTEST(RepoControllerTest, LoadSceneFromFile) {\n\tauto controller = getController();\n\tauto defaultG = core::model::RepoScene::GraphType::DEFAULT;\n\tauto optG = core::model::RepoScene::GraphType::OPTIMIZED;\n\n\t\/\/standard import\n\tuint8_t errCode;\n\tauto scene = controller->loadSceneFromFile(getDataPath(simpleModel), errCode);\n\tASSERT_TRUE(scene);\n\tEXPECT_EQ(errCode, 0);\n\tASSERT_TRUE(scene->getRoot(defaultG));\n\tASSERT_TRUE(scene->getRoot(optG));\n\tEXPECT_FALSE(scene->isMissingTexture());\n\tEXPECT_FALSE(scene->isRevisioned());\n\tEXPECT_TRUE(dynamic_cast(scene->getRoot(defaultG))->isIdentity());\n\n\t\/\/Import the scene with no transformation reduction\n\tauto sceneNoReduction = controller->loadSceneFromFile(getDataPath(simpleModel), errCode, repo::manipulator::modelconvertor::ModelImportConfig(false));\n\tEXPECT_EQ(errCode, 0);\n\tEXPECT_TRUE(sceneNoReduction);\n\tEXPECT_TRUE(sceneNoReduction->getRoot(defaultG));\n\tEXPECT_TRUE(sceneNoReduction->getRoot(optG));\n\tEXPECT_FALSE(sceneNoReduction->isMissingTexture());\n\t\/\/There should be more transformations in the non-reduced scene than the standard scene\n\tEXPECT_TRUE(sceneNoReduction->getAllTransformations(defaultG).size()\n\t\t\t> scene->getAllTransformations(defaultG).size());\n\n\t\/\/Import the scene with root trans rotated\n\tauto sceneRotated = controller->loadSceneFromFile(getDataPath(simpleModel), errCode, repo::manipulator::modelconvertor::ModelImportConfig(true, true, true));\n\tEXPECT_EQ(errCode, 0);\n\tEXPECT_TRUE(sceneRotated);\n\tASSERT_TRUE(sceneRotated->getRoot(defaultG));\n\tEXPECT_TRUE(sceneRotated->getRoot(optG));\n\tEXPECT_FALSE(sceneRotated->isMissingTexture());\n\t\/\/The root transformation should not be an identity\n\tcore::model::TransformationNode *rootTrans = dynamic_cast(sceneRotated->getRoot(defaultG));\n\tEXPECT_FALSE(rootTrans->isIdentity());\n\n\t\/\/Import the scene with non existant file\n\tauto sceneNoFile = controller->loadSceneFromFile(\"thisFileDoesntExist.obj\", errCode);\n\tEXPECT_EQ(errCode, REPOERR_MODEL_FILE_READ);\n\tEXPECT_FALSE(sceneNoFile);\n\n\t\/\/Import the scene with bad Extension\n\tauto sceneBadExt = controller->loadSceneFromFile(getDataPath(badExtensionFile), errCode);\n\tEXPECT_EQ(errCode, REPOERR_FILE_TYPE_NOT_SUPPORTED);\n\tEXPECT_FALSE(sceneBadExt);\n\n\t\/\/Import the scene with texture but not found\n\tauto sceneNoTex = controller->loadSceneFromFile(getDataPath(texturedModel), errCode);\n\tEXPECT_EQ(errCode, 0);\n\tEXPECT_TRUE(sceneNoTex);\n\tEXPECT_TRUE(sceneNoTex->getRoot(defaultG));\n\tEXPECT_TRUE(sceneNoTex->getRoot(optG));\n\tEXPECT_TRUE(sceneNoTex->isMissingTexture());\n\n\t\/\/Import the scene with texture but not found\n\tauto sceneTex = controller->loadSceneFromFile(getDataPath(texturedModel2), errCode);\n\tEXPECT_EQ(errCode, 0);\n\tEXPECT_TRUE(sceneTex);\n\tEXPECT_TRUE(sceneTex->getRoot(defaultG));\n\tEXPECT_TRUE(sceneTex->getRoot(optG));\n\tEXPECT_FALSE(sceneTex->isMissingTexture());\n\n\t\/\/FIXME: need to test with change of config, but this is probably not trival.\n}ISSUE #558 update test to the new behaviour\/**\n* Copyright (C) 2015 3D Repo Ltd\n*\n* This program is free software: you can redistribute it and\/or modify\n* it under the terms of the GNU Affero General Public License as\n* published by the Free Software Foundation, either version 3 of the\n* License, or (at your option) any later version.\n*\n* This program is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU Affero General Public License for more details.\n*\n* You should have received a copy of the GNU Affero General Public License\n* along with this program. If not, see .\n*\/\n\n#include \n#include \n#include \n#include \n#include \"..\/repo_test_database_info.h\"\n#include \"..\/repo_test_fileservice_info.h\"\n#include \"..\/repo_test_utils.h\"\n\nusing namespace repo;\n\nstatic std::shared_ptr getController()\n{\n\tstatic std::shared_ptr controller =\n\t\tstd::make_shared();\n\n\treturn controller;\n}\n\nTEST(RepoControllerTest, CommitScene) {\n\tauto controller = getController();\n\tauto token = initController(controller.get());\n\t\/\/Try to commit a scene without setting db\/project name\n\tuint8_t errCode;\n\tauto scene = controller->loadSceneFromFile(getDataPath(simpleModel), errCode);\n\tEXPECT_EQ(REPOERR_OK, errCode);\n\tEXPECT_EQ(REPOERR_UNKNOWN_ERR, controller->commitScene(token, scene));\n\tEXPECT_FALSE(scene->isRevisioned());\n\n\t\/\/Trying to commit a scene with empty db and project name should also fail\n\tscene->setDatabaseAndProjectName(\"\", \"\");\n\tEXPECT_EQ(REPOERR_UNKNOWN_ERR, controller->commitScene(token, scene));\n\tEXPECT_FALSE(scene->isRevisioned());\n\n\tscene->setDatabaseAndProjectName(\"balh\", \"\");\n\tEXPECT_EQ(REPOERR_UNKNOWN_ERR, controller->commitScene(token, scene));\n\tEXPECT_FALSE(scene->isRevisioned());\n\n\tscene->setDatabaseAndProjectName(\"\", \"blah\");\n\tEXPECT_EQ(REPOERR_UNKNOWN_ERR, controller->commitScene(token, scene));\n\tEXPECT_FALSE(scene->isRevisioned());\n\n\t\/\/Setting the db name and project name should allow commit successfully\n\tscene->setDatabaseAndProjectName(\"commitSceneTest\", \"commitCube\");\n\tEXPECT_EQ(REPOERR_OK, controller->commitScene(initController(controller.get()), scene));\n\tEXPECT_TRUE(scene->isRevisioned());\n\tEXPECT_TRUE(projectExists(\"commitSceneTest\", \"commitCube\"));\n\tEXPECT_EQ(scene->getOwner(), \"ANONYMOUS USER\");\n\n\tauto scene2 = controller->loadSceneFromFile(getDataPath(simpleModel), errCode);\n\tstd::string owner = \"dog\";\n\tEXPECT_EQ(errCode, 0);\n\tscene2->setDatabaseAndProjectName(\"commitSceneTest\", \"commitCube2\");\n\tEXPECT_EQ(REPOERR_OK, controller->commitScene(initController(controller.get()), scene2, owner));\n\tEXPECT_TRUE(scene2->isRevisioned());\n\tEXPECT_TRUE(projectExists(\"commitSceneTest\", \"commitCube2\"));\n\tEXPECT_EQ(scene2->getOwner(), owner);\n\n\t\/\/null pointer checks\n\tEXPECT_EQ(REPOERR_UNKNOWN_ERR, controller->commitScene(token, nullptr));\n\tEXPECT_EQ(REPOERR_UNKNOWN_ERR, controller->commitScene(nullptr, scene));\n}\n\nTEST(RepoControllerTest, LoadSceneFromFile) {\n\tauto controller = getController();\n\tauto defaultG = core::model::RepoScene::GraphType::DEFAULT;\n\tauto optG = core::model::RepoScene::GraphType::OPTIMIZED;\n\n\t\/\/standard import\n\tuint8_t errCode;\n\tauto scene = controller->loadSceneFromFile(getDataPath(simpleModel), errCode);\n\tASSERT_TRUE(scene);\n\tEXPECT_EQ(errCode, 0);\n\tASSERT_TRUE(scene->getRoot(defaultG));\n\tASSERT_TRUE(scene->getRoot(optG));\n\tEXPECT_FALSE(scene->isMissingTexture());\n\tEXPECT_FALSE(scene->isRevisioned());\n\tEXPECT_TRUE(dynamic_cast(scene->getRoot(defaultG))->isIdentity());\n\n\t\/\/Import the scene with no transformation reduction\n\tauto sceneNoReduction = controller->loadSceneFromFile(getDataPath(simpleModel), errCode, repo::manipulator::modelconvertor::ModelImportConfig(false));\n\tEXPECT_EQ(errCode, 0);\n\tEXPECT_TRUE(sceneNoReduction);\n\tEXPECT_TRUE(sceneNoReduction->getRoot(defaultG));\n\tEXPECT_TRUE(sceneNoReduction->getRoot(optG));\n\tEXPECT_FALSE(sceneNoReduction->isMissingTexture());\n\t\/\/There should be more transformations in the non-reduced scene than the standard scene\n\tEXPECT_TRUE(sceneNoReduction->getAllTransformations(defaultG).size()\n\t\t\t> scene->getAllTransformations(defaultG).size());\n\n\t\/\/Import the scene with root trans rotated\n\tauto sceneRotated = controller->loadSceneFromFile(getDataPath(simpleModel), errCode, repo::manipulator::modelconvertor::ModelImportConfig(true, true, true));\n\tEXPECT_EQ(errCode, 0);\n\tEXPECT_TRUE(sceneRotated);\n\tASSERT_TRUE(sceneRotated->getRoot(defaultG));\n\tEXPECT_TRUE(sceneRotated->getRoot(optG));\n\tEXPECT_FALSE(sceneRotated->isMissingTexture());\n\t\/\/The root transformation should not be an identity\n\tcore::model::TransformationNode *rootTrans = dynamic_cast(sceneRotated->getRoot(defaultG));\n\tEXPECT_FALSE(rootTrans->isIdentity());\n\n\t\/\/Import the scene with non existant file\n\tauto sceneNoFile = controller->loadSceneFromFile(\"thisFileDoesntExist.obj\", errCode);\n\tEXPECT_EQ(errCode, REPOERR_MODEL_FILE_READ);\n\tEXPECT_FALSE(sceneNoFile);\n\n\t\/\/Import the scene with bad Extension\n\tauto sceneBadExt = controller->loadSceneFromFile(getDataPath(badExtensionFile), errCode);\n\tEXPECT_EQ(errCode, REPOERR_FILE_TYPE_NOT_SUPPORTED);\n\tEXPECT_FALSE(sceneBadExt);\n\n\t\/\/Import the scene with texture but not found\n\tauto sceneNoTex = controller->loadSceneFromFile(getDataPath(texturedModel), errCode);\n\tEXPECT_EQ(errCode, 0);\n\tEXPECT_TRUE(sceneNoTex);\n\tEXPECT_TRUE(sceneNoTex->getRoot(defaultG));\n\tEXPECT_TRUE(sceneNoTex->getRoot(optG));\n\tEXPECT_TRUE(sceneNoTex->isMissingTexture());\n\n\t\/\/Import the scene with texture but not found\n\tauto sceneTex = controller->loadSceneFromFile(getDataPath(texturedModel2), errCode);\n\tEXPECT_EQ(errCode, 0);\n\tEXPECT_TRUE(sceneTex);\n\tEXPECT_TRUE(sceneTex->getRoot(defaultG));\n\tEXPECT_TRUE(sceneTex->getRoot(optG));\n\tEXPECT_FALSE(sceneTex->isMissingTexture());\n\n\t\/\/FIXME: need to test with change of config, but this is probably not trival.\n}<|endoftext|>"} {"text":"\/****************************************************************************\n *\n * Copyright (c) 2017 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file camera_feedback.cpp\n *\n * Online and offline geotagging from camera feedback\n *\n * @author Mohammed Kabir \n *\/\n\n#include \"camera_feedback.hpp\"\n\nnamespace camera_feedback\n{\nCameraFeedback\t*g_camera_feedback;\n}\n\nCameraFeedback::CameraFeedback() :\n\t_task_should_exit(false),\n\t_main_task(-1),\n\t_trigger_sub(-1),\n\t_lpos_sub(-1),\n\t_gpos_sub(-1),\n\t_att_sub(-1),\n\t_capture_pub(nullptr),\n\t_camera_feedback_mode(CAMERA_FEEDBACK_MODE_NONE)\n{\n\n\t\/\/ Parameters\n\t_p_feedback = param_find(\"CAM_FBACK_MODE\");\n\n\tparam_get(_p_feedback, &_camera_feedback_mode);\n\n}\n\nCameraFeedback::~CameraFeedback()\n{\n\n\tif (_main_task != -1) {\n\n\t\t\/* task wakes up every 100ms or so at the longest *\/\n\t\t_task_should_exit = true;\n\n\t\t\/* wait for a second for the task to quit at our request *\/\n\t\tunsigned i = 0;\n\n\t\tdo {\n\t\t\t\/* wait 20ms *\/\n\t\t\tusleep(20000);\n\n\t\t\t\/* if we have given up, kill it *\/\n\t\t\tif (++i > 50) {\n\t\t\t\tpx4_task_delete(_main_task);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} while (_main_task != -1);\n\t}\n\n\tcamera_feedback::g_camera_feedback = nullptr;\n}\n\nint\nCameraFeedback::start()\n{\n\n\tASSERT(_main_task == -1);\n\n\t\/* start the task *\/\n\t_main_task = px4_task_spawn_cmd(\"camera_feedback\",\n\t\t\t\t\tSCHED_DEFAULT,\n\t\t\t\t\tSCHED_PRIORITY_DEFAULT + 15,\n\t\t\t\t\t1600,\n\t\t\t\t\t(px4_main_t)&CameraFeedback::task_main_trampoline,\n\t\t\t\t\tnullptr);\n\n\tif (_main_task < 0) {\n\t\twarn(\"task start failed\");\n\t\treturn -errno;\n\t}\n\n\treturn OK;\n\n}\n\nvoid\nCameraFeedback::stop()\n{\n\tif (camera_feedback::g_camera_feedback != nullptr) {\n\t\tdelete (camera_feedback::g_camera_feedback);\n\t}\n}\n\n\nvoid\nCameraFeedback::task_main()\n{\n\n\t\/\/ We only support trigger feedback for now\n\t\/\/ This will later be extended to support hardware feedback from the camera.\n\tif (_camera_feedback_mode != CAMERA_FEEDBACK_MODE_TRIGGER) {\n\t\treturn;\n\t}\n\n\t\/\/ Polling sources\n\t_trigger_sub = orb_subscribe(ORB_ID(camera_trigger));\n\tstruct camera_trigger_s trig = {};\n\n\tpx4_pollfd_struct_t fds[1] = {};\n\tfds[0].fd = _trigger_sub;\n\tfds[0].events = POLLIN;\n\n\t\/\/ Geotagging subscriptions\n\t_lpos_sub = orb_subscribe(ORB_ID(vehicle_local_position));\n\t_gpos_sub = orb_subscribe(ORB_ID(vehicle_global_position));\n\t_att_sub = orb_subscribe(ORB_ID(vehicle_attitude));\n\tstruct vehicle_local_position_s lpos = {};\n\tstruct vehicle_global_position_s gpos = {};\n\tstruct vehicle_attitude_s att = {};\n\n\tbool updated = false;\n\n\twhile (!_task_should_exit) {\n\n\t\t\/* wait for up to 20ms for data *\/\n\t\tint pret = px4_poll(&fds[0], (sizeof(fds) \/ sizeof(fds[0])), 20);\n\n\t\tif (pret < 0) {\n\t\t\tPX4_WARN(\"poll error %d, %d\", pret, errno);\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/* trigger subscription updated *\/\n\t\tif (fds[0].revents & POLLIN) {\n\n\t\t\torb_copy(ORB_ID(camera_trigger), _trigger_sub, &trig);\n\n\t\t\t\/* update geotagging subscriptions *\/\n\t\t\torb_check(_gpos_sub, &updated);\n\n\t\t\tif (updated) {\n\t\t\t\torb_copy(ORB_ID(vehicle_global_position), _gpos_sub, &gpos);\n\t\t\t}\n\n\t\t\torb_check(_lpos_sub, &updated);\n\n\t\t\tif (updated) {\n\t\t\t\torb_copy(ORB_ID(vehicle_local_position), _lpos_sub, &lpos);\n\t\t\t}\n\n\t\t\torb_check(_att_sub, &updated);\n\n\t\t\tif (updated) {\n\t\t\t\torb_copy(ORB_ID(vehicle_attitude), _att_sub, &att);\n\t\t\t}\n\n\t\t\tif (gpos.timestamp == 0 ||\n\t\t\t lpos.timestamp == 0 ||\n\t\t\t att.timestamp == 0 ||\n\t\t\t !lpos.xy_valid) {\n\t\t\t\t\/\/ reject until we have valid data\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tstruct camera_capture_s capture = {};\n\n\t\t\t\/\/ Fill timestamps\n\t\t\tcapture.timestamp = trig.timestamp;\n\n\t\t\tcapture.timestamp_utc = trig.timestamp_utc;\n\n\t\t\t\/\/ Fill image sequence\n\t\t\tcapture.seq = trig.seq;\n\n\t\t\t\/\/ Fill position data\n\t\t\tcapture.lat = gpos.lat;\n\n\t\t\tcapture.lon = gpos.lon;\n\n\t\t\tcapture.alt = gpos.alt;\n\n\t\t\tcapture.ground_distance = lpos.dist_bottom_valid ? lpos.dist_bottom : -1.0f;\n\n\t\t\t\/\/ Fill attitude data\n\t\t\t\/\/ TODO : this needs to be rotated by camera orientation or set to gimbal orientation when available\n\t\t\tcapture.q[0] = att.q[0];\n\n\t\t\tcapture.q[1] = att.q[1];\n\n\t\t\tcapture.q[2] = att.q[2];\n\n\t\t\tcapture.q[3] = att.q[3];\n\n\t\t\t\/\/ Indicate that no capture feedback from camera is available\n\t\t\tcapture.result = -1;\n\n\t\t\tint instance_id;\n\n\t\t\torb_publish_auto(ORB_ID(camera_capture), &_capture_pub, &capture, &instance_id, ORB_PRIO_DEFAULT);\n\n\t\t}\n\n\t}\n\n\tPX4_INFO(\"Exiting.\");\n\t_main_task = -1;\n\n}\n\nvoid\nCameraFeedback::task_main_trampoline(int argc, char *argv[])\n{\n\tcamera_feedback::g_camera_feedback->task_main();\n}\n\nstatic int usage()\n{\n\tPX4_INFO(\"usage: camera_feedback {start|stop}\\n\");\n\treturn 1;\n}\n\nextern \"C\" __EXPORT int camera_feedback_main(int argc, char *argv[]);\n\nint camera_feedback_main(int argc, char *argv[])\n{\n\tif (argc < 2) {\n\t\treturn usage();\n\t}\n\n\tif (!strcmp(argv[1], \"start\")) {\n\n\t\tif (camera_feedback::g_camera_feedback != nullptr) {\n\t\t\tPX4_WARN(\"already running\");\n\t\t\treturn 0;\n\t\t}\n\n\t\tcamera_feedback::g_camera_feedback = new CameraFeedback();\n\n\t\tif (camera_feedback::g_camera_feedback == nullptr) {\n\t\t\tPX4_WARN(\"alloc failed\");\n\t\t\treturn 1;\n\t\t}\n\n\t\tcamera_feedback::g_camera_feedback->start();\n\t\treturn 0;\n\t}\n\n\tif (camera_feedback::g_camera_feedback == nullptr) {\n\t\tPX4_WARN(\"not running\");\n\t\treturn 1;\n\n\t} else if (!strcmp(argv[1], \"stop\")) {\n\t\tcamera_feedback::g_camera_feedback->stop();\n\n\t} else {\n\t\treturn usage();\n\t}\n\n\treturn 0;\n}camera_feedback : only use global position subscription to fill geotagging packet\/****************************************************************************\n *\n * Copyright (c) 2017 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file camera_feedback.cpp\n *\n * Online and offline geotagging from camera feedback\n *\n * @author Mohammed Kabir \n *\/\n\n#include \"camera_feedback.hpp\"\n\nnamespace camera_feedback\n{\nCameraFeedback\t*g_camera_feedback;\n}\n\nCameraFeedback::CameraFeedback() :\n\t_task_should_exit(false),\n\t_main_task(-1),\n\t_trigger_sub(-1),\n\t_gpos_sub(-1),\n\t_att_sub(-1),\n\t_capture_pub(nullptr),\n\t_camera_feedback_mode(CAMERA_FEEDBACK_MODE_NONE)\n{\n\n\t\/\/ Parameters\n\t_p_feedback = param_find(\"CAM_FBACK_MODE\");\n\n\tparam_get(_p_feedback, &_camera_feedback_mode);\n\n}\n\nCameraFeedback::~CameraFeedback()\n{\n\n\tif (_main_task != -1) {\n\n\t\t\/* task wakes up every 100ms or so at the longest *\/\n\t\t_task_should_exit = true;\n\n\t\t\/* wait for a second for the task to quit at our request *\/\n\t\tunsigned i = 0;\n\n\t\tdo {\n\t\t\t\/* wait 20ms *\/\n\t\t\tusleep(20000);\n\n\t\t\t\/* if we have given up, kill it *\/\n\t\t\tif (++i > 50) {\n\t\t\t\tpx4_task_delete(_main_task);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} while (_main_task != -1);\n\t}\n\n\tcamera_feedback::g_camera_feedback = nullptr;\n}\n\nint\nCameraFeedback::start()\n{\n\n\tASSERT(_main_task == -1);\n\n\t\/* start the task *\/\n\t_main_task = px4_task_spawn_cmd(\"camera_feedback\",\n\t\t\t\t\tSCHED_DEFAULT,\n\t\t\t\t\tSCHED_PRIORITY_DEFAULT + 15,\n\t\t\t\t\t1600,\n\t\t\t\t\t(px4_main_t)&CameraFeedback::task_main_trampoline,\n\t\t\t\t\tnullptr);\n\n\tif (_main_task < 0) {\n\t\twarn(\"task start failed\");\n\t\treturn -errno;\n\t}\n\n\treturn OK;\n\n}\n\nvoid\nCameraFeedback::stop()\n{\n\tif (camera_feedback::g_camera_feedback != nullptr) {\n\t\tdelete (camera_feedback::g_camera_feedback);\n\t}\n}\n\n\nvoid\nCameraFeedback::task_main()\n{\n\n\t\/\/ We only support trigger feedback for now\n\t\/\/ This will later be extended to support hardware feedback from the camera.\n\tif (_camera_feedback_mode != CAMERA_FEEDBACK_MODE_TRIGGER) {\n\t\treturn;\n\t}\n\n\t\/\/ Polling sources\n\t_trigger_sub = orb_subscribe(ORB_ID(camera_trigger));\n\tstruct camera_trigger_s trig = {};\n\n\tpx4_pollfd_struct_t fds[1] = {};\n\tfds[0].fd = _trigger_sub;\n\tfds[0].events = POLLIN;\n\n\t\/\/ Geotagging subscriptions\n\t_gpos_sub = orb_subscribe(ORB_ID(vehicle_global_position));\n\t_att_sub = orb_subscribe(ORB_ID(vehicle_attitude));\n\tstruct vehicle_global_position_s gpos = {};\n\tstruct vehicle_attitude_s att = {};\n\n\tbool updated = false;\n\n\twhile (!_task_should_exit) {\n\n\t\t\/* wait for up to 20ms for data *\/\n\t\tint pret = px4_poll(&fds[0], (sizeof(fds) \/ sizeof(fds[0])), 20);\n\n\t\tif (pret < 0) {\n\t\t\tPX4_WARN(\"poll error %d, %d\", pret, errno);\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/* trigger subscription updated *\/\n\t\tif (fds[0].revents & POLLIN) {\n\n\t\t\torb_copy(ORB_ID(camera_trigger), _trigger_sub, &trig);\n\n\t\t\t\/* update geotagging subscriptions *\/\n\t\t\torb_check(_gpos_sub, &updated);\n\n\t\t\tif (updated) {\n\t\t\t\torb_copy(ORB_ID(vehicle_global_position), _gpos_sub, &gpos);\n\t\t\t}\n\n\t\t\torb_check(_att_sub, &updated);\n\n\t\t\tif (updated) {\n\t\t\t\torb_copy(ORB_ID(vehicle_attitude), _att_sub, &att);\n\t\t\t}\n\n\t\t\tif (trig.timestamp == 0 ||\n\t\t\t gpos.timestamp == 0 ||\n\t\t\t att.timestamp == 0) {\n\t\t\t\t\/\/ reject until we have valid data\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tstruct camera_capture_s capture = {};\n\n\t\t\t\/\/ Fill timestamps\n\t\t\tcapture.timestamp = trig.timestamp;\n\n\t\t\tcapture.timestamp_utc = trig.timestamp_utc;\n\n\t\t\t\/\/ Fill image sequence\n\t\t\tcapture.seq = trig.seq;\n\n\t\t\t\/\/ Fill position data\n\t\t\tcapture.lat = gpos.lat;\n\n\t\t\tcapture.lon = gpos.lon;\n\n\t\t\tcapture.alt = gpos.alt;\n\n\t\t\tcapture.ground_distance = gpos.terrain_alt_valid ? (gpos.alt - gpos.terrain_alt) : -1.0f;\n\n\t\t\t\/\/ Fill attitude data\n\t\t\t\/\/ TODO : this needs to be rotated by camera orientation or set to gimbal orientation when available\n\t\t\tcapture.q[0] = att.q[0];\n\n\t\t\tcapture.q[1] = att.q[1];\n\n\t\t\tcapture.q[2] = att.q[2];\n\n\t\t\tcapture.q[3] = att.q[3];\n\n\t\t\t\/\/ Indicate that no capture feedback from camera is available\n\t\t\tcapture.result = -1;\n\n\t\t\tint instance_id;\n\n\t\t\torb_publish_auto(ORB_ID(camera_capture), &_capture_pub, &capture, &instance_id, ORB_PRIO_DEFAULT);\n\n\t\t}\n\n\t}\n\n\tPX4_INFO(\"Exiting.\");\n\t_main_task = -1;\n\n}\n\nvoid\nCameraFeedback::task_main_trampoline(int argc, char *argv[])\n{\n\tcamera_feedback::g_camera_feedback->task_main();\n}\n\nstatic int usage()\n{\n\tPX4_INFO(\"usage: camera_feedback {start|stop}\\n\");\n\treturn 1;\n}\n\nextern \"C\" __EXPORT int camera_feedback_main(int argc, char *argv[]);\n\nint camera_feedback_main(int argc, char *argv[])\n{\n\tif (argc < 2) {\n\t\treturn usage();\n\t}\n\n\tif (!strcmp(argv[1], \"start\")) {\n\n\t\tif (camera_feedback::g_camera_feedback != nullptr) {\n\t\t\tPX4_WARN(\"already running\");\n\t\t\treturn 0;\n\t\t}\n\n\t\tcamera_feedback::g_camera_feedback = new CameraFeedback();\n\n\t\tif (camera_feedback::g_camera_feedback == nullptr) {\n\t\t\tPX4_WARN(\"alloc failed\");\n\t\t\treturn 1;\n\t\t}\n\n\t\tcamera_feedback::g_camera_feedback->start();\n\t\treturn 0;\n\t}\n\n\tif (camera_feedback::g_camera_feedback == nullptr) {\n\t\tPX4_WARN(\"not running\");\n\t\treturn 1;\n\n\t} else if (!strcmp(argv[1], \"stop\")) {\n\t\tcamera_feedback::g_camera_feedback->stop();\n\n\t} else {\n\t\treturn usage();\n\t}\n\n\treturn 0;\n}<|endoftext|>"} {"text":"#ifndef EBITEN_GRAPHICS_DETAIL_OPENGL_DEVICE_HPP\n#define EBITEN_GRAPHICS_DETAIL_OPENGL_DEVICE_HPP\n\n#include \"ebiten\/graphics\/detail\/opengl\/graphics_context.hpp\"\n#include \"ebiten\/graphics\/detail\/opengl\/opengl_initializer.hpp\"\n#include \"ebiten\/graphics\/detail\/opengl\/texture_factory.hpp\"\n#include \"ebiten\/graphics\/detail\/opengl\/texture_pointer.hpp\"\n#include \"ebiten\/graphics\/native_view.hpp\"\n#include \"ebiten\/noncopyable.hpp\"\n#include \"ebiten\/platform.hpp\"\n\n#ifdef EBITEN_MACOSX\n# include \n#endif\n#ifdef EBITEN_IOS\n# import \n#endif\n\n#include \n#include \n#include \n\nnamespace ebiten {\nnamespace graphics {\nnamespace detail {\n\nclass device : private noncopyable {\nprivate:\n std::size_t screen_width_;\n std::size_t screen_height_;\n std::size_t const screen_scale_;\n std::function update_func_;\n std::function draw_func_;\n texture_factory texture_factory_;\n graphics_context graphics_context_;\n texture_pointer offscreen_texture_;\n opengl_initializer opengl_initializer_;\npublic:\n device(std::size_t screen_width,\n std::size_t screen_height,\n std::size_t screen_scale,\n native_view native_view,\n std::function const& update_func,\n std::function const& draw_func)\n : screen_width_(screen_width),\n screen_height_(screen_height),\n screen_scale_(screen_scale),\n update_func_(update_func),\n draw_func_(draw_func),\n texture_factory_(),\n graphics_context_(screen_width,\n screen_height,\n screen_scale,\n this->texture_factory_),\n opengl_initializer_(native_view) {\n assert(0 < this->screen_width_);\n assert(0 < this->screen_height_);\n assert(0 < this->screen_scale_);\n assert(this->screen_width_ <= 4096);\n assert(this->screen_height_ <= 4096);\n assert(this->screen_scale_ <= 4);\n assert(this->update_func_);\n assert(this->draw_func_);\n this->opengl_initializer_.initialize(std::bind(&device::update, this));\n }\n ~device() {\n \/\/ TODO: implement\n }\n void\n set_screen_size(std::size_t screen_width,\n std::size_t screen_height) {\n assert(0 < screen_width);\n assert(0 < screen_height);\n assert(screen_width <= 4096);\n assert(screen_height <= 4096);\n this->screen_width_ = screen_width;\n this->screen_height_ = screen_height;\n this->graphics_context_.set_screen_size(screen_width, screen_height);\n if (!this->offscreen_texture_) {\n return;\n }\n \/\/ TODO: How about the OpenGL context?\n \/\/ TODO: Should a texture include its framebuffer?\n this->graphics_context_.delete_framebuffer(*this->offscreen_texture_);\n this->offscreen_texture_ = nullptr;\n }\nprivate:\n \/*\n * NOTICE:\n * The OpenGL functions should be called only in this method 'update'.\n * Is that better to add an argument to this method?\n *\/\n bool\n update() {\n try {\n if (!this->offscreen_texture_) {\n this->offscreen_texture_ = this->texture_factory_.create(this->screen_width_,\n this->screen_height_);\n }\n assert(static_cast(this->offscreen_texture_));\n bool const terminated = this->update_func_(this->texture_factory_);\n detail::graphics_context& g = this->graphics_context_;\n ::glEnable(GL_TEXTURE_2D);\n ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n g.set_offscreen(*this->offscreen_texture_);\n g.clear();\n this->draw_func_(g, *this->offscreen_texture_);\n g.flush();\n ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n g.reset_offscreen();\n g.clear();\n geometry_matrix geom_mat;\n geom_mat.set_a(this->screen_scale_);\n geom_mat.set_d(this->screen_scale_);\n g.draw_texture(*this->offscreen_texture_,\n 0, 0, this->screen_width_, this->screen_height_,\n geom_mat, color_matrix::identity());\n g.flush();\n return terminated;\n } catch (std::runtime_error const& e) {\n \/\/ TODO: Logging\n std::cerr << e.what() << std::endl;\n std::abort();\n }\n return true;\n }\n};\n\n}\n}\n}\n\n#endif\nDestroy the offscreen texture in the OpenGL context#ifndef EBITEN_GRAPHICS_DETAIL_OPENGL_DEVICE_HPP\n#define EBITEN_GRAPHICS_DETAIL_OPENGL_DEVICE_HPP\n\n#include \"ebiten\/graphics\/detail\/opengl\/graphics_context.hpp\"\n#include \"ebiten\/graphics\/detail\/opengl\/opengl_initializer.hpp\"\n#include \"ebiten\/graphics\/detail\/opengl\/texture_factory.hpp\"\n#include \"ebiten\/graphics\/detail\/opengl\/texture_pointer.hpp\"\n#include \"ebiten\/graphics\/native_view.hpp\"\n#include \"ebiten\/noncopyable.hpp\"\n#include \"ebiten\/platform.hpp\"\n\n#ifdef EBITEN_MACOSX\n# include \n#endif\n#ifdef EBITEN_IOS\n# import \n#endif\n\n#include \n#include \n#include \n\nnamespace ebiten {\nnamespace graphics {\nnamespace detail {\n\nclass device : private noncopyable {\nprivate:\n std::size_t screen_width_;\n std::size_t screen_height_;\n std::size_t const screen_scale_;\n std::function update_func_;\n std::function draw_func_;\n texture_factory texture_factory_;\n graphics_context graphics_context_;\n texture_pointer offscreen_texture_;\n opengl_initializer opengl_initializer_;\n bool to_destory_offscreen_texture_;\npublic:\n device(std::size_t screen_width,\n std::size_t screen_height,\n std::size_t screen_scale,\n native_view native_view,\n std::function const& update_func,\n std::function const& draw_func)\n : screen_width_(screen_width),\n screen_height_(screen_height),\n screen_scale_(screen_scale),\n update_func_(update_func),\n draw_func_(draw_func),\n texture_factory_(),\n graphics_context_(screen_width,\n screen_height,\n screen_scale,\n this->texture_factory_),\n opengl_initializer_(native_view),\n to_destory_offscreen_texture_(false) {\n assert(0 < this->screen_width_);\n assert(0 < this->screen_height_);\n assert(0 < this->screen_scale_);\n assert(this->screen_width_ <= 4096);\n assert(this->screen_height_ <= 4096);\n assert(this->screen_scale_ <= 4);\n assert(this->update_func_);\n assert(this->draw_func_);\n this->opengl_initializer_.initialize(std::bind(&device::update, this));\n }\n ~device() {\n \/\/ TODO: implement\n }\n void\n set_screen_size(std::size_t screen_width,\n std::size_t screen_height) {\n assert(0 < screen_width);\n assert(0 < screen_height);\n assert(screen_width <= 4096);\n assert(screen_height <= 4096);\n this->screen_width_ = screen_width;\n this->screen_height_ = screen_height;\n this->graphics_context_.set_screen_size(screen_width, screen_height);\n this->to_destory_offscreen_texture_ = true;\n }\nprivate:\n \/*\n * NOTICE:\n * The OpenGL functions should be called only in this method 'update'.\n * Is that better to add an argument to this method?\n *\/\n bool\n update() {\n try {\n if (this->to_destory_offscreen_texture_) {\n if (this->offscreen_texture_) {\n \/\/ TODO: Should a texture include its framebuffer?\n this->graphics_context_.delete_framebuffer(*this->offscreen_texture_);\n this->offscreen_texture_ = nullptr;\n }\n this->to_destory_offscreen_texture_ = false;\n }\n if (!this->offscreen_texture_) {\n this->offscreen_texture_ = this->texture_factory_.create(this->screen_width_,\n this->screen_height_);\n }\n assert(static_cast(this->offscreen_texture_));\n bool const terminated = this->update_func_(this->texture_factory_);\n detail::graphics_context& g = this->graphics_context_;\n ::glEnable(GL_TEXTURE_2D);\n ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n g.set_offscreen(*this->offscreen_texture_);\n g.clear();\n this->draw_func_(g, *this->offscreen_texture_);\n g.flush();\n ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n g.reset_offscreen();\n g.clear();\n geometry_matrix geom_mat;\n geom_mat.set_a(this->screen_scale_);\n geom_mat.set_d(this->screen_scale_);\n g.draw_texture(*this->offscreen_texture_,\n 0, 0, this->screen_width_, this->screen_height_,\n geom_mat, color_matrix::identity());\n g.flush();\n return terminated;\n } catch (std::runtime_error const& e) {\n \/\/ TODO: Logging\n std::cerr << e.what() << std::endl;\n std::abort();\n }\n return true;\n }\n};\n\n}\n}\n}\n\n#endif\n<|endoftext|>"} {"text":"#pragma once\n\n#include \n#include \n#include \n#include \n\n\/\/#include \"printPattern.hpp\"\n\/\/#include \"printPercentage.hpp\"\n\/\/#include \"printTime.hpp\"\n#include \"Pattern.hpp\"\n#include \"Time.hpp\"\n#include \"Percentage.hpp\"\n#include \"Label.hpp\"\n\n\/**\n * @brief A set of fancy progress bars.\n *\/\nnamespace ElegantProgressbars{\n \n\/**\n * @brief Writes a fancy progressbar with minimal input\n *\n * Takes the total number of elements to process and creates a nice progressbar\n * from that. This is intended to be called in a loop \/ recursion \/ MPI thread\n * \/ pthread \/ etc. It should be called each time one of the nTotal elements is\n * done processing.\n * Operation can be fine-tuned to write time with high precision and different\n * length of the progressbar through template arguments.\n *\n * @param nTotal the total number of elements to process. If multiple values\n * are supplied in different calls, the function will try to use\n * the highest of those values.\n * @param current (optional) the element you are currently at. This can be used\n * to overwrite the default behaviour (which is to assume that an\n * element was successfully processed each time this function is\n * called)\n * @param highPrecision (template, optional) if set to true, time will be \n * displayed with additional milliseconds\n * @param length (template, optional) used to change the length of the printed\n * progressbar\n *\n *\/\ntemplate\ninline std::string fancyProgressBar(\n unsigned const nTotal, \n unsigned const current = 0\n ){\n\n using namespace std::chrono;\n typedef duration milliseconds;\n\n static unsigned maxNTotal = 0;\n static unsigned part = 0;\n static unsigned tic = 0;\n static time_point startTime;\n if(part==0){ startTime = steady_clock::now(); } \/\/ get the starting time on the very first call\n\n std::stringstream ss;\n auto const now = steady_clock::now();\n\n maxNTotal = std::max(maxNTotal, nTotal);\n part = current ? current : ++part;\n\n \/\/limit the update intervall (not faster than every 35ms. This would be madness.)\n duration const timeSpent = now - startTime;\n if(timeSpent.count() > 0.035f*tic || part == maxNTotal){\n ++tic;\n auto const percentage = static_cast(part) \/ static_cast(maxNTotal);\n std::string s;\n unsigned h;\n\n ss << \"\\r\";\n std::tie(s,h) = Label::print();\n ss << s;\n std::tie(s,h) = Pattern::print(part, maxNTotal, percentage);\n ss << s;\n std::tie(s,h) = Percentage::print(part, maxNTotal, percentage);\n ss << s;\n std::tie(s,h) = Time::print(part, maxNTotal, percentage);\n ss << s;\n if(part==maxNTotal) ss << std::endl;\n ss << std::flush;\n }\n\n return ss.str();\n}\n\n}\nAdopted @brief to autobrief option#pragma once\n\n#include \n#include \n#include \n#include \n\n\/\/#include \"printPattern.hpp\"\n\/\/#include \"printPercentage.hpp\"\n\/\/#include \"printTime.hpp\"\n#include \"Pattern.hpp\"\n#include \"Time.hpp\"\n#include \"Percentage.hpp\"\n#include \"Label.hpp\"\n\n\/**\n * A set of fancy progress bars.\n *\n *\/\nnamespace ElegantProgressbars{\n \n\/**\n * Writes a fancy progressbar with minimal input\n *\n * Takes the total number of elements to process and creates a nice progressbar\n * from that. This is intended to be called in a loop \/ recursion \/ MPI thread\n * \/ pthread \/ etc. It should be called each time one of the nTotal elements is\n * done processing.\n * Operation can be fine-tuned to write time with high precision and different\n * length of the progressbar through template arguments.\n *\n * @param nTotal the total number of elements to process. If multiple values\n * are supplied in different calls, the function will try to use\n * the highest of those values.\n * @param current (optional) the element you are currently at. This can be used\n * to overwrite the default behaviour (which is to assume that an\n * element was successfully processed each time this function is\n * called)\n * @param highPrecision (template, optional) if set to true, time will be \n * displayed with additional milliseconds\n * @param length (template, optional) used to change the length of the printed\n * progressbar\n *\n *\/\ntemplate\ninline std::string fancyProgressBar(\n unsigned const nTotal, \n unsigned const current = 0\n ){\n\n using namespace std::chrono;\n typedef duration milliseconds;\n\n static unsigned maxNTotal = 0;\n static unsigned part = 0;\n static unsigned tic = 0;\n static time_point startTime;\n if(part==0){ startTime = steady_clock::now(); } \/\/ get the starting time on the very first call\n\n std::stringstream ss;\n auto const now = steady_clock::now();\n\n maxNTotal = std::max(maxNTotal, nTotal);\n part = current ? current : ++part;\n\n \/\/limit the update intervall (not faster than every 35ms. This would be madness.)\n duration const timeSpent = now - startTime;\n if(timeSpent.count() > 0.035f*tic || part == maxNTotal){\n ++tic;\n auto const percentage = static_cast(part) \/ static_cast(maxNTotal);\n std::string s;\n unsigned h;\n\n ss << \"\\r\";\n std::tie(s,h) = Label::print();\n ss << s;\n std::tie(s,h) = Pattern::print(part, maxNTotal, percentage);\n ss << s;\n std::tie(s,h) = Percentage::print(part, maxNTotal, percentage);\n ss << s;\n std::tie(s,h) = Time::print(part, maxNTotal, percentage);\n ss << s;\n if(part==maxNTotal) ss << std::endl;\n ss << std::flush;\n }\n\n return ss.str();\n}\n\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2010-2012 Esrille Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"HTMLBodyElementImp.h\"\n\n#include \n\nnamespace org { namespace w3c { namespace dom { namespace bootstrap {\n\nvoid HTMLBodyElementImp::eval()\n{\n HTMLElementImp::eval();\n HTMLElementImp::evalBackground(this);\n HTMLElementImp::evalBgcolor(this);\n}\n\n\/\/ Node\nNode HTMLBodyElementImp::cloneNode(bool deep)\n{\n return new(std::nothrow) HTMLBodyElementImp(this, deep);\n}\n\n\/\/ HTMLBodyElement\nhtml::Function HTMLBodyElementImp::getOnafterprint()\n{\n \/\/ TODO: implement me!\n return static_cast(0);\n}\n\nvoid HTMLBodyElementImp::setOnafterprint(html::Function onafterprint)\n{\n \/\/ TODO: implement me!\n}\n\nhtml::Function HTMLBodyElementImp::getOnbeforeprint()\n{\n \/\/ TODO: implement me!\n return static_cast(0);\n}\n\nvoid HTMLBodyElementImp::setOnbeforeprint(html::Function onbeforeprint)\n{\n \/\/ TODO: implement me!\n}\n\nhtml::Function HTMLBodyElementImp::getOnbeforeunload()\n{\n \/\/ TODO: implement me!\n return static_cast(0);\n}\n\nvoid HTMLBodyElementImp::setOnbeforeunload(html::Function onbeforeunload)\n{\n \/\/ TODO: implement me!\n}\n\nhtml::Function HTMLBodyElementImp::getOnblur()\n{\n \/\/ TODO: implement me!\n return static_cast(0);\n}\n\nvoid HTMLBodyElementImp::setOnblur(html::Function onblur)\n{\n \/\/ TODO: implement me!\n}\n\nhtml::Function HTMLBodyElementImp::getOnerror()\n{\n \/\/ TODO: implement me!\n return static_cast(0);\n}\n\nvoid HTMLBodyElementImp::setOnerror(html::Function onerror)\n{\n \/\/ TODO: implement me!\n}\n\nhtml::Function HTMLBodyElementImp::getOnfocus()\n{\n \/\/ TODO: implement me!\n return static_cast(0);\n}\n\nvoid HTMLBodyElementImp::setOnfocus(html::Function onfocus)\n{\n \/\/ TODO: implement me!\n}\n\nhtml::Function HTMLBodyElementImp::getOnhashchange()\n{\n \/\/ TODO: implement me!\n return static_cast(0);\n}\n\nvoid HTMLBodyElementImp::setOnhashchange(html::Function onhashchange)\n{\n \/\/ TODO: implement me!\n}\n\nhtml::Function HTMLBodyElementImp::getOnload()\n{\n \/\/ TODO: implement me!\n return static_cast(0);\n}\n\nvoid HTMLBodyElementImp::setOnload(html::Function onload)\n{\n getOwnerDocument().getDefaultView().setOnload(onload);\n}\n\nhtml::Function HTMLBodyElementImp::getOnmessage()\n{\n \/\/ TODO: implement me!\n return static_cast(0);\n}\n\nvoid HTMLBodyElementImp::setOnmessage(html::Function onmessage)\n{\n \/\/ TODO: implement me!\n}\n\nhtml::Function HTMLBodyElementImp::getOnoffline()\n{\n \/\/ TODO: implement me!\n return static_cast(0);\n}\n\nvoid HTMLBodyElementImp::setOnoffline(html::Function onoffline)\n{\n \/\/ TODO: implement me!\n}\n\nhtml::Function HTMLBodyElementImp::getOnonline()\n{\n \/\/ TODO: implement me!\n return static_cast(0);\n}\n\nvoid HTMLBodyElementImp::setOnonline(html::Function ononline)\n{\n \/\/ TODO: implement me!\n}\n\nhtml::Function HTMLBodyElementImp::getOnpopstate()\n{\n \/\/ TODO: implement me!\n return static_cast(0);\n}\n\nvoid HTMLBodyElementImp::setOnpopstate(html::Function onpopstate)\n{\n \/\/ TODO: implement me!\n}\n\nhtml::Function HTMLBodyElementImp::getOnpagehide()\n{\n \/\/ TODO: implement me!\n return static_cast(0);\n}\n\nvoid HTMLBodyElementImp::setOnpagehide(html::Function onpagehide)\n{\n \/\/ TODO: implement me!\n}\n\nhtml::Function HTMLBodyElementImp::getOnpageshow()\n{\n \/\/ TODO: implement me!\n return static_cast(0);\n}\n\nvoid HTMLBodyElementImp::setOnpageshow(html::Function onpageshow)\n{\n \/\/ TODO: implement me!\n}\n\nhtml::Function HTMLBodyElementImp::getOnredo()\n{\n \/\/ TODO: implement me!\n return static_cast(0);\n}\n\nvoid HTMLBodyElementImp::setOnredo(html::Function onredo)\n{\n \/\/ TODO: implement me!\n}\n\nhtml::Function HTMLBodyElementImp::getOnresize()\n{\n \/\/ TODO: implement me!\n return static_cast(0);\n}\n\nvoid HTMLBodyElementImp::setOnresize(html::Function onresize)\n{\n \/\/ TODO: implement me!\n}\n\nhtml::Function HTMLBodyElementImp::getOnstorage()\n{\n \/\/ TODO: implement me!\n return static_cast(0);\n}\n\nvoid HTMLBodyElementImp::setOnstorage(html::Function onstorage)\n{\n \/\/ TODO: implement me!\n}\n\nhtml::Function HTMLBodyElementImp::getOnundo()\n{\n \/\/ TODO: implement me!\n return static_cast(0);\n}\n\nvoid HTMLBodyElementImp::setOnundo(html::Function onundo)\n{\n \/\/ TODO: implement me!\n}\n\nhtml::Function HTMLBodyElementImp::getOnunload()\n{\n \/\/ TODO: implement me!\n return static_cast(0);\n}\n\nvoid HTMLBodyElementImp::setOnunload(html::Function onunload)\n{\n \/\/ TODO: implement me!\n}\n\nstd::u16string HTMLBodyElementImp::getText()\n{\n \/\/ TODO: implement me!\n return u\"\";\n}\n\nvoid HTMLBodyElementImp::setText(std::u16string text)\n{\n \/\/ TODO: implement me!\n}\n\nstd::u16string HTMLBodyElementImp::getBgColor()\n{\n \/\/ TODO: implement me!\n return u\"\";\n}\n\nvoid HTMLBodyElementImp::setBgColor(std::u16string bgColor)\n{\n \/\/ TODO: implement me!\n}\n\nstd::u16string HTMLBodyElementImp::getBackground()\n{\n \/\/ TODO: implement me!\n return u\"\";\n}\n\nvoid HTMLBodyElementImp::setBackground(std::u16string background)\n{\n \/\/ TODO: implement me!\n}\n\nstd::u16string HTMLBodyElementImp::getLink()\n{\n \/\/ TODO: implement me!\n return u\"\";\n}\n\nvoid HTMLBodyElementImp::setLink(std::u16string link)\n{\n \/\/ TODO: implement me!\n}\n\nstd::u16string HTMLBodyElementImp::getVLink()\n{\n \/\/ TODO: implement me!\n return u\"\";\n}\n\nvoid HTMLBodyElementImp::setVLink(std::u16string vLink)\n{\n \/\/ TODO: implement me!\n}\n\nstd::u16string HTMLBodyElementImp::getALink()\n{\n \/\/ TODO: implement me!\n return u\"\";\n}\n\nvoid HTMLBodyElementImp::setALink(std::u16string aLink)\n{\n \/\/ TODO: implement me!\n}\n\n}}}} \/\/ org::w3c::dom::bootstrap\n(HTMLBodyElementImp::eval) : Evaluate text attribute.\/*\n * Copyright 2010-2012 Esrille Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"HTMLBodyElementImp.h\"\n\n#include \n\nnamespace org { namespace w3c { namespace dom { namespace bootstrap {\n\nvoid HTMLBodyElementImp::eval()\n{\n HTMLElementImp::eval();\n HTMLElementImp::evalBackground(this);\n HTMLElementImp::evalBgcolor(this);\n HTMLElementImp::evalColor(this, u\"text\", u\"color\");\n}\n\n\/\/ Node\nNode HTMLBodyElementImp::cloneNode(bool deep)\n{\n return new(std::nothrow) HTMLBodyElementImp(this, deep);\n}\n\n\/\/ HTMLBodyElement\nhtml::Function HTMLBodyElementImp::getOnafterprint()\n{\n \/\/ TODO: implement me!\n return static_cast(0);\n}\n\nvoid HTMLBodyElementImp::setOnafterprint(html::Function onafterprint)\n{\n \/\/ TODO: implement me!\n}\n\nhtml::Function HTMLBodyElementImp::getOnbeforeprint()\n{\n \/\/ TODO: implement me!\n return static_cast(0);\n}\n\nvoid HTMLBodyElementImp::setOnbeforeprint(html::Function onbeforeprint)\n{\n \/\/ TODO: implement me!\n}\n\nhtml::Function HTMLBodyElementImp::getOnbeforeunload()\n{\n \/\/ TODO: implement me!\n return static_cast(0);\n}\n\nvoid HTMLBodyElementImp::setOnbeforeunload(html::Function onbeforeunload)\n{\n \/\/ TODO: implement me!\n}\n\nhtml::Function HTMLBodyElementImp::getOnblur()\n{\n \/\/ TODO: implement me!\n return static_cast(0);\n}\n\nvoid HTMLBodyElementImp::setOnblur(html::Function onblur)\n{\n \/\/ TODO: implement me!\n}\n\nhtml::Function HTMLBodyElementImp::getOnerror()\n{\n \/\/ TODO: implement me!\n return static_cast(0);\n}\n\nvoid HTMLBodyElementImp::setOnerror(html::Function onerror)\n{\n \/\/ TODO: implement me!\n}\n\nhtml::Function HTMLBodyElementImp::getOnfocus()\n{\n \/\/ TODO: implement me!\n return static_cast(0);\n}\n\nvoid HTMLBodyElementImp::setOnfocus(html::Function onfocus)\n{\n \/\/ TODO: implement me!\n}\n\nhtml::Function HTMLBodyElementImp::getOnhashchange()\n{\n \/\/ TODO: implement me!\n return static_cast(0);\n}\n\nvoid HTMLBodyElementImp::setOnhashchange(html::Function onhashchange)\n{\n \/\/ TODO: implement me!\n}\n\nhtml::Function HTMLBodyElementImp::getOnload()\n{\n \/\/ TODO: implement me!\n return static_cast(0);\n}\n\nvoid HTMLBodyElementImp::setOnload(html::Function onload)\n{\n getOwnerDocument().getDefaultView().setOnload(onload);\n}\n\nhtml::Function HTMLBodyElementImp::getOnmessage()\n{\n \/\/ TODO: implement me!\n return static_cast(0);\n}\n\nvoid HTMLBodyElementImp::setOnmessage(html::Function onmessage)\n{\n \/\/ TODO: implement me!\n}\n\nhtml::Function HTMLBodyElementImp::getOnoffline()\n{\n \/\/ TODO: implement me!\n return static_cast(0);\n}\n\nvoid HTMLBodyElementImp::setOnoffline(html::Function onoffline)\n{\n \/\/ TODO: implement me!\n}\n\nhtml::Function HTMLBodyElementImp::getOnonline()\n{\n \/\/ TODO: implement me!\n return static_cast(0);\n}\n\nvoid HTMLBodyElementImp::setOnonline(html::Function ononline)\n{\n \/\/ TODO: implement me!\n}\n\nhtml::Function HTMLBodyElementImp::getOnpopstate()\n{\n \/\/ TODO: implement me!\n return static_cast(0);\n}\n\nvoid HTMLBodyElementImp::setOnpopstate(html::Function onpopstate)\n{\n \/\/ TODO: implement me!\n}\n\nhtml::Function HTMLBodyElementImp::getOnpagehide()\n{\n \/\/ TODO: implement me!\n return static_cast(0);\n}\n\nvoid HTMLBodyElementImp::setOnpagehide(html::Function onpagehide)\n{\n \/\/ TODO: implement me!\n}\n\nhtml::Function HTMLBodyElementImp::getOnpageshow()\n{\n \/\/ TODO: implement me!\n return static_cast(0);\n}\n\nvoid HTMLBodyElementImp::setOnpageshow(html::Function onpageshow)\n{\n \/\/ TODO: implement me!\n}\n\nhtml::Function HTMLBodyElementImp::getOnredo()\n{\n \/\/ TODO: implement me!\n return static_cast(0);\n}\n\nvoid HTMLBodyElementImp::setOnredo(html::Function onredo)\n{\n \/\/ TODO: implement me!\n}\n\nhtml::Function HTMLBodyElementImp::getOnresize()\n{\n \/\/ TODO: implement me!\n return static_cast(0);\n}\n\nvoid HTMLBodyElementImp::setOnresize(html::Function onresize)\n{\n \/\/ TODO: implement me!\n}\n\nhtml::Function HTMLBodyElementImp::getOnstorage()\n{\n \/\/ TODO: implement me!\n return static_cast(0);\n}\n\nvoid HTMLBodyElementImp::setOnstorage(html::Function onstorage)\n{\n \/\/ TODO: implement me!\n}\n\nhtml::Function HTMLBodyElementImp::getOnundo()\n{\n \/\/ TODO: implement me!\n return static_cast(0);\n}\n\nvoid HTMLBodyElementImp::setOnundo(html::Function onundo)\n{\n \/\/ TODO: implement me!\n}\n\nhtml::Function HTMLBodyElementImp::getOnunload()\n{\n \/\/ TODO: implement me!\n return static_cast(0);\n}\n\nvoid HTMLBodyElementImp::setOnunload(html::Function onunload)\n{\n \/\/ TODO: implement me!\n}\n\nstd::u16string HTMLBodyElementImp::getText()\n{\n \/\/ TODO: implement me!\n return u\"\";\n}\n\nvoid HTMLBodyElementImp::setText(std::u16string text)\n{\n \/\/ TODO: implement me!\n}\n\nstd::u16string HTMLBodyElementImp::getBgColor()\n{\n \/\/ TODO: implement me!\n return u\"\";\n}\n\nvoid HTMLBodyElementImp::setBgColor(std::u16string bgColor)\n{\n \/\/ TODO: implement me!\n}\n\nstd::u16string HTMLBodyElementImp::getBackground()\n{\n \/\/ TODO: implement me!\n return u\"\";\n}\n\nvoid HTMLBodyElementImp::setBackground(std::u16string background)\n{\n \/\/ TODO: implement me!\n}\n\nstd::u16string HTMLBodyElementImp::getLink()\n{\n \/\/ TODO: implement me!\n return u\"\";\n}\n\nvoid HTMLBodyElementImp::setLink(std::u16string link)\n{\n \/\/ TODO: implement me!\n}\n\nstd::u16string HTMLBodyElementImp::getVLink()\n{\n \/\/ TODO: implement me!\n return u\"\";\n}\n\nvoid HTMLBodyElementImp::setVLink(std::u16string vLink)\n{\n \/\/ TODO: implement me!\n}\n\nstd::u16string HTMLBodyElementImp::getALink()\n{\n \/\/ TODO: implement me!\n return u\"\";\n}\n\nvoid HTMLBodyElementImp::setALink(std::u16string aLink)\n{\n \/\/ TODO: implement me!\n}\n\n}}}} \/\/ org::w3c::dom::bootstrap\n<|endoftext|>"} {"text":"\/\/\n\/\/ This file is part of the Marble Virtual Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2009 Bastian Holst \n\/\/\n\n\/\/ Self\n#include \"WikipediaModel.h\"\n\n\/\/ Plugin\n#include \"GeonamesParser.h\"\n\n\/\/ Marble\n#include \"GeoDataLatLonAltBox.h\"\n#include \"MarbleGlobal.h\"\n#include \"MarbleWidget.h\"\n#include \"MarbleModel.h\"\n#include \"MarbleDirs.h\"\n#include \"WikipediaItem.h\"\n#include \"MarbleLocale.h\"\n#include \"MarbleDebug.h\"\n\n\/\/ Qt\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace Marble;\n\nWikipediaModel::WikipediaModel( QObject *parent )\n : AbstractDataPluginModel( \"wikipedia\", parent ),\n m_marbleWidget( 0 ),\n m_showThumbnail( true )\n{\n m_wikipediaIcon.addFile( MarbleDirs::path( \"svg\/wikipedia_shadow.svg\" ) );\n\n m_languageCode = MarbleLocale::languageCode();\n}\n\nWikipediaModel::~WikipediaModel()\n{\n}\n\nvoid WikipediaModel::setShowThumbnail( bool show )\n{\n m_showThumbnail = show;\n}\n\nvoid WikipediaModel::getAdditionalItems( const GeoDataLatLonAltBox& box,\n const MarbleModel *model,\n qint32 number )\n{\n \/\/ Geonames only supports wikipedia articles for earth\n if ( model->planetId() != \"earth\" ) {\n return;\n }\n \n QString geonamesUrl( \"http:\/\/ws.geonames.org\/wikipediaBoundingBox\" );\n geonamesUrl += \"?north=\";\n geonamesUrl += QString::number( box.north() * RAD2DEG );\n geonamesUrl += \"&south=\";\n geonamesUrl += QString::number( box.south() * RAD2DEG );\n geonamesUrl += \"&east=\";\n geonamesUrl += QString::number( box.east() * RAD2DEG );\n geonamesUrl += \"&west=\";\n geonamesUrl += QString::number( box.west() * RAD2DEG );\n geonamesUrl += \"&maxRows=\";\n geonamesUrl += QString::number( number );\n geonamesUrl += \"&lang=\";\n geonamesUrl += m_languageCode;\n \n downloadDescriptionFile( QUrl( geonamesUrl ) );\n}\n\nvoid WikipediaModel::parseFile( const QByteArray& file )\n{\n QList list;\n GeonamesParser parser( m_marbleWidget, &list, this );\n \n parser.read( file );\n \n QList items;\n QList::const_iterator it;\n \n for ( it = list.constBegin(); it != list.constEnd(); ++it ) {\n if ( itemExists( (*it)->id() ) ) {\n delete *it;\n continue;\n }\n\n (*it)->setIcon( m_wikipediaIcon );\n \/\/ Currently all wikipedia articles with geotags are on earth\n (*it)->setTarget( \"earth\" );\n QUrl thumbnailImageUrl = (*it)->thumbnailImageUrl();\n if ( m_showThumbnail && !thumbnailImageUrl.isEmpty() ) {\n downloadItem( thumbnailImageUrl, \"thumbnail\", *it );\n }\n else {\n items << *it;\n }\n }\n\n addItemsToList( items );\n}\n\nvoid WikipediaModel::setMarbleWidget(MarbleWidget *widget)\n{\n m_marbleWidget = widget;\n}\n\n#include \"WikipediaModel.moc\"\nconstruct a QUrl rather than a QString\/\/\n\/\/ This file is part of the Marble Virtual Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2009 Bastian Holst \n\/\/\n\n\/\/ Self\n#include \"WikipediaModel.h\"\n\n\/\/ Plugin\n#include \"GeonamesParser.h\"\n\n\/\/ Marble\n#include \"GeoDataLatLonAltBox.h\"\n#include \"MarbleGlobal.h\"\n#include \"MarbleWidget.h\"\n#include \"MarbleModel.h\"\n#include \"MarbleDirs.h\"\n#include \"WikipediaItem.h\"\n#include \"MarbleLocale.h\"\n#include \"MarbleDebug.h\"\n\n\/\/ Qt\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace Marble;\n\nWikipediaModel::WikipediaModel( QObject *parent )\n : AbstractDataPluginModel( \"wikipedia\", parent ),\n m_marbleWidget( 0 ),\n m_wikipediaIcon( MarbleDirs::path( \"svg\/wikipedia_shadow.svg\" ) ),\n m_showThumbnail( true )\n{\n m_languageCode = MarbleLocale::languageCode();\n}\n\nWikipediaModel::~WikipediaModel()\n{\n}\n\nvoid WikipediaModel::setShowThumbnail( bool show )\n{\n m_showThumbnail = show;\n}\n\nvoid WikipediaModel::getAdditionalItems( const GeoDataLatLonAltBox& box,\n const MarbleModel *model,\n qint32 number )\n{\n \/\/ Geonames only supports wikipedia articles for earth\n if ( model->planetId() != \"earth\" ) {\n return;\n }\n \n QUrl geonamesUrl( \"http:\/\/ws.geonames.org\/wikipediaBoundingBox\" );\n geonamesUrl.addQueryItem( \"north\", QString::number( box.north( GeoDataCoordinates::Degree ) ) );\n geonamesUrl.addQueryItem( \"south\", QString::number( box.south( GeoDataCoordinates::Degree ) ) );\n geonamesUrl.addQueryItem( \"east\", QString::number( box.east( GeoDataCoordinates::Degree ) ) );\n geonamesUrl.addQueryItem( \"west\", QString::number( box.west( GeoDataCoordinates::Degree ) ) );\n geonamesUrl.addQueryItem( \"maxRows\", QString::number( number ) );\n geonamesUrl.addQueryItem( \"lang\", m_languageCode );\n \n downloadDescriptionFile( geonamesUrl );\n}\n\nvoid WikipediaModel::parseFile( const QByteArray& file )\n{\n QList list;\n GeonamesParser parser( m_marbleWidget, &list, this );\n \n parser.read( file );\n \n QList items;\n QList::const_iterator it;\n \n for ( it = list.constBegin(); it != list.constEnd(); ++it ) {\n if ( itemExists( (*it)->id() ) ) {\n delete *it;\n continue;\n }\n\n (*it)->setIcon( m_wikipediaIcon );\n \/\/ Currently all wikipedia articles with geotags are on earth\n (*it)->setTarget( \"earth\" );\n QUrl thumbnailImageUrl = (*it)->thumbnailImageUrl();\n if ( m_showThumbnail && !thumbnailImageUrl.isEmpty() ) {\n downloadItem( thumbnailImageUrl, \"thumbnail\", *it );\n }\n else {\n items << *it;\n }\n }\n\n addItemsToList( items );\n}\n\nvoid WikipediaModel::setMarbleWidget(MarbleWidget *widget)\n{\n m_marbleWidget = widget;\n}\n\n#include \"WikipediaModel.moc\"\n<|endoftext|>"} {"text":"#include \"xchainer\/routines\/logic.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"xchainer\/array.h\"\n#include \"xchainer\/device_id.h\"\n#include \"xchainer\/dtype.h\"\n#include \"xchainer\/testing\/array.h\"\n#include \"xchainer\/testing\/array_check.h\"\n#include \"xchainer\/testing\/device_session.h\"\n\nnamespace xchainer {\nnamespace {\n\nclass LogicTest : public ::testing::TestWithParam {\nprotected:\n void SetUp() override {\n const std::string& backend_name = GetParam();\n device_session_.emplace(DeviceId{backend_name, 0});\n }\n\n void TearDown() override { device_session_.reset(); }\n\nprivate:\n nonstd::optional device_session_;\n};\n\nTEST_P(LogicTest, Equal) {\n using T = float;\n\n struct Param {\n T a;\n T b;\n bool e;\n };\n\n std::vector data = {{1.0f, 1.0f, true},\n {1.0f, -1.0f, false},\n {2.0f, 3.0f, false},\n {1.0f, std::nanf(\"\"), false},\n {std::nanf(\"\"), std::nanf(\"\"), false},\n {std::numeric_limits::infinity(), std::numeric_limits::infinity(), true},\n {0.0f, -0.0f, true}};\n std::vector a_data;\n std::vector b_data;\n std::vector e_data;\n std::transform(data.begin(), data.end(), std::back_inserter(a_data), [](const auto& param) { return param.a; });\n std::transform(data.begin(), data.end(), std::back_inserter(b_data), [](const auto& param) { return param.b; });\n std::transform(data.begin(), data.end(), std::back_inserter(e_data), [](const auto& param) { return param.e; });\n Shape shape{static_cast(data.size())};\n Array a = testing::BuildArray(shape).WithData(a_data);\n Array b = testing::BuildArray(shape).WithData(b_data);\n Array e = testing::BuildArray(shape).WithData(e_data);\n Array c = Equal(a, b);\n\n ASSERT_EQ(c.dtype(), Dtype::kBool);\n EXPECT_TRUE(c.IsContiguous());\n EXPECT_ARRAY_EQ(e, c);\n}\n\nTEST_P(LogicTest, EqualBroadcast) {\n using T = int32_t;\n\n Array a = testing::BuildArray({2, 3}).WithData({1, 2, 3, 4, 3, 2});\n Array b = testing::BuildArray({2, 1}).WithData({3, 2});\n Array e = testing::BuildArray({2, 3}).WithData({false, false, true, false, false, true});\n Array o = Equal(a, b);\n EXPECT_ARRAY_EQ(e, o);\n}\n\nTEST_P(LogicTest, Greater) {\n using T = float;\n\n struct Param {\n T a;\n T b;\n bool e;\n };\n\n std::vector data = {{1.0f, 1.0f, false},\n {1.0f, -1.0f, true},\n {2.0f, 3.0f, false},\n {1.0f, std::nanf(\"\"), false},\n {std::nanf(\"\"), std::nanf(\"\"), false},\n {std::numeric_limits::infinity(), std::numeric_limits::infinity(), false},\n {std::numeric_limits::infinity(), 100, true},\n {-std::numeric_limits::infinity(), 100, false},\n {0.0f, -0.0f, false}};\n std::vector a_data;\n std::vector b_data;\n std::vector e_data;\n std::transform(data.begin(), data.end(), std::back_inserter(a_data), [](const auto& param) { return param.a; });\n std::transform(data.begin(), data.end(), std::back_inserter(b_data), [](const auto& param) { return param.b; });\n std::transform(data.begin(), data.end(), std::back_inserter(e_data), [](const auto& param) { return param.e; });\n Shape shape{static_cast(data.size())};\n Array a = testing::BuildArray(shape).WithData(a_data);\n Array b = testing::BuildArray(shape).WithData(b_data);\n Array e = testing::BuildArray(shape).WithData(e_data);\n Array c = Greater(a, b);\n\n ASSERT_EQ(c.dtype(), Dtype::kBool);\n EXPECT_TRUE(c.IsContiguous());\n EXPECT_ARRAY_EQ(e, c);\n}\n\nTEST_P(LogicTest, GreaterBroadcast) {\n using T = int32_t;\n\n Array a = testing::BuildArray({2, 3}).WithData({1, 2, 3, 4, 3, 2});\n Array b = testing::BuildArray({2, 1}).WithData({2, 2});\n Array e = testing::BuildArray({2, 3}).WithData({false, false, true, true, true, false});\n Array o = Greater(a, b);\n EXPECT_ARRAY_EQ(e, o);\n}\n\nTEST_P(LogicTest, LogicalNot) {\n using T = float;\n\n struct Param {\n T a;\n bool e;\n };\n\n std::vector data = {\n {1.0f, false}, {0.0f, true}, {-0.0f, true}, {std::nanf(\"\"), false}, {std::numeric_limits::infinity(), false}};\n std::vector a_data;\n std::vector e_data;\n std::transform(data.begin(), data.end(), std::back_inserter(a_data), [](const auto& param) { return param.a; });\n std::transform(data.begin(), data.end(), std::back_inserter(e_data), [](const auto& param) { return param.e; });\n Shape shape{static_cast(data.size())};\n Array a = testing::BuildArray(shape).WithData(a_data);\n Array e = testing::BuildArray(shape).WithData(e_data);\n Array c = LogicalNot(a);\n\n ASSERT_EQ(c.dtype(), Dtype::kBool);\n EXPECT_TRUE(c.IsContiguous());\n EXPECT_ARRAY_EQ(e, c);\n}\n\nINSTANTIATE_TEST_CASE_P(\n ForEachBackend,\n LogicTest,\n ::testing::Values(\n#ifdef XCHAINER_ENABLE_CUDA\n std::string{\"cuda\"},\n#endif \/\/ XCHAINER_ENABLE_CUDA\n std::string{\"native\"}));\n\n} \/\/ namespace\n} \/\/ namespace xchainer\nlogic_test.cc: CheckForward#include \"xchainer\/routines\/logic.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"xchainer\/array.h\"\n#include \"xchainer\/device_id.h\"\n#include \"xchainer\/dtype.h\"\n#include \"xchainer\/testing\/array.h\"\n#include \"xchainer\/testing\/array_check.h\"\n#include \"xchainer\/testing\/device_session.h\"\n#include \"xchainer\/testing\/routines.h\"\n\nnamespace xchainer {\nnamespace {\n\nclass LogicTest : public ::testing::TestWithParam {\nprotected:\n void SetUp() override {\n const std::string& backend_name = GetParam();\n device_session_.emplace(DeviceId{backend_name, 0});\n }\n\n void TearDown() override { device_session_.reset(); }\n\nprivate:\n nonstd::optional device_session_;\n};\n\nTEST_P(LogicTest, Equal) {\n using T = float;\n\n struct Param {\n T a;\n T b;\n bool e;\n };\n\n std::vector data = {{1.0f, 1.0f, true},\n {1.0f, -1.0f, false},\n {2.0f, 3.0f, false},\n {1.0f, std::nanf(\"\"), false},\n {std::nanf(\"\"), std::nanf(\"\"), false},\n {std::numeric_limits::infinity(), std::numeric_limits::infinity(), true},\n {0.0f, -0.0f, true}};\n std::vector a_data;\n std::vector b_data;\n std::vector e_data;\n std::transform(data.begin(), data.end(), std::back_inserter(a_data), [](const auto& param) { return param.a; });\n std::transform(data.begin(), data.end(), std::back_inserter(b_data), [](const auto& param) { return param.b; });\n std::transform(data.begin(), data.end(), std::back_inserter(e_data), [](const auto& param) { return param.e; });\n Shape shape{static_cast(data.size())};\n Array a = testing::BuildArray(shape).WithData(a_data);\n Array b = testing::BuildArray(shape).WithData(b_data);\n Array e = testing::BuildArray(shape).WithData(e_data);\n\n testing::CheckForward(\n [](const std::vector& xs) {\n Array y = Equal(xs[0], xs[1]);\n EXPECT_EQ(y.dtype(), Dtype::kBool);\n EXPECT_TRUE(y.IsContiguous());\n return std::vector{y};\n },\n {a, b},\n {e},\n \/\/ TODO(sonots): Run concurrency test in CUDA\n GetParam() == \"cuda\" ? 0 : 1);\n}\n\nTEST_P(LogicTest, EqualBroadcast) {\n using T = int32_t;\n\n Array a = testing::BuildArray({2, 3}).WithData({1, 2, 3, 4, 3, 2});\n Array b = testing::BuildArray({2, 1}).WithData({3, 2});\n Array e = testing::BuildArray({2, 3}).WithData({false, false, true, false, false, true});\n\n testing::CheckForward(\n [](const std::vector& xs) { return std::vector{Equal(xs[0], xs[1])}; },\n {a, b},\n {e},\n \/\/ TODO(sonots): Run concurrency test in CUDA\n GetParam() == \"cuda\" ? 0 : 1);\n}\n\nTEST_P(LogicTest, Greater) {\n using T = float;\n\n struct Param {\n T a;\n T b;\n bool e;\n };\n\n std::vector data = {{1.0f, 1.0f, false},\n {1.0f, -1.0f, true},\n {2.0f, 3.0f, false},\n {1.0f, std::nanf(\"\"), false},\n {std::nanf(\"\"), std::nanf(\"\"), false},\n {std::numeric_limits::infinity(), std::numeric_limits::infinity(), false},\n {std::numeric_limits::infinity(), 100, true},\n {-std::numeric_limits::infinity(), 100, false},\n {0.0f, -0.0f, false}};\n std::vector a_data;\n std::vector b_data;\n std::vector e_data;\n std::transform(data.begin(), data.end(), std::back_inserter(a_data), [](const auto& param) { return param.a; });\n std::transform(data.begin(), data.end(), std::back_inserter(b_data), [](const auto& param) { return param.b; });\n std::transform(data.begin(), data.end(), std::back_inserter(e_data), [](const auto& param) { return param.e; });\n Shape shape{static_cast(data.size())};\n Array a = testing::BuildArray(shape).WithData(a_data);\n Array b = testing::BuildArray(shape).WithData(b_data);\n Array e = testing::BuildArray(shape).WithData(e_data);\n\n testing::CheckForward(\n [](const std::vector& xs) {\n Array y = Greater(xs[0], xs[1]);\n EXPECT_EQ(y.dtype(), Dtype::kBool);\n EXPECT_TRUE(y.IsContiguous());\n return std::vector{y};\n },\n {a, b},\n {e},\n \/\/ TODO(sonots): Run concurrency test in CUDA\n GetParam() == \"cuda\" ? 0 : 1);\n}\n\nTEST_P(LogicTest, GreaterBroadcast) {\n using T = int32_t;\n\n Array a = testing::BuildArray({2, 3}).WithData({1, 2, 3, 4, 3, 2});\n Array b = testing::BuildArray({2, 1}).WithData({2, 2});\n Array e = testing::BuildArray({2, 3}).WithData({false, false, true, true, true, false});\n\n testing::CheckForward(\n [](const std::vector& xs) { return std::vector{Greater(xs[0], xs[1])}; },\n {a, b},\n {e},\n \/\/ TODO(sonots): Run concurrency test in CUDA\n GetParam() == \"cuda\" ? 0 : 1);\n}\n\nTEST_P(LogicTest, LogicalNot) {\n using T = float;\n\n struct Param {\n T a;\n bool e;\n };\n\n std::vector data = {\n {1.0f, false}, {0.0f, true}, {-0.0f, true}, {std::nanf(\"\"), false}, {std::numeric_limits::infinity(), false}};\n std::vector a_data;\n std::vector e_data;\n std::transform(data.begin(), data.end(), std::back_inserter(a_data), [](const auto& param) { return param.a; });\n std::transform(data.begin(), data.end(), std::back_inserter(e_data), [](const auto& param) { return param.e; });\n Shape shape{static_cast(data.size())};\n Array a = testing::BuildArray(shape).WithData(a_data);\n Array e = testing::BuildArray(shape).WithData(e_data);\n\n testing::CheckForward(\n [](const std::vector& xs) {\n Array y = LogicalNot(xs[0]);\n EXPECT_EQ(y.dtype(), Dtype::kBool);\n EXPECT_TRUE(y.IsContiguous());\n return std::vector{y};\n },\n {a},\n {e},\n \/\/ TODO(sonots): Run concurrency test in CUDA\n GetParam() == \"cuda\" ? 0 : 1);\n}\n\nINSTANTIATE_TEST_CASE_P(\n ForEachBackend,\n LogicTest,\n ::testing::Values(\n#ifdef XCHAINER_ENABLE_CUDA\n std::string{\"cuda\"},\n#endif \/\/ XCHAINER_ENABLE_CUDA\n std::string{\"native\"}));\n\n} \/\/ namespace\n} \/\/ namespace xchainer\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: ximppage.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 14:00:16 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _XIMPPAGE_HXX\n#define _XIMPPAGE_HXX\n\n#ifndef _XMLOFF_XMLICTXT_HXX\n#include \"xmlictxt.hxx\"\n#endif\n\n#ifndef _SDXMLIMP_IMPL_HXX\n#include \"sdxmlimp_impl.hxx\"\n#endif\n\n#ifndef _XMLOFF_NMSPMAP_HXX\n#include \"nmspmap.hxx\"\n#endif\n\n#ifndef _COM_SUN_STAR_DRAWING_XSHAPES_HPP_\n#include \n#endif\n\n#ifndef _RTTI_HXX\n#include \n#endif\n\n#ifndef _XIMPSHAPE_HXX\n#include \"ximpshap.hxx\"\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ draw:g context (RECURSIVE)\n\nclass SdXMLGenericPageContext : public SvXMLImportContext\n{\n \/\/ the shape group this group is working on\n com::sun::star::uno::Reference< com::sun::star::drawing::XShapes > mxShapes;\n\nprotected:\n rtl::OUString maPageLayoutName;\n rtl::OUString maUseHeaderDeclName;\n rtl::OUString maUseFooterDeclName;\n rtl::OUString maUseDateTimeDeclName;\n\n void SetLocalShapesContext(com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rNew)\n { mxShapes = rNew; }\n\n \/** sets the page style on this page *\/\n void SetStyle( rtl::OUString& rStyleName );\n\n \/** sets the presentation layout at this page. It is used for drawing pages and for the handout master *\/\n void SetLayout();\n\n \/** deletes all shapes on this drawing page *\/\n void DeleteAllShapes();\n\n const SdXMLImport& GetSdImport() const { return (const SdXMLImport&)GetImport(); }\n SdXMLImport& GetSdImport() { return (SdXMLImport&)GetImport(); }\n\n \/** sets the properties from a page master style with the given name on this contexts page *\/\n void SetPageMaster( rtl::OUString& rsPageMasterName );\n\npublic:\n TYPEINFO();\n\n SdXMLGenericPageContext( SvXMLImport& rImport, USHORT nPrfx, const rtl::OUString& rLocalName,\n const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList,\n com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rShapes);\n virtual ~SdXMLGenericPageContext();\n\n virtual void StartElement( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );\n virtual SvXMLImportContext *CreateChildContext(\n USHORT nPrefix, const rtl::OUString& rLocalName,\n const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList );\n virtual void EndElement();\n\n const com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& GetLocalShapesContext() const\n { return mxShapes; }\n com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& GetLocalShapesContext()\n { return mxShapes; }\n};\n\n\n#endif \/\/ _XIMPGROUP_HXX\nINTEGRATION: CWS vgbugs07 (1.7.274); FILE MERGED 2007\/06\/04 13:23:25 vg 1.7.274.1: #i76605# Remove -I ...\/inc\/module hack introduced by hedaburemove01\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: ximppage.hxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: hr $ $Date: 2007-06-27 15:11:06 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _XIMPPAGE_HXX\n#define _XIMPPAGE_HXX\n\n#ifndef _XMLOFF_XMLICTXT_HXX\n#include \n#endif\n\n#ifndef _SDXMLIMP_IMPL_HXX\n#include \"sdxmlimp_impl.hxx\"\n#endif\n\n#ifndef _XMLOFF_NMSPMAP_HXX\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_DRAWING_XSHAPES_HPP_\n#include \n#endif\n\n#ifndef _RTTI_HXX\n#include \n#endif\n\n#ifndef _XIMPSHAPE_HXX\n#include \"ximpshap.hxx\"\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ draw:g context (RECURSIVE)\n\nclass SdXMLGenericPageContext : public SvXMLImportContext\n{\n \/\/ the shape group this group is working on\n com::sun::star::uno::Reference< com::sun::star::drawing::XShapes > mxShapes;\n\nprotected:\n rtl::OUString maPageLayoutName;\n rtl::OUString maUseHeaderDeclName;\n rtl::OUString maUseFooterDeclName;\n rtl::OUString maUseDateTimeDeclName;\n\n void SetLocalShapesContext(com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rNew)\n { mxShapes = rNew; }\n\n \/** sets the page style on this page *\/\n void SetStyle( rtl::OUString& rStyleName );\n\n \/** sets the presentation layout at this page. It is used for drawing pages and for the handout master *\/\n void SetLayout();\n\n \/** deletes all shapes on this drawing page *\/\n void DeleteAllShapes();\n\n const SdXMLImport& GetSdImport() const { return (const SdXMLImport&)GetImport(); }\n SdXMLImport& GetSdImport() { return (SdXMLImport&)GetImport(); }\n\n \/** sets the properties from a page master style with the given name on this contexts page *\/\n void SetPageMaster( rtl::OUString& rsPageMasterName );\n\npublic:\n TYPEINFO();\n\n SdXMLGenericPageContext( SvXMLImport& rImport, USHORT nPrfx, const rtl::OUString& rLocalName,\n const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList,\n com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rShapes);\n virtual ~SdXMLGenericPageContext();\n\n virtual void StartElement( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );\n virtual SvXMLImportContext *CreateChildContext(\n USHORT nPrefix, const rtl::OUString& rLocalName,\n const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList );\n virtual void EndElement();\n\n const com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& GetLocalShapesContext() const\n { return mxShapes; }\n com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& GetLocalShapesContext()\n { return mxShapes; }\n};\n\n\n#endif \/\/ _XIMPGROUP_HXX\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: fonthdl.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: dvo $ $Date: 2001-06-29 21:07:17 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _XMLOFF_PROPERTYHANDLER_FONTTYPES_HXX\n#include \n#endif\n\n#ifndef _XMLOFF_XMLTOKEN_HXX\n#include \"xmltoken.hxx\"\n#endif\n\n#ifndef _XMLOFF_XMLUCONV_HXX\n#include \"xmluconv.hxx\"\n#endif\n\n#ifndef _RTL_USTRBUF_HXX_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_UNO_ANY_HXX_\n#include \n#endif\n\n#ifndef _VCL_VCLENUM_HXX\n#include \n#endif\n\n#ifndef _XMLOFF_XMLEMENT_HXX\n#include \"xmlelement.hxx\"\n#endif\n\n#ifndef _STRING_HXX\n#include \n#endif\n\nusing namespace ::rtl;\nusing namespace ::com::sun::star;\nusing namespace ::xmloff::token;\n\nstatic SvXMLEnumMapEntry __READONLY_DATA aFontFamilyGenericMapping[] =\n{\n { XML_DECORATIVE, FAMILY_DECORATIVE },\n\n { XML_MODERN, FAMILY_MODERN },\n { XML_ROMAN, FAMILY_ROMAN },\n { XML_SCRIPT, FAMILY_SCRIPT },\n { XML_SWISS, FAMILY_SWISS },\n { XML_SYSTEM, FAMILY_SYSTEM },\n { XML_TOKEN_INVALID, 0 }\n};\n\nstatic SvXMLEnumMapEntry __READONLY_DATA aFontPitchMapping[] =\n{\n { XML_FIXED, PITCH_FIXED },\n { XML_VARIABLE, PITCH_VARIABLE },\n { XML_TOKEN_INVALID, 0 }\n};\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ class XMLFontFamilyNamePropHdl\n\/\/\n\nXMLFontFamilyNamePropHdl::~XMLFontFamilyNamePropHdl()\n{\n \/\/ Nothing to do\n}\n\nsal_Bool XMLFontFamilyNamePropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const\n{\n sal_Bool bRet = sal_False;\n String sValue;\n sal_Int32 nPos = 0;\n\n do\n {\n sal_Int32 nFirst = nPos;\n nPos = SvXMLUnitConverter::indexOfComma( rStrImpValue, nPos );\n sal_Int32 nLast = (-1 == nPos ? rStrImpValue.getLength() : nPos);\n if( nLast > 0 )\n nLast--;\n\n \/\/ skip trailing blanks\n while( sal_Unicode(' ') == rStrImpValue[nLast] && nLast > nFirst )\n nLast--;\n\n \/\/ skip leading blanks\n while( sal_Unicode(' ') == rStrImpValue[nFirst] && nFirst <= nLast )\n nFirst++;\n\n \/\/ remove quotes\n sal_Unicode c = rStrImpValue[nFirst];\n if( nFirst < nLast && (sal_Unicode('\\'') == c || sal_Unicode('\\\"') == c) && rStrImpValue[nLast] == c )\n {\n nFirst++;\n nLast--;\n }\n\n if( nFirst <= nLast )\n {\n if( sValue.Len() != 0 )\n sValue += sal_Unicode(';');\n\n OUString sTemp = rStrImpValue.copy( nFirst, nLast-nFirst+1 );\n sValue += sTemp.getStr();\n }\n\n if( -1 != nPos )\n nPos++;\n }\n while( -1 != nPos );\n\n if( sValue.Len() )\n {\n rValue <<= OUString(sValue.GetBuffer());\n bRet = sal_True;\n }\n\n return bRet;\n}\n\nsal_Bool XMLFontFamilyNamePropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const\n{\n sal_Bool bRet = sal_False;\n OUString aStrFamilyName;\n\n if( rValue >>= aStrFamilyName )\n {\n OUStringBuffer sValue( aStrFamilyName.getLength() + 2L );\n sal_Int32 nPos = 0L;\n do\n {\n sal_Int32 nFirst = nPos;\n nPos = aStrFamilyName.indexOf( sal_Unicode(';'), nPos );\n sal_Int32 nLast = (-1L == nPos ? aStrFamilyName.getLength() : nPos);\n\n \/\/ Set position to the character behind the ';', so we won't\n \/\/ forget this.\n if( -1L != nPos )\n nPos++;\n\n \/\/ If the property value was empty, we stop now.\n \/\/ If there is a ';' at the first position, the empty name\n \/\/ at the start will be removed.\n if( 0L == nLast )\n continue;\n\n \/\/ nFirst and nLast now denote the first and last character of\n \/\/ one font name.\n nLast--;\n\n \/\/ skip trailing blanks\n while( sal_Unicode(' ') == aStrFamilyName[nLast] && nLast > nFirst )\n nLast--;\n\n \/\/ skip leading blanks\n while( sal_Unicode(' ') == aStrFamilyName[nFirst] && nFirst <= nLast )\n nFirst++;\n\n if( nFirst <= nLast )\n {\n if( sValue.getLength() != 0L )\n {\n sValue.append( sal_Unicode( ',' ) );\n sValue.append( sal_Unicode( ' ' ));\n }\n sal_Int32 nLen = nLast-nFirst+1L;\n OUString sFamily( aStrFamilyName.copy( nFirst, nLen ) );\n sal_Bool bQuote = sal_False;\n for( sal_Int32 i=0; i < nLen; i++ )\n {\n sal_Unicode c = sFamily[i];\n if( sal_Unicode(' ') == c || sal_Unicode(',') == c )\n {\n bQuote = sal_True;\n break;\n }\n }\n if( bQuote )\n sValue.append( sal_Unicode('\\'') );\n sValue.append( sFamily );\n if( bQuote )\n sValue.append( sal_Unicode('\\'') );\n }\n }\n while( -1L != nPos );\n\n rStrExpValue = sValue.makeStringAndClear();\n\n bRet = sal_True;\n }\n\n return bRet;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ class XMLFontFamilyPropHdl\n\/\/\n\nXMLFontFamilyPropHdl::~XMLFontFamilyPropHdl()\n{\n \/\/ Nothing to do\n}\n\nsal_Bool XMLFontFamilyPropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const\n{\n sal_Bool bRet = sal_False;\n sal_uInt16 eNewFamily;\n\n if( ( bRet = rUnitConverter.convertEnum( eNewFamily, rStrImpValue, aFontFamilyGenericMapping ) ) )\n rValue <<= (sal_Int16)eNewFamily;\n\n return bRet;\n}\n\nsal_Bool XMLFontFamilyPropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const\n{\n sal_Bool bRet = sal_False;\n OUStringBuffer aOut;\n\n sal_Int16 nFamily;\n if( rValue >>= nFamily )\n {\n FontFamily eFamily = (FontFamily)nFamily;\n if( eFamily != FAMILY_DONTKNOW )\n bRet = rUnitConverter.convertEnum( aOut, eFamily, aFontFamilyGenericMapping );\n }\n\n rStrExpValue = aOut.makeStringAndClear();\n\n return bRet;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ class XMLFontEncodingPropHdl\n\/\/\n\nXMLFontEncodingPropHdl::~XMLFontEncodingPropHdl()\n{\n \/\/ Nothing to do\n}\n\nsal_Bool XMLFontEncodingPropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const\n{\n sal_Bool bRet = sal_True;\n\n if( IsXMLToken( rStrImpValue, XML_X_SYMBOL ) )\n rValue <<= (sal_Int16) RTL_TEXTENCODING_SYMBOL;\n\n return bRet;\n}\n\nsal_Bool XMLFontEncodingPropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const\n{\n sal_Bool bRet = sal_False;\n OUStringBuffer aOut;\n sal_Int16 nSet;\n\n if( rValue >>= nSet )\n {\n if( (rtl_TextEncoding)nSet == RTL_TEXTENCODING_SYMBOL )\n {\n aOut.append( GetXMLToken(XML_X_SYMBOL) );\n rStrExpValue = aOut.makeStringAndClear();\n bRet = sal_True;\n }\n }\n\n return bRet;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ class XMLFontPitchPropHdl\n\/\/\n\nXMLFontPitchPropHdl::~XMLFontPitchPropHdl()\n{\n \/\/ Nothing to do\n}\n\nsal_Bool XMLFontPitchPropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const\n{\n sal_Bool bRet = sal_False;\n USHORT eNewPitch;\n\n if( ( bRet = rUnitConverter.convertEnum( eNewPitch, rStrImpValue, aFontPitchMapping ) ) )\n rValue <<= (sal_Int16)eNewPitch;\n\n return bRet;\n}\n\nsal_Bool XMLFontPitchPropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const\n{\n sal_Bool bRet = sal_False;\n sal_Int16 nPitch;\n OUStringBuffer aOut;\n\n FontPitch ePitch;\n if( rValue >>= nPitch )\n ePitch = (FontPitch)nPitch;\n\n if( PITCH_DONTKNOW != ePitch )\n {\n bRet = rUnitConverter.convertEnum( aOut, ePitch, aFontPitchMapping, XML_FIXED );\n rStrExpValue = aOut.makeStringAndClear();\n }\n\n return bRet;\n}\nINTEGRATION: CWS ooo20040704 (1.6.344); FILE MERGED 2004\/07\/03 14:46:50 waratah 1.6.344.1: #i30874# Correct uninitiliased warnings\/*************************************************************************\n *\n * $RCSfile: fonthdl.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: rt $ $Date: 2004-09-08 15:00:02 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _XMLOFF_PROPERTYHANDLER_FONTTYPES_HXX\n#include \n#endif\n\n#ifndef _XMLOFF_XMLTOKEN_HXX\n#include \"xmltoken.hxx\"\n#endif\n\n#ifndef _XMLOFF_XMLUCONV_HXX\n#include \"xmluconv.hxx\"\n#endif\n\n#ifndef _RTL_USTRBUF_HXX_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_UNO_ANY_HXX_\n#include \n#endif\n\n#ifndef _VCL_VCLENUM_HXX\n#include \n#endif\n\n#ifndef _XMLOFF_XMLEMENT_HXX\n#include \"xmlelement.hxx\"\n#endif\n\n#ifndef _STRING_HXX\n#include \n#endif\n\nusing namespace ::rtl;\nusing namespace ::com::sun::star;\nusing namespace ::xmloff::token;\n\nstatic SvXMLEnumMapEntry __READONLY_DATA aFontFamilyGenericMapping[] =\n{\n { XML_DECORATIVE, FAMILY_DECORATIVE },\n\n { XML_MODERN, FAMILY_MODERN },\n { XML_ROMAN, FAMILY_ROMAN },\n { XML_SCRIPT, FAMILY_SCRIPT },\n { XML_SWISS, FAMILY_SWISS },\n { XML_SYSTEM, FAMILY_SYSTEM },\n { XML_TOKEN_INVALID, 0 }\n};\n\nstatic SvXMLEnumMapEntry __READONLY_DATA aFontPitchMapping[] =\n{\n { XML_FIXED, PITCH_FIXED },\n { XML_VARIABLE, PITCH_VARIABLE },\n { XML_TOKEN_INVALID, 0 }\n};\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ class XMLFontFamilyNamePropHdl\n\/\/\n\nXMLFontFamilyNamePropHdl::~XMLFontFamilyNamePropHdl()\n{\n \/\/ Nothing to do\n}\n\nsal_Bool XMLFontFamilyNamePropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const\n{\n sal_Bool bRet = sal_False;\n String sValue;\n sal_Int32 nPos = 0;\n\n do\n {\n sal_Int32 nFirst = nPos;\n nPos = SvXMLUnitConverter::indexOfComma( rStrImpValue, nPos );\n sal_Int32 nLast = (-1 == nPos ? rStrImpValue.getLength() : nPos);\n if( nLast > 0 )\n nLast--;\n\n \/\/ skip trailing blanks\n while( sal_Unicode(' ') == rStrImpValue[nLast] && nLast > nFirst )\n nLast--;\n\n \/\/ skip leading blanks\n while( sal_Unicode(' ') == rStrImpValue[nFirst] && nFirst <= nLast )\n nFirst++;\n\n \/\/ remove quotes\n sal_Unicode c = rStrImpValue[nFirst];\n if( nFirst < nLast && (sal_Unicode('\\'') == c || sal_Unicode('\\\"') == c) && rStrImpValue[nLast] == c )\n {\n nFirst++;\n nLast--;\n }\n\n if( nFirst <= nLast )\n {\n if( sValue.Len() != 0 )\n sValue += sal_Unicode(';');\n\n OUString sTemp = rStrImpValue.copy( nFirst, nLast-nFirst+1 );\n sValue += sTemp.getStr();\n }\n\n if( -1 != nPos )\n nPos++;\n }\n while( -1 != nPos );\n\n if( sValue.Len() )\n {\n rValue <<= OUString(sValue.GetBuffer());\n bRet = sal_True;\n }\n\n return bRet;\n}\n\nsal_Bool XMLFontFamilyNamePropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const\n{\n sal_Bool bRet = sal_False;\n OUString aStrFamilyName;\n\n if( rValue >>= aStrFamilyName )\n {\n OUStringBuffer sValue( aStrFamilyName.getLength() + 2L );\n sal_Int32 nPos = 0L;\n do\n {\n sal_Int32 nFirst = nPos;\n nPos = aStrFamilyName.indexOf( sal_Unicode(';'), nPos );\n sal_Int32 nLast = (-1L == nPos ? aStrFamilyName.getLength() : nPos);\n\n \/\/ Set position to the character behind the ';', so we won't\n \/\/ forget this.\n if( -1L != nPos )\n nPos++;\n\n \/\/ If the property value was empty, we stop now.\n \/\/ If there is a ';' at the first position, the empty name\n \/\/ at the start will be removed.\n if( 0L == nLast )\n continue;\n\n \/\/ nFirst and nLast now denote the first and last character of\n \/\/ one font name.\n nLast--;\n\n \/\/ skip trailing blanks\n while( sal_Unicode(' ') == aStrFamilyName[nLast] && nLast > nFirst )\n nLast--;\n\n \/\/ skip leading blanks\n while( sal_Unicode(' ') == aStrFamilyName[nFirst] && nFirst <= nLast )\n nFirst++;\n\n if( nFirst <= nLast )\n {\n if( sValue.getLength() != 0L )\n {\n sValue.append( sal_Unicode( ',' ) );\n sValue.append( sal_Unicode( ' ' ));\n }\n sal_Int32 nLen = nLast-nFirst+1L;\n OUString sFamily( aStrFamilyName.copy( nFirst, nLen ) );\n sal_Bool bQuote = sal_False;\n for( sal_Int32 i=0; i < nLen; i++ )\n {\n sal_Unicode c = sFamily[i];\n if( sal_Unicode(' ') == c || sal_Unicode(',') == c )\n {\n bQuote = sal_True;\n break;\n }\n }\n if( bQuote )\n sValue.append( sal_Unicode('\\'') );\n sValue.append( sFamily );\n if( bQuote )\n sValue.append( sal_Unicode('\\'') );\n }\n }\n while( -1L != nPos );\n\n rStrExpValue = sValue.makeStringAndClear();\n\n bRet = sal_True;\n }\n\n return bRet;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ class XMLFontFamilyPropHdl\n\/\/\n\nXMLFontFamilyPropHdl::~XMLFontFamilyPropHdl()\n{\n \/\/ Nothing to do\n}\n\nsal_Bool XMLFontFamilyPropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const\n{\n sal_Bool bRet = sal_False;\n sal_uInt16 eNewFamily;\n\n if( ( bRet = rUnitConverter.convertEnum( eNewFamily, rStrImpValue, aFontFamilyGenericMapping ) ) )\n rValue <<= (sal_Int16)eNewFamily;\n\n return bRet;\n}\n\nsal_Bool XMLFontFamilyPropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const\n{\n sal_Bool bRet = sal_False;\n OUStringBuffer aOut;\n\n sal_Int16 nFamily;\n if( rValue >>= nFamily )\n {\n FontFamily eFamily = (FontFamily)nFamily;\n if( eFamily != FAMILY_DONTKNOW )\n bRet = rUnitConverter.convertEnum( aOut, eFamily, aFontFamilyGenericMapping );\n }\n\n rStrExpValue = aOut.makeStringAndClear();\n\n return bRet;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ class XMLFontEncodingPropHdl\n\/\/\n\nXMLFontEncodingPropHdl::~XMLFontEncodingPropHdl()\n{\n \/\/ Nothing to do\n}\n\nsal_Bool XMLFontEncodingPropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const\n{\n sal_Bool bRet = sal_True;\n\n if( IsXMLToken( rStrImpValue, XML_X_SYMBOL ) )\n rValue <<= (sal_Int16) RTL_TEXTENCODING_SYMBOL;\n\n return bRet;\n}\n\nsal_Bool XMLFontEncodingPropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const\n{\n sal_Bool bRet = sal_False;\n OUStringBuffer aOut;\n sal_Int16 nSet;\n\n if( rValue >>= nSet )\n {\n if( (rtl_TextEncoding)nSet == RTL_TEXTENCODING_SYMBOL )\n {\n aOut.append( GetXMLToken(XML_X_SYMBOL) );\n rStrExpValue = aOut.makeStringAndClear();\n bRet = sal_True;\n }\n }\n\n return bRet;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ class XMLFontPitchPropHdl\n\/\/\n\nXMLFontPitchPropHdl::~XMLFontPitchPropHdl()\n{\n \/\/ Nothing to do\n}\n\nsal_Bool XMLFontPitchPropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const\n{\n sal_Bool bRet = sal_False;\n USHORT eNewPitch;\n\n if( ( bRet = rUnitConverter.convertEnum( eNewPitch, rStrImpValue, aFontPitchMapping ) ) )\n rValue <<= (sal_Int16)eNewPitch;\n\n return bRet;\n}\n\nsal_Bool XMLFontPitchPropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const\n{\n sal_Bool bRet = sal_False;\n sal_Int16 nPitch;\n OUStringBuffer aOut;\n\n FontPitch ePitch = PITCH_DONTKNOW;\n if( rValue >>= nPitch )\n ePitch = (FontPitch)nPitch;\n\n if( PITCH_DONTKNOW != ePitch )\n {\n bRet = rUnitConverter.convertEnum( aOut, ePitch, aFontPitchMapping, XML_FIXED );\n rStrExpValue = aOut.makeStringAndClear();\n }\n\n return bRet;\n}\n<|endoftext|>"} {"text":"lowered dist threshhold<|endoftext|>"} {"text":"#pragma once\n\n#include \n#include \n#include \n#include \n\n#include \"cxxtest\/TestSuite.h\"\n\n#include \n\nusing namespace std;\n\nclass MessageTrackerTest : public CxxTest::TestSuite\n{\n public:\n void setUp() override {}\n void tearDown() override {}\n\n struct example_t {\n uint64_t utime;\n int decode(void* data, int start, int max) { return 0; }\n static const char* getTypeName() { return \"example_t\"; }\n };\n\n struct data_t {\n uint64_t utime;\n int offset;\n int bufInd;\n };\n\n void testFreqStats()\n {\n constexpr size_t numMsgs = 1000;\n zcm::MessageTracker mt(nullptr, \"\", 0.25, numMsgs);\n for (size_t i = 0; i < 1000; ++i) {\n example_t tmp;\n tmp.utime = i * 1e4;\n mt.newMsg(&tmp, tmp.utime + 1);\n TS_ASSERT_EQUALS(mt.lastMsgHostUtime(), tmp.utime + 1);\n }\n TS_ASSERT_DELTA(mt.getHz(), 100, 1e-5);\n TS_ASSERT_LESS_THAN(mt.getJitterUs(), 1e-5);\n }\n\n void testGetRange()\n {\n constexpr size_t numMsgs = 1000;\n \/\/ RRR (Bendes) You're telling the message tracker to not track any\n \/\/ messages older than 100 us 0.0001s = 100us\n zcm::MessageTracker mt(nullptr, \"\", 0.0001, numMsgs);\n for (size_t i = 0; i < 1000; ++i) {\n example_t tmp;\n tmp.utime = i + 101;\n mt.newMsg(&tmp);\n }\n\n vector gotRange = mt.getRange(101, 105);\n TS_ASSERT_EQUALS(gotRange.size(), 5);\n for (auto msg : gotRange) {\n TS_ASSERT(msg->utime >= 101 && msg->utime <= 105);\n delete msg;\n }\n\n gotRange = mt.getRange(105, 105);\n TS_ASSERT_EQUALS(gotRange.size(), 1);\n for (auto msg : gotRange) {\n TS_ASSERT_EQUALS(msg->utime, 105);\n delete msg;\n }\n\n gotRange = mt.getRange(110, 105);\n TS_ASSERT_EQUALS(gotRange.size(), 0);\n\n gotRange = mt.getRange(0, 1);\n TS_ASSERT_EQUALS(gotRange.size(), 1);\n for (auto msg : gotRange) {\n TS_ASSERT_EQUALS(msg->utime, 101);\n delete msg;\n }\n\n gotRange = mt.getRange(1200, 1300);\n TS_ASSERT_EQUALS(gotRange.size(), 1);\n for (auto msg : gotRange) {\n TS_ASSERT_EQUALS(msg->utime, 1100);\n delete msg;\n }\n\n gotRange = mt.getRange(1201, 1300);\n TS_ASSERT_EQUALS(gotRange.size(), 0);\n\n gotRange = mt.getRange(0, 0);\n TS_ASSERT_EQUALS(gotRange.size(), 0);\n\n gotRange = mt.getRange(100, 100);\n TS_ASSERT_EQUALS(gotRange.size(), 1);\n for (auto msg : gotRange) {\n TS_ASSERT_EQUALS(msg->utime, 101);\n delete msg;\n }\n\n gotRange = mt.getRange(1102, 1205);\n TS_ASSERT_EQUALS(gotRange.size(), 1);\n for (auto msg : gotRange) {\n TS_ASSERT_EQUALS(msg->utime, 1100);\n delete msg;\n }\n }\n\n void testGetInternalBuf()\n {\n struct data_t {\n uint64_t utime;\n int offset;\n int bufInd;\n int decode(void* data, int start, int max) { return 0; }\n static const char* getTypeName() { return \"data_t\"; }\n };\n\n size_t numMsgs = 10;\n zcm::MessageTracker mt(nullptr, \"\", 0.25, numMsgs);\n for (int i = 0; i < 10; i++) {\n data_t d = {123456780 + (uint64_t)i, 100 + i, i};\n mt.newMsg(&d, 0);\n }\n data_t* out = mt.get((uint64_t)123456785);\n TS_ASSERT(out != nullptr);\n if (out!= nullptr)\n TS_ASSERT_EQUALS(out->bufInd, 5);\n out = mt.get((uint64_t)123456790);\n TS_ASSERT_EQUALS(out->bufInd, 9);\n TS_ASSERT(out != nullptr);\n if (out!= nullptr)\n TS_ASSERT_EQUALS(out->bufInd, 9);\n\n }\n\n void testGetTrackerUsingInternalBuf()\n {\n size_t numMsgs = 100;\n zcm::Tracker mt(0.25, numMsgs);\n for (int i = 0; i < (int) numMsgs; i++) {\n data_t d = {1234567810 + (uint64_t)i, 100 + i, i};\n mt.newMsg(&d);\n }\n data_t* out = mt.get((uint64_t)1234567815);\n TS_ASSERT(out != nullptr);\n if (out!= nullptr)\n TS_ASSERT_EQUALS(out->bufInd, 5);\n out = mt.get((uint64_t)1234567950);\n TS_ASSERT(out != nullptr);\n if (out!= nullptr)\n TS_ASSERT_EQUALS(out->bufInd, (uint64_t) 99);\n out = mt.get((uint64_t)1234567890);\n TS_ASSERT(out != nullptr);\n if (out!= nullptr)\n TS_ASSERT_EQUALS(out->utime, (uint64_t)1234567890);\n\n }\n\n void testGetTrackerUsingProvidedBuf()\n {\n\n size_t numMsgs = 10;\n zcm::Tracker mt(0.25, numMsgs);\n std::vector buf(10);\n data_t d;\n for (int i = 0; i < 10; i++) {\n d.utime = 1234567810 + (uint64_t)i;\n d.bufInd = i;\n data_t* tmp = new data_t(d);\n buf[i] = tmp;\n }\n\n std::mutex bufLock;\n std::unique_lock lk(bufLock);\n data_t* out = mt.get((uint64_t)1234567815, buf.begin(), buf.end(), lk);\n TS_ASSERT(out != nullptr);\n if (out!= nullptr)\n TS_ASSERT_EQUALS(out->bufInd, 5);\n out = mt.get((uint64_t)1234567840, buf.begin(), buf.end(), lk);\n TS_ASSERT(out != nullptr);\n if (out!= nullptr)\n TS_ASSERT_EQUALS(out->bufInd, 9);\n out = mt.get((uint64_t)1234567813, std::next(buf.begin(), 5), buf.end(), lk);\n TS_ASSERT(out != nullptr);\n if (out!= nullptr)\n TS_ASSERT_EQUALS(out->bufInd, 5);\n\n \/\/ free the dynamically allocated memory\n for (int i = 0; i < 10; i++) {\n delete buf[i];\n }\n }\n};\ntest fix#pragma once\n\n#include \n#include \n#include \n#include \n\n#include \"cxxtest\/TestSuite.h\"\n\n#include \n\nusing namespace std;\n\nclass MessageTrackerTest : public CxxTest::TestSuite\n{\n public:\n void setUp() override {}\n void tearDown() override {}\n\n struct example_t {\n uint64_t utime;\n int decode(void* data, int start, int max) { return 0; }\n static const char* getTypeName() { return \"example_t\"; }\n };\n\n struct data_t {\n uint64_t utime;\n int offset;\n int bufInd;\n };\n\n void testFreqStats()\n {\n constexpr size_t numMsgs = 1000;\n zcm::MessageTracker mt(nullptr, \"\", 0.25, numMsgs);\n for (size_t i = 0; i < 1000; ++i) {\n example_t tmp;\n tmp.utime = i * 1e4;\n mt.newMsg(&tmp, tmp.utime + 1);\n TS_ASSERT_EQUALS(mt.lastMsgHostUtime(), tmp.utime + 1);\n }\n TS_ASSERT_DELTA(mt.getHz(), 100, 1e-5);\n TS_ASSERT_LESS_THAN(mt.getJitterUs(), 1e-5);\n }\n\n void testGetRange()\n {\n constexpr size_t numMsgs = 1000;\n zcm::MessageTracker mt(nullptr, \"\", 0.001, numMsgs);\n for (size_t i = 0; i < 1000; ++i) {\n example_t tmp;\n tmp.utime = i + 101;\n mt.newMsg(&tmp);\n }\n\n vector gotRange = mt.getRange(101, 105);\n TS_ASSERT_EQUALS(gotRange.size(), 5);\n for (auto msg : gotRange) {\n TS_ASSERT(msg->utime >= 101 && msg->utime <= 105);\n delete msg;\n }\n\n gotRange = mt.getRange(105, 105);\n TS_ASSERT_EQUALS(gotRange.size(), 1);\n for (auto msg : gotRange) {\n TS_ASSERT_EQUALS(msg->utime, 105);\n delete msg;\n }\n\n gotRange = mt.getRange(110, 105);\n TS_ASSERT_EQUALS(gotRange.size(), 0);\n\n gotRange = mt.getRange(0, 1);\n TS_ASSERT_EQUALS(gotRange.size(), 1);\n for (auto msg : gotRange) {\n TS_ASSERT_EQUALS(msg->utime, 101);\n delete msg;\n }\n\n gotRange = mt.getRange(1200, 1300);\n TS_ASSERT_EQUALS(gotRange.size(), 1);\n for (auto msg : gotRange) {\n TS_ASSERT_EQUALS(msg->utime, 1100);\n delete msg;\n }\n\n gotRange = mt.getRange(100, 100);\n TS_ASSERT_EQUALS(gotRange.size(), 1);\n for (auto msg : gotRange) {\n TS_ASSERT_EQUALS(msg->utime, 101);\n delete msg;\n }\n\n gotRange = mt.getRange(1102, 1205);\n TS_ASSERT_EQUALS(gotRange.size(), 1);\n for (auto msg : gotRange) {\n TS_ASSERT_EQUALS(msg->utime, 1100);\n delete msg;\n }\n }\n\n void testGetInternalBuf()\n {\n struct data_t {\n uint64_t utime;\n int offset;\n int bufInd;\n int decode(void* data, int start, int max) { return 0; }\n static const char* getTypeName() { return \"data_t\"; }\n };\n\n size_t numMsgs = 10;\n zcm::MessageTracker mt(nullptr, \"\", 0.25, numMsgs);\n for (int i = 0; i < 10; i++) {\n data_t d = {123456780 + (uint64_t)i, 100 + i, i};\n mt.newMsg(&d, 0);\n }\n data_t* out = mt.get((uint64_t)123456785);\n TS_ASSERT(out != nullptr);\n if (out!= nullptr)\n TS_ASSERT_EQUALS(out->bufInd, 5);\n out = mt.get((uint64_t)123456790);\n TS_ASSERT_EQUALS(out->bufInd, 9);\n TS_ASSERT(out != nullptr);\n if (out!= nullptr)\n TS_ASSERT_EQUALS(out->bufInd, 9);\n\n }\n\n void testGetTrackerUsingInternalBuf()\n {\n size_t numMsgs = 100;\n zcm::Tracker mt(0.25, numMsgs);\n for (int i = 0; i < (int) numMsgs; i++) {\n data_t d = {1234567810 + (uint64_t)i, 100 + i, i};\n mt.newMsg(&d);\n }\n data_t* out = mt.get((uint64_t)1234567815);\n TS_ASSERT(out != nullptr);\n if (out!= nullptr)\n TS_ASSERT_EQUALS(out->bufInd, 5);\n out = mt.get((uint64_t)1234567950);\n TS_ASSERT(out != nullptr);\n if (out!= nullptr)\n TS_ASSERT_EQUALS(out->bufInd, (uint64_t) 99);\n out = mt.get((uint64_t)1234567890);\n TS_ASSERT(out != nullptr);\n if (out!= nullptr)\n TS_ASSERT_EQUALS(out->utime, (uint64_t)1234567890);\n\n }\n\n void testGetTrackerUsingProvidedBuf()\n {\n\n size_t numMsgs = 10;\n zcm::Tracker mt(0.25, numMsgs);\n std::vector buf(10);\n data_t d;\n for (int i = 0; i < 10; i++) {\n d.utime = 1234567810 + (uint64_t)i;\n d.bufInd = i;\n data_t* tmp = new data_t(d);\n buf[i] = tmp;\n }\n\n std::mutex bufLock;\n std::unique_lock lk(bufLock);\n data_t* out = mt.get((uint64_t)1234567815, buf.begin(), buf.end(), lk);\n TS_ASSERT(out != nullptr);\n if (out!= nullptr)\n TS_ASSERT_EQUALS(out->bufInd, 5);\n out = mt.get((uint64_t)1234567840, buf.begin(), buf.end(), lk);\n TS_ASSERT(out != nullptr);\n if (out!= nullptr)\n TS_ASSERT_EQUALS(out->bufInd, 9);\n out = mt.get((uint64_t)1234567813, std::next(buf.begin(), 5), buf.end(), lk);\n TS_ASSERT(out != nullptr);\n if (out!= nullptr)\n TS_ASSERT_EQUALS(out->bufInd, 5);\n\n \/\/ free the dynamically allocated memory\n for (int i = 0; i < 10; i++) {\n delete buf[i];\n }\n }\n};\n<|endoftext|>"} {"text":"\/**\n * File : B.cpp\n * Author : Kazune Takahashi\n * Created : 2018-4-7 14:05:18\n * Powered by Visual Studio Code\n *\/\n\n#include \n#include \/\/ << fixed << setprecision(xxx)\n#include \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include \n#include \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include \n#include \n#include \n#include \n#include \/\/ if (M.find(key) != M.end()) { }\n#include \n#include \/\/ random_device rd; mt19937 mt(rd());\n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\n#define DEBUG 0 \/\/ change 0 -> 1 if we need debug.\n\ntypedef long long ll;\n\nconst int dx[4] = {1, 0, -1, 0};\nconst int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\n\/\/ const ll M = 1000000007;\n\ntypedef tuple state; \/\/ x, y, dir, a, b\n\nint A, B;\nint h, w;\nstring c[100];\n\nstack S;\n\nbool valid(int x, int y, int a, int b)\n{\n return (a <= A && b <= B && c[x][y] == '.');\n}\n\nint main()\n{\n auto start = std::chrono::system_clock::now();\n cin >> A >> B;\n cin >> h >> w;\n for (auto i = 0; i < h; i++)\n {\n cin >> c[i];\n }\n S.push(state(1, 1, 0, 0, 0));\n while (!S.empty())\n {\n auto end = std::chrono::system_clock::now();\n double elapsed = std::chrono::duration_cast(end-start).count();\n if (elapsed > 2000) {\n cout << \"Yes\" << endl;\n return 0;\n }\n int now_x = get<0>(S.top());\n int now_y = get<1>(S.top());\n int now_dir = get<2>(S.top());\n int now_a = get<3>(S.top());\n int now_b = get<4>(S.top());\n #if DEBUG == 1\n cerr << \"(\" << now_x << \", \" << now_y << \"), \"\n << now_dir << \", \"\n << \"(\" << now_a << \", \" << now_b << \")\" << endl;\n #endif\n S.pop();\n if (now_x == h - 2 && now_y == w - 2 && now_a == A && now_b == B)\n {\n cout << \"Yes\" << endl;\n return 0;\n }\n else\n {\n int new_dir[3] = {(now_dir + 1) % 4, (now_dir + 3) % 4, now_dir};\n int new_a[3] = {now_a + 1, now_a, now_a};\n int new_b[3] = {now_b, now_b + 1, now_b};\n for (auto k = 0; k < 3; k++)\n {\n int new_x = now_x + dx[new_dir[k]];\n int new_y = now_y + dy[new_dir[k]];\n if (valid(new_x, new_y, new_a[k], new_b[k]))\n {\n S.push(state(new_x, new_y, new_dir[k], new_a[k], new_b[k]));\n }\n }\n }\n }\n cout << \"No\" << endl;\n}submit B.cpp to 'B - 駆け抜けろ!埼大山車部!!' (maximum-cup-2018) [C++14 (GCC 5.4.1)]\/**\n * File : B.cpp\n * Author : Kazune Takahashi\n * Created : 2018-4-7 14:05:18\n * Powered by Visual Studio Code\n *\/\n\n#include \n#include \/\/ << fixed << setprecision(xxx)\n#include \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include \n#include \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include \n#include \n#include \n#include \n#include \/\/ if (M.find(key) != M.end()) { }\n#include \n#include \/\/ random_device rd; mt19937 mt(rd());\n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\n#define DEBUG 0 \/\/ change 0 -> 1 if we need debug.\n\ntypedef long long ll;\n\nconst int dx[4] = {1, 0, -1, 0};\nconst int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\n\/\/ const ll M = 1000000007;\n\ntypedef tuple state; \/\/ x, y, dir, a, b\n\nint A, B;\nint h, w;\nstring c[100];\n\nstack S;\n\nbool valid(int x, int y, int a, int b)\n{\n return (a <= A && b <= B && c[x][y] == '.');\n}\n\nint main()\n{\n auto start = std::chrono::system_clock::now();\n cin >> A >> B;\n cin >> h >> w;\n for (auto i = 0; i < h; i++)\n {\n cin >> c[i];\n }\n S.push(state(1, 1, 0, 0, 0));\n while (!S.empty())\n {\n auto end = std::chrono::system_clock::now();\n double elapsed = std::chrono::duration_cast(end-start).count();\n if (elapsed > 2950) {\n cout << \"No\" << endl;\n return 0;\n }\n int now_x = get<0>(S.top());\n int now_y = get<1>(S.top());\n int now_dir = get<2>(S.top());\n int now_a = get<3>(S.top());\n int now_b = get<4>(S.top());\n #if DEBUG == 1\n cerr << \"(\" << now_x << \", \" << now_y << \"), \"\n << now_dir << \", \"\n << \"(\" << now_a << \", \" << now_b << \")\" << endl;\n #endif\n S.pop();\n if (now_x == h - 2 && now_y == w - 2 && now_a == A && now_b == B)\n {\n cout << \"Yes\" << endl;\n return 0;\n }\n else\n {\n int new_dir[3] = {(now_dir + 1) % 4, (now_dir + 3) % 4, now_dir};\n int new_a[3] = {now_a + 1, now_a, now_a};\n int new_b[3] = {now_b, now_b + 1, now_b};\n for (auto k = 0; k < 3; k++)\n {\n int new_x = now_x + dx[new_dir[k]];\n int new_y = now_y + dy[new_dir[k]];\n if (valid(new_x, new_y, new_a[k], new_b[k]))\n {\n S.push(state(new_x, new_y, new_dir[k], new_a[k], new_b[k]));\n }\n }\n }\n }\n cout << \"No\" << endl;\n}<|endoftext|>"} {"text":"#ifndef STAN_MCMC_HMC_INTEGRATORS_BASE_LEAPFROG_HPP\n#define STAN_MCMC_HMC_INTEGRATORS_BASE_LEAPFROG_HPP\n\n#include \n#include \n#include \n#include \n\nnamespace stan {\n namespace mcmc {\n\n template \n class base_leapfrog : public base_integrator {\n public:\n base_leapfrog()\n : base_integrator() {}\n\n void evolve(typename Hamiltonian::PointType& z,\n Hamiltonian& hamiltonian,\n const double epsilon,\n interface_callbacks::writer::base_writer& writer) {\n begin_update_p(z, hamiltonian, 0.5 * epsilon);\n\n update_q(z, hamiltonian, epsilon);\n hamiltonian.update(z, writer);\n\n end_update_p(z, hamiltonian, 0.5 * epsilon);\n }\n\n void verbose_evolve(typename Hamiltonian::PointType& z,\n Hamiltonian& hamiltonian,\n const double epsilon,\n interface_callbacks::writer::base_writer& writer) {\n std::stringstream msg;\n msg.precision(6);\n\n int width = 14;\n int nColumn = 4;\n\n msg << \"Verbose Hamiltonian Evolution, Step Size = \" << epsilon << \":\";\n this->writer_(msg.str());\n\n msg.str(\"\");\n msg << \" \" << std::setw(nColumn * width)\n << std::setfill('-')\n << \"\" << std::setfill(' ');\n this->writer_(msg.str());\n\n msg.str(\"\");\n msg << \" \"\n << std::setw(width) << std::left << \"Poisson\"\n << std::setw(width) << std::left << \"Initial\"\n << std::setw(width) << std::left << \"Current\"\n << std::setw(width) << std::left << \"DeltaH\";\n this->writer_(msg.str());\n\n msg.str(\"\");\n msg << \" \"\n << std::setw(width) << std::left << \"Operator\"\n << std::setw(width) << std::left << \"Hamiltonian\"\n << std::setw(width) << std::left << \"Hamiltonian\"\n << std::setw(width) << std::left << \"\/ Stepsize^{2}\";\n this->writer_(msg.str());\n\n msg.str(\"\");\n msg << \" \" << std::setw(nColumn * width)\n << std::setfill('-')\n << \"\" << std::setfill(' ');\n this->writer_(msg.str());\n\n double H0 = hamiltonian.H(z);\n\n begin_update_p(z, hamiltonian, 0.5 * epsilon);\n\n double H1 = hamiltonian.H(z);\n\n msg.str(\"\");\n msg << \" \"\n << std::setw(width) << std::left << \"hat{V}\/2\"\n << std::setw(width) << std::left << H0\n << std::setw(width) << std::left << H1\n << std::setw(width) << std::left << (H1 - H0) \/ (epsilon * epsilon);\n this->writer_(msg.str());\n\n update_q(z, hamiltonian, epsilon);\n hamiltonian.update(z, writer);\n\n double H2 = hamiltonian.H(z);\n\n msg.str(\"\");\n msg << \" \"\n << std::setw(width) << std::left << \"hat{T}\"\n << std::setw(width) << std::left << H0\n << std::setw(width) << std::left << H2\n << std::setw(width) << std::left << (H2 - H0) \/ (epsilon * epsilon);\n this->writer_(msg.str());\n\n end_update_p(z, hamiltonian, 0.5 * epsilon);\n\n double H3 = hamiltonian.H(z);\n\n msg.str(\"\");\n msg << \" \"\n << std::setw(width) << std::left << \"hat{V}\/2\"\n << std::setw(width) << std::left << H0\n << std::setw(width) << std::left << H3\n << std::setw(width) << std::left << (H3 - H0) \/ (epsilon * epsilon);\n this->writer_(msg.str());\n\n msg.str(\"\");\n msg << \" \"\n << std::setw(nColumn * width)\n << std::setfill('-')\n << \"\"\n << std::setfill(' ');\n this->writer_(msg.str());\n }\n\n virtual void begin_update_p(typename Hamiltonian::PointType& z,\n Hamiltonian& hamiltonian,\n double epsilon) = 0;\n virtual void update_q(typename Hamiltonian::PointType& z,\n Hamiltonian& hamiltonian,\n double epsilon) = 0;\n virtual void end_update_p(typename Hamiltonian::PointType& z,\n Hamiltonian& hamiltonian,\n double epsilon) = 0;\n };\n\n } \/\/ mcmc\n} \/\/ stan\n#endif\nFixing use of writer in base_leapfrog.hpp#ifndef STAN_MCMC_HMC_INTEGRATORS_BASE_LEAPFROG_HPP\n#define STAN_MCMC_HMC_INTEGRATORS_BASE_LEAPFROG_HPP\n\n#include \n#include \n#include \n#include \n\nnamespace stan {\n namespace mcmc {\n\n template \n class base_leapfrog : public base_integrator {\n public:\n base_leapfrog()\n : base_integrator() {}\n\n void evolve(typename Hamiltonian::PointType& z,\n Hamiltonian& hamiltonian,\n const double epsilon,\n interface_callbacks::writer::base_writer& writer) {\n begin_update_p(z, hamiltonian, 0.5 * epsilon);\n\n update_q(z, hamiltonian, epsilon);\n hamiltonian.update(z, writer);\n\n end_update_p(z, hamiltonian, 0.5 * epsilon);\n }\n\n void verbose_evolve(typename Hamiltonian::PointType& z,\n Hamiltonian& hamiltonian,\n const double epsilon,\n interface_callbacks::writer::base_writer& writer) {\n std::stringstream msg;\n msg.precision(6);\n\n int width = 14;\n int nColumn = 4;\n\n msg << \"Verbose Hamiltonian Evolution, Step Size = \" << epsilon << \":\";\n writer(msg.str());\n\n msg.str(\"\");\n msg << \" \" << std::setw(nColumn * width)\n << std::setfill('-')\n << \"\" << std::setfill(' ');\n writer(msg.str());\n\n msg.str(\"\");\n msg << \" \"\n << std::setw(width) << std::left << \"Poisson\"\n << std::setw(width) << std::left << \"Initial\"\n << std::setw(width) << std::left << \"Current\"\n << std::setw(width) << std::left << \"DeltaH\";\n writer(msg.str());\n\n msg.str(\"\");\n msg << \" \"\n << std::setw(width) << std::left << \"Operator\"\n << std::setw(width) << std::left << \"Hamiltonian\"\n << std::setw(width) << std::left << \"Hamiltonian\"\n << std::setw(width) << std::left << \"\/ Stepsize^{2}\";\n writer(msg.str());\n\n msg.str(\"\");\n msg << \" \" << std::setw(nColumn * width)\n << std::setfill('-')\n << \"\" << std::setfill(' ');\n writer(msg.str());\n\n double H0 = hamiltonian.H(z);\n\n begin_update_p(z, hamiltonian, 0.5 * epsilon);\n\n double H1 = hamiltonian.H(z);\n\n msg.str(\"\");\n msg << \" \"\n << std::setw(width) << std::left << \"hat{V}\/2\"\n << std::setw(width) << std::left << H0\n << std::setw(width) << std::left << H1\n << std::setw(width) << std::left << (H1 - H0) \/ (epsilon * epsilon);\n writer(msg.str());\n\n update_q(z, hamiltonian, epsilon);\n hamiltonian.update(z, writer);\n\n double H2 = hamiltonian.H(z);\n\n msg.str(\"\");\n msg << \" \"\n << std::setw(width) << std::left << \"hat{T}\"\n << std::setw(width) << std::left << H0\n << std::setw(width) << std::left << H2\n << std::setw(width) << std::left << (H2 - H0) \/ (epsilon * epsilon);\n writer(msg.str());\n\n end_update_p(z, hamiltonian, 0.5 * epsilon);\n\n double H3 = hamiltonian.H(z);\n\n msg.str(\"\");\n msg << \" \"\n << std::setw(width) << std::left << \"hat{V}\/2\"\n << std::setw(width) << std::left << H0\n << std::setw(width) << std::left << H3\n << std::setw(width) << std::left << (H3 - H0) \/ (epsilon * epsilon);\n writer(msg.str());\n\n msg.str(\"\");\n msg << \" \"\n << std::setw(nColumn * width)\n << std::setfill('-')\n << \"\"\n << std::setfill(' ');\n writer(msg.str());\n }\n\n virtual void begin_update_p(typename Hamiltonian::PointType& z,\n Hamiltonian& hamiltonian,\n double epsilon) = 0;\n virtual void update_q(typename Hamiltonian::PointType& z,\n Hamiltonian& hamiltonian,\n double epsilon) = 0;\n virtual void end_update_p(typename Hamiltonian::PointType& z,\n Hamiltonian& hamiltonian,\n double epsilon) = 0;\n };\n\n } \/\/ mcmc\n} \/\/ stan\n#endif\n<|endoftext|>"} {"text":"#ifndef STAN_MATH_OPENCL_KERNELS_NORMAL_ID_GLM_LPDF_HPP\n#define STAN_MATH_OPENCL_KERNELS_NORMAL_ID_GLM_LPDF_HPP\n#ifdef STAN_OPENCL\n\n#include \n\nnamespace stan {\nnamespace math {\nnamespace opencl_kernels {\n\n\/\/ \\cond\nstatic const char* normal_id_glm_kernel_code = STRINGIFY(\n \/\/ \\endcond\n \/**\n * GPU implementation of Generalized Linear Model (GLM)\n * with Normal distribution and identity link function.\n *\n * Must be run with at least N threads and local size equal to LOCAL_SIZE_.\n * @param[in] y_glob vector parameter\n * @param[in] x design matrix\n * @param[in] alpha intercept (in log odds)\n * @param[in] beta weight vector\n * @param[in] sigma_glob (Sequence of) scale parameters for the normal\n * @param[out] mu_derivative_glob intermediate variable used in the model\n * @param[out] mu_derivative_sum partially summed mu_derivative_glob (1\n * value per work group)\n * @param[out] y_minus_mu_over_sigma_squared_sum intermediate variable used\n * in the model\n * @param[out] sigma_derivative derivative with respect to sigma\n * @param[out] log_sigma_sum partially summed logarithm of sigma (1 value\n * per work group)\n * @param N number of cases\n * @param M number of attributes\n * @param is_alpha_vector 0 or 1 - whether alpha is a vector (alternatively\n * it is a scalar)\n * @param is_sigma_vector 0 or 1 - whether sigma is a vector (alternatively\n * it is a scalar)\n * @param need_mu_derivative interpreted as boolean - whether mu_derivative\n * needs to be computed\n * @param need_mu_derivative_sum interpreted as boolean - whether\n * mu_derivative_sum needs to be computed\n * @param need_sigma_derivative interpreted as boolean - whether\n * sigma_derivative needs to be computed\n * @param need_log_sigma_sum interpreted as boolean - whether log_sigma_sum\n * needs to be computed\n *\/\n __kernel void normal_id_glm(\n __global double* mu_derivative_glob, __global double* mu_derivative_sum,\n __global double* y_minus_mu_over_sigma_squared_sum,\n __global double* sigma_derivative, __global double* log_sigma_sum,\n const __global double* y_glob, const __global double* x,\n const __global double* alpha, const __global double* beta,\n const __global double* sigma_glob, const int N, const int M,\n const int is_alpha_vector, const int is_sigma_vector,\n const int need_mu_derivative, const int need_mu_derivative_sum,\n const int need_sigma_derivative, const int need_log_sigma_sum) {\n const int gid = get_global_id(0);\n const int lid = get_local_id(0);\n const int lsize = get_local_size(0);\n const int wgid = get_group_id(0);\n\n __local double res_loc[LOCAL_SIZE_];\n\n double y_minus_mu_over_sigma_squared = 0;\n double log_sigma = 0;\n double mu_derivative = 0;\n if (gid < N) {\n double y_minus_mu_over_sigma = 0;\n for (int i = 0, j = 0; i < M; i++, j += N) {\n y_minus_mu_over_sigma += x[j + gid] * beta[i];\n }\n double sigma = sigma_glob[gid * is_sigma_vector];\n double inv_sigma = 1 \/ sigma;\n y_minus_mu_over_sigma = (y_glob[gid] - y_minus_mu_over_sigma\n - alpha[gid * is_alpha_vector])\n * inv_sigma;\n mu_derivative = inv_sigma * y_minus_mu_over_sigma;\n if (need_mu_derivative) {\n mu_derivative_glob[gid] = mu_derivative;\n }\n y_minus_mu_over_sigma_squared\n = y_minus_mu_over_sigma * y_minus_mu_over_sigma;\n if (need_sigma_derivative) {\n sigma_derivative[gid]\n = (y_minus_mu_over_sigma_squared - 1) * inv_sigma;\n }\n if (need_log_sigma_sum) {\n log_sigma = log(sigma);\n }\n }\n res_loc[lid] = y_minus_mu_over_sigma_squared;\n barrier(CLK_LOCAL_MEM_FENCE);\n for (int step = lsize \/ REDUCTION_STEP_SIZE; step > 0;\n step \/= REDUCTION_STEP_SIZE) {\n if (lid < step) {\n for (int i = 1; i < REDUCTION_STEP_SIZE; i++) {\n res_loc[lid] += res_loc[lid + step * i];\n }\n }\n barrier(CLK_LOCAL_MEM_FENCE);\n }\n if (lid == 0) {\n y_minus_mu_over_sigma_squared_sum[wgid] = res_loc[0];\n }\n\n if (need_mu_derivative_sum) {\n barrier(CLK_LOCAL_MEM_FENCE);\n res_loc[lid] = mu_derivative;\n barrier(CLK_LOCAL_MEM_FENCE);\n for (int step = lsize \/ REDUCTION_STEP_SIZE; step > 0;\n step \/= REDUCTION_STEP_SIZE) {\n if (lid < step) {\n for (int i = 1; i < REDUCTION_STEP_SIZE; i++) {\n res_loc[lid] += res_loc[lid + step * i];\n }\n }\n barrier(CLK_LOCAL_MEM_FENCE);\n }\n if (lid == 0) {\n mu_derivative_sum[wgid] = res_loc[0];\n }\n }\n\n if (need_log_sigma_sum) {\n barrier(CLK_LOCAL_MEM_FENCE);\n res_loc[lid] = log_sigma;\n barrier(CLK_LOCAL_MEM_FENCE);\n for (int step = lsize \/ REDUCTION_STEP_SIZE; step > 0;\n step \/= REDUCTION_STEP_SIZE) {\n if (lid < step) {\n for (int i = 1; i < REDUCTION_STEP_SIZE; i++) {\n res_loc[lid] += res_loc[lid + step * i];\n }\n }\n barrier(CLK_LOCAL_MEM_FENCE);\n }\n if (lid == 0) {\n log_sigma_sum[wgid] = res_loc[0];\n }\n }\n }\n \/\/ \\cond\n);\n\/\/ \\endcond\n\n\/**\n * See the docs for \\link kernels\/normal_id_glm_lpdf.hpp\n * normal_id_glm() \\endlink\n *\/\nconst kernel_cl\n normal_id_glm(\"normal_id_glm\", normal_id_glm_kernel_code,\n {{\"REDUCTION_STEP_SIZE\", 4}, {\"LOCAL_SIZE_\", 64}});\n\n} \/\/ namespace opencl_kernels\n} \/\/ namespace math\n} \/\/ namespace stan\n\n#endif\n#endif\nimproved docs#ifndef STAN_MATH_OPENCL_KERNELS_NORMAL_ID_GLM_LPDF_HPP\n#define STAN_MATH_OPENCL_KERNELS_NORMAL_ID_GLM_LPDF_HPP\n#ifdef STAN_OPENCL\n\n#include \n\nnamespace stan {\nnamespace math {\nnamespace opencl_kernels {\n\n\/\/ \\cond\nstatic const char* normal_id_glm_kernel_code = STRINGIFY(\n \/\/ \\endcond\n \/**\n * GPU implementation of Generalized Linear Model (GLM)\n * with Normal distribution and identity link function.\n *\n * Must be run with at least N threads and local size equal to LOCAL_SIZE_.\n * @param[in] y_glob vector parameter\n * @param[in] x design matrix\n * @param[in] alpha intercept (in log odds)\n * @param[in] beta weight vector\n * @param[in] sigma_glob (Sequence of) scale parameters for the normal\n * @param[out] mu_derivative_glob intermediate variable used in the model\n * @param[out] mu_derivative_sum partially summed mu_derivative_glob (1\n * value per work group)\n * @param[out] y_minus_mu_over_sigma_squared_sum Partial sum of squares of\n * y, scaled by expected mean and given variance.\n * @param[out] sigma_derivative derivative with respect to sigma\n * @param[out] log_sigma_sum partially summed logarithm of sigma (1 value\n * per work group)\n * @param N number of cases\n * @param M number of attributes\n * @param is_alpha_vector 0 or 1 - whether alpha is a vector (alternatively\n * it is a scalar)\n * @param is_sigma_vector 0 or 1 - whether sigma is a vector (alternatively\n * it is a scalar)\n * @param need_mu_derivative interpreted as boolean - whether mu_derivative\n * needs to be computed\n * @param need_mu_derivative_sum interpreted as boolean - whether\n * mu_derivative_sum needs to be computed\n * @param need_sigma_derivative interpreted as boolean - whether\n * sigma_derivative needs to be computed\n * @param need_log_sigma_sum interpreted as boolean - whether log_sigma_sum\n * needs to be computed\n *\/\n __kernel void normal_id_glm(\n __global double* mu_derivative_glob, __global double* mu_derivative_sum,\n __global double* y_minus_mu_over_sigma_squared_sum,\n __global double* sigma_derivative, __global double* log_sigma_sum,\n const __global double* y_glob, const __global double* x,\n const __global double* alpha, const __global double* beta,\n const __global double* sigma_glob, const int N, const int M,\n const int is_alpha_vector, const int is_sigma_vector,\n const int need_mu_derivative, const int need_mu_derivative_sum,\n const int need_sigma_derivative, const int need_log_sigma_sum) {\n const int gid = get_global_id(0);\n const int lid = get_local_id(0);\n const int lsize = get_local_size(0);\n const int wgid = get_group_id(0);\n\n __local double res_loc[LOCAL_SIZE_];\n\n double y_minus_mu_over_sigma_squared = 0;\n double log_sigma = 0;\n double mu_derivative = 0;\n if (gid < N) {\n double y_minus_mu_over_sigma = 0;\n for (int i = 0, j = 0; i < M; i++, j += N) {\n y_minus_mu_over_sigma += x[j + gid] * beta[i];\n }\n double sigma = sigma_glob[gid * is_sigma_vector];\n double inv_sigma = 1 \/ sigma;\n y_minus_mu_over_sigma = (y_glob[gid] - y_minus_mu_over_sigma\n - alpha[gid * is_alpha_vector])\n * inv_sigma;\n mu_derivative = inv_sigma * y_minus_mu_over_sigma;\n if (need_mu_derivative) {\n mu_derivative_glob[gid] = mu_derivative;\n }\n y_minus_mu_over_sigma_squared\n = y_minus_mu_over_sigma * y_minus_mu_over_sigma;\n if (need_sigma_derivative) {\n sigma_derivative[gid]\n = (y_minus_mu_over_sigma_squared - 1) * inv_sigma;\n }\n if (need_log_sigma_sum) {\n log_sigma = log(sigma);\n }\n }\n res_loc[lid] = y_minus_mu_over_sigma_squared;\n barrier(CLK_LOCAL_MEM_FENCE);\n for (int step = lsize \/ REDUCTION_STEP_SIZE; step > 0;\n step \/= REDUCTION_STEP_SIZE) {\n if (lid < step) {\n for (int i = 1; i < REDUCTION_STEP_SIZE; i++) {\n res_loc[lid] += res_loc[lid + step * i];\n }\n }\n barrier(CLK_LOCAL_MEM_FENCE);\n }\n if (lid == 0) {\n y_minus_mu_over_sigma_squared_sum[wgid] = res_loc[0];\n }\n\n if (need_mu_derivative_sum) {\n barrier(CLK_LOCAL_MEM_FENCE);\n res_loc[lid] = mu_derivative;\n barrier(CLK_LOCAL_MEM_FENCE);\n for (int step = lsize \/ REDUCTION_STEP_SIZE; step > 0;\n step \/= REDUCTION_STEP_SIZE) {\n if (lid < step) {\n for (int i = 1; i < REDUCTION_STEP_SIZE; i++) {\n res_loc[lid] += res_loc[lid + step * i];\n }\n }\n barrier(CLK_LOCAL_MEM_FENCE);\n }\n if (lid == 0) {\n mu_derivative_sum[wgid] = res_loc[0];\n }\n }\n\n if (need_log_sigma_sum) {\n barrier(CLK_LOCAL_MEM_FENCE);\n res_loc[lid] = log_sigma;\n barrier(CLK_LOCAL_MEM_FENCE);\n for (int step = lsize \/ REDUCTION_STEP_SIZE; step > 0;\n step \/= REDUCTION_STEP_SIZE) {\n if (lid < step) {\n for (int i = 1; i < REDUCTION_STEP_SIZE; i++) {\n res_loc[lid] += res_loc[lid + step * i];\n }\n }\n barrier(CLK_LOCAL_MEM_FENCE);\n }\n if (lid == 0) {\n log_sigma_sum[wgid] = res_loc[0];\n }\n }\n }\n \/\/ \\cond\n);\n\/\/ \\endcond\n\n\/**\n * See the docs for \\link kernels\/normal_id_glm_lpdf.hpp\n * normal_id_glm() \\endlink\n *\/\nconst kernel_cl\n normal_id_glm(\"normal_id_glm\", normal_id_glm_kernel_code,\n {{\"REDUCTION_STEP_SIZE\", 4}, {\"LOCAL_SIZE_\", 64}});\n\n} \/\/ namespace opencl_kernels\n} \/\/ namespace math\n} \/\/ namespace stan\n\n#endif\n#endif\n<|endoftext|>"} {"text":"#ifndef STAN_MATH_PRIM_MAT_FUN_COV_MATRIX_CONSTRAIN_HPP\n#define STAN_MATH_PRIM_MAT_FUN_COV_MATRIX_CONSTRAIN_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace stan {\n\nnamespace math {\n\n\/**\n * Return the symmetric, positive-definite matrix of dimensions K\n * by K resulting from transforming the specified finite vector of\n * size K plus (K choose 2).\n *\n *

See cov_matrix_free()<\/code> for the inverse transform.\n *\n * @param x The vector to convert to a covariance matrix.\n * @param K The number of rows and columns of the resulting\n * covariance matrix.\n * @throws std::invalid_argument if (x.size() != K + (K choose 2)).\n *\/\ntemplate \nEigen::Matrix cov_matrix_constrain(\n const Eigen::Matrix& x,\n typename math::index_type >::type K) {\n using Eigen::Dynamic;\n using Eigen::Matrix;\n using std::exp;\n typedef typename index_type >::type index_t;\n\n Matrix L(K, K);\n check_size_match(\"cov_matrix_constrain\", \"x.size()\", x.size(),\n \"K + (K choose 2)\", (K * (K + 1)) \/ 2);\n int i = 0;\n for (index_t m = 0; m < K; ++m) {\n for (int n = 0; n < m; ++n)\n L(m, n) = x(i++);\n L(m, m) = exp(x(i++));\n for (index_t n = m + 1; n < K; ++n)\n L(m, n) = 0.0;\n }\n return multiply_lower_tri_self_transpose(L);\n}\n\n\/**\n * Return the symmetric, positive-definite matrix of dimensions K\n * by K resulting from transforming the specified finite vector of\n * size K plus (K choose 2).\n *\n *

See cov_matrix_free()<\/code> for the inverse transform.\n *\n * @param x The vector to convert to a covariance matrix.\n * @param K The dimensions of the resulting covariance matrix.\n * @param lp Reference\n * @throws std::domain_error if (x.size() != K + (K choose 2)).\n *\/\ntemplate \nEigen::Matrix cov_matrix_constrain(\n const Eigen::Matrix& x,\n typename math::index_type<\n Eigen::Matrix >::type K,\n T& lp) {\n using Eigen::Dynamic;\n using Eigen::Matrix;\n using std::exp;\n using std::log;\n typedef typename index_type >::type index_t;\n check_size_match(\"cov_matrix_constrain\", \"x.size()\", x.size(),\n \"K + (K choose 2)\", (K * (K + 1)) \/ 2);\n Matrix L(K, K);\n int i = 0;\n for (index_t m = 0; m < K; ++m) {\n for (index_t n = 0; n < m; ++n)\n L(m, n) = x(i++);\n L(m, m) = exp(x(i++));\n for (index_t n = m + 1; n < K; ++n)\n L(m, n) = 0.0;\n }\n \/\/ Jacobian for complete transform, including exp() above\n lp += (K * LOG_2); \/\/ needless constant; want propto\n for (index_t k = 0; k < K; ++k)\n lp += (K - k + 1) * log(L(k, k)); \/\/ only +1 because index from 0\n return multiply_lower_tri_self_transpose(L);\n}\n\n} \/\/ namespace math\n} \/\/ namespace stan\n#endif\nmeta include#ifndef STAN_MATH_PRIM_MAT_FUN_COV_MATRIX_CONSTRAIN_HPP\n#define STAN_MATH_PRIM_MAT_FUN_COV_MATRIX_CONSTRAIN_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace stan {\n\nnamespace math {\n\n\/**\n * Return the symmetric, positive-definite matrix of dimensions K\n * by K resulting from transforming the specified finite vector of\n * size K plus (K choose 2).\n *\n *

See cov_matrix_free()<\/code> for the inverse transform.\n *\n * @param x The vector to convert to a covariance matrix.\n * @param K The number of rows and columns of the resulting\n * covariance matrix.\n * @throws std::invalid_argument if (x.size() != K + (K choose 2)).\n *\/\ntemplate \nEigen::Matrix cov_matrix_constrain(\n const Eigen::Matrix& x,\n typename math::index_type >::type K) {\n using Eigen::Dynamic;\n using Eigen::Matrix;\n using std::exp;\n typedef typename index_type >::type index_t;\n\n Matrix L(K, K);\n check_size_match(\"cov_matrix_constrain\", \"x.size()\", x.size(),\n \"K + (K choose 2)\", (K * (K + 1)) \/ 2);\n int i = 0;\n for (index_t m = 0; m < K; ++m) {\n for (int n = 0; n < m; ++n)\n L(m, n) = x(i++);\n L(m, m) = exp(x(i++));\n for (index_t n = m + 1; n < K; ++n)\n L(m, n) = 0.0;\n }\n return multiply_lower_tri_self_transpose(L);\n}\n\n\/**\n * Return the symmetric, positive-definite matrix of dimensions K\n * by K resulting from transforming the specified finite vector of\n * size K plus (K choose 2).\n *\n *

See cov_matrix_free()<\/code> for the inverse transform.\n *\n * @param x The vector to convert to a covariance matrix.\n * @param K The dimensions of the resulting covariance matrix.\n * @param lp Reference\n * @throws std::domain_error if (x.size() != K + (K choose 2)).\n *\/\ntemplate \nEigen::Matrix cov_matrix_constrain(\n const Eigen::Matrix& x,\n typename math::index_type<\n Eigen::Matrix >::type K,\n T& lp) {\n using Eigen::Dynamic;\n using Eigen::Matrix;\n using std::exp;\n using std::log;\n typedef typename index_type >::type index_t;\n check_size_match(\"cov_matrix_constrain\", \"x.size()\", x.size(),\n \"K + (K choose 2)\", (K * (K + 1)) \/ 2);\n Matrix L(K, K);\n int i = 0;\n for (index_t m = 0; m < K; ++m) {\n for (index_t n = 0; n < m; ++n)\n L(m, n) = x(i++);\n L(m, m) = exp(x(i++));\n for (index_t n = m + 1; n < K; ++n)\n L(m, n) = 0.0;\n }\n \/\/ Jacobian for complete transform, including exp() above\n lp += (K * LOG_2); \/\/ needless constant; want propto\n for (index_t k = 0; k < K; ++k)\n lp += (K - k + 1) * log(L(k, k)); \/\/ only +1 because index from 0\n return multiply_lower_tri_self_transpose(L);\n}\n\n} \/\/ namespace math\n} \/\/ namespace stan\n#endif\n<|endoftext|>"} {"text":"#include \"MainVisitor.hpp\"\n\n#include \n#include \n#include \"Event.hpp\"\n#include \"typedefs.hpp\"\n\n#include \"MainModule.hpp\"\n\n#include \"events\/Terminate.hpp\"\n#include \"events\/CmdResponseReceived.hpp\"\n#include \"events\/WebClientRequestReceived.hpp\"\n#include \"..\/..\/utils\/Machine.hpp\"\n\n#include \"..\/..\/network\/websocket\/typedefs.hpp\"\n#include \"..\/..\/network\/websocket\/events\/MessageSendRequest.hpp\"\n#include \"..\/..\/network\/websocket\/events\/MessageBroadcastRequest.hpp\"\n#include \"..\/..\/network\/bsdsocket\/events\/MessageRequest.hpp\"\n\nnamespace events = tin::controllers::main::events;\nnamespace main = tin::controllers::main;\nnamespace websocket = tin::network::websocket;\nnamespace bsdsocket = tin::network::bsdsocket;\nusing nlohmann::json;\n\ntin::controllers::main::MainVisitor::MainVisitor(tin::controllers::main::MainModule& controller):\ncontroller(controller)\n{}\n\nvoid tin::controllers::main::MainVisitor::visit(events::Terminate &evt)\n{\n this->controller.terminate();\n}\n\nvoid tin::controllers::main::MainVisitor::visit(events::CmdResponseReceived &evt)\n{\n std::cout << \"[Supervisor] [MainCtrl] Received response: \" << evt.jsonPtr->dump() << std::endl;\n std::cout << \" Source: \" << evt.ip << \":\" << evt.port << std::endl;\n\n auto& machine = this->controller.machines.getMachine(evt.ip, evt.port);\n\n json& temp = *(evt.jsonPtr);\n\n if(temp[\"cmd\"].is_string())\n {\n const std::string cmd = temp[\"cmd\"];\n\n if (cmd == \"sync\")\n {\n auto ms = std::chrono::duration_cast(\n std::chrono::system_clock::now().time_since_epoch());\n machine.lastSynchronization = ms.count();\n }\n else if (cmd == \"ping\")\n {\n auto queueIt = this->controller.pingsQueue.find(std::pair(evt.ip, evt.port));\n\n if (temp[\"error\"].is_object() && temp[\"error\"][\"notConnected\"].is_boolean() && temp[\"error\"][\"notConnected\"])\n {\n machine.status = \"offline\";\n }\n else if (temp[\"response\"].is_string())\n {\n std::string tt = temp[\"response\"];\n machine.status = tt;\n }\n\n if (queueIt != this->controller.pingsQueue.end())\n {\n auto& temp = *(queueIt->second.second);\n temp[\"data\"] = {{ \"success\", true }};\n\n this->controller.networkManagerQueue.push(\n std::make_shared(queueIt->second.first, queueIt->second.second)\n );\n\n this->controller.pingsQueue.erase(queueIt);\n }\n }\n\n else if (cmd == \"change_filter\")\n {\n \tconst std::string expr = temp[\"expression\"];\n \tmachine.filter = expr;\n \tmachine.status = \"sniffing\";\n }\n }\n else\n {\n std::cout << \"Invalid response received\" << std::endl;\n }\n\n}\n\nvoid tin::controllers::main::MainVisitor::visit(events::WebClientRequestReceived &evt)\n{\n std::cout << \"[Supervisor] WebClient Request Received, processing\" << std::endl;\n\n json& temp = *(evt.jsonPtr);\n\n try\n {\n if(temp.find(\"route\") == temp.end() || temp.find(\"type\") == temp.end() || !temp[\"route\"].is_string() || !temp[\"type\"].is_string())\n {\n temp[\"error\"] = {{ \"invalid\", { {\"route\", \"type\"} } }};\n\n std::cout << \"[Supervisor] Bad WebClient request\" << std::endl;\n\n this->resendEvent(evt);\n return;\n }\n\n std::string route = temp[\"route\"];\n std::string type = temp[\"type\"];\n\n if (route == \"machine\" && type == \"GET\")\n {\n temp[\"data\"] = {\n { \"machines\", json::array() }\n };\n\n for(auto& it: this->controller.machines.idMachineMap)\n {\n temp[\"data\"][\"machines\"][temp[\"data\"][\"machines\"].size()] = {\n { \"id\", it.second.id},\n { \"name\", it.second.name },\n { \"ip\", it.second.ip },\n { \"port\", it.second.port },\n { \"status\", it.second.status },\n { \"lastSync\", it.second.lastSynchronization }\n };\n }\n }\n else if(route == \"machine\" && type == \"POST\")\n {\n if(!temp[\"data\"].is_object() || !temp[\"data\"][\"ip\"].is_string() || !temp[\"data\"][\"name\"].is_string() || !temp[\"data\"][\"port\"].is_number())\n {\n std::cout << \"[Supervisor] No data in POST\" << std::endl;\n\n temp[\"error\"] = {{ \"invalid\", { {\"data\", true} } }};\n\n this->resendEvent(evt);\n return;\n }\n\n const std::string ip = temp[\"data\"][\"ip\"];\n const std::string name = temp[\"data\"][\"name\"];\n unsigned port = temp[\"data\"][\"port\"];\n\n this->controller.machines.newMachine(name, ip, port);\n\n temp[\"data\"] = {{ \"success\", true }};\n }\n else if (route.substr(0, 8) == \"machine\/\")\n {\n auto routeRest = route.substr(8);\n auto action = std::string(\"\");\n if (routeRest.find(\"\/\") != std::string::npos)\n {\n action = routeRest.substr(routeRest.find(\"\/\") + 1);\n routeRest = routeRest.substr(0, routeRest.find(\"\/\"));\n }\n\n try\n {\n int machineID = static_cast(std::stoul(routeRest));\n\n auto& machine = this->controller.machines.getMachine(machineID);\n\n if (action == \"\" && type == \"GET\")\n {\n temp[\"data\"] = {\n { \"id\", machineID },\n { \"name\", machine.name },\n { \"ip\", machine.ip },\n { \"port\", machine.port },\n { \"status\", machine.status },\n { \"lastSync\", machine.lastSynchronization }\n };\n }\n else if (action == \"\" && type == \"PATCH\")\n {\n if(!temp[\"data\"].is_object() || !temp[\"data\"][\"ip\"].is_string() || !temp[\"data\"][\"name\"].is_string() || !temp[\"data\"][\"port\"].is_number())\n {\n std::cout << \"[Supervisor] No data in PATCH\" << std::endl;\n\n temp[\"error\"] = {{ \"invalid\", { {\"data\", true} } }};\n\n this->resendEvent(evt);\n return;\n }\n\n std::string name = temp[\"data\"][\"name\"];\n std::string ip = temp[\"data\"][\"ip\"];\n unsigned int port = temp[\"data\"][\"port\"];\n\n machine.name = name;\n machine.ip = ip;\n machine.port = port;\n\n temp[\"data\"] = {{ \"success\", true }};\n }\n else if (action == \"\" && type == \"DELETE\")\n {\n this->controller.machines.removeMachine(machineID);\n\n temp[\"data\"] = {{ \"success\", true }};\n }\n else if (action == \"sync\" && type == \"POST\")\n {\n this->controller.pingsQueue.insert({\n std::pair(machine.ip, machine.port),\n std::pair(evt.connectionID, evt.jsonPtr)\n });\n\n this->controller.bsdQueue.push(\n std::make_shared(\n machine.ip,\n machine.port,\n tin::utils::json::makeSharedInstance(\"{ \\\"cmd\\\": \\\"ping\\\" }\"),\n true\n )\n );\n\n \/\/ Do synchronization\n\n \/\/ auto ms = std::chrono::duration_cast(\n \/\/ std::chrono::system_clock::now().time_since_epoch()\n \/\/ );\n\n \/\/ machine.lastSynchronization = ms.count();\n\n \/\/ temp[\"data\"] = {{ \"success\", true }};\n return;\n }\n else if (action == \"toggle-sniffer\" && type == \"POST\")\n {\n \/\/ Toggle sniffer\n\n if (machine.status == \"sniffing\")\n {\n machine.status = \"stand-by\";\n temp[\"data\"] = {{ \"success\", true }};\n }\n else if (machine.status == \"stand-by\")\n {\n machine.status = \"sniffing\";\n temp[\"data\"] = {{ \"success\", true }};\n }\n else\n {\n temp[\"error\"] = {{ \"invalid\", { {\"status\", machine.status} } }};\n }\n }\n else\n {\n temp[\"error\"] = {{ \"invalid\", { { \"action\", action } } }};\n }\n }\n catch (std::invalid_argument& e)\n {\n temp[\"error\"] = {{ \"invalid\", { {\"routeID\", true} } }};\n }\n }\n }\n catch (std::exception& e)\n {\n temp[\"error\"] = {{ \"unknown\", true }};\n }\n\n this->resendEvent(evt);\n}\n\nvoid tin::controllers::main::MainVisitor::resendEvent(events::WebClientRequestReceived &evt)\n{\n this->controller.networkManagerQueue.push(\n std::make_shared(evt.connectionID, evt.jsonPtr)\n );\n}\nWe should have ping command#include \"MainVisitor.hpp\"\n\n#include \n#include \n#include \"Event.hpp\"\n#include \"typedefs.hpp\"\n\n#include \"MainModule.hpp\"\n\n#include \"events\/Terminate.hpp\"\n#include \"events\/CmdResponseReceived.hpp\"\n#include \"events\/WebClientRequestReceived.hpp\"\n#include \"..\/..\/utils\/Machine.hpp\"\n\n#include \"..\/..\/network\/websocket\/typedefs.hpp\"\n#include \"..\/..\/network\/websocket\/events\/MessageSendRequest.hpp\"\n#include \"..\/..\/network\/websocket\/events\/MessageBroadcastRequest.hpp\"\n#include \"..\/..\/network\/bsdsocket\/events\/MessageRequest.hpp\"\n\nnamespace events = tin::controllers::main::events;\nnamespace main = tin::controllers::main;\nnamespace websocket = tin::network::websocket;\nnamespace bsdsocket = tin::network::bsdsocket;\nusing nlohmann::json;\n\ntin::controllers::main::MainVisitor::MainVisitor(tin::controllers::main::MainModule& controller):\ncontroller(controller)\n{}\n\nvoid tin::controllers::main::MainVisitor::visit(events::Terminate &evt)\n{\n this->controller.terminate();\n}\n\nvoid tin::controllers::main::MainVisitor::visit(events::CmdResponseReceived &evt)\n{\n std::cout << \"[Supervisor] [MainCtrl] Received response: \" << evt.jsonPtr->dump() << std::endl;\n std::cout << \" Source: \" << evt.ip << \":\" << evt.port << std::endl;\n\n auto& machine = this->controller.machines.getMachine(evt.ip, evt.port);\n\n json& temp = *(evt.jsonPtr);\n\n if(temp[\"cmd\"].is_string())\n {\n const std::string cmd = temp[\"cmd\"];\n\n if (cmd == \"sync\")\n {\n auto ms = std::chrono::duration_cast(\n std::chrono::system_clock::now().time_since_epoch());\n machine.lastSynchronization = ms.count();\n }\n else if (cmd == \"ping\")\n {\n auto queueIt = this->controller.pingsQueue.find(std::pair(evt.ip, evt.port));\n\n if (temp[\"error\"].is_object() && temp[\"error\"][\"notConnected\"].is_boolean() && temp[\"error\"][\"notConnected\"])\n {\n machine.status = \"offline\";\n }\n else if (temp[\"response\"].is_string())\n {\n std::string tt = temp[\"response\"];\n machine.status = tt;\n }\n\n if (queueIt != this->controller.pingsQueue.end())\n {\n auto& temp = *(queueIt->second.second);\n temp[\"data\"] = {{ \"success\", true }};\n\n this->controller.networkManagerQueue.push(\n std::make_shared(queueIt->second.first, queueIt->second.second)\n );\n\n this->controller.pingsQueue.erase(queueIt);\n }\n }\n\n else if (cmd == \"change_filter\")\n {\n \tconst std::string expr = temp[\"expression\"];\n \tmachine.filter = expr;\n \tmachine.status = \"sniffing\";\n }\n }\n else\n {\n std::cout << \"Invalid response received\" << std::endl;\n }\n\n}\n\nvoid tin::controllers::main::MainVisitor::visit(events::WebClientRequestReceived &evt)\n{\n std::cout << \"[Supervisor] WebClient Request Received, processing\" << std::endl;\n\n json& temp = *(evt.jsonPtr);\n\n try\n {\n if(temp.find(\"route\") == temp.end() || temp.find(\"type\") == temp.end() || !temp[\"route\"].is_string() || !temp[\"type\"].is_string())\n {\n temp[\"error\"] = {{ \"invalid\", { {\"route\", \"type\"} } }};\n\n std::cout << \"[Supervisor] Bad WebClient request\" << std::endl;\n\n this->resendEvent(evt);\n return;\n }\n\n std::string route = temp[\"route\"];\n std::string type = temp[\"type\"];\n\n if (route == \"machine\" && type == \"GET\")\n {\n temp[\"data\"] = {\n { \"machines\", json::array() }\n };\n\n for(auto& it: this->controller.machines.idMachineMap)\n {\n temp[\"data\"][\"machines\"][temp[\"data\"][\"machines\"].size()] = {\n { \"id\", it.second.id},\n { \"name\", it.second.name },\n { \"ip\", it.second.ip },\n { \"port\", it.second.port },\n { \"status\", it.second.status },\n { \"lastSync\", it.second.lastSynchronization }\n };\n }\n }\n else if(route == \"machine\" && type == \"POST\")\n {\n if(!temp[\"data\"].is_object() || !temp[\"data\"][\"ip\"].is_string() || !temp[\"data\"][\"name\"].is_string() || !temp[\"data\"][\"port\"].is_number())\n {\n std::cout << \"[Supervisor] No data in POST\" << std::endl;\n\n temp[\"error\"] = {{ \"invalid\", { {\"data\", true} } }};\n\n this->resendEvent(evt);\n return;\n }\n\n const std::string ip = temp[\"data\"][\"ip\"];\n const std::string name = temp[\"data\"][\"name\"];\n unsigned port = temp[\"data\"][\"port\"];\n\n this->controller.machines.newMachine(name, ip, port);\n\n temp[\"data\"] = {{ \"success\", true }};\n }\n else if (route.substr(0, 8) == \"machine\/\")\n {\n auto routeRest = route.substr(8);\n auto action = std::string(\"\");\n if (routeRest.find(\"\/\") != std::string::npos)\n {\n action = routeRest.substr(routeRest.find(\"\/\") + 1);\n routeRest = routeRest.substr(0, routeRest.find(\"\/\"));\n }\n\n try\n {\n int machineID = static_cast(std::stoul(routeRest));\n\n auto& machine = this->controller.machines.getMachine(machineID);\n\n if (action == \"\" && type == \"GET\")\n {\n temp[\"data\"] = {\n { \"id\", machineID },\n { \"name\", machine.name },\n { \"ip\", machine.ip },\n { \"port\", machine.port },\n { \"status\", machine.status },\n { \"lastSync\", machine.lastSynchronization }\n };\n }\n else if (action == \"\" && type == \"PATCH\")\n {\n if(!temp[\"data\"].is_object() || !temp[\"data\"][\"ip\"].is_string() || !temp[\"data\"][\"name\"].is_string() || !temp[\"data\"][\"port\"].is_number())\n {\n std::cout << \"[Supervisor] No data in PATCH\" << std::endl;\n\n temp[\"error\"] = {{ \"invalid\", { {\"data\", true} } }};\n\n this->resendEvent(evt);\n return;\n }\n\n std::string name = temp[\"data\"][\"name\"];\n std::string ip = temp[\"data\"][\"ip\"];\n unsigned int port = temp[\"data\"][\"port\"];\n\n machine.name = name;\n machine.ip = ip;\n machine.port = port;\n\n temp[\"data\"] = {{ \"success\", true }};\n }\n else if (action == \"\" && type == \"DELETE\")\n {\n this->controller.machines.removeMachine(machineID);\n\n temp[\"data\"] = {{ \"success\", true }};\n }\n else if (action == \"ping\" && type == \"POST\")\n {\n this->controller.pingsQueue.insert({\n std::pair(machine.ip, machine.port),\n std::pair(evt.connectionID, evt.jsonPtr)\n });\n\n this->controller.bsdQueue.push(\n std::make_shared(\n machine.ip,\n machine.port,\n tin::utils::json::makeSharedInstance(\"{ \\\"cmd\\\": \\\"ping\\\" }\"),\n true\n )\n );\n }\n else if (action == \"sync\" && type == \"POST\")\n {\n \/\/ Do synchronization\n\n \/\/ auto ms = std::chrono::duration_cast(\n \/\/ std::chrono::system_clock::now().time_since_epoch()\n \/\/ );\n\n \/\/ machine.lastSynchronization = ms.count();\n\n \/\/ temp[\"data\"] = {{ \"success\", true }};\n return;\n }\n else if (action == \"toggle-sniffer\" && type == \"POST\")\n {\n \/\/ Toggle sniffer\n\n if (machine.status == \"sniffing\")\n {\n machine.status = \"stand-by\";\n temp[\"data\"] = {{ \"success\", true }};\n }\n else if (machine.status == \"stand-by\")\n {\n machine.status = \"sniffing\";\n temp[\"data\"] = {{ \"success\", true }};\n }\n else\n {\n temp[\"error\"] = {{ \"invalid\", { {\"status\", machine.status} } }};\n }\n }\n else\n {\n temp[\"error\"] = {{ \"invalid\", { { \"action\", action } } }};\n }\n }\n catch (std::invalid_argument& e)\n {\n temp[\"error\"] = {{ \"invalid\", { {\"routeID\", true} } }};\n }\n }\n }\n catch (std::exception& e)\n {\n temp[\"error\"] = {{ \"unknown\", true }};\n }\n\n this->resendEvent(evt);\n}\n\nvoid tin::controllers::main::MainVisitor::resendEvent(events::WebClientRequestReceived &evt)\n{\n this->controller.networkManagerQueue.push(\n std::make_shared(evt.connectionID, evt.jsonPtr)\n );\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: defaultproperties.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: rt $ $Date: 2003-11-24 16:48:43 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _SDR_PROPERTIES_DEFAULTPROPERTIES_HXX\n#include \n#endif\n\n#ifndef _SDR_PROPERTIES_ITEMSETTOOLS_HXX\n#include \n#endif\n\n#ifndef _SFXITEMSET_HXX\n#include \n#endif\n\n#ifndef _SFX_WHITER_HXX\n#include \n#endif\n\n#include \n\n#ifndef _SVDOBJ_HXX\n#include \n#endif\n\n#ifndef _SVDDEF_HXX\n#include \n#endif\n\n#ifndef _SVDPOOL_HXX\n#include \n#endif\n\n#ifndef _EEITEM_HXX\n#include \n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace sdr\n{\n namespace properties\n {\n SfxItemSet& DefaultProperties::CreateObjectSpecificItemSet(SfxItemPool& rPool)\n {\n \/\/ Basic implementation; Basic object has NO attributes\n return *(new SfxItemSet(rPool));\n }\n\n DefaultProperties::DefaultProperties(SdrObject& rObj)\n : BaseProperties(rObj),\n mpItemSet(0L)\n {\n }\n\n DefaultProperties::DefaultProperties(const DefaultProperties& rProps, SdrObject& rObj)\n : BaseProperties(rObj),\n mpItemSet(0L)\n {\n if(rProps.mpItemSet)\n {\n mpItemSet = rProps.mpItemSet->Clone(TRUE);\n\n \/\/ do not keep parent info, this may be changed by later construrtors.\n \/\/ This class just copies the ItemSet, ignore parent.\n if(mpItemSet && mpItemSet->GetParent())\n {\n mpItemSet->SetParent(0L);\n }\n }\n }\n\n BaseProperties& DefaultProperties::Clone(SdrObject& rObj) const\n {\n return *(new DefaultProperties(*this, rObj));\n }\n\n DefaultProperties::~DefaultProperties()\n {\n if(mpItemSet)\n {\n delete mpItemSet;\n mpItemSet = 0L;\n }\n }\n\n const SfxItemSet& DefaultProperties::GetObjectItemSet() const\n {\n if(!mpItemSet)\n {\n ((DefaultProperties*)this)->mpItemSet = &(((DefaultProperties*)this)->CreateObjectSpecificItemSet(*GetSdrObject().GetItemPool()));\n ((DefaultProperties*)this)->ForceDefaultAttributes();\n }\n\n DBG_ASSERT(mpItemSet, \"Could not create an SfxItemSet(!)\");\n\n return *mpItemSet;\n }\n\n void DefaultProperties::SetObjectItem(const SfxPoolItem& rItem)\n {\n const sal_uInt16 nWhichID(rItem.Which());\n\n if(AllowItemChange(nWhichID, &rItem))\n {\n ItemChange(nWhichID, &rItem);\n PostItemChange(nWhichID);\n\n SfxItemSet aSet(*GetSdrObject().GetItemPool(), nWhichID, nWhichID);\n aSet.Put(rItem);\n ItemSetChanged(aSet);\n }\n }\n\n void DefaultProperties::SetObjectItemDirect(const SfxPoolItem& rItem)\n {\n const sal_uInt16 nWhichID(rItem.Which());\n\n if(AllowItemChange(nWhichID, &rItem))\n {\n ItemChange(nWhichID, &rItem);\n }\n }\n\n void DefaultProperties::ClearObjectItem(const sal_uInt16 nWhich)\n {\n if(AllowItemChange(nWhich))\n {\n ItemChange(nWhich);\n PostItemChange(nWhich);\n\n if(nWhich)\n {\n SfxItemSet aSet(*GetSdrObject().GetItemPool(), nWhich, nWhich, 0, 0);\n ItemSetChanged(aSet);\n }\n }\n }\n\n void DefaultProperties::ClearObjectItemDirect(const sal_uInt16 nWhich)\n {\n if(AllowItemChange(nWhich))\n {\n ItemChange(nWhich);\n }\n }\n\n void DefaultProperties::SetObjectItemSet(const SfxItemSet& rSet)\n {\n SfxWhichIter aWhichIter(rSet);\n sal_uInt16 nWhich(aWhichIter.FirstWhich());\n const SfxPoolItem *pPoolItem;\n std::vector< sal_uInt16 > aPostItemChangeList;\n sal_Bool bDidChange(sal_False);\n SfxItemSet aSet(*GetSdrObject().GetItemPool(), SDRATTR_START, EE_ITEMS_END, 0, 0);\n\n \/\/ give a hint to STL_Vector\n aPostItemChangeList.reserve(rSet.Count());\n\n while(nWhich)\n {\n if(SFX_ITEM_SET == rSet.GetItemState(nWhich, FALSE, &pPoolItem))\n {\n if(AllowItemChange(nWhich, pPoolItem))\n {\n bDidChange = sal_True;\n ItemChange(nWhich, pPoolItem);\n aPostItemChangeList.push_back( nWhich );\n aSet.Put(*pPoolItem);\n }\n }\n\n nWhich = aWhichIter.NextWhich();\n }\n\n if(bDidChange)\n {\n std::vector< sal_uInt16 >::iterator aIter = aPostItemChangeList.begin();\n const std::vector< sal_uInt16 >::iterator aEnd = aPostItemChangeList.end();\n\n while(aIter != aEnd)\n {\n PostItemChange(*aIter);\n aIter++;\n }\n\n ItemSetChanged(aSet);\n }\n }\n\n void DefaultProperties::ItemSetChanged(const SfxItemSet& rSet)\n {\n }\n\n sal_Bool DefaultProperties::AllowItemChange(const sal_uInt16 nWhich, const SfxPoolItem* pNewItem) const\n {\n return sal_True;\n }\n\n void DefaultProperties::ItemChange(const sal_uInt16 nWhich, const SfxPoolItem* pNewItem)\n {\n }\n\n void DefaultProperties::PostItemChange(const sal_uInt16 nWhich)\n {\n }\n\n void DefaultProperties::SetStyleSheet(SfxStyleSheet* pNewStyleSheet, sal_Bool bDontRemoveHardAttr)\n {\n \/\/ no StyleSheet in DefaultProperties\n }\n\n SfxStyleSheet* DefaultProperties::GetStyleSheet() const\n {\n \/\/ no StyleSheet in DefaultProperties\n return 0L;\n }\n\n void DefaultProperties::PreProcessSave()\n {\n }\n\n void DefaultProperties::PostProcessSave()\n {\n }\n\n void DefaultProperties::ForceDefaultAttributes()\n {\n }\n\n void DefaultProperties::Scale(const Fraction& rScale)\n {\n if(mpItemSet)\n {\n ScaleItemSet(*mpItemSet, rScale);\n }\n }\n } \/\/ end of namespace properties\n} \/\/ end of namespace sdr\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ eof\nINTEGRATION: CWS aw019 (1.2.450); FILE MERGED 2004\/09\/28 15:53:10 aw 1.2.450.1: #i11190#\/*************************************************************************\n *\n * $RCSfile: defaultproperties.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: pjunck $ $Date: 2004-11-03 10:49:06 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _SDR_PROPERTIES_DEFAULTPROPERTIES_HXX\n#include \n#endif\n\n#ifndef _SDR_PROPERTIES_ITEMSETTOOLS_HXX\n#include \n#endif\n\n#ifndef _SFXITEMSET_HXX\n#include \n#endif\n\n#ifndef _SFX_WHITER_HXX\n#include \n#endif\n\n#include \n\n#ifndef _SVDOBJ_HXX\n#include \n#endif\n\n#ifndef _SVDDEF_HXX\n#include \n#endif\n\n#ifndef _SVDPOOL_HXX\n#include \n#endif\n\n#ifndef _EEITEM_HXX\n#include \n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace sdr\n{\n namespace properties\n {\n SfxItemSet& DefaultProperties::CreateObjectSpecificItemSet(SfxItemPool& rPool)\n {\n \/\/ Basic implementation; Basic object has NO attributes\n return *(new SfxItemSet(rPool));\n }\n\n DefaultProperties::DefaultProperties(SdrObject& rObj)\n : BaseProperties(rObj),\n mpItemSet(0L)\n {\n }\n\n DefaultProperties::DefaultProperties(const DefaultProperties& rProps, SdrObject& rObj)\n : BaseProperties(rObj),\n mpItemSet(0L)\n {\n if(rProps.mpItemSet)\n {\n mpItemSet = rProps.mpItemSet->Clone(TRUE);\n\n \/\/ do not keep parent info, this may be changed by later construrtors.\n \/\/ This class just copies the ItemSet, ignore parent.\n if(mpItemSet && mpItemSet->GetParent())\n {\n mpItemSet->SetParent(0L);\n }\n }\n }\n\n BaseProperties& DefaultProperties::Clone(SdrObject& rObj) const\n {\n return *(new DefaultProperties(*this, rObj));\n }\n\n DefaultProperties::~DefaultProperties()\n {\n if(mpItemSet)\n {\n delete mpItemSet;\n mpItemSet = 0L;\n }\n }\n\n const SfxItemSet& DefaultProperties::GetObjectItemSet() const\n {\n if(!mpItemSet)\n {\n ((DefaultProperties*)this)->mpItemSet = &(((DefaultProperties*)this)->CreateObjectSpecificItemSet(*GetSdrObject().GetObjectItemPool()));\n ((DefaultProperties*)this)->ForceDefaultAttributes();\n }\n\n DBG_ASSERT(mpItemSet, \"Could not create an SfxItemSet(!)\");\n\n return *mpItemSet;\n }\n\n void DefaultProperties::SetObjectItem(const SfxPoolItem& rItem)\n {\n const sal_uInt16 nWhichID(rItem.Which());\n\n if(AllowItemChange(nWhichID, &rItem))\n {\n ItemChange(nWhichID, &rItem);\n PostItemChange(nWhichID);\n\n SfxItemSet aSet(*GetSdrObject().GetObjectItemPool(), nWhichID, nWhichID);\n aSet.Put(rItem);\n ItemSetChanged(aSet);\n }\n }\n\n void DefaultProperties::SetObjectItemDirect(const SfxPoolItem& rItem)\n {\n const sal_uInt16 nWhichID(rItem.Which());\n\n if(AllowItemChange(nWhichID, &rItem))\n {\n ItemChange(nWhichID, &rItem);\n }\n }\n\n void DefaultProperties::ClearObjectItem(const sal_uInt16 nWhich)\n {\n if(AllowItemChange(nWhich))\n {\n ItemChange(nWhich);\n PostItemChange(nWhich);\n\n if(nWhich)\n {\n SfxItemSet aSet(*GetSdrObject().GetObjectItemPool(), nWhich, nWhich, 0, 0);\n ItemSetChanged(aSet);\n }\n }\n }\n\n void DefaultProperties::ClearObjectItemDirect(const sal_uInt16 nWhich)\n {\n if(AllowItemChange(nWhich))\n {\n ItemChange(nWhich);\n }\n }\n\n void DefaultProperties::SetObjectItemSet(const SfxItemSet& rSet)\n {\n SfxWhichIter aWhichIter(rSet);\n sal_uInt16 nWhich(aWhichIter.FirstWhich());\n const SfxPoolItem *pPoolItem;\n std::vector< sal_uInt16 > aPostItemChangeList;\n sal_Bool bDidChange(sal_False);\n SfxItemSet aSet(*GetSdrObject().GetObjectItemPool(), SDRATTR_START, EE_ITEMS_END, 0, 0);\n\n \/\/ give a hint to STL_Vector\n aPostItemChangeList.reserve(rSet.Count());\n\n while(nWhich)\n {\n if(SFX_ITEM_SET == rSet.GetItemState(nWhich, FALSE, &pPoolItem))\n {\n if(AllowItemChange(nWhich, pPoolItem))\n {\n bDidChange = sal_True;\n ItemChange(nWhich, pPoolItem);\n aPostItemChangeList.push_back( nWhich );\n aSet.Put(*pPoolItem);\n }\n }\n\n nWhich = aWhichIter.NextWhich();\n }\n\n if(bDidChange)\n {\n std::vector< sal_uInt16 >::iterator aIter = aPostItemChangeList.begin();\n const std::vector< sal_uInt16 >::iterator aEnd = aPostItemChangeList.end();\n\n while(aIter != aEnd)\n {\n PostItemChange(*aIter);\n aIter++;\n }\n\n ItemSetChanged(aSet);\n }\n }\n\n void DefaultProperties::ItemSetChanged(const SfxItemSet& rSet)\n {\n }\n\n sal_Bool DefaultProperties::AllowItemChange(const sal_uInt16 nWhich, const SfxPoolItem* pNewItem) const\n {\n return sal_True;\n }\n\n void DefaultProperties::ItemChange(const sal_uInt16 nWhich, const SfxPoolItem* pNewItem)\n {\n }\n\n void DefaultProperties::PostItemChange(const sal_uInt16 nWhich)\n {\n }\n\n void DefaultProperties::SetStyleSheet(SfxStyleSheet* pNewStyleSheet, sal_Bool bDontRemoveHardAttr)\n {\n \/\/ no StyleSheet in DefaultProperties\n }\n\n SfxStyleSheet* DefaultProperties::GetStyleSheet() const\n {\n \/\/ no StyleSheet in DefaultProperties\n return 0L;\n }\n\n\/\/BFS01 void DefaultProperties::PreProcessSave()\n\/\/BFS01 {\n\/\/BFS01 }\n\n\/\/BFS01 void DefaultProperties::PostProcessSave()\n\/\/BFS01 {\n\/\/BFS01 }\n\n void DefaultProperties::ForceDefaultAttributes()\n {\n }\n\n void DefaultProperties::Scale(const Fraction& rScale)\n {\n if(mpItemSet)\n {\n ScaleItemSet(*mpItemSet, rScale);\n }\n }\n } \/\/ end of namespace properties\n} \/\/ end of namespace sdr\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ eof\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: graphicproperties.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: pjunck $ $Date: 2004-11-03 10:51:15 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _SDR_PROPERTIES_GRAPHICPROPERTIES_HXX\n#include \n#endif\n\n#ifndef _SFXITEMSET_HXX\n#include \n#endif\n\n#ifndef _SFXSTYLE_HXX\n#include \n#endif\n\n#ifndef _SVDDEF_HXX\n#include \n#endif\n\n#ifndef _EEITEM_HXX\n#include \n#endif\n\n#ifndef _SVDOGRAF_HXX\n#include \n#endif\n\n#define ITEMID_GRF_CROP 0\n\n#ifndef _SDGCPITM_HXX\n#include \n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace sdr\n{\n namespace properties\n {\n \/\/ create a new itemset\n SfxItemSet& GraphicProperties::CreateObjectSpecificItemSet(SfxItemPool& rPool)\n {\n return *(new SfxItemSet(rPool,\n\n \/\/ range from SdrAttrObj\n SDRATTR_START, SDRATTR_SHADOW_LAST,\n SDRATTR_MISC_FIRST, SDRATTR_MISC_LAST,\n SDRATTR_TEXTDIRECTION, SDRATTR_TEXTDIRECTION,\n\n \/\/ range from SdrGrafObj\n SDRATTR_GRAF_FIRST, SDRATTR_GRAF_LAST,\n\n \/\/ range from SdrTextObj\n EE_ITEMS_START, EE_ITEMS_END,\n\n \/\/ end\n 0, 0));\n }\n\n GraphicProperties::GraphicProperties(SdrObject& rObj)\n : RectangleProperties(rObj)\n {\n }\n\n GraphicProperties::GraphicProperties(const GraphicProperties& rProps, SdrObject& rObj)\n : RectangleProperties(rProps, rObj)\n {\n }\n\n GraphicProperties::~GraphicProperties()\n {\n }\n\n BaseProperties& GraphicProperties::Clone(SdrObject& rObj) const\n {\n return *(new GraphicProperties(*this, rObj));\n }\n\n void GraphicProperties::ItemSetChanged(const SfxItemSet& rSet)\n {\n SdrGrafObj& rObj = (SdrGrafObj&)GetSdrObject();\n\n \/\/ local changes\n rObj.SetXPolyDirty();\n\n \/\/ #i29367# Update GraphicAttr, too. This was formerly\n \/\/ triggered by SdrGrafObj::SFX_NOTIFY, which is no longer\n \/\/ called nowadays. BTW: strictly speaking, the whole\n \/\/ ImpSetAttrToGrafInfo\/ImpSetGrafInfoToAttr stuff could\n \/\/ be dumped, when SdrGrafObj::aGrafInfo is removed and\n \/\/ always created on the fly for repaint.\n rObj.ImpSetAttrToGrafInfo();\n\n \/\/ call parent\n RectangleProperties::ItemSetChanged(rSet);\n }\n\n void GraphicProperties::SetStyleSheet(SfxStyleSheet* pNewStyleSheet, sal_Bool bDontRemoveHardAttr)\n {\n SdrGrafObj& rObj = (SdrGrafObj&)GetSdrObject();\n\n \/\/ local changes\n rObj.SetXPolyDirty();\n\n \/\/ call parent\n RectangleProperties::SetStyleSheet(pNewStyleSheet, bDontRemoveHardAttr);\n\n \/\/ local changes\n rObj.ImpSetAttrToGrafInfo();\n }\n\n\/\/BFS01 void GraphicProperties::PreProcessSave()\n\/\/BFS01 {\n\/\/BFS01 \/\/ call parent\n\/\/BFS01 RectangleProperties::PreProcessSave();\n\/\/BFS01\n\/\/BFS01 \/\/ force ItemSet\n\/\/BFS01 GetObjectItemSet();\n\/\/BFS01\n\/\/BFS01 \/\/ prepare SetItems for storage\n\/\/BFS01 const SfxItemSet& rSet = *mpItemSet;\n\/\/BFS01 const SfxItemSet* pParent = mpStyleSheet ? &(mpStyleSheet->GetItemSet()) : 0L;\n\/\/BFS01\n\/\/BFS01 SdrGrafSetItem aGrafAttr(rSet.GetPool());\n\/\/BFS01 aGrafAttr.GetItemSet().Put(rSet);\n\/\/BFS01 aGrafAttr.GetItemSet().SetParent(pParent);\n\/\/BFS01 mpItemSet->Put(aGrafAttr);\n\/\/BFS01 }\n\n\/\/BFS01 void GraphicProperties::PostProcessSave()\n\/\/BFS01 {\n\/\/BFS01 \/\/ call parent\n\/\/BFS01 RectangleProperties::PostProcessSave();\n\/\/BFS01\n\/\/BFS01 \/\/ remove SetItems from local itemset\n\/\/BFS01 if(mpItemSet)\n\/\/BFS01 {\n\/\/BFS01 mpItemSet->ClearItem(SDRATTRSET_GRAF);\n\/\/BFS01 }\n\/\/BFS01 }\n\n void GraphicProperties::ForceDefaultAttributes()\n {\n \/\/ call parent\n RectangleProperties::ForceDefaultAttributes();\n\n \/\/ force ItemSet\n GetObjectItemSet();\n\n mpItemSet->Put( SdrGrafLuminanceItem( 0 ) );\n mpItemSet->Put( SdrGrafContrastItem( 0 ) );\n mpItemSet->Put( SdrGrafRedItem( 0 ) );\n mpItemSet->Put( SdrGrafGreenItem( 0 ) );\n mpItemSet->Put( SdrGrafBlueItem( 0 ) );\n mpItemSet->Put( SdrGrafGamma100Item( 100 ) );\n mpItemSet->Put( SdrGrafTransparenceItem( 0 ) );\n mpItemSet->Put( SdrGrafInvertItem( FALSE ) );\n mpItemSet->Put( SdrGrafModeItem( GRAPHICDRAWMODE_STANDARD ) );\n mpItemSet->Put( SdrGrafCropItem( 0, 0, 0, 0 ) );\n\n \/\/ #i25616#\n mpItemSet->Put( XFillStyleItem(XFILL_NONE) );\n mpItemSet->Put( XLineStyleItem(XLINE_NONE) );\n }\n } \/\/ end of namespace properties\n} \/\/ end of namespace sdr\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ eof\nINTEGRATION: CWS ooo19126 (1.6.598); FILE MERGED 2005\/09\/05 14:26:39 rt 1.6.598.1: #i54170# Change license header: remove SISSL\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: graphicproperties.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 00:14:22 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _SDR_PROPERTIES_GRAPHICPROPERTIES_HXX\n#include \n#endif\n\n#ifndef _SFXITEMSET_HXX\n#include \n#endif\n\n#ifndef _SFXSTYLE_HXX\n#include \n#endif\n\n#ifndef _SVDDEF_HXX\n#include \n#endif\n\n#ifndef _EEITEM_HXX\n#include \n#endif\n\n#ifndef _SVDOGRAF_HXX\n#include \n#endif\n\n#define ITEMID_GRF_CROP 0\n\n#ifndef _SDGCPITM_HXX\n#include \n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace sdr\n{\n namespace properties\n {\n \/\/ create a new itemset\n SfxItemSet& GraphicProperties::CreateObjectSpecificItemSet(SfxItemPool& rPool)\n {\n return *(new SfxItemSet(rPool,\n\n \/\/ range from SdrAttrObj\n SDRATTR_START, SDRATTR_SHADOW_LAST,\n SDRATTR_MISC_FIRST, SDRATTR_MISC_LAST,\n SDRATTR_TEXTDIRECTION, SDRATTR_TEXTDIRECTION,\n\n \/\/ range from SdrGrafObj\n SDRATTR_GRAF_FIRST, SDRATTR_GRAF_LAST,\n\n \/\/ range from SdrTextObj\n EE_ITEMS_START, EE_ITEMS_END,\n\n \/\/ end\n 0, 0));\n }\n\n GraphicProperties::GraphicProperties(SdrObject& rObj)\n : RectangleProperties(rObj)\n {\n }\n\n GraphicProperties::GraphicProperties(const GraphicProperties& rProps, SdrObject& rObj)\n : RectangleProperties(rProps, rObj)\n {\n }\n\n GraphicProperties::~GraphicProperties()\n {\n }\n\n BaseProperties& GraphicProperties::Clone(SdrObject& rObj) const\n {\n return *(new GraphicProperties(*this, rObj));\n }\n\n void GraphicProperties::ItemSetChanged(const SfxItemSet& rSet)\n {\n SdrGrafObj& rObj = (SdrGrafObj&)GetSdrObject();\n\n \/\/ local changes\n rObj.SetXPolyDirty();\n\n \/\/ #i29367# Update GraphicAttr, too. This was formerly\n \/\/ triggered by SdrGrafObj::SFX_NOTIFY, which is no longer\n \/\/ called nowadays. BTW: strictly speaking, the whole\n \/\/ ImpSetAttrToGrafInfo\/ImpSetGrafInfoToAttr stuff could\n \/\/ be dumped, when SdrGrafObj::aGrafInfo is removed and\n \/\/ always created on the fly for repaint.\n rObj.ImpSetAttrToGrafInfo();\n\n \/\/ call parent\n RectangleProperties::ItemSetChanged(rSet);\n }\n\n void GraphicProperties::SetStyleSheet(SfxStyleSheet* pNewStyleSheet, sal_Bool bDontRemoveHardAttr)\n {\n SdrGrafObj& rObj = (SdrGrafObj&)GetSdrObject();\n\n \/\/ local changes\n rObj.SetXPolyDirty();\n\n \/\/ call parent\n RectangleProperties::SetStyleSheet(pNewStyleSheet, bDontRemoveHardAttr);\n\n \/\/ local changes\n rObj.ImpSetAttrToGrafInfo();\n }\n\n\/\/BFS01 void GraphicProperties::PreProcessSave()\n\/\/BFS01 {\n\/\/BFS01 \/\/ call parent\n\/\/BFS01 RectangleProperties::PreProcessSave();\n\/\/BFS01\n\/\/BFS01 \/\/ force ItemSet\n\/\/BFS01 GetObjectItemSet();\n\/\/BFS01\n\/\/BFS01 \/\/ prepare SetItems for storage\n\/\/BFS01 const SfxItemSet& rSet = *mpItemSet;\n\/\/BFS01 const SfxItemSet* pParent = mpStyleSheet ? &(mpStyleSheet->GetItemSet()) : 0L;\n\/\/BFS01\n\/\/BFS01 SdrGrafSetItem aGrafAttr(rSet.GetPool());\n\/\/BFS01 aGrafAttr.GetItemSet().Put(rSet);\n\/\/BFS01 aGrafAttr.GetItemSet().SetParent(pParent);\n\/\/BFS01 mpItemSet->Put(aGrafAttr);\n\/\/BFS01 }\n\n\/\/BFS01 void GraphicProperties::PostProcessSave()\n\/\/BFS01 {\n\/\/BFS01 \/\/ call parent\n\/\/BFS01 RectangleProperties::PostProcessSave();\n\/\/BFS01\n\/\/BFS01 \/\/ remove SetItems from local itemset\n\/\/BFS01 if(mpItemSet)\n\/\/BFS01 {\n\/\/BFS01 mpItemSet->ClearItem(SDRATTRSET_GRAF);\n\/\/BFS01 }\n\/\/BFS01 }\n\n void GraphicProperties::ForceDefaultAttributes()\n {\n \/\/ call parent\n RectangleProperties::ForceDefaultAttributes();\n\n \/\/ force ItemSet\n GetObjectItemSet();\n\n mpItemSet->Put( SdrGrafLuminanceItem( 0 ) );\n mpItemSet->Put( SdrGrafContrastItem( 0 ) );\n mpItemSet->Put( SdrGrafRedItem( 0 ) );\n mpItemSet->Put( SdrGrafGreenItem( 0 ) );\n mpItemSet->Put( SdrGrafBlueItem( 0 ) );\n mpItemSet->Put( SdrGrafGamma100Item( 100 ) );\n mpItemSet->Put( SdrGrafTransparenceItem( 0 ) );\n mpItemSet->Put( SdrGrafInvertItem( FALSE ) );\n mpItemSet->Put( SdrGrafModeItem( GRAPHICDRAWMODE_STANDARD ) );\n mpItemSet->Put( SdrGrafCropItem( 0, 0, 0, 0 ) );\n\n \/\/ #i25616#\n mpItemSet->Put( XFillStyleItem(XFILL_NONE) );\n mpItemSet->Put( XLineStyleItem(XLINE_NONE) );\n }\n } \/\/ end of namespace properties\n} \/\/ end of namespace sdr\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ eof\n<|endoftext|>"} {"text":"\/*\n *\n * Copyright 2016, Google Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"src\/proto\/grpc\/health\/v1\/health.grpc.pb.h\"\n#include \"src\/proto\/grpc\/testing\/duplicate\/echo_duplicate.grpc.pb.h\"\n#include \"src\/proto\/grpc\/testing\/echo.grpc.pb.h\"\n#include \"test\/core\/util\/port.h\"\n#include \"test\/core\/util\/test_config.h\"\n#include \"test\/cpp\/end2end\/test_service_impl.h\"\n\nusing grpc::health::v1::Health;\nusing grpc::health::v1::HealthCheckRequest;\nusing grpc::health::v1::HealthCheckResponse;\n\nnamespace grpc {\nnamespace testing {\nnamespace {\n\n\/\/ A sample sync implementation of the health checking service. This does the\n\/\/ same thing as the default one.\nclass HealthCheckServiceImpl : public ::grpc::health::v1::Health::Service {\n public:\n Status Check(ServerContext* context, const HealthCheckRequest* request,\n HealthCheckResponse* response) override {\n std::lock_guard lock(mu_);\n auto iter = status_map_.find(request->service());\n if (iter == status_map_.end()) {\n return Status(StatusCode::NOT_FOUND, \"\");\n }\n response->set_status(iter->second);\n return Status::OK;\n }\n\n void SetStatus(const grpc::string& service_name,\n HealthCheckResponse::ServingStatus status) {\n std::lock_guard lock(mu_);\n status_map_[service_name] = status;\n }\n\n void SetAll(HealthCheckResponse::ServingStatus status) {\n std::lock_guard lock(mu_);\n for (auto iter = status_map_.begin(); iter != status_map_.end(); ++iter) {\n iter->second = status;\n }\n }\n\n private:\n std::mutex mu_;\n std::map status_map_;\n};\n\n\/\/ A custom implementation of the health checking service interface. This is\n\/\/ used to test that it prevents the server from creating a default service and\n\/\/ also serves as an example of how to override the default service.\nclass CustomHealthCheckService : public HealthCheckServiceInterface {\n public:\n explicit CustomHealthCheckService(HealthCheckServiceImpl* impl)\n : impl_(impl) {\n impl_->SetStatus(\"\", HealthCheckResponse::SERVING);\n }\n void SetServingStatus(const grpc::string& service_name,\n bool serving) override {\n impl_->SetStatus(service_name, serving ? HealthCheckResponse::SERVING\n : HealthCheckResponse::NOT_SERVING);\n }\n\n void SetServingStatus(bool serving) override {\n impl_->SetAll(serving ? HealthCheckResponse::SERVING\n : HealthCheckResponse::NOT_SERVING);\n }\n\n private:\n HealthCheckServiceImpl* impl_; \/\/ not owned\n};\n\nvoid LoopCompletionQueue(ServerCompletionQueue* cq) {\n void* tag;\n bool ok;\n while (cq->Next(&tag, &ok)) {\n abort(); \/\/ Nothing should come out of the cq.\n }\n}\n\nclass HealthServiceEnd2endTest : public ::testing::Test {\n protected:\n HealthServiceEnd2endTest() {}\n\n void SetUpServer(bool register_sync_test_service,\n bool explicit_health_service,\n std::unique_ptr service) {\n int port = grpc_pick_unused_port_or_die();\n server_address_ << \"localhost:\" << port;\n\n bool register_sync_health_service_impl =\n explicit_health_service && service != nullptr;\n\n \/\/ Setup server\n ServerBuilder builder;\n if (explicit_health_service) {\n std::unique_ptr option(\n new HealthCheckServiceServerBuilderOption(std::move(service)));\n builder.SetOption(std::move(option));\n }\n builder.AddListeningPort(server_address_.str(),\n grpc::InsecureServerCredentials());\n if (register_sync_test_service) {\n \/\/ Register a sync service.\n builder.RegisterService(&echo_test_service_);\n }\n if (register_sync_health_service_impl) {\n builder.RegisterService(&health_check_service_impl_);\n }\n cq_ = builder.AddCompletionQueue();\n server_ = builder.BuildAndStart();\n }\n\n void TearDown() override {\n if (server_) {\n server_->Shutdown();\n cq_->Shutdown();\n if (cq_thread_.joinable()) {\n cq_thread_.join();\n }\n LoopCompletionQueue(cq_.get());\n }\n }\n\n void ResetStubs() {\n std::shared_ptr channel =\n CreateChannel(server_address_.str(), InsecureChannelCredentials());\n hc_stub_ = grpc::health::v1::Health::NewStub(channel);\n }\n\n \/\/ When the expected_status is NOT OK, we do not care about the response.\n void SendHealthCheckRpc(const grpc::string& service_name,\n const Status& expected_status) {\n EXPECT_FALSE(expected_status.ok());\n SendHealthCheckRpc(service_name, expected_status,\n HealthCheckResponse::UNKNOWN);\n }\n\n void SendHealthCheckRpc(\n const grpc::string& service_name, const Status& expected_status,\n HealthCheckResponse::ServingStatus expected_serving_status) {\n HealthCheckRequest request;\n request.set_service(service_name);\n HealthCheckResponse response;\n ClientContext context;\n Status s = hc_stub_->Check(&context, request, &response);\n EXPECT_EQ(expected_status.error_code(), s.error_code());\n if (s.ok()) {\n EXPECT_EQ(expected_serving_status, response.status());\n }\n }\n\n void VerifyHealthCheckService() {\n HealthCheckServiceInterface* service = server_->GetHealthCheckService();\n EXPECT_TRUE(service != nullptr);\n const grpc::string kHealthyService(\"healthy_service\");\n const grpc::string kUnhealthyService(\"unhealthy_service\");\n const grpc::string kNotRegisteredService(\"not_registered\");\n service->SetServingStatus(kHealthyService, true);\n service->SetServingStatus(kUnhealthyService, false);\n\n ResetStubs();\n\n SendHealthCheckRpc(\"\", Status::OK, HealthCheckResponse::SERVING);\n SendHealthCheckRpc(kHealthyService, Status::OK,\n HealthCheckResponse::SERVING);\n SendHealthCheckRpc(kUnhealthyService, Status::OK,\n HealthCheckResponse::NOT_SERVING);\n SendHealthCheckRpc(kNotRegisteredService,\n Status(StatusCode::NOT_FOUND, \"\"));\n\n service->SetServingStatus(false);\n SendHealthCheckRpc(\"\", Status::OK, HealthCheckResponse::NOT_SERVING);\n SendHealthCheckRpc(kHealthyService, Status::OK,\n HealthCheckResponse::NOT_SERVING);\n SendHealthCheckRpc(kUnhealthyService, Status::OK,\n HealthCheckResponse::NOT_SERVING);\n SendHealthCheckRpc(kNotRegisteredService,\n Status(StatusCode::NOT_FOUND, \"\"));\n }\n\n TestServiceImpl echo_test_service_;\n HealthCheckServiceImpl health_check_service_impl_;\n std::unique_ptr hc_stub_;\n std::unique_ptr cq_;\n std::unique_ptr server_;\n std::ostringstream server_address_;\n std::thread cq_thread_;\n};\n\nTEST_F(HealthServiceEnd2endTest, DefaultHealthServiceDisabled) {\n EnableDefaultHealthCheckService(false);\n EXPECT_FALSE(DefaultHealthCheckServiceEnabled());\n SetUpServer(true, false, nullptr);\n HealthCheckServiceInterface* default_service =\n server_->GetHealthCheckService();\n EXPECT_TRUE(default_service == nullptr);\n\n ResetStubs();\n\n SendHealthCheckRpc(\"\", Status(StatusCode::UNIMPLEMENTED, \"\"));\n}\n\nTEST_F(HealthServiceEnd2endTest, DefaultHealthService) {\n EnableDefaultHealthCheckService(true);\n EXPECT_TRUE(DefaultHealthCheckServiceEnabled());\n SetUpServer(true, false, nullptr);\n VerifyHealthCheckService();\n\n \/\/ The default service has a size limit of the service name.\n const grpc::string kTooLongServiceName(201, 'x');\n SendHealthCheckRpc(kTooLongServiceName,\n Status(StatusCode::INVALID_ARGUMENT, \"\"));\n}\n\nTEST_F(HealthServiceEnd2endTest, DefaultHealthServiceAsync) {\n EnableDefaultHealthCheckService(true);\n EXPECT_TRUE(DefaultHealthCheckServiceEnabled());\n SetUpServer(false, false, nullptr);\n cq_thread_ = std::thread(LoopCompletionQueue, cq_.get());\n VerifyHealthCheckService();\n\n \/\/ The default service has a size limit of the service name.\n const grpc::string kTooLongServiceName(201, 'x');\n SendHealthCheckRpc(kTooLongServiceName,\n Status(StatusCode::INVALID_ARGUMENT, \"\"));\n}\n\n\/\/ Provide an empty service to disable the default service.\nTEST_F(HealthServiceEnd2endTest, ExplicitlyDisableViaOverride) {\n EnableDefaultHealthCheckService(true);\n EXPECT_TRUE(DefaultHealthCheckServiceEnabled());\n std::unique_ptr empty_service;\n SetUpServer(true, true, std::move(empty_service));\n HealthCheckServiceInterface* service = server_->GetHealthCheckService();\n EXPECT_TRUE(service == nullptr);\n\n ResetStubs();\n\n SendHealthCheckRpc(\"\", Status(StatusCode::UNIMPLEMENTED, \"\"));\n}\n\n\/\/ Provide an explicit override of health checking service interface.\nTEST_F(HealthServiceEnd2endTest, ExplicitlyOverride) {\n EnableDefaultHealthCheckService(true);\n EXPECT_TRUE(DefaultHealthCheckServiceEnabled());\n std::unique_ptr override_service(\n new CustomHealthCheckService(&health_check_service_impl_));\n HealthCheckServiceInterface* underlying_service = override_service.get();\n SetUpServer(false, true, std::move(override_service));\n HealthCheckServiceInterface* service = server_->GetHealthCheckService();\n EXPECT_TRUE(service == underlying_service);\n\n ResetStubs();\n\n VerifyHealthCheckService();\n}\n\n} \/\/ namespace\n} \/\/ namespace testing\n} \/\/ namespace grpc\n\nint main(int argc, char** argv) {\n grpc_test_init(argc, argv);\n ::testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\nmake test robust\/*\n *\n * Copyright 2016, Google Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"src\/proto\/grpc\/health\/v1\/health.grpc.pb.h\"\n#include \"src\/proto\/grpc\/testing\/duplicate\/echo_duplicate.grpc.pb.h\"\n#include \"src\/proto\/grpc\/testing\/echo.grpc.pb.h\"\n#include \"test\/core\/util\/port.h\"\n#include \"test\/core\/util\/test_config.h\"\n#include \"test\/cpp\/end2end\/test_service_impl.h\"\n\nusing grpc::health::v1::Health;\nusing grpc::health::v1::HealthCheckRequest;\nusing grpc::health::v1::HealthCheckResponse;\n\nnamespace grpc {\nnamespace testing {\nnamespace {\n\n\/\/ A sample sync implementation of the health checking service. This does the\n\/\/ same thing as the default one.\nclass HealthCheckServiceImpl : public ::grpc::health::v1::Health::Service {\n public:\n Status Check(ServerContext* context, const HealthCheckRequest* request,\n HealthCheckResponse* response) override {\n std::lock_guard lock(mu_);\n auto iter = status_map_.find(request->service());\n if (iter == status_map_.end()) {\n return Status(StatusCode::NOT_FOUND, \"\");\n }\n response->set_status(iter->second);\n return Status::OK;\n }\n\n void SetStatus(const grpc::string& service_name,\n HealthCheckResponse::ServingStatus status) {\n std::lock_guard lock(mu_);\n status_map_[service_name] = status;\n }\n\n void SetAll(HealthCheckResponse::ServingStatus status) {\n std::lock_guard lock(mu_);\n for (auto iter = status_map_.begin(); iter != status_map_.end(); ++iter) {\n iter->second = status;\n }\n }\n\n private:\n std::mutex mu_;\n std::map status_map_;\n};\n\n\/\/ A custom implementation of the health checking service interface. This is\n\/\/ used to test that it prevents the server from creating a default service and\n\/\/ also serves as an example of how to override the default service.\nclass CustomHealthCheckService : public HealthCheckServiceInterface {\n public:\n explicit CustomHealthCheckService(HealthCheckServiceImpl* impl)\n : impl_(impl) {\n impl_->SetStatus(\"\", HealthCheckResponse::SERVING);\n }\n void SetServingStatus(const grpc::string& service_name,\n bool serving) override {\n impl_->SetStatus(service_name, serving ? HealthCheckResponse::SERVING\n : HealthCheckResponse::NOT_SERVING);\n }\n\n void SetServingStatus(bool serving) override {\n impl_->SetAll(serving ? HealthCheckResponse::SERVING\n : HealthCheckResponse::NOT_SERVING);\n }\n\n private:\n HealthCheckServiceImpl* impl_; \/\/ not owned\n};\n\nvoid LoopCompletionQueue(ServerCompletionQueue* cq) {\n void* tag;\n bool ok;\n while (cq->Next(&tag, &ok)) {\n abort(); \/\/ Nothing should come out of the cq.\n }\n}\n\nclass HealthServiceEnd2endTest : public ::testing::Test {\n protected:\n HealthServiceEnd2endTest() {}\n\n void SetUpServer(bool register_sync_test_service, bool add_async_cq,\n bool explicit_health_service,\n std::unique_ptr service) {\n int port = grpc_pick_unused_port_or_die();\n server_address_ << \"localhost:\" << port;\n\n bool register_sync_health_service_impl =\n explicit_health_service && service != nullptr;\n\n \/\/ Setup server\n ServerBuilder builder;\n if (explicit_health_service) {\n std::unique_ptr option(\n new HealthCheckServiceServerBuilderOption(std::move(service)));\n builder.SetOption(std::move(option));\n }\n builder.AddListeningPort(server_address_.str(),\n grpc::InsecureServerCredentials());\n if (register_sync_test_service) {\n \/\/ Register a sync service.\n builder.RegisterService(&echo_test_service_);\n }\n if (register_sync_health_service_impl) {\n builder.RegisterService(&health_check_service_impl_);\n }\n if (add_async_cq) {\n cq_ = builder.AddCompletionQueue();\n }\n server_ = builder.BuildAndStart();\n }\n\n void TearDown() override {\n if (server_) {\n server_->Shutdown();\n if (cq_ != nullptr) {\n cq_->Shutdown();\n }\n if (cq_thread_.joinable()) {\n cq_thread_.join();\n }\n }\n }\n\n void ResetStubs() {\n std::shared_ptr channel =\n CreateChannel(server_address_.str(), InsecureChannelCredentials());\n hc_stub_ = grpc::health::v1::Health::NewStub(channel);\n }\n\n \/\/ When the expected_status is NOT OK, we do not care about the response.\n void SendHealthCheckRpc(const grpc::string& service_name,\n const Status& expected_status) {\n EXPECT_FALSE(expected_status.ok());\n SendHealthCheckRpc(service_name, expected_status,\n HealthCheckResponse::UNKNOWN);\n }\n\n void SendHealthCheckRpc(\n const grpc::string& service_name, const Status& expected_status,\n HealthCheckResponse::ServingStatus expected_serving_status) {\n HealthCheckRequest request;\n request.set_service(service_name);\n HealthCheckResponse response;\n ClientContext context;\n Status s = hc_stub_->Check(&context, request, &response);\n EXPECT_EQ(expected_status.error_code(), s.error_code());\n if (s.ok()) {\n EXPECT_EQ(expected_serving_status, response.status());\n }\n }\n\n void VerifyHealthCheckService() {\n HealthCheckServiceInterface* service = server_->GetHealthCheckService();\n EXPECT_TRUE(service != nullptr);\n const grpc::string kHealthyService(\"healthy_service\");\n const grpc::string kUnhealthyService(\"unhealthy_service\");\n const grpc::string kNotRegisteredService(\"not_registered\");\n service->SetServingStatus(kHealthyService, true);\n service->SetServingStatus(kUnhealthyService, false);\n\n ResetStubs();\n\n SendHealthCheckRpc(\"\", Status::OK, HealthCheckResponse::SERVING);\n SendHealthCheckRpc(kHealthyService, Status::OK,\n HealthCheckResponse::SERVING);\n SendHealthCheckRpc(kUnhealthyService, Status::OK,\n HealthCheckResponse::NOT_SERVING);\n SendHealthCheckRpc(kNotRegisteredService,\n Status(StatusCode::NOT_FOUND, \"\"));\n\n service->SetServingStatus(false);\n SendHealthCheckRpc(\"\", Status::OK, HealthCheckResponse::NOT_SERVING);\n SendHealthCheckRpc(kHealthyService, Status::OK,\n HealthCheckResponse::NOT_SERVING);\n SendHealthCheckRpc(kUnhealthyService, Status::OK,\n HealthCheckResponse::NOT_SERVING);\n SendHealthCheckRpc(kNotRegisteredService,\n Status(StatusCode::NOT_FOUND, \"\"));\n }\n\n TestServiceImpl echo_test_service_;\n HealthCheckServiceImpl health_check_service_impl_;\n std::unique_ptr hc_stub_;\n std::unique_ptr cq_;\n std::unique_ptr server_;\n std::ostringstream server_address_;\n std::thread cq_thread_;\n};\n\nTEST_F(HealthServiceEnd2endTest, DefaultHealthServiceDisabled) {\n EnableDefaultHealthCheckService(false);\n EXPECT_FALSE(DefaultHealthCheckServiceEnabled());\n SetUpServer(true, false, false, nullptr);\n HealthCheckServiceInterface* default_service =\n server_->GetHealthCheckService();\n EXPECT_TRUE(default_service == nullptr);\n\n ResetStubs();\n\n SendHealthCheckRpc(\"\", Status(StatusCode::UNIMPLEMENTED, \"\"));\n}\n\nTEST_F(HealthServiceEnd2endTest, DefaultHealthService) {\n EnableDefaultHealthCheckService(true);\n EXPECT_TRUE(DefaultHealthCheckServiceEnabled());\n SetUpServer(true, false, false, nullptr);\n VerifyHealthCheckService();\n\n \/\/ The default service has a size limit of the service name.\n const grpc::string kTooLongServiceName(201, 'x');\n SendHealthCheckRpc(kTooLongServiceName,\n Status(StatusCode::INVALID_ARGUMENT, \"\"));\n}\n\n\/\/ The server has no sync service.\nTEST_F(HealthServiceEnd2endTest, DefaultHealthServiceAsyncOnly) {\n EnableDefaultHealthCheckService(true);\n EXPECT_TRUE(DefaultHealthCheckServiceEnabled());\n SetUpServer(false, true, false, nullptr);\n cq_thread_ = std::thread(LoopCompletionQueue, cq_.get());\n\n VerifyHealthCheckService();\n\n \/\/ The default service has a size limit of the service name.\n const grpc::string kTooLongServiceName(201, 'x');\n SendHealthCheckRpc(kTooLongServiceName,\n Status(StatusCode::INVALID_ARGUMENT, \"\"));\n}\n\n\/\/ Provide an empty service to disable the default service.\nTEST_F(HealthServiceEnd2endTest, ExplicitlyDisableViaOverride) {\n EnableDefaultHealthCheckService(true);\n EXPECT_TRUE(DefaultHealthCheckServiceEnabled());\n std::unique_ptr empty_service;\n SetUpServer(true, false, true, std::move(empty_service));\n HealthCheckServiceInterface* service = server_->GetHealthCheckService();\n EXPECT_TRUE(service == nullptr);\n\n ResetStubs();\n\n SendHealthCheckRpc(\"\", Status(StatusCode::UNIMPLEMENTED, \"\"));\n}\n\n\/\/ Provide an explicit override of health checking service interface.\nTEST_F(HealthServiceEnd2endTest, ExplicitlyOverride) {\n EnableDefaultHealthCheckService(true);\n EXPECT_TRUE(DefaultHealthCheckServiceEnabled());\n std::unique_ptr override_service(\n new CustomHealthCheckService(&health_check_service_impl_));\n HealthCheckServiceInterface* underlying_service = override_service.get();\n SetUpServer(false, false, true, std::move(override_service));\n HealthCheckServiceInterface* service = server_->GetHealthCheckService();\n EXPECT_TRUE(service == underlying_service);\n\n ResetStubs();\n\n VerifyHealthCheckService();\n}\n\n} \/\/ namespace\n} \/\/ namespace testing\n} \/\/ namespace grpc\n\nint main(int argc, char** argv) {\n grpc_test_init(argc, argv);\n ::testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ guaranteed_minimum_withdrawal_benefit.cpp\n\/\/ -----------------------------------------\n\/\/\n\/\/ Computes the price of a Guaranteed Minimum Withdrawal Benefit (GMWB) using an\n\/\/ implicit, impulse control formulation.\n\/\/\n\/\/ Author: Parsiad Azimzadeh\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \n#include \n#include \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \/\/ max, min\n#include \/\/ cout\n#include \/\/ accumulate\n#include \/\/ get\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nusing namespace QuantPDE;\nusing namespace QuantPDE::Modules;\n\nusing namespace std;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass Withdrawal final : public ControlledLinearSystem2 {\n\n\tstatic constexpr Real epsilon = 1e-12;\n\n\tRectilinearGrid2 &grid;\n\tNoncontrollable2 contractRate, kappa;\n\n\tControllable2 control;\n\npublic:\n\n\ttemplate \n\tWithdrawal(G &grid, F1 &&contractRate, F2 &&kappa) noexcept :\n\t\tgrid(grid),\n\t\tcontractRate(contractRate),\n\t\tkappa(kappa),\n\t\tcontrol( Control2(grid) )\n\t{\n\t\tregisterControl( control );\n\t}\n\n\tvirtual Matrix A(Real t) {\n\t\tMatrix M(grid.size(), grid.size());\n\t\tM.reserve(IntegerVector::Constant(grid.size(), 4));\n\n\t\tIndex i = 0;\n\t\tfor(auto node : grid) {\n\t\t\tconst Real S = node[0]; \/\/ Investment\n\t\t\tconst Real W = node[1]; \/\/ Withdrawal\n\n\t\t\t\/\/ Contract rate of withdrawal\n\t\t\tconst Real Gdt = contractRate(t, S, W);\n\n\t\t\t\/\/ Control\n\t\t\tconst Real q = control(t, S, W);\n\n\t\t\t\/\/ Amount withdrawn, pre-penalty\n\t\t\t\/\/const Real lambdaW = q * W;\n\t\t\tReal lambdaW;\n\t\t\tif(Gdt <= W) {\n\t\t\t\tlambdaW = (q<=1.) ? (q*Gdt) : ((q-1.)*(W - Gdt) + Gdt);\n\t\t\t} else {\n\t\t\t\tlambdaW = q\/2.*W;\n\t\t\t}\n\n\t\t\t\/\/ Interpolation data\n\t\t\tauto data = interpolationData<2>(\n\t\t\t\tgrid,\n\t\t\t\t{\n\t\t\t\t\tmax(S - lambdaW, 0.),\n\t\t\t\t\tW - lambdaW\n\t\t\t\t}\n\t\t\t);\n\n\t\t\tconst Index i0 = get<0>( data[0] );\n\t\t\tconst Index i1 = get<0>( data[1] );\n\t\t\tconst Real w0 = get<1>( data[0] );\n\t\t\tconst Real w1 = get<1>( data[1] );\n\n\t\t\tconst Index j = grid.index(i0, i1);\n\n\t\t\tM.insert(i, j ) = w0 * w1 ;\n\t\t\tM.insert(i, j + grid[0].size()) = w0 * (1-w1);\n\t\t\tM.insert(i, j + 1 ) = (1-w0) * w1 ;\n\t\t\tM.insert(i, j + 1 + grid[0].size()) = (1-w0) * (1-w1);\n\n\t\t\t++i;\n\t\t}\n\n\t\tM.makeCompressed();\n\t\treturn grid.identity() - M;\n\t}\n\n\tvirtual Vector b(Real t) {\n\t\tVector b( grid.vector() );\n\t\tfor(auto node : accessor(grid, b)) {\n\t\t\tconst Real S = (&node)[0]; \/\/ Investment\n\t\t\tconst Real W = (&node)[1]; \/\/ Withdrawal\n\n\t\t\t\/\/ You have no money :(\n\t\t\tif(W <= epsilon) {\n\t\t\t\t*node = 0.;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t\/\/ Contract rate of withdrawal\n\t\t\tconst Real Gdt = contractRate(t, S, W);\n\n\t\t\t\/\/ Control\n\t\t\tconst Real q = control(t, S, W);\n\n\t\t\t\/\/ Amount withdrawn, pre-penalty\n\t\t\t\/\/const Real lambdaW = q * W;\n\t\t\tReal lambdaW;\n\t\t\tif(Gdt <= W) {\n\t\t\t\tlambdaW = (q<=1.) ? (q*Gdt) : ((q-1.)*(W - Gdt) + Gdt);\n\t\t\t} else {\n\t\t\t\tlambdaW = q\/2.*W;\n\t\t\t}\n\n\t\t\t\/\/ Withdrawal at no penalty\n\t\t\tif(lambdaW < Gdt) {\n\t\t\t\t*node = lambdaW;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t\/\/ Withdrawal at a penalty\n\t\t\t*node = lambdaW - kappa(t, S, W) * (lambdaW - Gdt);\n\t\t}\n\n\t\treturn b;\n\t}\n\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint main() {\n\n\tint n = 10; \/\/ Initial optimal control partition size\n\tint N = 32; \/\/ Initial number of timesteps\n\n\tReal T = 10.;\n\tReal r = .05;\n\tReal v = .2;\n\n\tReal alpha = 0.013886; \/\/ Hedging fee\n\n\tReal G = 10.; \/\/ Contract rate\n\tReal kappa = 0.1; \/\/ Penalty rate\n\n\tint refinement = 1;\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Solution grid\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\tRectilinearGrid2 grid(\n\t\tAxis {\n\t\t\t0., 5., 10., 15., 20., 25.,\n\t\t\t30., 35., 40., 45.,\n\t\t\t50., 55., 60., 65., 70., 72.5, 75., 77.5, 80., 82., 84.,\n\t\t\t86., 88., 90., 91., 92., 93., 94., 95.,\n\t\t\t96., 97., 98., 99., 100.,\n\t\t\t101., 102., 103., 104., 105., 106.,\n\t\t\t107., 108., 109., 110., 112., 114.,\n\t\t\t116., 118., 120., 123., 126.,\n\t\t\t130., 135., 140., 145., 150., 160., 175., 200., 225.,\n\t\t\t250., 300., 500., 750., 1000.\n\t\t},\n\t\tAxis::range(0., 2., 100.)\n\t);\n\n\tunsigned pow2l = 1; \/\/ 2^l\n\tfor(int l = 0; l < refinement; ++l) {\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ Control grid\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\t\/\/ Control partition 0 : 1\/n : 1 (MATLAB notation)\n\t\tRectilinearGrid1 controls( Axis::range(0., 1. \/ (n * pow2l), 2.) );\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ Iteration tree\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\tReverseConstantStepper stepper(\n\t\t\t0., \/\/ Initial time\n\t\t\tT, \/\/ Expiry time\n\t\t\tT \/ (N * pow2l) \/\/ Timestep size\n\t\t);\n\t\tToleranceIteration tolerance;\n\t\tstepper.setInnerIteration(tolerance);\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ Linear system tree\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\tBlackScholes<2, 0> bs(grid, r, v, alpha);\n\t\tReverseRannacher discretization(grid, bs);\n\t\tdiscretization.setIteration(stepper);\n\n\t\tWithdrawal impulse(grid, G * T \/ (N * pow2l), kappa);\n\t\tMinPolicyIteration2_1 policy(grid, controls, impulse);\n\n\t\tPenaltyMethod penalty(grid, discretization, policy);\n\n\t\t\/\/ TODO: It currently matters what order each linear system is\n\t\t\/\/ associated with an iteration; fix this.\n\n\t\tpenalty.setIteration(tolerance);\n\t\tpolicy.setIteration(tolerance);\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ Payoff\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\tFunction2 payoff = [=] (Real S, Real W) {\n\t\t\treturn max(S, (1 - kappa) * W);\n\t\t};\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ Running\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\tBiCGSTABSolver solver;\n\n\t\tauto V = stepper.solve(\n\t\t\tgrid, \/\/ Domain\n\t\t\tpayoff, \/\/ Initial condition\n\t\t\tpenalty, \/\/ Root of linear system tree\n\t\t\tsolver \/\/ Linear system solver\n\t\t);\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ Print solution\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\tRectilinearGrid2 printGrid(\n\t\t\tAxis::range(0., 25., 200.),\n\t\t\tAxis { 100. }\n\t\t);\n\t\tcout << accessor( printGrid, V );\n\n\t\tcout << endl;\n\n\t\tauto its = tolerance.iterations();\n\t\tReal inner = accumulate(its.begin(), its.end(), 0.)\/its.size();\n\n\t\tcout << \"average number of inner iterations: \" << inner << endl;\n\n\t\tcout << endl;\n\n\t\tpow2l *= 2;\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ Refine Solution grid\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\tgrid.refine( RectilinearGrid2::NewTickBetweenEachPair() );\n\t}\n\n\treturn 0;\n}\n\nAdded comment with exact nonwithdrawal solution.\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ guaranteed_minimum_withdrawal_benefit.cpp\n\/\/ -----------------------------------------\n\/\/\n\/\/ Computes the price of a Guaranteed Minimum Withdrawal Benefit (GMWB) using an\n\/\/ implicit, impulse control formulation.\n\/\/\n\/\/ Author: Parsiad Azimzadeh\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \n#include \n#include \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \/\/ max, min\n#include \/\/ cout\n#include \/\/ accumulate\n#include \/\/ get\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nusing namespace QuantPDE;\nusing namespace QuantPDE::Modules;\n\nusing namespace std;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass Withdrawal final : public ControlledLinearSystem2 {\n\n\tRectilinearGrid2 &grid;\n\tNoncontrollable2 contractRate, kappa;\n\n\tControllable2 control;\n\npublic:\n\n\ttemplate \n\tWithdrawal(G &grid, F1 &&contractRate, F2 &&kappa) noexcept :\n\t\tgrid(grid),\n\t\tcontractRate(contractRate),\n\t\tkappa(kappa),\n\t\tcontrol( Control2(grid) )\n\t{\n\t\tregisterControl( control );\n\t}\n\n\tvirtual Matrix A(Real t) {\n\t\tMatrix M(grid.size(), grid.size());\n\t\tM.reserve(IntegerVector::Constant(grid.size(), 4));\n\n\t\tIndex i = 0;\n\t\tfor(auto node : grid) {\n\t\t\tconst Real S = node[0]; \/\/ Investment\n\t\t\tconst Real W = node[1]; \/\/ Withdrawal\n\n\t\t\t\/\/ Contract rate of withdrawal\n\t\t\tconst Real Gdt = contractRate(t, S, W);\n\n\t\t\t\/\/ Control\n\t\t\tconst Real q = control(t, S, W);\n\n\t\t\t\/\/ Amount withdrawn, pre-penalty\n\t\t\t\/\/const Real lambdaW = q * W;\n\t\t\tReal lambdaW;\n\t\t\tif(Gdt <= W) {\n\t\t\t\tlambdaW = (q<=1.) ? (q*Gdt) :\n\t\t\t\t\t\t((q-1.)*(W - Gdt) + Gdt);\n\t\t\t} else {\n\t\t\t\tlambdaW = q\/2.*W;\n\t\t\t}\n\n\t\t\t\/\/ Interpolation data\n\t\t\tauto data = interpolationData<2>(\n\t\t\t\tgrid,\n\t\t\t\t{\n\t\t\t\t\tmax(S - lambdaW, 0.),\n\t\t\t\t\tW - lambdaW\n\t\t\t\t}\n\t\t\t);\n\n\t\t\tconst Index i0 = get<0>( data[0] );\n\t\t\tconst Index i1 = get<0>( data[1] );\n\t\t\tconst Real w0 = get<1>( data[0] );\n\t\t\tconst Real w1 = get<1>( data[1] );\n\n\t\t\tconst Index j = grid.index(i0, i1);\n\n\t\t\tM.insert(i, j ) = w0 * w1 ;\n\t\t\tM.insert(i, j + grid[0].size()) = w0 * (1-w1);\n\t\t\tM.insert(i, j + 1 ) = (1-w0) * w1 ;\n\t\t\tM.insert(i, j + 1 + grid[0].size()) = (1-w0) * (1-w1);\n\n\t\t\t++i;\n\t\t}\n\n\t\tM.makeCompressed();\n\t\treturn grid.identity() - M;\n\t}\n\n\tvirtual Vector b(Real t) {\n\t\tVector b( grid.vector() );\n\t\tfor(auto node : accessor(grid, b)) {\n\t\t\tconst Real S = (&node)[0]; \/\/ Investment\n\t\t\tconst Real W = (&node)[1]; \/\/ Withdrawal\n\n\t\t\t\/\/ You have no money :(\n\t\t\tif(W <= epsilon) {\n\t\t\t\t*node = 0.;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t\/\/ Contract rate of withdrawal\n\t\t\tconst Real Gdt = contractRate(t, S, W);\n\n\t\t\t\/\/ Control\n\t\t\tconst Real q = control(t, S, W);\n\n\t\t\t\/\/ Amount withdrawn, pre-penalty\n\t\t\t\/\/const Real lambdaW = q * W;\n\t\t\tReal lambdaW;\n\t\t\tif(Gdt <= W) {\n\t\t\t\tlambdaW = (q<=1.) ? (q*Gdt) : ((q-1.)*(W - Gdt) + Gdt);\n\t\t\t} else {\n\t\t\t\tlambdaW = q\/2.*W;\n\t\t\t}\n\n\t\t\t\/\/ Withdrawal at no penalty\n\t\t\tif(lambdaW < Gdt) {\n\t\t\t\t*node = lambdaW;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t\/\/ Withdrawal at a penalty\n\t\t\t*node = lambdaW - kappa(t, S, W) * (lambdaW - Gdt);\n\t\t}\n\n\t\treturn b;\n\t}\n\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint main() {\n\n\t\/\/ 2014-10-15: Tested without withdrawals; closed-form is\n\t\/\/ dm := (log(S0 \/ (1-kappa) * (r - alpha - 1\/2 * sigma * sigma) * T))\n\t\/\/ \/ (sigma * sqrt(T))\n\t\/\/ V = S0 * exp(-alpha T) * normcdf(dm + sigma * sqrt(T))\n\t\/\/ + W0 exp(-r * T) * (1 - kappa) * (1 - normcdf(dm))\n\n\tint n = 10; \/\/ Initial optimal control partition size\n\tint N = 32; \/\/ Initial number of timesteps\n\n\tReal T = 10.;\n\tReal r = .05;\n\tReal v = .2;\n\n\tReal alpha = 0.013886; \/\/ Hedging fee\n\n\tReal G = 10.; \/\/ Contract rate\n\tReal kappa = 0.1; \/\/ Penalty rate\n\n\tint refinement = 5;\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Solution grid\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\tRectilinearGrid2 grid(\n\t\tAxis {\n\t\t\t0., 5., 10., 15., 20., 25.,\n\t\t\t30., 35., 40., 45.,\n\t\t\t50., 55., 60., 65., 70., 72.5, 75., 77.5, 80., 82., 84.,\n\t\t\t86., 88., 90., 91., 92., 93., 94., 95.,\n\t\t\t96., 97., 98., 99., 100.,\n\t\t\t101., 102., 103., 104., 105., 106.,\n\t\t\t107., 108., 109., 110., 112., 114.,\n\t\t\t116., 118., 120., 123., 126.,\n\t\t\t130., 135., 140., 145., 150., 160., 175., 200., 225.,\n\t\t\t250., 300., 500., 750., 1000.\n\t\t},\n\t\tAxis::range(0., 2., 100.)\n\t);\n\n\tunsigned pow2l = 1; \/\/ 2^l\n\tfor(int l = 0; l < refinement; ++l) {\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ Control grid\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\t\/\/ Control partition 0 : 1\/n : 1 (MATLAB notation)\n\t\tRectilinearGrid1 controls( Axis::range(0., 1. \/ (n * pow2l), 2.) );\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ Iteration tree\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\tReverseConstantStepper stepper(\n\t\t\t0., \/\/ Initial time\n\t\t\tT, \/\/ Expiry time\n\t\t\tT \/ (N * pow2l) \/\/ Timestep size\n\t\t);\n\t\tToleranceIteration tolerance;\n\t\tstepper.setInnerIteration(tolerance);\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ Linear system tree\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\tBlackScholes<2, 0> bs(grid, r, v, alpha);\n\t\tReverseLinearBDFOne discretization(grid, bs);\n\t\tdiscretization.setIteration(stepper);\n\n\t\tWithdrawal impulse(grid, G * T \/ (N * pow2l), kappa);\n\t\tMinPolicyIteration2_1 policy(grid, controls, impulse);\n\n\t\tPenaltyMethod penalty(grid, discretization, policy);\n\n\t\t\/\/ TODO: It currently matters what order each linear system is\n\t\t\/\/ associated with an iteration; fix this.\n\n\t\tpenalty.setIteration(tolerance);\n\t\tpolicy.setIteration(tolerance);\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ Payoff\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\tFunction2 payoff = [=] (Real S, Real W) {\n\t\t\treturn max(S, (1 - kappa) * W);\n\t\t};\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ Running\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\tBiCGSTABSolver solver;\n\n\t\tauto V = stepper.solve(\n\t\t\tgrid, \/\/ Domain\n\t\t\tpayoff, \/\/ Initial condition\n\t\t\tpenalty, \/\/ Root of linear system tree\n\t\t\tsolver \/\/ Linear system solver\n\t\t);\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ Print solution\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\tRectilinearGrid2 printGrid(\n\t\t\tAxis::range(0., 25., 200.),\n\t\t\tAxis { 100. }\n\t\t);\n\t\tcout << accessor( printGrid, V ) << endl;\n\n\t\tauto its = tolerance.iterations();\n\t\tReal inner = accumulate(its.begin(), its.end(), 0.)\/its.size();\n\n\t\tcout << \"average number of inner iterations: \" << inner << endl;\n\n\t\tcout << endl;\n\n\t\tpow2l *= 2;\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ Refine Solution grid\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\tgrid.refine( RectilinearGrid2::NewTickBetweenEachPair() );\n\t}\n\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"\/*\r\n * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde\r\n * All rights reserved.\r\n *\r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions are met:\r\n * * Redistributions of source code must retain the above copyright\r\n * notice, this list of conditions and the following disclaimer.\r\n * * Redistributions in binary form must reproduce the above copyright\r\n * notice, this list of conditions and the following disclaimer in the\r\n * documentation and\/or other materials provided with the distribution.\r\n * * Neither the name of the nor the\r\n * names of its contributors may be used to endorse or promote products\r\n * derived from this software without specific prior written permission.\r\n *\r\n * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY\r\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\r\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\r\n * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY\r\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\r\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\r\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\r\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n *\/\r\n\r\n#include \"CppUTest\/TestHarness.h\"\r\n#include \"CppUTest\/SimpleString.h\"\r\n#include \"CppUTest\/Extensions\/SimpleStringFromStdInt.h\"\r\n#include \r\n\r\nTEST_GROUP(SimpleStringFromStdint)\r\n{\r\n};\r\n\r\nusing namespace std;\r\n\r\n\/\/uint64_t silently not supported in C++\r\nTEST(SimpleStringFromStdint, Uint64_t)\r\n{\r\n\/\/I'd like this test, but can't get it to pass\r\n\/\/ uint64_t = 0xffffffffffffffff;\r\n\/\/ \r\n\/\/ SimpleString result = StringFrom(i);\r\n\/\/ CHECK_EQUAL(\"18446744073709551615 (0xffffffffffffffff)\", result);\r\n\r\n uint64_t i = 10;\r\n SimpleString result = StringFrom(i);\r\n CHECK_EQUAL(\"uint64_t not supported\", result);\r\n \r\n}\r\n\r\nTEST(SimpleStringFromStdint, Int64_t)\r\n{\r\n\/\/I'd like this test, but can't get it to pass\r\n\/\/ int64_t i = 0xffffffffffffffff>>1;\r\n\/\/ \r\n\/\/ SimpleString result = StringFrom(i);\r\n\/\/ CHECK_EQUAL(\"something\", result);\r\n\r\n int64_t i = 10;\r\n SimpleString result = StringFrom(i);\r\n CHECK_EQUAL(\"int64_t not supported\", result);\r\n \r\n}\r\n\r\nTEST(SimpleStringFromStdint, Uint32_t)\r\n{\r\n uint32_t i = 0xffffffff;\r\n \r\n SimpleString result = StringFrom(i);\r\n CHECK_EQUAL(\"4294967295 (0xffffffff)\", result);\r\n}\r\n\r\nTEST(SimpleStringFromStdint, Uint16_t)\r\n{\r\n uint16_t i = 0xffff;\r\n \r\n SimpleString result = StringFrom(i);\r\n CHECK_EQUAL(\"65535 (0xffff)\", result);\r\n}\r\n\r\nTEST(SimpleStringFromStdint, Uint8_t)\r\n{\r\n uint8_t i = 0xff;\r\n \r\n SimpleString result = StringFrom(i);\r\n CHECK_EQUAL(\"255 (0xff)\", result);\r\n}\r\n\r\nIGNORE_TEST(SimpleStringFromStdint, CHECK_EQUAL_Uint64_t)\r\n{\r\n\/\/ uint64_t i = 0xffffffffffffffff;\r\n\/\/ CHECK_EQUAL(i, i);\r\n}\r\n\r\nTEST(SimpleStringFromStdint, CHECK_EQUAL_Uint32_t)\r\n{\r\n uint32_t i = 0xffffffff;\r\n CHECK_EQUAL(i, i);\r\n}\r\n\r\nTEST(SimpleStringFromStdint, CHECK_EQUAL_Uint16_t)\r\n{\r\n uint16_t i = 0xffff;\r\n CHECK_EQUAL(i, i);\r\n}\r\n\r\nTEST(SimpleStringFromStdint, CHECK_EQUAL_Uint8_t)\r\n{\r\n uint8_t i = 0xff;\r\n CHECK_EQUAL(i, i);\r\n}\r\n\r\nI -> i\/*\r\n * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde\r\n * All rights reserved.\r\n *\r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions are met:\r\n * * Redistributions of source code must retain the above copyright\r\n * notice, this list of conditions and the following disclaimer.\r\n * * Redistributions in binary form must reproduce the above copyright\r\n * notice, this list of conditions and the following disclaimer in the\r\n * documentation and\/or other materials provided with the distribution.\r\n * * Neither the name of the nor the\r\n * names of its contributors may be used to endorse or promote products\r\n * derived from this software without specific prior written permission.\r\n *\r\n * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY\r\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\r\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\r\n * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY\r\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\r\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\r\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\r\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n *\/\r\n\r\n#include \"CppUTest\/TestHarness.h\"\r\n#include \"CppUTest\/SimpleString.h\"\r\n#include \"CppUTest\/Extensions\/SimpleStringFromStdint.h\"\r\n#include \r\n\r\nTEST_GROUP(SimpleStringFromStdint)\r\n{\r\n};\r\n\r\nusing namespace std;\r\n\r\n\/\/uint64_t silently not supported in C++\r\nTEST(SimpleStringFromStdint, Uint64_t)\r\n{\r\n\/\/I'd like this test, but can't get it to pass\r\n\/\/ uint64_t = 0xffffffffffffffff;\r\n\/\/ \r\n\/\/ SimpleString result = StringFrom(i);\r\n\/\/ CHECK_EQUAL(\"18446744073709551615 (0xffffffffffffffff)\", result);\r\n\r\n uint64_t i = 10;\r\n SimpleString result = StringFrom(i);\r\n CHECK_EQUAL(\"uint64_t not supported\", result);\r\n \r\n}\r\n\r\nTEST(SimpleStringFromStdint, Int64_t)\r\n{\r\n\/\/I'd like this test, but can't get it to pass\r\n\/\/ int64_t i = 0xffffffffffffffff>>1;\r\n\/\/ \r\n\/\/ SimpleString result = StringFrom(i);\r\n\/\/ CHECK_EQUAL(\"something\", result);\r\n\r\n int64_t i = 10;\r\n SimpleString result = StringFrom(i);\r\n CHECK_EQUAL(\"int64_t not supported\", result);\r\n \r\n}\r\n\r\nTEST(SimpleStringFromStdint, Uint32_t)\r\n{\r\n uint32_t i = 0xffffffff;\r\n \r\n SimpleString result = StringFrom(i);\r\n CHECK_EQUAL(\"4294967295 (0xffffffff)\", result);\r\n}\r\n\r\nTEST(SimpleStringFromStdint, Uint16_t)\r\n{\r\n uint16_t i = 0xffff;\r\n \r\n SimpleString result = StringFrom(i);\r\n CHECK_EQUAL(\"65535 (0xffff)\", result);\r\n}\r\n\r\nTEST(SimpleStringFromStdint, Uint8_t)\r\n{\r\n uint8_t i = 0xff;\r\n \r\n SimpleString result = StringFrom(i);\r\n CHECK_EQUAL(\"255 (0xff)\", result);\r\n}\r\n\r\nIGNORE_TEST(SimpleStringFromStdint, CHECK_EQUAL_Uint64_t)\r\n{\r\n\/\/ uint64_t i = 0xffffffffffffffff;\r\n\/\/ CHECK_EQUAL(i, i);\r\n}\r\n\r\nTEST(SimpleStringFromStdint, CHECK_EQUAL_Uint32_t)\r\n{\r\n uint32_t i = 0xffffffff;\r\n CHECK_EQUAL(i, i);\r\n}\r\n\r\nTEST(SimpleStringFromStdint, CHECK_EQUAL_Uint16_t)\r\n{\r\n uint16_t i = 0xffff;\r\n CHECK_EQUAL(i, i);\r\n}\r\n\r\nTEST(SimpleStringFromStdint, CHECK_EQUAL_Uint8_t)\r\n{\r\n uint8_t i = 0xff;\r\n CHECK_EQUAL(i, i);\r\n}\r\n\r\n<|endoftext|>"} {"text":"\/* -*- Mode: C; indent-tabs-mode: s; c-basic-offset: 4; tab-width: 4 -*- *\/\n\/* vim:set et sw=4 ts=4 sts=4: *\/\n#include \"ut_wallpaperwidget.h\"\n#include \"wallpaperwidget.h\"\n#include \"wallpaperbusinesslogic.h\"\n#include \"wallpaperdescriptor.h\"\n#include \"wallpapercurrentdescriptor.h\"\n#include \"wallpapermodel.h\"\n\n#include \n\n\/\/#define DEBUG\n#include \"..\/..\/src\/debug.h\"\n\n\/******************************************************************************\n * SignalSink implementation. \n *\/\nSignalSink::SignalSink () :\n m_ChangeWidgetCame (false)\n{\n m_WidgetID = 0;\n}\n\nvoid\nSignalSink::changeWidget (\n\t\tint widgetId)\n{\n m_ChangeWidgetCame = true;\n m_WidgetID = widgetId;\n}\n\nvoid\nSignalSink::reset()\n{\n m_WallpaperImageEditRequestedCame = false;\n}\n\nvoid\nSignalSink::imageEditRequested()\n{\n SYS_DEBUG (\"\");\n m_WallpaperImageEditRequestedCame = true;\n}\n\/******************************************************************************\n * Ut_WallpaperWidget implementation. \n *\/\nvoid \nUt_WallpaperWidget::init()\n{\n}\n\nvoid \nUt_WallpaperWidget::cleanup()\n{\n}\n\n\nstatic int argc = 1;\nstatic char *app_name = (char*) \".\/Ut_WallpaperWidget\";\n\nvoid \nUt_WallpaperWidget::initTestCase()\n{\n bool connectSuccess;\n\n m_App = new MApplication (argc, &app_name);\n m_BusinessLogic = new WallpaperBusinessLogic;\n\n m_Widget = new WallpaperWidget (m_BusinessLogic);\n connectSuccess = connect (\n m_Widget, SIGNAL(changeWidget(int)),\n &m_Sink, SLOT(changeWidget(int)));\n QVERIFY(connectSuccess);\n\n connectSuccess = connect(\n m_BusinessLogic, SIGNAL(imageEditRequested()),\n &m_Sink, SLOT(imageEditRequested()));\n QVERIFY(connectSuccess);\n\n QTest::qWait (150);\n QVERIFY (m_Widget->m_ImageList);\n}\n\nvoid \nUt_WallpaperWidget::cleanupTestCase()\n{\n delete m_BusinessLogic;\n delete m_Widget;\n m_App->deleteLater ();\n}\n\n\/*!\n * Tests what happens when a decriptor is activated. The widget have to set the\n * edited image in the businesslogic and it has to send a signal to show that\n * the editor widget should be shown.\n * FIXME:\n * 1) maybe we could send a signal of the list, that way we could check the\n * connection also.\n * 2) Maybe we should not use the literal 1 here.\n *\/\nvoid \nUt_WallpaperWidget::testImageActivated ()\n{\n WallpaperDescriptor *curr = WallpaperCurrentDescriptor::instance ();\n\n m_Widget->slotImageActivated (curr);\n \/\/ The loading of the image is happening in a separate thread, we need to\n \/\/ give a chance to be executed.\n QTest::qWait (500);\n\n QVERIFY (m_Widget->m_WallpaperBusinessLogic->editedImage() == curr);\n QVERIFY (m_Sink.m_ChangeWidgetCame);\n QVERIFY (m_Sink.m_WidgetID == 1);\n}\n\nvoid\nUt_WallpaperWidget::testGalleryImageSelected()\n{\n m_Widget->galleryImageSelected(\"file:\/\/\/nodir\/NoSuchFile.png\");\n QVERIFY(m_Sink.m_WallpaperImageEditRequestedCame);\n}\n\nvoid\nUt_WallpaperWidget::testImageBrowserDismissed()\n{\n m_Widget->imageBrowserDismissed();\n QVERIFY (m_Widget->m_noImageBrowser);\n}\n\nQTEST_APPLESS_MAIN(Ut_WallpaperWidget)\n\nTrying to fix a test case.\/* -*- Mode: C; indent-tabs-mode: s; c-basic-offset: 4; tab-width: 4 -*- *\/\n\/* vim:set et sw=4 ts=4 sts=4: *\/\n#include \"ut_wallpaperwidget.h\"\n#include \"wallpaperwidget.h\"\n#include \"wallpaperbusinesslogic.h\"\n#include \"wallpaperdescriptor.h\"\n#include \"wallpapercurrentdescriptor.h\"\n#include \"wallpapermodel.h\"\n\n#include \n\n\/\/#define DEBUG\n#include \"..\/..\/src\/debug.h\"\n\n\/******************************************************************************\n * SignalSink implementation. \n *\/\nSignalSink::SignalSink () :\n m_ChangeWidgetCame (false)\n{\n m_WidgetID = 0;\n}\n\nvoid\nSignalSink::changeWidget (\n\t\tint widgetId)\n{\n m_ChangeWidgetCame = true;\n m_WidgetID = widgetId;\n}\n\nvoid\nSignalSink::reset()\n{\n m_WallpaperImageEditRequestedCame = false;\n}\n\nvoid\nSignalSink::imageEditRequested()\n{\n SYS_DEBUG (\"\");\n m_WallpaperImageEditRequestedCame = true;\n}\n\/******************************************************************************\n * Ut_WallpaperWidget implementation. \n *\/\nvoid \nUt_WallpaperWidget::init()\n{\n}\n\nvoid \nUt_WallpaperWidget::cleanup()\n{\n}\n\n\nstatic int argc = 1;\nstatic char *app_name = (char*) \".\/Ut_WallpaperWidget\";\n\nvoid \nUt_WallpaperWidget::initTestCase()\n{\n bool connectSuccess;\n\n m_App = new MApplication (argc, &app_name);\n m_BusinessLogic = new WallpaperBusinessLogic;\n\n m_Widget = new WallpaperWidget (m_BusinessLogic);\n connectSuccess = connect (\n m_Widget, SIGNAL(changeWidget(int)),\n &m_Sink, SLOT(changeWidget(int)));\n QVERIFY(connectSuccess);\n\n connectSuccess = connect(\n m_BusinessLogic, SIGNAL(imageEditRequested()),\n &m_Sink, SLOT(imageEditRequested()));\n QVERIFY(connectSuccess);\n\n QTest::qWait (150);\n QVERIFY (m_Widget->m_ImageList);\n}\n\nvoid \nUt_WallpaperWidget::cleanupTestCase()\n{\n delete m_BusinessLogic;\n delete m_Widget;\n m_App->deleteLater ();\n}\n\n\/*!\n * Tests what happens when a decriptor is activated. The widget have to set the\n * edited image in the businesslogic and it has to send a signal to show that\n * the editor widget should be shown.\n * FIXME:\n * 1) maybe we could send a signal of the list, that way we could check the\n * connection also.\n * 2) Maybe we should not use the literal 1 here.\n *\/\nvoid \nUt_WallpaperWidget::testImageActivated ()\n{\n WallpaperDescriptor *curr = WallpaperCurrentDescriptor::instance ();\n\n m_Widget->slotImageActivated (curr);\n \/\/ The loading of the image is happening in a separate thread, we need to\n \/\/ give a chance to be executed.\n QTest::qWait (500);\n\n QVERIFY (m_Widget->m_WallpaperBusinessLogic->editedImage() == curr);\n QVERIFY (m_Sink.m_ChangeWidgetCame);\n QVERIFY (m_Sink.m_WidgetID == 1);\n}\n\nvoid\nUt_WallpaperWidget::testGalleryImageSelected()\n{\n m_Widget->galleryImageSelected(\"file:\/\/\/nodir\/NoSuchFile.png\");\n \/\/ The loading of the image is happening in a separate thread, we need to\n \/\/ give a chance to be executed.\n QTest::qWait (500);\n QVERIFY(m_Sink.m_WallpaperImageEditRequestedCame);\n}\n\nvoid\nUt_WallpaperWidget::testImageBrowserDismissed()\n{\n m_Widget->imageBrowserDismissed();\n QVERIFY (m_Widget->m_noImageBrowser);\n}\n\nQTEST_APPLESS_MAIN(Ut_WallpaperWidget)\n\n<|endoftext|>"} {"text":"\/***********************************************************************\n filename: CEGUIAnimationInstance.cpp\n created: 7\/8\/2010\n author: Martin Preisler\n\n purpose: Implements the AnimationInstance class\n*************************************************************************\/\n\/***************************************************************************\n * Copyright (C) 2004 - 2010 Paul D Turner & The CEGUI Development Team\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n ***************************************************************************\/\n#include \"CEGUIAnimationInstance.h\"\n#include \"CEGUIAnimation.h\"\n#include \"CEGUIExceptions.h\"\n#include \"CEGUIWindow.h\"\n#include \"CEGUIAffector.h\"\n\n\/\/ Start of CEGUI namespace section\nnamespace CEGUI\n{\n\n\/\/----------------------------------------------------------------------------\/\/\nconst String AnimationInstance::EventNamespace(\"AnimationInstance\");\n\nconst String AnimationInstance::EventAnimationStarted(\"AnimationStarted\");\nconst String AnimationInstance::EventAnimationStopped(\"AnimationStopped\");\nconst String AnimationInstance::EventAnimationPaused(\"AnimationPaused\");\nconst String AnimationInstance::EventAnimationUnpaused(\"AnimationUnpaused\");\nconst String AnimationInstance::EventAnimationEnded(\"AnimationEnded\");\nconst String AnimationInstance::EventAnimationLooped(\"AnimationLooped\");\n\n\/\/----------------------------------------------------------------------------\/\/\nAnimationInstance::AnimationInstance(Animation* definition):\n d_definition(definition),\n\n d_target(0),\n d_eventReceiver(0),\n d_eventSender(0),\n\n d_position(0.0),\n d_speed(1.0),\n d_bounceBackwards(false),\n d_running(false),\n d_skipNextStep(false),\n \/\/ default behaviour is to never skip\n d_maxStepDeltaSkip(-1.0f),\n \/\/ default behaviour is to never clamp\n d_maxStepDeltaClamp(-1.0f)\n{}\n\n\/\/----------------------------------------------------------------------------\/\/\nAnimationInstance::~AnimationInstance(void)\n{\n if (d_eventSender)\n {\n d_definition->autoUnsubscribe(this);\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nAnimation* AnimationInstance::getDefinition() const\n{\n return d_definition;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::setTarget(PropertySet* target)\n{\n d_target = target;\n\n purgeSavedPropertyValues();\n\n if (d_definition->getAutoStart() && !isRunning())\n {\n start();\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nPropertySet* AnimationInstance::getTarget() const\n{\n return d_target;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::setEventReceiver(EventSet* receiver)\n{\n d_eventReceiver = receiver;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nEventSet* AnimationInstance::getEventReceiver() const\n{\n return d_eventReceiver;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::setEventSender(EventSet* sender)\n{\n if (d_eventSender)\n {\n d_definition->autoUnsubscribe(this);\n }\n\n d_eventSender = sender;\n\n if (d_eventSender)\n {\n d_definition->autoSubscribe(this);\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nEventSet* AnimationInstance::getEventSender() const\n{\n return d_eventSender;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::setTargetWindow(Window* target)\n{\n setTarget(target);\n setEventReceiver(target);\n setEventSender(target);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::setPosition(float position)\n{\n if (position < 0.0 || position > d_definition->getDuration())\n {\n CEGUI_THROW(InvalidRequestException(\n \"AnimationInstance::setPosition: Unable to set position \"\n \"of this animation instace because given position isn't \"\n \"in interval [0.0, duration of animation].\"));\n }\n\n d_position = position;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nfloat AnimationInstance::getPosition() const\n{\n return d_position;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::setSpeed(float speed)\n{\n \/\/ first sort out the adventurous users\n if (speed < 0.0f)\n {\n CEGUI_THROW(InvalidRequestException(\n \"AnimationInstance::setSpeed: You can't set playback speed \"\n \"to a value that's lower than 0.0\"));\n }\n\n if (speed == 0.0f)\n {\n CEGUI_THROW(InvalidRequestException(\n \"AnimationInstance::setSpeed: You can't set playback speed \"\n \"to zero, please use AnimationInstance::pause instead\"));\n }\n\n d_speed = speed;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nfloat AnimationInstance::getSpeed() const\n{\n return d_speed;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::setSkipNextStep(bool skip)\n{\n d_skipNextStep = skip;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nbool AnimationInstance::getSkipNextStep() const\n{\n return d_skipNextStep;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::setMaxStepDeltaSkip(float maxDelta)\n{\n d_maxStepDeltaSkip = maxDelta;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nfloat AnimationInstance::getMaxStepDeltaSkip() const\n{\n return d_maxStepDeltaSkip;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::setMaxStepDeltaClamp(float maxDelta)\n{\n d_maxStepDeltaClamp = maxDelta;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nfloat AnimationInstance::getMaxStepDeltaClamp() const\n{\n return d_maxStepDeltaClamp;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::start(bool skipNextStep)\n{\n setPosition(0.0);\n d_running = true;\n d_skipNextStep = skipNextStep;\n onAnimationStarted();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::stop()\n{\n setPosition(0.0);\n d_running = false;\n onAnimationStopped();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::pause()\n{\n d_running = false;\n onAnimationPaused();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::unpause(bool skipNextStep)\n{\n d_running = true;\n d_skipNextStep = skipNextStep;\n onAnimationUnpaused();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::togglePause(bool skipNextStep)\n{\n if (isRunning())\n {\n pause();\n }\n else\n {\n unpause(skipNextStep);\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nbool AnimationInstance::isRunning() const\n{\n return d_running;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::step(float delta)\n{\n if (!d_running)\n {\n \/\/ nothing to do if this animation instance isn't running\n return;\n }\n\n if (delta < 0.0f)\n {\n CEGUI_THROW(InvalidRequestException(\n \"AnimationInstance::step: You can't step the Animation Instance \"\n \"with negative delta! You can't reverse the flow of time, stop \"\n \"trying!\"));\n }\n\n \/\/ first we deal with delta size\n if (d_maxStepDeltaSkip > 0.0f && delta > d_maxStepDeltaSkip)\n {\n \/\/ skip the step entirely if delta gets over the threshold\n \/\/ note that default value is 0.0f which means this never gets triggered\n delta = 0.0f;\n }\n\n if (d_maxStepDeltaClamp > 0.0f)\n {\n \/\/ clamp to threshold, note that default value is -1.0f which means\n \/\/ this line does nothing (delta should always be larger or equal than 0.0f\n delta = std::min(delta, d_maxStepDeltaClamp);\n }\n\n \/\/ if asked to do so, we skip this step, but mark that the next one\n \/\/ shouldn't be skipped\n \/\/ NB: This gets rid of annoying animation skips when FPS gets too low\n \/\/ after complex layout loading, etc...\n if (d_skipNextStep)\n {\n d_skipNextStep = false;\n \/\/ we skip the step by setting delta to 0, this doesn't step the time\n \/\/ but still sets the animation position accordingly\n delta = 0.0f;\n }\n\n const float duration = d_definition->getDuration();\n\n \/\/ we modify the delta according to playback speed\n delta *= d_speed;\n\n \/\/ the position could have gotten out of the desired range, we have to\n \/\/ alter it depending on replay method of our animation definition\n\n \/\/ first a simple clamp with RM_Once\n if (d_definition->getReplayMode() == Animation::RM_Once)\n {\n float newPosition = d_position + delta;\n\n newPosition = std::max(0.0f, newPosition);\n\n if (newPosition >= duration)\n {\n newPosition = duration;\n\n stop();\n onAnimationEnded();\n }\n\n setPosition(newPosition);\n }\n \/\/ a both sided wrap with RM_Loop\n else if (d_definition->getReplayMode() == Animation::RM_Loop)\n {\n float newPosition = d_position + delta;\n\n while (newPosition > duration)\n {\n newPosition -= duration;\n onAnimationLooped();\n }\n\n setPosition(newPosition);\n }\n \/\/ bounce back and forth with RM_Bounce\n else if (d_definition->getReplayMode() == Animation::RM_Bounce)\n {\n if (d_bounceBackwards)\n {\n delta = -delta;\n }\n\n float newPosition = d_position + delta;\n\n while (newPosition <= 0 || newPosition > duration)\n {\n if (newPosition <= 0)\n {\n d_bounceBackwards = false;\n\n newPosition = -newPosition;\n onAnimationLooped();\n }\n\n if (newPosition > duration)\n {\n d_bounceBackwards = true;\n\n newPosition = 2.0f * duration - newPosition;\n onAnimationLooped();\n }\n }\n\n setPosition(newPosition);\n }\n\n apply();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nbool AnimationInstance::handleStart(const CEGUI::EventArgs& e)\n{\n start();\n\n return true;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nbool AnimationInstance::handleStop(const CEGUI::EventArgs& e)\n{\n stop();\n\n return true;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nbool AnimationInstance::handlePause(const CEGUI::EventArgs& e)\n{\n pause();\n\n return true;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nbool AnimationInstance::handleUnpause(const CEGUI::EventArgs& e)\n{\n unpause();\n\n return true;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nbool AnimationInstance::handleTogglePause(const CEGUI::EventArgs& e)\n{\n togglePause();\n\n return true;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::savePropertyValue(const String& propertyName)\n{\n assert(d_target);\n\n d_savedPropertyValues[propertyName] = d_target->getProperty(propertyName);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::purgeSavedPropertyValues(void)\n{\n d_savedPropertyValues.clear();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nconst String& AnimationInstance::getSavedPropertyValue(const String& propertyName)\n{\n PropertyValueMap::iterator it = d_savedPropertyValues.find(propertyName);\n\n if (it == d_savedPropertyValues.end())\n {\n \/\/ even though we explicitly save all used property values when\n \/\/ starting the animation, this can happen when user changes\n \/\/ animation definition whilst the animation is running\n \/\/ (Yes, it's nasty, but people do nasty things)\n savePropertyValue(propertyName);\n return getSavedPropertyValue(propertyName);\n }\n\n return it->second;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::addAutoConnection(Event::Connection conn)\n{\n d_autoConnections.push_back(conn);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::unsubscribeAutoConnections()\n{\n for (ConnectionTracker::iterator it = d_autoConnections.begin();\n it != d_autoConnections.end(); ++it)\n {\n (*it)->disconnect();\n }\n\n d_autoConnections.clear();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::apply()\n{\n if (d_target)\n {\n d_definition->apply(this);\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::onAnimationStarted()\n{\n purgeSavedPropertyValues();\n d_definition->savePropertyValues(this);\n\n if (d_eventReceiver)\n {\n AnimationEventArgs args(this);\n d_eventReceiver->fireEvent(EventAnimationStarted, args, EventNamespace);\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::onAnimationStopped()\n{\n if (d_eventReceiver)\n {\n AnimationEventArgs args(this);\n d_eventReceiver->fireEvent(EventAnimationStopped, args, EventNamespace);\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::onAnimationPaused()\n{\n if (d_eventReceiver)\n {\n AnimationEventArgs args(this);\n d_eventReceiver->fireEvent(EventAnimationPaused, args, EventNamespace);\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::onAnimationUnpaused()\n{\n if (d_eventReceiver)\n {\n AnimationEventArgs args(this);\n d_eventReceiver->fireEvent(EventAnimationUnpaused, args, EventNamespace);\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::onAnimationEnded()\n{\n if (d_eventReceiver)\n {\n AnimationEventArgs args(this);\n d_eventReceiver->fireEvent(EventAnimationEnded, args, EventNamespace);\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::onAnimationLooped()\n{\n if (d_eventReceiver)\n {\n AnimationEventArgs args(this);\n d_eventReceiver->fireEvent(EventAnimationLooped, args, EventNamespace);\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\n\n} \/\/ End of CEGUI namespace section\n\nDo not start or unpause an animation with no definition or 0 duration\/***********************************************************************\n filename: CEGUIAnimationInstance.cpp\n created: 7\/8\/2010\n author: Martin Preisler\n\n purpose: Implements the AnimationInstance class\n*************************************************************************\/\n\/***************************************************************************\n * Copyright (C) 2004 - 2010 Paul D Turner & The CEGUI Development Team\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n ***************************************************************************\/\n#include \"CEGUIAnimationInstance.h\"\n#include \"CEGUIAnimation.h\"\n#include \"CEGUIExceptions.h\"\n#include \"CEGUIWindow.h\"\n#include \"CEGUIAffector.h\"\n#include \"CEGUILogger.h\"\n\n\/\/ Start of CEGUI namespace section\nnamespace CEGUI\n{\n\n\/\/----------------------------------------------------------------------------\/\/\nconst String AnimationInstance::EventNamespace(\"AnimationInstance\");\n\nconst String AnimationInstance::EventAnimationStarted(\"AnimationStarted\");\nconst String AnimationInstance::EventAnimationStopped(\"AnimationStopped\");\nconst String AnimationInstance::EventAnimationPaused(\"AnimationPaused\");\nconst String AnimationInstance::EventAnimationUnpaused(\"AnimationUnpaused\");\nconst String AnimationInstance::EventAnimationEnded(\"AnimationEnded\");\nconst String AnimationInstance::EventAnimationLooped(\"AnimationLooped\");\n\n\/\/----------------------------------------------------------------------------\/\/\nAnimationInstance::AnimationInstance(Animation* definition):\n d_definition(definition),\n\n d_target(0),\n d_eventReceiver(0),\n d_eventSender(0),\n\n d_position(0.0),\n d_speed(1.0),\n d_bounceBackwards(false),\n d_running(false),\n d_skipNextStep(false),\n \/\/ default behaviour is to never skip\n d_maxStepDeltaSkip(-1.0f),\n \/\/ default behaviour is to never clamp\n d_maxStepDeltaClamp(-1.0f)\n{}\n\n\/\/----------------------------------------------------------------------------\/\/\nAnimationInstance::~AnimationInstance(void)\n{\n if (d_eventSender)\n {\n d_definition->autoUnsubscribe(this);\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nAnimation* AnimationInstance::getDefinition() const\n{\n return d_definition;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::setTarget(PropertySet* target)\n{\n d_target = target;\n\n purgeSavedPropertyValues();\n\n if (d_definition->getAutoStart() && !isRunning())\n {\n start();\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nPropertySet* AnimationInstance::getTarget() const\n{\n return d_target;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::setEventReceiver(EventSet* receiver)\n{\n d_eventReceiver = receiver;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nEventSet* AnimationInstance::getEventReceiver() const\n{\n return d_eventReceiver;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::setEventSender(EventSet* sender)\n{\n if (d_eventSender)\n {\n d_definition->autoUnsubscribe(this);\n }\n\n d_eventSender = sender;\n\n if (d_eventSender)\n {\n d_definition->autoSubscribe(this);\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nEventSet* AnimationInstance::getEventSender() const\n{\n return d_eventSender;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::setTargetWindow(Window* target)\n{\n setTarget(target);\n setEventReceiver(target);\n setEventSender(target);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::setPosition(float position)\n{\n if (position < 0.0 || position > d_definition->getDuration())\n {\n CEGUI_THROW(InvalidRequestException(\n \"AnimationInstance::setPosition: Unable to set position \"\n \"of this animation instace because given position isn't \"\n \"in interval [0.0, duration of animation].\"));\n }\n\n d_position = position;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nfloat AnimationInstance::getPosition() const\n{\n return d_position;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::setSpeed(float speed)\n{\n \/\/ first sort out the adventurous users\n if (speed < 0.0f)\n {\n CEGUI_THROW(InvalidRequestException(\n \"AnimationInstance::setSpeed: You can't set playback speed \"\n \"to a value that's lower than 0.0\"));\n }\n\n if (speed == 0.0f)\n {\n CEGUI_THROW(InvalidRequestException(\n \"AnimationInstance::setSpeed: You can't set playback speed \"\n \"to zero, please use AnimationInstance::pause instead\"));\n }\n\n d_speed = speed;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nfloat AnimationInstance::getSpeed() const\n{\n return d_speed;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::setSkipNextStep(bool skip)\n{\n d_skipNextStep = skip;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nbool AnimationInstance::getSkipNextStep() const\n{\n return d_skipNextStep;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::setMaxStepDeltaSkip(float maxDelta)\n{\n d_maxStepDeltaSkip = maxDelta;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nfloat AnimationInstance::getMaxStepDeltaSkip() const\n{\n return d_maxStepDeltaSkip;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::setMaxStepDeltaClamp(float maxDelta)\n{\n d_maxStepDeltaClamp = maxDelta;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nfloat AnimationInstance::getMaxStepDeltaClamp() const\n{\n return d_maxStepDeltaClamp;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::start(bool skipNextStep)\n{\n setPosition(0.0);\n d_skipNextStep = skipNextStep;\n\n if (d_definition && d_definition->getDuration() > 0)\n {\n d_running = true;\n onAnimationStarted();\n }\n else\n {\n Logger::getSingleton().logEvent(\n \"AnimationInstance::start - Starting an animation instance with \"\n \"no animation definition or 0 duration has no effect!\", Warnings);\n onAnimationStarted();\n onAnimationEnded();\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::stop()\n{\n setPosition(0.0);\n d_running = false;\n onAnimationStopped();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::pause()\n{\n d_running = false;\n onAnimationPaused();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::unpause(bool skipNextStep)\n{\n d_skipNextStep = skipNextStep;\n\n if (d_definition && d_definition->getDuration() > 0)\n {\n d_running = true;\n onAnimationUnpaused();\n }\n else\n {\n Logger::getSingleton().logEvent(\n \"AnimationInstance::unpause - Unpausing an animation instance with \"\n \"no animation definition or 0 duration has no effect!\", Warnings);\n onAnimationUnpaused();\n onAnimationEnded();\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::togglePause(bool skipNextStep)\n{\n if (isRunning())\n {\n pause();\n }\n else\n {\n unpause(skipNextStep);\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nbool AnimationInstance::isRunning() const\n{\n return d_running;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::step(float delta)\n{\n if (!d_running)\n {\n \/\/ nothing to do if this animation instance isn't running\n return;\n }\n\n if (delta < 0.0f)\n {\n CEGUI_THROW(InvalidRequestException(\n \"AnimationInstance::step: You can't step the Animation Instance \"\n \"with negative delta! You can't reverse the flow of time, stop \"\n \"trying!\"));\n }\n\n \/\/ first we deal with delta size\n if (d_maxStepDeltaSkip > 0.0f && delta > d_maxStepDeltaSkip)\n {\n \/\/ skip the step entirely if delta gets over the threshold\n \/\/ note that default value is 0.0f which means this never gets triggered\n delta = 0.0f;\n }\n\n if (d_maxStepDeltaClamp > 0.0f)\n {\n \/\/ clamp to threshold, note that default value is -1.0f which means\n \/\/ this line does nothing (delta should always be larger or equal than 0.0f\n delta = std::min(delta, d_maxStepDeltaClamp);\n }\n\n \/\/ if asked to do so, we skip this step, but mark that the next one\n \/\/ shouldn't be skipped\n \/\/ NB: This gets rid of annoying animation skips when FPS gets too low\n \/\/ after complex layout loading, etc...\n if (d_skipNextStep)\n {\n d_skipNextStep = false;\n \/\/ we skip the step by setting delta to 0, this doesn't step the time\n \/\/ but still sets the animation position accordingly\n delta = 0.0f;\n }\n\n const float duration = d_definition->getDuration();\n\n \/\/ we modify the delta according to playback speed\n delta *= d_speed;\n\n \/\/ the position could have gotten out of the desired range, we have to\n \/\/ alter it depending on replay method of our animation definition\n\n \/\/ first a simple clamp with RM_Once\n if (d_definition->getReplayMode() == Animation::RM_Once)\n {\n float newPosition = d_position + delta;\n\n newPosition = std::max(0.0f, newPosition);\n\n if (newPosition >= duration)\n {\n newPosition = duration;\n\n stop();\n onAnimationEnded();\n }\n\n setPosition(newPosition);\n }\n \/\/ a both sided wrap with RM_Loop\n else if (d_definition->getReplayMode() == Animation::RM_Loop)\n {\n float newPosition = d_position + delta;\n\n while (newPosition > duration)\n {\n newPosition -= duration;\n onAnimationLooped();\n }\n\n setPosition(newPosition);\n }\n \/\/ bounce back and forth with RM_Bounce\n else if (d_definition->getReplayMode() == Animation::RM_Bounce)\n {\n if (d_bounceBackwards)\n {\n delta = -delta;\n }\n\n float newPosition = d_position + delta;\n\n while (newPosition <= 0 || newPosition > duration)\n {\n if (newPosition <= 0)\n {\n d_bounceBackwards = false;\n\n newPosition = -newPosition;\n onAnimationLooped();\n }\n\n if (newPosition > duration)\n {\n d_bounceBackwards = true;\n\n newPosition = 2.0f * duration - newPosition;\n onAnimationLooped();\n }\n }\n\n setPosition(newPosition);\n }\n\n apply();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nbool AnimationInstance::handleStart(const CEGUI::EventArgs& e)\n{\n start();\n\n return true;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nbool AnimationInstance::handleStop(const CEGUI::EventArgs& e)\n{\n stop();\n\n return true;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nbool AnimationInstance::handlePause(const CEGUI::EventArgs& e)\n{\n pause();\n\n return true;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nbool AnimationInstance::handleUnpause(const CEGUI::EventArgs& e)\n{\n unpause();\n\n return true;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nbool AnimationInstance::handleTogglePause(const CEGUI::EventArgs& e)\n{\n togglePause();\n\n return true;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::savePropertyValue(const String& propertyName)\n{\n assert(d_target);\n\n d_savedPropertyValues[propertyName] = d_target->getProperty(propertyName);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::purgeSavedPropertyValues(void)\n{\n d_savedPropertyValues.clear();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nconst String& AnimationInstance::getSavedPropertyValue(const String& propertyName)\n{\n PropertyValueMap::iterator it = d_savedPropertyValues.find(propertyName);\n\n if (it == d_savedPropertyValues.end())\n {\n \/\/ even though we explicitly save all used property values when\n \/\/ starting the animation, this can happen when user changes\n \/\/ animation definition whilst the animation is running\n \/\/ (Yes, it's nasty, but people do nasty things)\n savePropertyValue(propertyName);\n return getSavedPropertyValue(propertyName);\n }\n\n return it->second;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::addAutoConnection(Event::Connection conn)\n{\n d_autoConnections.push_back(conn);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::unsubscribeAutoConnections()\n{\n for (ConnectionTracker::iterator it = d_autoConnections.begin();\n it != d_autoConnections.end(); ++it)\n {\n (*it)->disconnect();\n }\n\n d_autoConnections.clear();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::apply()\n{\n if (d_target)\n {\n d_definition->apply(this);\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::onAnimationStarted()\n{\n purgeSavedPropertyValues();\n d_definition->savePropertyValues(this);\n\n if (d_eventReceiver)\n {\n AnimationEventArgs args(this);\n d_eventReceiver->fireEvent(EventAnimationStarted, args, EventNamespace);\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::onAnimationStopped()\n{\n if (d_eventReceiver)\n {\n AnimationEventArgs args(this);\n d_eventReceiver->fireEvent(EventAnimationStopped, args, EventNamespace);\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::onAnimationPaused()\n{\n if (d_eventReceiver)\n {\n AnimationEventArgs args(this);\n d_eventReceiver->fireEvent(EventAnimationPaused, args, EventNamespace);\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::onAnimationUnpaused()\n{\n if (d_eventReceiver)\n {\n AnimationEventArgs args(this);\n d_eventReceiver->fireEvent(EventAnimationUnpaused, args, EventNamespace);\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::onAnimationEnded()\n{\n if (d_eventReceiver)\n {\n AnimationEventArgs args(this);\n d_eventReceiver->fireEvent(EventAnimationEnded, args, EventNamespace);\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid AnimationInstance::onAnimationLooped()\n{\n if (d_eventReceiver)\n {\n AnimationEventArgs args(this);\n d_eventReceiver->fireEvent(EventAnimationLooped, args, EventNamespace);\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\n\n} \/\/ End of CEGUI namespace section\n\n<|endoftext|>"} {"text":"#include \"medida\/reporting\/udp_reporter.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \"util.h\"\n#include \n#include \n\nextern \"C\" {\n#include \n#include \n#include \n#include \n#include \n#include \n}\n\n\nnamespace medida {\n namespace reporting {\n class UdpSender {\/\/_NOT_ thread safe\n\n std::string host_;\n std::uint16_t port_;\n std::uint32_t reconnect_after_;\n std::uint64_t messages_sent_;\n bool connected_;\n\n std::vector connections_;\n\n void disconnect() {\n assert(connected_);\n connected_ = false;\n\n for (int conn : connections_) {\n close(conn);\n }\n connections_.clear();\n }\n\n void reconnect() {\n assert(! connected_);\n\n char buff[256];\n struct addrinfo hints, *res = NULL, *r;\n memset(&hints, 0, sizeof(hints));\n hints.ai_family = AF_INET;\n hints.ai_socktype = SOCK_DGRAM;\n auto port_str = std::to_string(port_);\n int ret = getaddrinfo(host_.c_str(), port_str.c_str(), &hints, &res);\n if (ret != 0) {\n std::cerr << \"Couldn't get addrinfo: \" << strerror_r(ret, buff, sizeof(buff)) << \"\\n\";\n return;\n }\n\n for (r = res; r != NULL; r = r->ai_next) {\n int sock = socket(r->ai_family, r->ai_socktype, r->ai_protocol);\n if (sock < 0) {\n std::cerr << \"Couldn't create socket: \" << strerror_r(errno, buff, sizeof(buff)) << \"\\n\";\n continue;\n }\n\n if (connect(sock, r->ai_addr, r->ai_addrlen) < 0) {\n std::cerr << \"Failed to connect socket: \" << sock << \" error: \" << strerror_r(errno, buff, sizeof(buff)) << \"\\n\";\n close(sock);\n continue;\n }\n\n connections_.push_back(sock);\n }\n\n freeaddrinfo(res);\n\n connected_ = true;\n }\n\n void do_send(const char* msg, int len) {\n if (! connected_) return;\n for (auto conn : connections_) {\n auto sent = ::send(conn, msg, len, 0);\n if (sent < 0) {\n std::cerr << \"Failed to report metric (errno: \" << errno << \", fd: \" << conn << \")\\n\";\n }\n assert(sent == len);\n }\n }\n\n public:\n UdpSender(const std::string& host, std::uint16_t port, std::uint32_t reconnect_after) :\n host_(host), port_(port), reconnect_after_(reconnect_after), messages_sent_(0), connected_(false) { }\n\n ~UdpSender() { if (connected_) disconnect(); }\n\n void send(std::string&& msg) {\n if (connected_ && ((messages_sent_++ % reconnect_after_) == 0)) {\n disconnect();\n }\n if (! connected_) reconnect();\n do_send(msg.c_str(), msg.length());\n }\n };\n\n class UdpReporter::Impl : public MetricProcessor {\n\n public:\n Impl(MetricsRegistry ®istry, Formatter& formatter, std::uint16_t port, const std::string& hostname, std::uint32_t reconnect_after);\n\n ~Impl();\n\n void run();\n\n using MetricProcessor::process;\n\n void process(Counter& counter);\n\n void process(Meter& meter);\n\n void process(Histogram& histogram);\n\n void process(Timer& timer);\n\n template void send(Args... args);\n\n private:\n medida::MetricsRegistry& registry_;\n\n Formatter& format_;\n\n UdpSender sender_;\n };\n\n\n UdpReporter::UdpReporter(MetricsRegistry ®istry, Formatter& formatter, std::uint16_t port, const std::string& hostname, std::uint32_t reconnect_after)\n : AbstractPollingReporter(),\n impl_ {new UdpReporter::Impl {registry, formatter, port, hostname, reconnect_after}} { }\n\n\n UdpReporter::~UdpReporter() { }\n\n\n void UdpReporter::run() {\n impl_->run();\n }\n\n\n\/\/ === Implementation ===\n\n\n UdpReporter::Impl::Impl(MetricsRegistry ®istry, Formatter& formatter, std::uint16_t port, const std::string& hostname, std::uint32_t reconnect_after)\n :registry_ (registry), format_ (formatter), sender_(hostname, port, reconnect_after) { }\n\n\n UdpReporter::Impl::~Impl() { }\n\n\n void UdpReporter::Impl::run() {\n for (auto& kv : registry_.get_all_metrics()) {\n auto name = kv.first;\n auto metric = kv.second;\n format_.set_name(name.to_string());\n metric->process(*this);\n }\n }\n\n\n template void UdpReporter::Impl::send(Args... args) {\n sender_.send(format_(args...));\n }\n\n\n void UdpReporter::Impl::process(Counter& counter) {\n send(\"counter\", \"count\", counter.count());\n }\n\n\n void UdpReporter::Impl::process(Meter& meter) {\n auto event_type = meter.event_type();\n auto unit = format_rate_unit(meter.rate_unit());\n send(\"meter\", \"count\", meter.count());\n send(\"meter\", event_type, \"mean_rate\", meter.mean_rate(), unit);\n send(\"meter\", event_type, \"1min_rate\", meter.one_minute_rate(), unit);\n send(\"meter\", event_type, \"5min_rate\", meter.five_minute_rate(), unit);\n send(\"meter\", event_type, \"15min_rate\", meter.fifteen_minute_rate(), unit);\n }\n\n\n void UdpReporter::Impl::process(Histogram& histogram) {\n auto snapshot = histogram.snapshot();\n send(\"histogram\", \"min\", histogram.min());\n send(\"histogram\", \"max\", histogram.max());\n send(\"histogram\", \"mean\", histogram.mean());\n send(\"histogram\", \"std_dev\", histogram.std_dev());\n send(\"histogram\", \"median\", snapshot.median());\n send(\"histogram\", \"75pct\", snapshot.percentile_75());\n send(\"histogram\", \"95pct\", snapshot.percentile_95());\n send(\"histogram\", \"98pct\", snapshot.percentile_98());\n send(\"histogram\", \"99pct\", snapshot.percentile_99());\n send(\"histogram\", \"999pct\", snapshot.percentile_999());\n }\n\n\n void UdpReporter::Impl::process(Timer& timer) {\n auto snapshot = timer.snapshot();\n auto event_type = timer.event_type();\n auto rate_unit = format_rate_unit(timer.rate_unit());\n auto duration_unit = format_rate_unit(timer.duration_unit());\n\n send(\"timer\", \"count\", timer.count());\n send(\"timer\", event_type, \"mean_rate\", timer.mean_rate(), rate_unit);\n send(\"timer\", event_type, \"1min_rate\", timer.one_minute_rate(), rate_unit);\n send(\"timer\", event_type, \"5min_rate\", timer.five_minute_rate(), rate_unit);\n send(\"timer\", event_type, \"15min_rate\", timer.fifteen_minute_rate(), rate_unit);\n send(\"timer\", \"min\", timer.min(), duration_unit);\n send(\"timer\", \"max\", timer.max(), duration_unit);\n send(\"timer\", \"mean\", timer.mean(), duration_unit);\n send(\"timer\", \"std_dev\", timer.std_dev(), duration_unit);\n send(\"timer\", \"median\", snapshot.median(), duration_unit);\n send(\"timer\", \"75pct\", snapshot.percentile_75(), duration_unit);\n send(\"timer\", \"95pct\", snapshot.percentile_95(), duration_unit);\n send(\"timer\", \"98pct\", snapshot.percentile_98(), duration_unit);\n send(\"timer\", \"99pct\", snapshot.percentile_99(), duration_unit);\n send(\"timer\", \"999pct\", snapshot.percentile_999(), duration_unit);\n }\n }\n}\nReport errors on udp-send failing#include \"medida\/reporting\/udp_reporter.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \"util.h\"\n#include \n#include \n\nextern \"C\" {\n#include \n#include \n#include \n#include \n#include \n#include \n}\n\n\nnamespace medida {\n namespace reporting {\n class UdpSender {\/\/_NOT_ thread safe\n\n std::string host_;\n std::uint16_t port_;\n std::uint32_t reconnect_after_;\n std::uint64_t messages_sent_;\n bool connected_;\n\n std::vector connections_;\n\n char buff[256];\n\n const char* err_str(int err_code) {\n return strerror_r(err_code, buff, sizeof(buff));\n }\n\n void disconnect() {\n assert(connected_);\n connected_ = false;\n\n for (int conn : connections_) {\n close(conn);\n }\n connections_.clear();\n }\n\n void reconnect() {\n assert(! connected_);\n\n struct addrinfo hints, *res = NULL, *r;\n memset(&hints, 0, sizeof(hints));\n hints.ai_family = AF_INET;\n hints.ai_socktype = SOCK_DGRAM;\n auto port_str = std::to_string(port_);\n int ret = getaddrinfo(host_.c_str(), port_str.c_str(), &hints, &res);\n if (ret != 0) {\n std::cerr << \"Couldn't get addrinfo: \" << err_str(ret) << \"\\n\";\n return;\n }\n\n for (r = res; r != NULL; r = r->ai_next) {\n int sock = socket(r->ai_family, r->ai_socktype, r->ai_protocol);\n if (sock < 0) {\n int err = errno;\n std::cerr << \"Couldn't create socket: \" << err_str(err) << \"\\n\";\n continue;\n }\n\n if (connect(sock, r->ai_addr, r->ai_addrlen) < 0) {\n int err = errno;\n std::cerr << \"Failed to connect socket: \" << sock << \" error: \" << err_str(err) << \"\\n\";\n close(sock);\n continue;\n }\n\n connections_.push_back(sock);\n }\n\n freeaddrinfo(res);\n\n connected_ = true;\n }\n\n void do_send(const char* msg, int len) {\n if (! connected_) return;\n for (auto conn : connections_) {\n auto sent = ::send(conn, msg, len, 0);\n if (sent < 0) {\n int err = errno;\n std::cerr << \"Failed to report metric (errno: \" << err << \", error: '\" << err_str(err) << \"', fd: \" << conn << \")\\n\";\n } else assert(sent == len);\n }\n }\n\n public:\n UdpSender(const std::string& host, std::uint16_t port, std::uint32_t reconnect_after) :\n host_(host), port_(port), reconnect_after_(reconnect_after), messages_sent_(0), connected_(false) { }\n\n ~UdpSender() { if (connected_) disconnect(); }\n\n void send(std::string&& msg) {\n if (connected_ && ((messages_sent_++ % reconnect_after_) == 0)) {\n disconnect();\n }\n if (! connected_) reconnect();\n do_send(msg.c_str(), msg.length());\n }\n };\n\n class UdpReporter::Impl : public MetricProcessor {\n\n public:\n Impl(MetricsRegistry ®istry, Formatter& formatter, std::uint16_t port, const std::string& hostname, std::uint32_t reconnect_after);\n\n ~Impl();\n\n void run();\n\n using MetricProcessor::process;\n\n void process(Counter& counter);\n\n void process(Meter& meter);\n\n void process(Histogram& histogram);\n\n void process(Timer& timer);\n\n template void send(Args... args);\n\n private:\n medida::MetricsRegistry& registry_;\n\n Formatter& format_;\n\n UdpSender sender_;\n };\n\n\n UdpReporter::UdpReporter(MetricsRegistry ®istry, Formatter& formatter, std::uint16_t port, const std::string& hostname, std::uint32_t reconnect_after)\n : AbstractPollingReporter(),\n impl_ {new UdpReporter::Impl {registry, formatter, port, hostname, reconnect_after}} { }\n\n\n UdpReporter::~UdpReporter() { }\n\n\n void UdpReporter::run() {\n impl_->run();\n }\n\n\n\/\/ === Implementation ===\n\n\n UdpReporter::Impl::Impl(MetricsRegistry ®istry, Formatter& formatter, std::uint16_t port, const std::string& hostname, std::uint32_t reconnect_after)\n :registry_ (registry), format_ (formatter), sender_(hostname, port, reconnect_after) { }\n\n\n UdpReporter::Impl::~Impl() { }\n\n\n void UdpReporter::Impl::run() {\n for (auto& kv : registry_.get_all_metrics()) {\n auto name = kv.first;\n auto metric = kv.second;\n format_.set_name(name.to_string());\n metric->process(*this);\n }\n }\n\n\n template void UdpReporter::Impl::send(Args... args) {\n sender_.send(format_(args...));\n }\n\n\n void UdpReporter::Impl::process(Counter& counter) {\n send(\"counter\", \"count\", counter.count());\n }\n\n\n void UdpReporter::Impl::process(Meter& meter) {\n auto event_type = meter.event_type();\n auto unit = format_rate_unit(meter.rate_unit());\n send(\"meter\", \"count\", meter.count());\n send(\"meter\", event_type, \"mean_rate\", meter.mean_rate(), unit);\n send(\"meter\", event_type, \"1min_rate\", meter.one_minute_rate(), unit);\n send(\"meter\", event_type, \"5min_rate\", meter.five_minute_rate(), unit);\n send(\"meter\", event_type, \"15min_rate\", meter.fifteen_minute_rate(), unit);\n }\n\n\n void UdpReporter::Impl::process(Histogram& histogram) {\n auto snapshot = histogram.snapshot();\n send(\"histogram\", \"min\", histogram.min());\n send(\"histogram\", \"max\", histogram.max());\n send(\"histogram\", \"mean\", histogram.mean());\n send(\"histogram\", \"std_dev\", histogram.std_dev());\n send(\"histogram\", \"median\", snapshot.median());\n send(\"histogram\", \"75pct\", snapshot.percentile_75());\n send(\"histogram\", \"95pct\", snapshot.percentile_95());\n send(\"histogram\", \"98pct\", snapshot.percentile_98());\n send(\"histogram\", \"99pct\", snapshot.percentile_99());\n send(\"histogram\", \"999pct\", snapshot.percentile_999());\n }\n\n\n void UdpReporter::Impl::process(Timer& timer) {\n auto snapshot = timer.snapshot();\n auto event_type = timer.event_type();\n auto rate_unit = format_rate_unit(timer.rate_unit());\n auto duration_unit = format_rate_unit(timer.duration_unit());\n\n send(\"timer\", \"count\", timer.count());\n send(\"timer\", event_type, \"mean_rate\", timer.mean_rate(), rate_unit);\n send(\"timer\", event_type, \"1min_rate\", timer.one_minute_rate(), rate_unit);\n send(\"timer\", event_type, \"5min_rate\", timer.five_minute_rate(), rate_unit);\n send(\"timer\", event_type, \"15min_rate\", timer.fifteen_minute_rate(), rate_unit);\n send(\"timer\", \"min\", timer.min(), duration_unit);\n send(\"timer\", \"max\", timer.max(), duration_unit);\n send(\"timer\", \"mean\", timer.mean(), duration_unit);\n send(\"timer\", \"std_dev\", timer.std_dev(), duration_unit);\n send(\"timer\", \"median\", snapshot.median(), duration_unit);\n send(\"timer\", \"75pct\", snapshot.percentile_75(), duration_unit);\n send(\"timer\", \"95pct\", snapshot.percentile_95(), duration_unit);\n send(\"timer\", \"98pct\", snapshot.percentile_98(), duration_unit);\n send(\"timer\", \"99pct\", snapshot.percentile_99(), duration_unit);\n send(\"timer\", \"999pct\", snapshot.percentile_999(), duration_unit);\n }\n }\n}\n<|endoftext|>"} {"text":"#include \n#include \"regression_objective.hpp\"\n#include \"binary_objective.hpp\"\n#include \"rank_objective.hpp\"\n#include \"multiclass_objective.hpp\"\n#include \"xentropy_objective.hpp\"\n\nnamespace LightGBM {\n\nObjectiveFunction* ObjectiveFunction::CreateObjectiveFunction(const std::string& type, const Config& config) {\n if (type == std::string(\"regression\") || type == std::string(\"regression_l2\")\n || type == std::string(\"mean_squared_error\") || type == std::string(\"mse\") \n || type == std::string(\"l2_root\") || type == std::string(\"root_mean_squared_error\") || type == std::string(\"rmse\")) {\n return new RegressionL2loss(config);\n } else if (type == std::string(\"regression_l1\") || type == std::string(\"mean_absolute_error\") || type == std::string(\"mae\")) {\n return new RegressionL1loss(config);\n } else if (type == std::string(\"quantile\")) {\n return new RegressionQuantileloss(config);\n } else if (type == std::string(\"huber\")) {\n return new RegressionHuberLoss(config);\n } else if (type == std::string(\"fair\")) {\n return new RegressionFairLoss(config);\n } else if (type == std::string(\"poisson\")) {\n return new RegressionPoissonLoss(config);\n } else if (type == std::string(\"binary\")) {\n return new BinaryLogloss(config);\n } else if (type == std::string(\"lambdarank\")) {\n return new LambdarankNDCG(config);\n } else if (type == std::string(\"multiclass\") || type == std::string(\"softmax\")) {\n return new MulticlassSoftmax(config);\n } else if (type == std::string(\"multiclassova\") || type == std::string(\"multiclass_ova\") || type == std::string(\"ova\") || type == std::string(\"ovr\")) {\n return new MulticlassOVA(config);\n } else if (type == std::string(\"xentropy\") || type == std::string(\"cross_entropy\")) {\n return new CrossEntropy(config);\n } else if (type == std::string(\"xentlambda\") || type == std::string(\"cross_entropy_lambda\")) {\n return new CrossEntropyLambda(config);\n } else if (type == std::string(\"mean_absolute_percentage_error\") || type == std::string(\"mape\")) {\n return new RegressionMAPELOSS(config);\n } else if (type == std::string(\"gamma\")) {\n return new RegressionGammaLoss(config);\n } else if (type == std::string(\"tweedie\")) {\n return new RegressionTweedieLoss(config);\n } else if (type == std::string(\"none\") || type == std::string(\"null\") || type == std::string(\"custom\")) {\n return nullptr;\n }\n Log::Fatal(\"Unknown objective type name: %s\", type.c_str());\n}\n\nObjectiveFunction* ObjectiveFunction::CreateObjectiveFunction(const std::string& str) {\n auto strs = Common::Split(str.c_str(), ' ');\n auto type = strs[0];\n if (type == std::string(\"regression\")) {\n return new RegressionL2loss(strs);\n } else if (type == std::string(\"regression_l1\")) {\n return new RegressionL1loss(strs);\n } else if (type == std::string(\"quantile\")) {\n return new RegressionQuantileloss(strs);\n } else if (type == std::string(\"huber\")) {\n return new RegressionHuberLoss(strs);\n } else if (type == std::string(\"fair\")) {\n return new RegressionFairLoss(strs);\n } else if (type == std::string(\"poisson\")) {\n return new RegressionPoissonLoss(strs);\n } else if (type == std::string(\"binary\")) {\n return new BinaryLogloss(strs);\n } else if (type == std::string(\"lambdarank\")) {\n return new LambdarankNDCG(strs);\n } else if (type == std::string(\"multiclass\")) {\n return new MulticlassSoftmax(strs);\n } else if (type == std::string(\"multiclassova\")) {\n return new MulticlassOVA(strs);\n } else if (type == std::string(\"xentropy\") || type == std::string(\"cross_entropy\")) {\n return new CrossEntropy(strs);\n } else if (type == std::string(\"xentlambda\") || type == std::string(\"cross_entropy_lambda\")) {\n return new CrossEntropyLambda(strs);\n } else if (type == std::string(\"gamma\")) {\n return new RegressionGammaLoss(strs);\n } else if (type == std::string(\"tweedie\")) {\n return new RegressionTweedieLoss(strs);\n } else if (type == std::string(\"none\") || type == std::string(\"null\") || type == std::string(\"custom\")) {\n return nullptr;\n }\n Log::Fatal(\"Unknown objective type name: %s\", type.c_str());\n}\n\n} \/\/ namespace LightGBM\nfix #1461#include \n#include \"regression_objective.hpp\"\n#include \"binary_objective.hpp\"\n#include \"rank_objective.hpp\"\n#include \"multiclass_objective.hpp\"\n#include \"xentropy_objective.hpp\"\n\nnamespace LightGBM {\n\nObjectiveFunction* ObjectiveFunction::CreateObjectiveFunction(const std::string& type, const Config& config) {\n if (type == std::string(\"regression\") || type == std::string(\"regression_l2\")\n || type == std::string(\"mean_squared_error\") || type == std::string(\"mse\") \n || type == std::string(\"l2_root\") || type == std::string(\"root_mean_squared_error\") || type == std::string(\"rmse\")) {\n return new RegressionL2loss(config);\n } else if (type == std::string(\"regression_l1\") || type == std::string(\"mean_absolute_error\") || type == std::string(\"mae\")) {\n return new RegressionL1loss(config);\n } else if (type == std::string(\"quantile\")) {\n return new RegressionQuantileloss(config);\n } else if (type == std::string(\"huber\")) {\n return new RegressionHuberLoss(config);\n } else if (type == std::string(\"fair\")) {\n return new RegressionFairLoss(config);\n } else if (type == std::string(\"poisson\")) {\n return new RegressionPoissonLoss(config);\n } else if (type == std::string(\"binary\")) {\n return new BinaryLogloss(config);\n } else if (type == std::string(\"lambdarank\")) {\n return new LambdarankNDCG(config);\n } else if (type == std::string(\"multiclass\") || type == std::string(\"softmax\")) {\n return new MulticlassSoftmax(config);\n } else if (type == std::string(\"multiclassova\") || type == std::string(\"multiclass_ova\") || type == std::string(\"ova\") || type == std::string(\"ovr\")) {\n return new MulticlassOVA(config);\n } else if (type == std::string(\"xentropy\") || type == std::string(\"cross_entropy\")) {\n return new CrossEntropy(config);\n } else if (type == std::string(\"xentlambda\") || type == std::string(\"cross_entropy_lambda\")) {\n return new CrossEntropyLambda(config);\n } else if (type == std::string(\"mean_absolute_percentage_error\") || type == std::string(\"mape\")) {\n return new RegressionMAPELOSS(config);\n } else if (type == std::string(\"gamma\")) {\n return new RegressionGammaLoss(config);\n } else if (type == std::string(\"tweedie\")) {\n return new RegressionTweedieLoss(config);\n } else if (type == std::string(\"none\") || type == std::string(\"null\") || type == std::string(\"custom\")) {\n return nullptr;\n }\n Log::Fatal(\"Unknown objective type name: %s\", type.c_str());\n}\n\nObjectiveFunction* ObjectiveFunction::CreateObjectiveFunction(const std::string& str) {\n auto strs = Common::Split(str.c_str(), ' ');\n auto type = strs[0];\n if (type == std::string(\"regression\")) {\n return new RegressionL2loss(strs);\n } else if (type == std::string(\"regression_l1\")) {\n return new RegressionL1loss(strs);\n } else if (type == std::string(\"quantile\")) {\n return new RegressionQuantileloss(strs);\n } else if (type == std::string(\"huber\")) {\n return new RegressionHuberLoss(strs);\n } else if (type == std::string(\"fair\")) {\n return new RegressionFairLoss(strs);\n } else if (type == std::string(\"poisson\")) {\n return new RegressionPoissonLoss(strs);\n } else if (type == std::string(\"binary\")) {\n return new BinaryLogloss(strs);\n } else if (type == std::string(\"lambdarank\")) {\n return new LambdarankNDCG(strs);\n } else if (type == std::string(\"multiclass\")) {\n return new MulticlassSoftmax(strs);\n } else if (type == std::string(\"multiclassova\")) {\n return new MulticlassOVA(strs);\n } else if (type == std::string(\"xentropy\") || type == std::string(\"cross_entropy\")) {\n return new CrossEntropy(strs);\n } else if (type == std::string(\"xentlambda\") || type == std::string(\"cross_entropy_lambda\")) {\n return new CrossEntropyLambda(strs);\n } else if (type == std::string(\"mean_absolute_percentage_error\") || type == std::string(\"mape\")) {\n return new RegressionMAPELOSS(strs);\n } else if (type == std::string(\"gamma\")) {\n return new RegressionGammaLoss(strs);\n } else if (type == std::string(\"tweedie\")) {\n return new RegressionTweedieLoss(strs);\n } else if (type == std::string(\"none\") || type == std::string(\"null\") || type == std::string(\"custom\")) {\n return nullptr;\n }\n Log::Fatal(\"Unknown objective type name: %s\", type.c_str());\n}\n\n} \/\/ namespace LightGBM\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright © 2020 Arm Ltd and Contributors. All rights reserved.\n\/\/ SPDX-License-Identifier: MIT\n\/\/\n\n#pragma once\n\n#include \n#include \n\n#include \n\n#include \n\nusing Half = half_float::half;\n\nnamespace armnnDelegate\n{\n\n\/\/\/ Can be used to assign input data from a vector to a model input.\n\/\/\/ Example usage can be found in ResizeTesthelper.hpp\ntemplate \nvoid FillInput(std::unique_ptr& interpreter, int inputIndex, std::vector& inputValues)\n{\n auto tfLiteDelegateInputId = interpreter->inputs()[inputIndex];\n auto tfLiteDelageInputData = interpreter->typed_tensor(tfLiteDelegateInputId);\n for (unsigned int i = 0; i < inputValues.size(); ++i)\n {\n tfLiteDelageInputData[i] = inputValues[i];\n }\n}\n\n\/\/\/ Can be used to compare bool data coming from a tflite interpreter\n\/\/\/ Boolean types get converted to a bit representation in a vector. vector.data() returns a void pointer\n\/\/\/ instead of a pointer to bool. Therefore a special function to compare to vector of bool is required\nvoid CompareData(std::vector& tensor1, bool tensor2[], size_t tensorSize);\nvoid CompareData(bool tensor1[], bool tensor2[], size_t tensorSize);\n\n\/\/\/ Can be used to compare float data coming from a tflite interpreter with a tolerance of limit_of_float*100\nvoid CompareData(float tensor1[], float tensor2[], size_t tensorSize);\n\n\/\/\/ Can be used to compare int8_t data coming from a tflite interpreter with a tolerance of 1\nvoid CompareData(int8_t tensor1[], int8_t tensor2[], size_t tensorSize);\n\n\/\/\/ Can be used to compare uint8_t data coming from a tflite interpreter with a tolerance of 1\nvoid CompareData(uint8_t tensor1[], uint8_t tensor2[], size_t tensorSize);\n\n\/\/\/ Can be used to compare int16_t data coming from a tflite interpreter with a tolerance of 1\nvoid CompareData(int16_t tensor1[], int16_t tensor2[], size_t tensorSize);\n\n\/\/\/ Can be used to compare Half (Float16) data with a tolerance of limit_of_float*100\nvoid CompareData(Half tensor1[], Half tensor2[], size_t tensorSize);\n\n\/\/\/ Can be used to compare TfLiteFloat16 data coming from a tflite interpreter\nvoid CompareData(TfLiteFloat16 tensor1[], TfLiteFloat16 tensor2[], size_t tensorSize);\n\n\/\/\/ Can be used to compare Half (Float16) data and TfLiteFloat16 data coming from a tflite interpreter\nvoid CompareData(TfLiteFloat16 tensor1[], Half tensor2[], size_t tensorSize);\n\n\/\/\/ Can be used to compare the output tensor shape and values\n\/\/\/ from armnnDelegateInterpreter and tfLiteInterpreter.\n\/\/\/ Example usage can be found in ControlTestHelper.hpp\ntemplate \nvoid CompareOutputData(std::unique_ptr& tfLiteInterpreter,\n std::unique_ptr& armnnDelegateInterpreter,\n std::vector& expectedOutputShape,\n std::vector& expectedOutputValues,\n unsigned int outputIndex = 0)\n{\n auto tfLiteDelegateOutputId = tfLiteInterpreter->outputs()[outputIndex];\n auto tfLiteDelegateOutputTensor = tfLiteInterpreter->tensor(tfLiteDelegateOutputId);\n auto tfLiteDelegateOutputData = tfLiteInterpreter->typed_tensor(tfLiteDelegateOutputId);\n auto armnnDelegateOutputId = armnnDelegateInterpreter->outputs()[outputIndex];\n auto armnnDelegateOutputTensor = armnnDelegateInterpreter->tensor(armnnDelegateOutputId);\n auto armnnDelegateOutputData = armnnDelegateInterpreter->typed_tensor(armnnDelegateOutputId);\n\n CHECK(expectedOutputShape.size() == tfLiteDelegateOutputTensor->dims->size);\n CHECK(expectedOutputShape.size() == armnnDelegateOutputTensor->dims->size);\n\n for (size_t i = 0; i < expectedOutputShape.size(); i++)\n {\n CHECK(expectedOutputShape[i] == armnnDelegateOutputTensor->dims->data[i]);\n CHECK(tfLiteDelegateOutputTensor->dims->data[i] == expectedOutputShape[i]);\n CHECK(tfLiteDelegateOutputTensor->dims->data[i] == armnnDelegateOutputTensor->dims->data[i]);\n }\n\n armnnDelegate::CompareData(expectedOutputValues.data(), armnnDelegateOutputData , expectedOutputValues.size());\n armnnDelegate::CompareData(tfLiteDelegateOutputData , expectedOutputValues.data(), expectedOutputValues.size());\n armnnDelegate::CompareData(tfLiteDelegateOutputData , armnnDelegateOutputData , expectedOutputValues.size());\n}\n\n} \/\/ namespace armnnDelegate\nIVGCVSW-5654 Fix failing float 16 delegate tests on android\/\/\n\/\/ Copyright © 2020 Arm Ltd and Contributors. All rights reserved.\n\/\/ SPDX-License-Identifier: MIT\n\/\/\n\n#pragma once\n\n#include \n#include \n\n#include \n\n#include \n\nusing Half = half_float::half;\n\nnamespace armnnDelegate\n{\n\n\/\/\/ Can be used to assign input data from a vector to a model input.\n\/\/\/ Example usage can be found in ResizeTesthelper.hpp\ntemplate \nvoid FillInput(std::unique_ptr& interpreter, int inputIndex, std::vector& inputValues)\n{\n auto tfLiteDelegateInputId = interpreter->inputs()[inputIndex];\n auto tfLiteDelageInputData = interpreter->typed_tensor(tfLiteDelegateInputId);\n for (unsigned int i = 0; i < inputValues.size(); ++i)\n {\n tfLiteDelageInputData[i] = inputValues[i];\n }\n}\n\ntemplate <>\nvoid FillInput(std::unique_ptr& interpreter, int inputIndex, std::vector& inputValues);\n\n\/\/\/ Can be used to compare bool data coming from a tflite interpreter\n\/\/\/ Boolean types get converted to a bit representation in a vector. vector.data() returns a void pointer\n\/\/\/ instead of a pointer to bool. Therefore a special function to compare to vector of bool is required\nvoid CompareData(std::vector& tensor1, bool tensor2[], size_t tensorSize);\nvoid CompareData(bool tensor1[], bool tensor2[], size_t tensorSize);\n\n\/\/\/ Can be used to compare float data coming from a tflite interpreter with a tolerance of limit_of_float*100\nvoid CompareData(float tensor1[], float tensor2[], size_t tensorSize);\n\n\/\/\/ Can be used to compare int8_t data coming from a tflite interpreter with a tolerance of 1\nvoid CompareData(int8_t tensor1[], int8_t tensor2[], size_t tensorSize);\n\n\/\/\/ Can be used to compare uint8_t data coming from a tflite interpreter with a tolerance of 1\nvoid CompareData(uint8_t tensor1[], uint8_t tensor2[], size_t tensorSize);\n\n\/\/\/ Can be used to compare int16_t data coming from a tflite interpreter with a tolerance of 1\nvoid CompareData(int16_t tensor1[], int16_t tensor2[], size_t tensorSize);\n\n\/\/\/ Can be used to compare Half (Float16) data with a tolerance of limit_of_float*100\nvoid CompareData(Half tensor1[], Half tensor2[], size_t tensorSize);\n\n\/\/\/ Can be used to compare TfLiteFloat16 data coming from a tflite interpreter\nvoid CompareData(TfLiteFloat16 tensor1[], TfLiteFloat16 tensor2[], size_t tensorSize);\n\n\/\/\/ Can be used to compare Half (Float16) data and TfLiteFloat16 data coming from a tflite interpreter\nvoid CompareData(TfLiteFloat16 tensor1[], Half tensor2[], size_t tensorSize);\n\n\/\/\/ Can be used to compare the output tensor shape and values\n\/\/\/ from armnnDelegateInterpreter and tfLiteInterpreter.\n\/\/\/ Example usage can be found in ControlTestHelper.hpp\ntemplate \nvoid CompareOutputData(std::unique_ptr& tfLiteInterpreter,\n std::unique_ptr& armnnDelegateInterpreter,\n std::vector& expectedOutputShape,\n std::vector& expectedOutputValues,\n unsigned int outputIndex = 0)\n{\n auto tfLiteDelegateOutputId = tfLiteInterpreter->outputs()[outputIndex];\n auto tfLiteDelegateOutputTensor = tfLiteInterpreter->tensor(tfLiteDelegateOutputId);\n auto tfLiteDelegateOutputData = tfLiteInterpreter->typed_tensor(tfLiteDelegateOutputId);\n auto armnnDelegateOutputId = armnnDelegateInterpreter->outputs()[outputIndex];\n auto armnnDelegateOutputTensor = armnnDelegateInterpreter->tensor(armnnDelegateOutputId);\n auto armnnDelegateOutputData = armnnDelegateInterpreter->typed_tensor(armnnDelegateOutputId);\n\n CHECK(expectedOutputShape.size() == tfLiteDelegateOutputTensor->dims->size);\n CHECK(expectedOutputShape.size() == armnnDelegateOutputTensor->dims->size);\n\n for (size_t i = 0; i < expectedOutputShape.size(); i++)\n {\n CHECK(expectedOutputShape[i] == armnnDelegateOutputTensor->dims->data[i]);\n CHECK(tfLiteDelegateOutputTensor->dims->data[i] == expectedOutputShape[i]);\n CHECK(tfLiteDelegateOutputTensor->dims->data[i] == armnnDelegateOutputTensor->dims->data[i]);\n }\n\n armnnDelegate::CompareData(expectedOutputValues.data(), armnnDelegateOutputData , expectedOutputValues.size());\n armnnDelegate::CompareData(tfLiteDelegateOutputData , expectedOutputValues.data(), expectedOutputValues.size());\n armnnDelegate::CompareData(tfLiteDelegateOutputData , armnnDelegateOutputData , expectedOutputValues.size());\n}\n\n} \/\/ namespace armnnDelegate\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"net\/third_party\/quiche\/src\/quic\/core\/congestion_control\/pacing_sender.h\"\n\n#include \"net\/third_party\/quiche\/src\/quic\/core\/quic_bandwidth.h\"\n#include \"net\/third_party\/quiche\/src\/quic\/platform\/api\/quic_flag_utils.h\"\n#include \"net\/third_party\/quiche\/src\/quic\/platform\/api\/quic_flags.h\"\n#include \"net\/third_party\/quiche\/src\/quic\/platform\/api\/quic_logging.h\"\n\nnamespace quic {\nnamespace {\n\n\/\/ Configured maximum size of the burst coming out of quiescence. The burst\n\/\/ is never larger than the current CWND in packets.\nstatic const uint32_t kInitialUnpacedBurst = 10;\n\n} \/\/ namespace\n\nPacingSender::PacingSender()\n : sender_(nullptr),\n max_pacing_rate_(QuicBandwidth::Zero()),\n burst_tokens_(kInitialUnpacedBurst),\n ideal_next_packet_send_time_(QuicTime::Zero()),\n initial_burst_size_(kInitialUnpacedBurst),\n lumpy_tokens_(0),\n alarm_granularity_(QuicTime::Delta::FromMilliseconds(1)),\n pacing_limited_(false) {\n if (GetQuicReloadableFlag(quic_donot_reset_ideal_next_packet_send_time)) {\n QUIC_RELOADABLE_FLAG_COUNT(quic_donot_reset_ideal_next_packet_send_time);\n }\n}\n\nPacingSender::~PacingSender() {}\n\nvoid PacingSender::set_sender(SendAlgorithmInterface* sender) {\n DCHECK(sender != nullptr);\n sender_ = sender;\n}\n\nvoid PacingSender::OnCongestionEvent(bool rtt_updated,\n QuicByteCount bytes_in_flight,\n QuicTime event_time,\n const AckedPacketVector& acked_packets,\n const LostPacketVector& lost_packets) {\n DCHECK(sender_ != nullptr);\n if (!lost_packets.empty()) {\n \/\/ Clear any burst tokens when entering recovery.\n burst_tokens_ = 0;\n }\n sender_->OnCongestionEvent(rtt_updated, bytes_in_flight, event_time,\n acked_packets, lost_packets);\n}\n\nvoid PacingSender::OnPacketSent(\n QuicTime sent_time,\n QuicByteCount bytes_in_flight,\n QuicPacketNumber packet_number,\n QuicByteCount bytes,\n HasRetransmittableData has_retransmittable_data) {\n DCHECK(sender_ != nullptr);\n sender_->OnPacketSent(sent_time, bytes_in_flight, packet_number, bytes,\n has_retransmittable_data);\n if (has_retransmittable_data != HAS_RETRANSMITTABLE_DATA) {\n return;\n }\n \/\/ If in recovery, the connection is not coming out of quiescence.\n if (bytes_in_flight == 0 && !sender_->InRecovery()) {\n \/\/ Add more burst tokens anytime the connection is leaving quiescence, but\n \/\/ limit it to the equivalent of a single bulk write, not exceeding the\n \/\/ current CWND in packets.\n burst_tokens_ = std::min(\n initial_burst_size_,\n static_cast(sender_->GetCongestionWindow() \/ kDefaultTCPMSS));\n }\n if (burst_tokens_ > 0) {\n --burst_tokens_;\n if (!GetQuicReloadableFlag(quic_donot_reset_ideal_next_packet_send_time)) {\n ideal_next_packet_send_time_ = QuicTime::Zero();\n }\n pacing_limited_ = false;\n return;\n }\n \/\/ The next packet should be sent as soon as the current packet has been\n \/\/ transferred. PacingRate is based on bytes in flight including this packet.\n QuicTime::Delta delay =\n PacingRate(bytes_in_flight + bytes).TransferTime(bytes);\n if (!pacing_limited_ || lumpy_tokens_ == 0) {\n \/\/ Reset lumpy_tokens_ if either application or cwnd throttles sending or\n \/\/ token runs out.\n lumpy_tokens_ = std::max(\n 1u, std::min(static_cast(\n GetQuicFlag(FLAGS_quic_lumpy_pacing_size)),\n static_cast(\n (sender_->GetCongestionWindow() *\n GetQuicFlag(FLAGS_quic_lumpy_pacing_cwnd_fraction)) \/\n kDefaultTCPMSS)));\n if (GetQuicReloadableFlag(quic_no_lumpy_pacing_at_low_bw) &&\n sender_->BandwidthEstimate() <\n QuicBandwidth::FromKBitsPerSecond(1200)) {\n \/\/ Below 1.2Mbps, send 1 packet at once, because one full-sized packet\n \/\/ is about 10ms of queueing.\n lumpy_tokens_ = 1u;\n }\n }\n --lumpy_tokens_;\n if (pacing_limited_) {\n \/\/ Make up for lost time since pacing throttles the sending.\n ideal_next_packet_send_time_ = ideal_next_packet_send_time_ + delay;\n } else {\n ideal_next_packet_send_time_ =\n std::max(ideal_next_packet_send_time_ + delay, sent_time + delay);\n }\n \/\/ Stop making up for lost time if underlying sender prevents sending.\n pacing_limited_ = sender_->CanSend(bytes_in_flight + bytes);\n}\n\nvoid PacingSender::OnApplicationLimited() {\n \/\/ The send is application limited, stop making up for lost time.\n pacing_limited_ = false;\n}\n\nQuicTime::Delta PacingSender::TimeUntilSend(\n QuicTime now,\n QuicByteCount bytes_in_flight) const {\n DCHECK(sender_ != nullptr);\n\n if (!sender_->CanSend(bytes_in_flight)) {\n \/\/ The underlying sender prevents sending.\n return QuicTime::Delta::Infinite();\n }\n\n if (burst_tokens_ > 0 || bytes_in_flight == 0 || lumpy_tokens_ > 0) {\n \/\/ Don't pace if we have burst tokens available or leaving quiescence.\n return QuicTime::Delta::Zero();\n }\n\n \/\/ If the next send time is within the alarm granularity, send immediately.\n if (ideal_next_packet_send_time_ > now + alarm_granularity_) {\n QUIC_DVLOG(1) << \"Delaying packet: \"\n << (ideal_next_packet_send_time_ - now).ToMicroseconds();\n return ideal_next_packet_send_time_ - now;\n }\n\n QUIC_DVLOG(1) << \"Sending packet now. ideal_next_packet_send_time: \"\n << ideal_next_packet_send_time_ << \", now: \" << now;\n return QuicTime::Delta::Zero();\n}\n\nQuicBandwidth PacingSender::PacingRate(QuicByteCount bytes_in_flight) const {\n DCHECK(sender_ != nullptr);\n if (!max_pacing_rate_.IsZero()) {\n return QuicBandwidth::FromBitsPerSecond(\n std::min(max_pacing_rate_.ToBitsPerSecond(),\n sender_->PacingRate(bytes_in_flight).ToBitsPerSecond()));\n }\n return sender_->PacingRate(bytes_in_flight);\n}\n\n} \/\/ namespace quic\ngfe-relnote: (n\/a) Add a flag count for --gfe2_reloadable_flag_quic_no_lumpy_pacing_at_low_bw. Flag count only.\/\/ Copyright (c) 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"net\/third_party\/quiche\/src\/quic\/core\/congestion_control\/pacing_sender.h\"\n\n#include \"net\/third_party\/quiche\/src\/quic\/core\/quic_bandwidth.h\"\n#include \"net\/third_party\/quiche\/src\/quic\/platform\/api\/quic_flag_utils.h\"\n#include \"net\/third_party\/quiche\/src\/quic\/platform\/api\/quic_flags.h\"\n#include \"net\/third_party\/quiche\/src\/quic\/platform\/api\/quic_logging.h\"\n\nnamespace quic {\nnamespace {\n\n\/\/ Configured maximum size of the burst coming out of quiescence. The burst\n\/\/ is never larger than the current CWND in packets.\nstatic const uint32_t kInitialUnpacedBurst = 10;\n\n} \/\/ namespace\n\nPacingSender::PacingSender()\n : sender_(nullptr),\n max_pacing_rate_(QuicBandwidth::Zero()),\n burst_tokens_(kInitialUnpacedBurst),\n ideal_next_packet_send_time_(QuicTime::Zero()),\n initial_burst_size_(kInitialUnpacedBurst),\n lumpy_tokens_(0),\n alarm_granularity_(QuicTime::Delta::FromMilliseconds(1)),\n pacing_limited_(false) {\n if (GetQuicReloadableFlag(quic_donot_reset_ideal_next_packet_send_time)) {\n QUIC_RELOADABLE_FLAG_COUNT(quic_donot_reset_ideal_next_packet_send_time);\n }\n}\n\nPacingSender::~PacingSender() {}\n\nvoid PacingSender::set_sender(SendAlgorithmInterface* sender) {\n DCHECK(sender != nullptr);\n sender_ = sender;\n}\n\nvoid PacingSender::OnCongestionEvent(bool rtt_updated,\n QuicByteCount bytes_in_flight,\n QuicTime event_time,\n const AckedPacketVector& acked_packets,\n const LostPacketVector& lost_packets) {\n DCHECK(sender_ != nullptr);\n if (!lost_packets.empty()) {\n \/\/ Clear any burst tokens when entering recovery.\n burst_tokens_ = 0;\n }\n sender_->OnCongestionEvent(rtt_updated, bytes_in_flight, event_time,\n acked_packets, lost_packets);\n}\n\nvoid PacingSender::OnPacketSent(\n QuicTime sent_time,\n QuicByteCount bytes_in_flight,\n QuicPacketNumber packet_number,\n QuicByteCount bytes,\n HasRetransmittableData has_retransmittable_data) {\n DCHECK(sender_ != nullptr);\n sender_->OnPacketSent(sent_time, bytes_in_flight, packet_number, bytes,\n has_retransmittable_data);\n if (has_retransmittable_data != HAS_RETRANSMITTABLE_DATA) {\n return;\n }\n \/\/ If in recovery, the connection is not coming out of quiescence.\n if (bytes_in_flight == 0 && !sender_->InRecovery()) {\n \/\/ Add more burst tokens anytime the connection is leaving quiescence, but\n \/\/ limit it to the equivalent of a single bulk write, not exceeding the\n \/\/ current CWND in packets.\n burst_tokens_ = std::min(\n initial_burst_size_,\n static_cast(sender_->GetCongestionWindow() \/ kDefaultTCPMSS));\n }\n if (burst_tokens_ > 0) {\n --burst_tokens_;\n if (!GetQuicReloadableFlag(quic_donot_reset_ideal_next_packet_send_time)) {\n ideal_next_packet_send_time_ = QuicTime::Zero();\n }\n pacing_limited_ = false;\n return;\n }\n \/\/ The next packet should be sent as soon as the current packet has been\n \/\/ transferred. PacingRate is based on bytes in flight including this packet.\n QuicTime::Delta delay =\n PacingRate(bytes_in_flight + bytes).TransferTime(bytes);\n if (!pacing_limited_ || lumpy_tokens_ == 0) {\n \/\/ Reset lumpy_tokens_ if either application or cwnd throttles sending or\n \/\/ token runs out.\n lumpy_tokens_ = std::max(\n 1u, std::min(static_cast(\n GetQuicFlag(FLAGS_quic_lumpy_pacing_size)),\n static_cast(\n (sender_->GetCongestionWindow() *\n GetQuicFlag(FLAGS_quic_lumpy_pacing_cwnd_fraction)) \/\n kDefaultTCPMSS)));\n if (GetQuicReloadableFlag(quic_no_lumpy_pacing_at_low_bw) &&\n sender_->BandwidthEstimate() <\n QuicBandwidth::FromKBitsPerSecond(1200)) {\n QUIC_RELOADABLE_FLAG_COUNT(quic_no_lumpy_pacing_at_low_bw);\n \/\/ Below 1.2Mbps, send 1 packet at once, because one full-sized packet\n \/\/ is about 10ms of queueing.\n lumpy_tokens_ = 1u;\n }\n }\n --lumpy_tokens_;\n if (pacing_limited_) {\n \/\/ Make up for lost time since pacing throttles the sending.\n ideal_next_packet_send_time_ = ideal_next_packet_send_time_ + delay;\n } else {\n ideal_next_packet_send_time_ =\n std::max(ideal_next_packet_send_time_ + delay, sent_time + delay);\n }\n \/\/ Stop making up for lost time if underlying sender prevents sending.\n pacing_limited_ = sender_->CanSend(bytes_in_flight + bytes);\n}\n\nvoid PacingSender::OnApplicationLimited() {\n \/\/ The send is application limited, stop making up for lost time.\n pacing_limited_ = false;\n}\n\nQuicTime::Delta PacingSender::TimeUntilSend(\n QuicTime now,\n QuicByteCount bytes_in_flight) const {\n DCHECK(sender_ != nullptr);\n\n if (!sender_->CanSend(bytes_in_flight)) {\n \/\/ The underlying sender prevents sending.\n return QuicTime::Delta::Infinite();\n }\n\n if (burst_tokens_ > 0 || bytes_in_flight == 0 || lumpy_tokens_ > 0) {\n \/\/ Don't pace if we have burst tokens available or leaving quiescence.\n return QuicTime::Delta::Zero();\n }\n\n \/\/ If the next send time is within the alarm granularity, send immediately.\n if (ideal_next_packet_send_time_ > now + alarm_granularity_) {\n QUIC_DVLOG(1) << \"Delaying packet: \"\n << (ideal_next_packet_send_time_ - now).ToMicroseconds();\n return ideal_next_packet_send_time_ - now;\n }\n\n QUIC_DVLOG(1) << \"Sending packet now. ideal_next_packet_send_time: \"\n << ideal_next_packet_send_time_ << \", now: \" << now;\n return QuicTime::Delta::Zero();\n}\n\nQuicBandwidth PacingSender::PacingRate(QuicByteCount bytes_in_flight) const {\n DCHECK(sender_ != nullptr);\n if (!max_pacing_rate_.IsZero()) {\n return QuicBandwidth::FromBitsPerSecond(\n std::min(max_pacing_rate_.ToBitsPerSecond(),\n sender_->PacingRate(bytes_in_flight).ToBitsPerSecond()));\n }\n return sender_->PacingRate(bytes_in_flight);\n}\n\n} \/\/ namespace quic\n<|endoftext|>"} {"text":"#include \/\/std::stringstream\n#include \/\/std::time\n#include \"request.h\"\n#include \"lib\/curl_wrapper.h\"\n#include \"lib\/exceptions.h\"\n\nusing namespace bittrex;\nusing namespace bittrex::lib;\n\nstd::string Request::get(const std::string &key,\n const std::string &secret,\n const std::string &payloads,\n const std::string &endpoint,\n ApiType type) {\n\n std::string res;\n auto uri = BASE_URL + endpoint;\n CurlWrapper r;\n try {\n auto nonce = std::time(nullptr);\n if (type != ApiType::PUBLIC)\n uri += \"apikey=\" + key + \"&nonce=\" + std::to_string(nonce) + \"&\" + payloads;\n else\n uri += payloads;\n\n std::string apisign = \"apisign:\" + hmac_sha512(uri, secret);\n r.setOpt(curl::options::HttpHeader(apisign));\n r.setOpt(curl::options::WriteData(res));\n r.setOpt(curl::options::Url(uri));\n\n r.perform();\n }\n catch (fail &e) {\n std::cout << e.what() << std::endl;\n }\n return res;\n}\n\n\nminor#include \/\/std::stringstream\n#include \/\/std::time\n#include \"request.h\"\n#include \"lib\/curl_wrapper.h\"\n#include \"lib\/exceptions.h\"\n\nusing namespace bittrex;\nusing namespace bittrex::lib;\n\nstd::string Request::get(const std::string &key,\n const std::string &secret,\n const std::string &payloads,\n const std::string &endpoint,\n ApiType type) {\n\n std::string res;\n auto uri = BASE_URL + endpoint;\n\n CurlWrapper r;\n try {\n auto nonce = std::time(nullptr);\n (type != ApiType::PUBLIC) ?\n uri += \"apikey=\" + key + \"&nonce=\" + std::to_string(nonce) + \"&\" + payloads :\n uri += payloads;\n\n std::string apisign = \"apisign:\" + hmac_sha512(uri, secret);\n r.setOpt(curl::options::HttpHeader(apisign));\n r.setOpt(curl::options::WriteData(res));\n r.setOpt(curl::options::Url(uri));\n\n r.perform();\n }\n catch (fail &e) {\n std::cout << e.what() << std::endl;\n }\n return res;\n}\n\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \"..\/src\/reactor\/reactor.h\"\n\nusing namespace testing;\n\nclass pair_socket_wrapper : public socket_wrapper_base\n{\npublic:\n\tpair_socket_wrapper(const std::shared_ptr context, const std::string &addr)\n\t\t: socket_wrapper_base(context, zmq::socket_type::pair, addr, false),\n\t\t local_socket_(*context, zmq::socket_type::pair), context_(context)\n\t{\n\t\tlocal_socket_.setsockopt(ZMQ_LINGER, 0);\n\t\tlocal_socket_.bind(addr_);\n\t\tsocket_.close();\n\t}\n\n\tvoid initialize()\n\t{\n\t\t\/\/ called by the reactor\n\t\tsocket_ = zmq::socket_t(*context_, zmq::socket_type::pair);\n\t\tsocket_.setsockopt(ZMQ_LINGER, 0);\n\t\tsocket_.connect(addr_);\n\t}\n\n\tbool send_message(const message_container &message)\n\t{\n\t\treturn socket_send(socket_, message);\n\t}\n\n\tbool receive_message(message_container &message)\n\t{\n\t\treturn socket_receive(socket_, message);\n\t}\n\n\tbool send_message_local(const message_container &message)\n\t{\n\t\treturn socket_send(local_socket_, message);\n\t}\n\n\tbool receive_message_local(message_container &message)\n\t{\n\t\treturn socket_receive(local_socket_, message, true);\n\t}\n\nprivate:\n\tzmq::socket_t local_socket_;\n\tstd::shared_ptr context_;\n\n\tbool socket_send(zmq::socket_t &socket, const message_container &message)\n\t{\n\t\tbool retval;\n\t\tzmq::message_t zmessage(message.identity.c_str(), message.identity.size());\n\t\tretval = socket.send(zmessage, ZMQ_SNDMORE);\n\n\t\tif (!retval) {\n\t\t\treturn false;\n\t\t}\n\n\t\tfor (auto it = std::begin(message.data); it != std::end(message.data); ++it) {\n\t\t\tzmessage.rebuild(it->c_str(), it->size());\n\t\t\tretval = socket.send(zmessage, std::next(it) != std::end(message.data) ? ZMQ_SNDMORE : 0);\n\n\t\t\tif (!retval) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tbool socket_receive(zmq::socket_t &socket, message_container &message, bool noblock = false)\n\t{\n\t\tzmq::message_t received_message;\n\t\tbool retval;\n\n\t\tretval = socket.recv(&received_message, noblock ? ZMQ_NOBLOCK : 0);\n\n\t\tif (!retval) {\n\t\t\treturn false;\n\t\t}\n\n\t\tmessage.identity = std::string((char *) received_message.data(), received_message.size());\n\n\t\twhile (received_message.more()) {\n\t\t\tretval = socket.recv(&received_message);\n\n\t\t\tif (!retval) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tmessage.data.emplace_back((char *) received_message.data(), received_message.size());\n\t\t}\n\n\t\treturn true;\n\t}\n};\n\n\/**\n * A handler driven by a function passed on creation\n *\/\nclass pluggable_handler : public handler_interface\n{\npublic:\n\ttypedef std::function fnc_t;\n\n\tstd::vector received;\n\n\tpluggable_handler(fnc_t fnc) : fnc_(fnc)\n\t{\n\t}\n\n\tstatic std::shared_ptr create(fnc_t fnc)\n\t{\n\t\treturn std::make_shared(fnc);\n\t}\n\n\tvoid on_request(const message_container &message, response_cb response)\n\t{\n\t\treceived.push_back(message);\n\t\tfnc_(message, response);\n\t}\n\nprivate:\n\tfnc_t fnc_;\n};\n\nTEST(reactor, synchronous_handler)\n{\n\tauto context = std::make_shared(1);\n\treactor r(context);\n\tauto socket = std::make_shared(context, \"inproc:\/\/synchronous_handler_1\");\n\tauto handler = pluggable_handler::create([](const message_container &msg, handler_interface::response_cb respond) {\n\t\trespond(message_container(\"socket\", \"id1\", {\"Hello!\"}));\n\t});\n\n\tr.add_socket(\"socket\", socket);\n\tr.add_handler({\"socket\"}, handler);\n\n\tstd::thread thread([&r]() { r.start_loop(); });\n\tstd::this_thread::sleep_for(std::chrono::milliseconds(10));\n\n\tsocket->send_message_local(message_container(\"\", \"id1\", {\"Hello??\"}));\n\tstd::this_thread::sleep_for(std::chrono::milliseconds(10));\n\n\tEXPECT_THAT(handler->received, ElementsAre(message_container(\"socket\", \"id1\", {\"Hello??\"})));\n\n\tmessage_container message;\n\tsocket->receive_message_local(message);\n\n\tEXPECT_EQ(\"id1\", message.identity);\n\tEXPECT_THAT(message.data, ElementsAre(\"Hello!\"));\n\n\tr.terminate();\n\tthread.join();\n}\n\nTEST(reactor, asynchronous_handler)\n{\n\tauto context = std::make_shared(1);\n\treactor r(context);\n\tauto socket = std::make_shared(context, \"inproc:\/\/asynchronous_handler_1\");\n\tauto handler = pluggable_handler::create([](const message_container &msg, handler_interface::response_cb respond) {\n\t\trespond(message_container(\"socket\", \"id1\", {\"Hello!\"}));\n\t});\n\n\tr.add_socket(\"socket\", socket);\n\tr.add_async_handler({\"socket\"}, handler);\n\n\tstd::thread thread([&r]() { r.start_loop(); });\n\tstd::this_thread::sleep_for(std::chrono::milliseconds(10));\n\n\tsocket->send_message_local(message_container(\"\", \"id1\", {\"Hello??\"}));\n\tstd::this_thread::sleep_for(std::chrono::milliseconds(10));\n\n\tEXPECT_THAT(handler->received, ElementsAre(message_container(\"socket\", \"id1\", {\"Hello??\"})));\n\n\tmessage_container message;\n\tsocket->receive_message_local(message);\n\n\tEXPECT_EQ(\"id1\", message.identity);\n\tEXPECT_THAT(message.data, ElementsAre(\"Hello!\"));\n\n\tr.terminate();\n\tthread.join();\n}\n\nTEST(reactor, timers)\n{\n\tauto context = std::make_shared(1);\n\treactor r(context);\n\tauto socket = std::make_shared(context, \"inproc:\/\/timers_1\");\n\tauto handler = pluggable_handler::create([](const message_container &msg, handler_interface::response_cb respond) { });\n\n\tr.add_async_handler({r.KEY_TIMER}, handler);\n\n\tstd::thread thread([&r]() { r.start_loop(); });\n\tstd::this_thread::sleep_for(std::chrono::milliseconds(200));\n\n\tASSERT_GE(1, handler->received.size());\n\n\tr.terminate();\n\tthread.join();\n}\nadd a test to make sure messages to async handlers don't get mixed up#include \n#include \n#include \n\n#include \"..\/src\/reactor\/reactor.h\"\n\nusing namespace testing;\n\nclass pair_socket_wrapper : public socket_wrapper_base\n{\npublic:\n\tpair_socket_wrapper(const std::shared_ptr context, const std::string &addr)\n\t\t: socket_wrapper_base(context, zmq::socket_type::pair, addr, false),\n\t\t local_socket_(*context, zmq::socket_type::pair), context_(context)\n\t{\n\t\tlocal_socket_.setsockopt(ZMQ_LINGER, 0);\n\t\tlocal_socket_.bind(addr_);\n\t\tsocket_.close();\n\t}\n\n\tvoid initialize()\n\t{\n\t\t\/\/ called by the reactor\n\t\tsocket_ = zmq::socket_t(*context_, zmq::socket_type::pair);\n\t\tsocket_.setsockopt(ZMQ_LINGER, 0);\n\t\tsocket_.connect(addr_);\n\t}\n\n\tbool send_message(const message_container &message)\n\t{\n\t\treturn socket_send(socket_, message);\n\t}\n\n\tbool receive_message(message_container &message)\n\t{\n\t\treturn socket_receive(socket_, message);\n\t}\n\n\tbool send_message_local(const message_container &message)\n\t{\n\t\treturn socket_send(local_socket_, message);\n\t}\n\n\tbool receive_message_local(message_container &message)\n\t{\n\t\treturn socket_receive(local_socket_, message, true);\n\t}\n\nprivate:\n\tzmq::socket_t local_socket_;\n\tstd::shared_ptr context_;\n\n\tbool socket_send(zmq::socket_t &socket, const message_container &message)\n\t{\n\t\tbool retval;\n\t\tzmq::message_t zmessage(message.identity.c_str(), message.identity.size());\n\t\tretval = socket.send(zmessage, ZMQ_SNDMORE);\n\n\t\tif (!retval) {\n\t\t\treturn false;\n\t\t}\n\n\t\tfor (auto it = std::begin(message.data); it != std::end(message.data); ++it) {\n\t\t\tzmessage.rebuild(it->c_str(), it->size());\n\t\t\tretval = socket.send(zmessage, std::next(it) != std::end(message.data) ? ZMQ_SNDMORE : 0);\n\n\t\t\tif (!retval) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tbool socket_receive(zmq::socket_t &socket, message_container &message, bool noblock = false)\n\t{\n\t\tzmq::message_t received_message;\n\t\tbool retval;\n\n\t\tretval = socket.recv(&received_message, noblock ? ZMQ_NOBLOCK : 0);\n\n\t\tif (!retval) {\n\t\t\treturn false;\n\t\t}\n\n\t\tmessage.identity = std::string((char *) received_message.data(), received_message.size());\n\n\t\twhile (received_message.more()) {\n\t\t\tretval = socket.recv(&received_message);\n\n\t\t\tif (!retval) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tmessage.data.emplace_back((char *) received_message.data(), received_message.size());\n\t\t}\n\n\t\treturn true;\n\t}\n};\n\n\/**\n * A handler driven by a function passed on creation\n *\/\nclass pluggable_handler : public handler_interface\n{\npublic:\n\ttypedef std::function fnc_t;\n\n\tstd::vector received;\n\n\tpluggable_handler(fnc_t fnc) : fnc_(fnc)\n\t{\n\t}\n\n\tstatic std::shared_ptr create(fnc_t fnc)\n\t{\n\t\treturn std::make_shared(fnc);\n\t}\n\n\tvoid on_request(const message_container &message, response_cb response)\n\t{\n\t\treceived.push_back(message);\n\t\tfnc_(message, response);\n\t}\n\nprivate:\n\tfnc_t fnc_;\n};\n\nTEST(reactor, synchronous_handler)\n{\n\tauto context = std::make_shared(1);\n\treactor r(context);\n\tauto socket = std::make_shared(context, \"inproc:\/\/synchronous_handler_1\");\n\tauto handler = pluggable_handler::create([](const message_container &msg, handler_interface::response_cb respond) {\n\t\trespond(message_container(\"socket\", \"id1\", {\"Hello!\"}));\n\t});\n\n\tr.add_socket(\"socket\", socket);\n\tr.add_handler({\"socket\"}, handler);\n\n\tstd::thread thread([&r]() { r.start_loop(); });\n\tstd::this_thread::sleep_for(std::chrono::milliseconds(10));\n\n\tsocket->send_message_local(message_container(\"\", \"id1\", {\"Hello??\"}));\n\tstd::this_thread::sleep_for(std::chrono::milliseconds(10));\n\n\tEXPECT_THAT(handler->received, ElementsAre(message_container(\"socket\", \"id1\", {\"Hello??\"})));\n\n\tmessage_container message;\n\tsocket->receive_message_local(message);\n\n\tEXPECT_EQ(\"id1\", message.identity);\n\tEXPECT_THAT(message.data, ElementsAre(\"Hello!\"));\n\n\tr.terminate();\n\tthread.join();\n}\n\nTEST(reactor, asynchronous_handler)\n{\n\tauto context = std::make_shared(1);\n\treactor r(context);\n\tauto socket = std::make_shared(context, \"inproc:\/\/asynchronous_handler_1\");\n\tauto handler = pluggable_handler::create([](const message_container &msg, handler_interface::response_cb respond) {\n\t\trespond(message_container(\"socket\", \"id1\", {\"Hello!\"}));\n\t});\n\n\tr.add_socket(\"socket\", socket);\n\tr.add_async_handler({\"socket\"}, handler);\n\n\tstd::thread thread([&r]() { r.start_loop(); });\n\tstd::this_thread::sleep_for(std::chrono::milliseconds(10));\n\n\tsocket->send_message_local(message_container(\"\", \"id1\", {\"Hello??\"}));\n\tstd::this_thread::sleep_for(std::chrono::milliseconds(10));\n\n\tEXPECT_THAT(handler->received, ElementsAre(message_container(\"socket\", \"id1\", {\"Hello??\"})));\n\n\tmessage_container message;\n\tsocket->receive_message_local(message);\n\n\tEXPECT_EQ(\"id1\", message.identity);\n\tEXPECT_THAT(message.data, ElementsAre(\"Hello!\"));\n\n\tr.terminate();\n\tthread.join();\n}\n\nTEST(reactor, timers)\n{\n\tauto context = std::make_shared(1);\n\treactor r(context);\n\tauto handler = pluggable_handler::create([](const message_container &msg, handler_interface::response_cb respond) { });\n\n\tr.add_async_handler({r.KEY_TIMER}, handler);\n\n\tstd::thread thread([&r]() { r.start_loop(); });\n\tstd::this_thread::sleep_for(std::chrono::milliseconds(200));\n\n\tASSERT_GE(1, handler->received.size());\n\n\tr.terminate();\n\tthread.join();\n}\n\n\/\/ Make sure that messages to asynchronous handlers don't get mixed up\nTEST(reactor, multiple_asynchronous_handlers)\n{\n\tauto context = std::make_shared(1);\n\treactor r(context);\n\n\tauto socket_1 = std::make_shared(context, \"inproc:\/\/asynchronous_handler_1\");\n\tauto socket_2 = std::make_shared(context, \"inproc:\/\/asynchronous_handler_2\");\n\n\tauto handler_1 = pluggable_handler::create([](const message_container &msg, handler_interface::response_cb respond) {});\n\tauto handler_2a = pluggable_handler::create([](const message_container &msg, handler_interface::response_cb respond) {});\n\tauto handler_2b = pluggable_handler::create([](const message_container &msg, handler_interface::response_cb respond) {});\n\n\tsize_t message_count = 100;\n\n\tr.add_socket(\"socket_1\", socket_1);\n\tr.add_socket(\"socket_2\", socket_2);\n\tr.add_async_handler({\"socket_1\"}, handler_1);\n\tr.add_async_handler({\"socket_2\"}, handler_2a);\n\tr.add_async_handler({\"socket_2\"}, handler_2b);\n\n\tstd::thread thread([&r]() { r.start_loop(); });\n\tstd::this_thread::sleep_for(std::chrono::milliseconds(10));\n\n\tfor (size_t i = 0; i < message_count; i++) {\n\t\tsocket_1->send_message_local(message_container(\"\", \"id1\", {\"socket_1\"}));\n\t\tsocket_2->send_message_local(message_container(\"\", \"id1\", {\"socket_2\"}));\n\t}\n\n\tstd::this_thread::sleep_for(std::chrono::milliseconds(10));\n\n\tASSERT_EQ(message_count, handler_1->received.size());\n\tASSERT_EQ(message_count, handler_2a->received.size());\n\tASSERT_EQ(message_count, handler_2b->received.size());\n\n\tfor (size_t i = 0; i < message_count; i++) {\n\t\tEXPECT_EQ(handler_1->received.at(i), message_container(\"socket_1\", \"id1\", {\"socket_1\"}));\n\t\tEXPECT_EQ(handler_2a->received.at(i), message_container(\"socket_2\", \"id1\", {\"socket_2\"}));\n\t\tEXPECT_EQ(handler_2b->received.at(i), message_container(\"socket_2\", \"id1\", {\"socket_2\"}));\n\t}\n\n\tr.terminate();\n\tthread.join();\n}\n<|endoftext|>"} {"text":"#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"Render\/GeometryManagement\/SimpleGeometry.hh\"\n\n#define DEFERRED_SHADING_SCREEN_VERTEX \"deferred_shading\/deferred_shader_screen.vp\"\n#define DEFERRED_SHADING_SCREEN_FRAG \"deferred_shading\/deferred_shader_screen.fp\"\n\nnamespace AGE\n{\n\tenum Programs\n\t{\n\t\tPROGRAM_SCREEN = 0,\n\t\tPROGRAM_NBR\n\t};\n\n\tDeferredOnScreen::DeferredOnScreen(glm::uvec2 const &screenSize, std::shared_ptr painterManager,\n\t\tstd::shared_ptr diffuse) :\n\t\tScreenRender(screenSize, painterManager)\n\t{\n\t\t_diffuseInput = diffuse;\n\n\t\t_programs.resize(PROGRAM_NBR);\n\n\t\tauto confManager = GetEngine()->getInstance();\n\n\t\tauto shaderPath = confManager->getConfiguration(\"ShadersPath\");\n\n\t\t\/\/ you have to set shader directory in configuration path\n\t\tAGE_ASSERT(shaderPath != nullptr);\n\n\t\tauto vertexShaderPath = shaderPath->getValue() + DEFERRED_SHADING_SCREEN_VERTEX;\n\t\tauto fragmentShaderPath = shaderPath->getValue() + DEFERRED_SHADING_SCREEN_FRAG;\n\n\t\t_programs[PROGRAM_SCREEN] = std::make_shared(Program(std::string(\"basic_3d_render\"),\n\t\t{\n\t\t\tstd::make_shared(vertexShaderPath, GL_VERTEX_SHADER),\n\t\t\tstd::make_shared(fragmentShaderPath, GL_FRAGMENT_SHADER)\n\t\t}));\n\n\t\tKey quadPainterKey;\n\n\t\tGetRenderThread()->getQuadGeometry(_quadVertices, quadPainterKey);\n\t\t_quadPainter = _painterManager->get_painter(quadPainterKey);\n\t}\n\n\tvoid DeferredOnScreen::renderPass(const DRBCameraDrawableList &infos)\n\t{\n\t\tSCOPE_profile_gpu_i(\"DefferedOnScreen\");\n\t\tSCOPE_profile_cpu_function(\"RenderTime\", \"DefferedOnScreen\");\n\t\t_programs[PROGRAM_SCREEN]->use();\n\t\t_programs[PROGRAM_SCREEN]->get_resource(\"screen\").set(_diffuseInput);\n\n\t\tOpenGLState::glDisable(GL_BLEND);\n\t\tOpenGLState::glDisable(GL_CULL_FACE);\n\t\tOpenGLState::glDisable(GL_DEPTH_TEST);\n\t\tOpenGLState::glDisable(GL_STENCIL_TEST);\n\t\t{\n\t\t\tSCOPE_profile_gpu_i(\"Overhead pipeline\");\n\t\t\tSCOPE_profile_cpu_function(\"RenderTime\", \"Overhead pipeline\");\n\t\t\t_programs[PROGRAM_SCREEN]->get_resource(\"resolution\").set(glm::vec2(viewport.x, viewport.y));\n\t\t\t_programs[PROGRAM_SCREEN]->get_resource(\"activated\").set(infos.cameraInfos.data.fxaa == true ? 1.0f : 0.f);\n\t\t}\n\n\t\t_quadPainter->uniqueDrawBegin(_programs[PROGRAM_SCREEN]);\n\t\t_quadPainter->uniqueDraw(GL_TRIANGLES, _programs[PROGRAM_SCREEN], Properties(), _quadVertices);\n\t\t_quadPainter->uniqueDrawEnd();\n\t}\n\n}\nWarning removed#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"Render\/GeometryManagement\/SimpleGeometry.hh\"\n\n#define DEFERRED_SHADING_SCREEN_VERTEX \"deferred_shading\/deferred_shader_screen.vp\"\n#define DEFERRED_SHADING_SCREEN_FRAG \"deferred_shading\/deferred_shader_screen.fp\"\n\nnamespace AGE\n{\n\tenum Programs\n\t{\n\t\tPROGRAM_SCREEN = 0,\n\t\tPROGRAM_NBR\n\t};\n\n\tDeferredOnScreen::DeferredOnScreen(glm::uvec2 const &screenSize, std::shared_ptr painterManager,\n\t\tstd::shared_ptr diffuse) :\n\t\tScreenRender(screenSize, painterManager)\n\t{\n\t\t_diffuseInput = diffuse;\n\n\t\t_programs.resize(PROGRAM_NBR);\n\n\t\tauto confManager = GetEngine()->getInstance();\n\n\t\tauto shaderPath = confManager->getConfiguration(\"ShadersPath\");\n\n\t\t\/\/ you have to set shader directory in configuration path\n\t\tAGE_ASSERT(shaderPath != nullptr);\n\n\t\tauto vertexShaderPath = shaderPath->getValue() + DEFERRED_SHADING_SCREEN_VERTEX;\n\t\tauto fragmentShaderPath = shaderPath->getValue() + DEFERRED_SHADING_SCREEN_FRAG;\n\n\t\t_programs[PROGRAM_SCREEN] = std::make_shared(Program(std::string(\"basic_3d_render\"),\n\t\t{\n\t\t\tstd::make_shared(vertexShaderPath, GL_VERTEX_SHADER),\n\t\t\tstd::make_shared(fragmentShaderPath, GL_FRAGMENT_SHADER)\n\t\t}));\n\n\t\tKey quadPainterKey;\n\n\t\tGetRenderThread()->getQuadGeometry(_quadVertices, quadPainterKey);\n\t\t_quadPainter = _painterManager->get_painter(quadPainterKey);\n\t}\n\n\tvoid DeferredOnScreen::renderPass(const DRBCameraDrawableList &infos)\n\t{\n\t\tSCOPE_profile_gpu_i(\"DefferedOnScreen\");\n\t\tSCOPE_profile_cpu_function(\"RenderTime\");\n\t\t_programs[PROGRAM_SCREEN]->use();\n\t\t_programs[PROGRAM_SCREEN]->get_resource(\"screen\").set(_diffuseInput);\n\n\t\tOpenGLState::glDisable(GL_BLEND);\n\t\tOpenGLState::glDisable(GL_CULL_FACE);\n\t\tOpenGLState::glDisable(GL_DEPTH_TEST);\n\t\tOpenGLState::glDisable(GL_STENCIL_TEST);\n\t\t{\n\t\t\tSCOPE_profile_gpu_i(\"Overhead pipeline\");\n\t\t\tSCOPE_profile_cpu_i(\"RenderTime\", \"Overhead pipeline\");\n\t\t\t_programs[PROGRAM_SCREEN]->get_resource(\"resolution\").set(glm::vec2(viewport.x, viewport.y));\n\t\t\t_programs[PROGRAM_SCREEN]->get_resource(\"activated\").set(infos.cameraInfos.data.fxaa == true ? 1.0f : 0.f);\n\t\t}\n\n\t\t_quadPainter->uniqueDrawBegin(_programs[PROGRAM_SCREEN]);\n\t\t_quadPainter->uniqueDraw(GL_TRIANGLES, _programs[PROGRAM_SCREEN], Properties(), _quadVertices);\n\t\t_quadPainter->uniqueDrawEnd();\n\t}\n\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \"level.h\"\n\n#define CHUNK_TABLE 0x14\n\n\/\/ TODO: spin this shit into an actual file class like KALE\/KDCE have\nbool bigEndian = false;\n\ntypedef uint16_t u16;\ntypedef int16_t i16;\ntypedef uint32_t u32;\ntypedef int32_t i32;\n\ntemplate type readNum(QFile &file) {\n type num;\n file.read((char*)&num, sizeof(type));\n\n if (bigEndian)\n return qFromBigEndian((uchar*)&num);\n\n return num;\n}\n\nuint chunkOffset(QFile &file, uint chunk) {\n file.seek(CHUNK_TABLE + (4 * chunk));\n return readNum(file);\n}\n\nvoid seekChunk(QFile& file, uint chunk) {\n file.seek(chunkOffset(file, chunk));\n}\n\nvoid LevelData::loadBreakable(QFile &file, uint chunk) {\n\n seekChunk(file, chunk);\n \/\/ read width\/height\n uint width = readNum(file);\n uint height = readNum(file);\n\n this->width = width;\n this->height = height;\n\n this->blocks.resize(height);\n \/\/ read info\n for (int y = height - 1; y >= 0; y--) {\n this->blocks[y].resize(width);\n for (uint x = 0; x < width; x++) {\n this->blocks[y][x].breakable = readNum(file);\n }\n }\n}\n\nvoid LevelData::loadCollision(QFile &file, uint chunk) {\n\n seekChunk(file, chunk);\n \/\/ read pointer\n uint ptr = readNum(file);\n file.seek(ptr);\n \/\/ read info\n uint width = readNum(file);\n uint height = readNum(file);\n\n \/\/ is there a mismatch between the width\/height given here and elsewhere?\n if (width != this->width || height != this->height)\n printf(\"data3 size mismatch: (%u, %u) != (%u, %u)\\n\",\n this->width, this->height, width, height);\n\n for (int y = height - 1; y >= 0; y--) {\n for (uint x = 0; x < width; x++) {\n this->blocks[y][x].collision = readNum(file);\n }\n }\n}\n\nvoid LevelData::loadCollisionRTDL(QFile &file, uint chunk) {\n\n seekChunk(file, chunk);\n\n \/\/ dunno what these are\n \/\/ (this is the only difference between this part and its\n \/\/ corresponding part in Triple Deluxe)\n printf(\"RTDL chunk 3 unknown = 0x%X\\n\", readNum(file));\n\n \/\/ read pointer\n uint ptr = readNum(file);\n file.seek(ptr);\n\n \/\/ read info\n uint width = readNum(file);\n uint height = readNum(file);\n\n \/\/ do this here since it's the first chunk read for RTDL right now\n this->width = width;\n this->height = height;\n this->blocks.resize(height);\n\n \/\/ is there a mismatch between the width\/height given here and elsewhere?\n if (width != this->width || height != this->height)\n printf(\"data3 size mismatch: (%u, %u) != (%u, %u)\\n\",\n this->width, this->height, width, height);\n\n for (int y = height - 1; y >= 0; y--) {\n \/\/ do this here too for now\n this->blocks[y].resize(width);\n for (uint x = 0; x < width; x++) {\n uint tileInfo = readNum(file);\n \/\/ i don't know how this shit works but this should at least give\n \/\/ us something to look at (pretty sure it's a bitfield but it doesn't\n \/\/ work the same way as TDX's collision data does for drawing purposes\n \/\/ but this might give us the same sort of view...\n this->blocks[y][x].collision = tileInfo >> 24;\n\n \/\/ and this (TODO: read the actual breakable data from somewhere)\n this->blocks[y][x].breakable = -1;\n }\n }\n}\n\nvoid LevelData::loadVisual(QFile &file, uint chunk) {\n uint ptrs[3];\n\n seekChunk(file, chunk);\n \/\/ get two unknown values\n this->unknown1 = readNum(file);\n this->unknown2 = readNum(file);\n printf(\"chunk 4 unknown 1 = 0x%X unknown 2 = 0x%X\\n\", this->unknown1, this->unknown2);\n \/\/ get pointers to body\n ptrs[0] = readNum(file);\n ptrs[1] = readNum(file);\n ptrs[2] = readNum(file);\n \/\/ get data\n for (uint i = 0; i < 3; i++) {\n file.seek(ptrs[i]);\n uint width = readNum(file);\n uint height = readNum(file);\n\n \/\/ is there a mismatch between the width\/height given here and elsewhere?\n if (width != this->width || height != this->height)\n printf(\"data4 size mismatch (body %u): (%u, %u) != (%u, %u)\\n\",\n i, this->width, this->height, width, height);\n\n this->blocks.resize(height);\n for (int y = height - 1; y >= 0; y--) {\n for (uint x = 0; x < width && this->width; x++) {\n this->blocks[y].resize(width);\n this->blocks[y][x].visual[i].first = readNum(file);\n this->blocks[y][x].visual[i].second = readNum(file);\n }\n }\n }\n\n}\n\nvoid LevelData::loadEnemies(QFile &file, uint chunk) {\n\n seekChunk(file, chunk);\n uint count = readNum(file);\n for (uint i = 0; i < count; i++) {\n enemy_t enemy;\n\n \/\/ save position, read name\n uint namePtr = readNum(file);\n uint tempPtr = file.pos();\n file.seek(namePtr);\n uint size = readNum(file);\n enemy.name = file.read(size);\n\n \/\/ seek back\n file.seek(tempPtr);\n\n \/\/ TODO: update with known fields\n enemy.data1[0] = readNum(file);\n enemy.data1[1] = readNum(file);\n enemy.data1[2] = readNum(file);\n\n enemy.type = readNum(file);\n enemy.x = readNum(file);\n enemy.y = readNum(file);\n\n enemy.data2[0] = readNum(file);\n enemy.data2[1] = readNum(file);\n\n this->enemies.push_back(enemy);\n }\n}\n\nvoid LevelData::loadEnemyTypes(QFile &file, uint chunk) {\n\n seekChunk(file, chunk);\n uint count = readNum(file);\n for (uint i = 0; i < count; i++) {\n enemytype_t type;\n \/\/ name pointer\n uint namePtr = readNum(file);\n \/\/ state pointer\n uint statePtr = readNum(file);\n\n \/\/ save pos\n uint tempPtr = file.pos();\n\n \/\/ get name\n file.seek(namePtr);\n uint size = readNum(file);\n type.name = file.read(size);\n \/\/ get state\n file.seek(statePtr);\n size = readNum(file);\n type.state = file.read(size);\n\n this->enemyTypes.push_back(type);\n\n \/\/ seek back\n file.seek(tempPtr);\n }\n}\n\nvoid LevelData::loadMusic(QFile &file, uint chunk) {\n\n \/\/ TODO: other stuff besides filename, maybe\n seekChunk(file, chunk);\n uint ptr = readNum(file);\n file.seek(ptr);\n uint count= readNum(file);\n this->musicName = file.read(count);\n}\n\nvoid LevelData::loadObjects(QFile &file, uint chunk) {\n\n seekChunk(file, chunk);\n uint objListPtr = readNum(file);\n uint nameListPtr = readNum(file);\n \/\/ object table\n file.seek(objListPtr);\n uint count = readNum(file);\n\n this->objects.resize(count);\n for (uint i = 0; i < count; i++) {\n \/\/ TODO: update with known fields\n this->objects[i].x = readNum(file);\n this->objects[i].y = readNum(file);\n this->objects[i].type = readNum(file);\n\n this->objects[i].unknown = readNum(file);\n this->objects[i].enabled = readNum(file);\n\n for (uint j = 0; j < 8; j++) {\n this->objects[i].params[j] = readNum(file);\n }\n }\n \/\/ object names\n file.seek(nameListPtr);\n count = readNum(file);\n\n this->objectNames.resize(count);\n for (uint i = 0; i < count; i++) {\n uint namePtr = readNum(file);\n uint tempPtr = file.pos();\n file.seek(namePtr);\n uint size = readNum(file);\n this->objectNames[i] = file.read(size);\n file.seek(tempPtr);\n }\n}\n\nvoid LevelData::loadItems(QFile &file, uint chunk) {\n\n seekChunk(file, chunk);\n uint count = readNum(file);\n this->items.resize(count);\n for (uint i = 0; i < count; i++) {\n for (uint j = 0; j < 3; j++) {\n this->items[i].data[j] = readNum(file);\n }\n this->items[i].x = readNum(file);\n this->items[i].y = readNum(file);\n this->items[i].data2 = readNum(file);\n }\n}\n\nbool LevelData::open(QFile& file) {\n this->clear();\n\n file.seek(4);\n bigEndian = file.read(2) == \"\\x12\\x34\";\n\n if (!bigEndian && chunkOffset(file, 9) == 0x12345678) {\n \/\/ main game map\n loadBreakable(file, 0);\n \/\/ TODO: check if map data 2 is ever actually used\n loadCollision(file, 2);\n loadVisual(file, 3);\n loadEnemies(file, 4);\n loadEnemyTypes(file, 5);\n loadMusic(file, 6);\n loadObjects(file, 7);\n loadItems(file, 8);\n } else if (!bigEndian && chunkOffset(file, 5) == 0x12345678) {\n \/\/ Kirby Fighters map\n loadBreakable(file, 0);\n loadCollision(file, 1);\n loadVisual(file, 2);\n loadMusic(file, 3);\n loadObjects(file, 4);\n } else if (bigEndian && chunkOffset(file, 9) == 0x12345678) {\n \/\/ Return to Dream Land map\n \/\/ just a test...\n loadCollisionRTDL(file, 2);\n loadVisual(file, 4);\n } else {\n QMessageBox::critical(0, \"Load Map\", \"Unrecognized map format.\",\n QMessageBox::Ok);\n return false;\n }\n\n fflush(stdout);\n return true;\n}\n\nvoid LevelData::clear() {\n this->width = 0;\n this->height = 0;\n\n this->musicName = \"\";\n\n this->blocks.clear();\n this->enemyTypes.clear();\n this->enemies.clear();\n this->objects.clear();\n this->objectNames.clear();\n this->items.clear();\n}\nten little endians#include \n#include \n#include \n#include \"level.h\"\n\n#define CHUNK_TABLE 0x14\n\n\/\/ TODO: spin this shit into an actual file class like KALE\/KDCE have\nbool bigEndian = false;\n\ntypedef uint16_t u16;\ntypedef int16_t i16;\ntypedef uint32_t u32;\ntypedef int32_t i32;\n\ntemplate type readNum(QFile &file) {\n type num;\n file.read((char*)&num, sizeof(type));\n\n if (bigEndian)\n return qFromBigEndian((uchar*)&num);\n\n return qFromLittleEndian((uchar*)&num);\n}\n\nuint chunkOffset(QFile &file, uint chunk) {\n file.seek(CHUNK_TABLE + (4 * chunk));\n return readNum(file);\n}\n\nvoid seekChunk(QFile& file, uint chunk) {\n file.seek(chunkOffset(file, chunk));\n}\n\nvoid LevelData::loadBreakable(QFile &file, uint chunk) {\n\n seekChunk(file, chunk);\n \/\/ read width\/height\n uint width = readNum(file);\n uint height = readNum(file);\n\n this->width = width;\n this->height = height;\n\n this->blocks.resize(height);\n \/\/ read info\n for (int y = height - 1; y >= 0; y--) {\n this->blocks[y].resize(width);\n for (uint x = 0; x < width; x++) {\n this->blocks[y][x].breakable = readNum(file);\n }\n }\n}\n\nvoid LevelData::loadCollision(QFile &file, uint chunk) {\n\n seekChunk(file, chunk);\n \/\/ read pointer\n uint ptr = readNum(file);\n file.seek(ptr);\n \/\/ read info\n uint width = readNum(file);\n uint height = readNum(file);\n\n \/\/ is there a mismatch between the width\/height given here and elsewhere?\n if (width != this->width || height != this->height)\n printf(\"data3 size mismatch: (%u, %u) != (%u, %u)\\n\",\n this->width, this->height, width, height);\n\n for (int y = height - 1; y >= 0; y--) {\n for (uint x = 0; x < width; x++) {\n this->blocks[y][x].collision = readNum(file);\n }\n }\n}\n\nvoid LevelData::loadCollisionRTDL(QFile &file, uint chunk) {\n\n seekChunk(file, chunk);\n\n \/\/ dunno what these are\n \/\/ (this is the only difference between this part and its\n \/\/ corresponding part in Triple Deluxe)\n printf(\"RTDL chunk 3 unknown = 0x%X\\n\", readNum(file));\n\n \/\/ read pointer\n uint ptr = readNum(file);\n file.seek(ptr);\n\n \/\/ read info\n uint width = readNum(file);\n uint height = readNum(file);\n\n \/\/ do this here since it's the first chunk read for RTDL right now\n this->width = width;\n this->height = height;\n this->blocks.resize(height);\n\n \/\/ is there a mismatch between the width\/height given here and elsewhere?\n if (width != this->width || height != this->height)\n printf(\"data3 size mismatch: (%u, %u) != (%u, %u)\\n\",\n this->width, this->height, width, height);\n\n for (int y = height - 1; y >= 0; y--) {\n \/\/ do this here too for now\n this->blocks[y].resize(width);\n for (uint x = 0; x < width; x++) {\n uint tileInfo = readNum(file);\n \/\/ i don't know how this shit works but this should at least give\n \/\/ us something to look at (pretty sure it's a bitfield but it doesn't\n \/\/ work the same way as TDX's collision data does for drawing purposes\n \/\/ but this might give us the same sort of view...\n this->blocks[y][x].collision = tileInfo >> 24;\n\n \/\/ and this (TODO: read the actual breakable data from somewhere)\n this->blocks[y][x].breakable = -1;\n }\n }\n}\n\nvoid LevelData::loadVisual(QFile &file, uint chunk) {\n uint ptrs[3];\n\n seekChunk(file, chunk);\n \/\/ get two unknown values\n this->unknown1 = readNum(file);\n this->unknown2 = readNum(file);\n printf(\"chunk 4 unknown 1 = 0x%X unknown 2 = 0x%X\\n\", this->unknown1, this->unknown2);\n \/\/ get pointers to body\n ptrs[0] = readNum(file);\n ptrs[1] = readNum(file);\n ptrs[2] = readNum(file);\n \/\/ get data\n for (uint i = 0; i < 3; i++) {\n file.seek(ptrs[i]);\n uint width = readNum(file);\n uint height = readNum(file);\n\n \/\/ is there a mismatch between the width\/height given here and elsewhere?\n if (width != this->width || height != this->height)\n printf(\"data4 size mismatch (body %u): (%u, %u) != (%u, %u)\\n\",\n i, this->width, this->height, width, height);\n\n this->blocks.resize(height);\n for (int y = height - 1; y >= 0; y--) {\n for (uint x = 0; x < width && this->width; x++) {\n this->blocks[y].resize(width);\n this->blocks[y][x].visual[i].first = readNum(file);\n this->blocks[y][x].visual[i].second = readNum(file);\n }\n }\n }\n\n}\n\nvoid LevelData::loadEnemies(QFile &file, uint chunk) {\n\n seekChunk(file, chunk);\n uint count = readNum(file);\n for (uint i = 0; i < count; i++) {\n enemy_t enemy;\n\n \/\/ save position, read name\n uint namePtr = readNum(file);\n uint tempPtr = file.pos();\n file.seek(namePtr);\n uint size = readNum(file);\n enemy.name = file.read(size);\n\n \/\/ seek back\n file.seek(tempPtr);\n\n \/\/ TODO: update with known fields\n enemy.data1[0] = readNum(file);\n enemy.data1[1] = readNum(file);\n enemy.data1[2] = readNum(file);\n\n enemy.type = readNum(file);\n enemy.x = readNum(file);\n enemy.y = readNum(file);\n\n enemy.data2[0] = readNum(file);\n enemy.data2[1] = readNum(file);\n\n this->enemies.push_back(enemy);\n }\n}\n\nvoid LevelData::loadEnemyTypes(QFile &file, uint chunk) {\n\n seekChunk(file, chunk);\n uint count = readNum(file);\n for (uint i = 0; i < count; i++) {\n enemytype_t type;\n \/\/ name pointer\n uint namePtr = readNum(file);\n \/\/ state pointer\n uint statePtr = readNum(file);\n\n \/\/ save pos\n uint tempPtr = file.pos();\n\n \/\/ get name\n file.seek(namePtr);\n uint size = readNum(file);\n type.name = file.read(size);\n \/\/ get state\n file.seek(statePtr);\n size = readNum(file);\n type.state = file.read(size);\n\n this->enemyTypes.push_back(type);\n\n \/\/ seek back\n file.seek(tempPtr);\n }\n}\n\nvoid LevelData::loadMusic(QFile &file, uint chunk) {\n\n \/\/ TODO: other stuff besides filename, maybe\n seekChunk(file, chunk);\n uint ptr = readNum(file);\n file.seek(ptr);\n uint count= readNum(file);\n this->musicName = file.read(count);\n}\n\nvoid LevelData::loadObjects(QFile &file, uint chunk) {\n\n seekChunk(file, chunk);\n uint objListPtr = readNum(file);\n uint nameListPtr = readNum(file);\n \/\/ object table\n file.seek(objListPtr);\n uint count = readNum(file);\n\n this->objects.resize(count);\n for (uint i = 0; i < count; i++) {\n \/\/ TODO: update with known fields\n this->objects[i].x = readNum(file);\n this->objects[i].y = readNum(file);\n this->objects[i].type = readNum(file);\n\n this->objects[i].unknown = readNum(file);\n this->objects[i].enabled = readNum(file);\n\n for (uint j = 0; j < 8; j++) {\n this->objects[i].params[j] = readNum(file);\n }\n }\n \/\/ object names\n file.seek(nameListPtr);\n count = readNum(file);\n\n this->objectNames.resize(count);\n for (uint i = 0; i < count; i++) {\n uint namePtr = readNum(file);\n uint tempPtr = file.pos();\n file.seek(namePtr);\n uint size = readNum(file);\n this->objectNames[i] = file.read(size);\n file.seek(tempPtr);\n }\n}\n\nvoid LevelData::loadItems(QFile &file, uint chunk) {\n\n seekChunk(file, chunk);\n uint count = readNum(file);\n this->items.resize(count);\n for (uint i = 0; i < count; i++) {\n for (uint j = 0; j < 3; j++) {\n this->items[i].data[j] = readNum(file);\n }\n this->items[i].x = readNum(file);\n this->items[i].y = readNum(file);\n this->items[i].data2 = readNum(file);\n }\n}\n\nbool LevelData::open(QFile& file) {\n this->clear();\n\n file.seek(4);\n bigEndian = file.read(2) == \"\\x12\\x34\";\n\n if (!bigEndian && chunkOffset(file, 9) == 0x12345678) {\n \/\/ main game map\n loadBreakable(file, 0);\n \/\/ TODO: check if map data 2 is ever actually used\n loadCollision(file, 2);\n loadVisual(file, 3);\n loadEnemies(file, 4);\n loadEnemyTypes(file, 5);\n loadMusic(file, 6);\n loadObjects(file, 7);\n loadItems(file, 8);\n } else if (!bigEndian && chunkOffset(file, 5) == 0x12345678) {\n \/\/ Kirby Fighters map\n loadBreakable(file, 0);\n loadCollision(file, 1);\n loadVisual(file, 2);\n loadMusic(file, 3);\n loadObjects(file, 4);\n } else if (bigEndian && chunkOffset(file, 9) == 0x12345678) {\n \/\/ Return to Dream Land map\n \/\/ just a test...\n loadCollisionRTDL(file, 2);\n loadVisual(file, 4);\n } else {\n QMessageBox::critical(0, \"Load Map\", \"Unrecognized map format.\",\n QMessageBox::Ok);\n return false;\n }\n\n fflush(stdout);\n return true;\n}\n\nvoid LevelData::clear() {\n this->width = 0;\n this->height = 0;\n\n this->musicName = \"\";\n\n this->blocks.clear();\n this->enemyTypes.clear();\n this->enemies.clear();\n this->objects.clear();\n this->objectNames.clear();\n this->items.clear();\n}\n<|endoftext|>"} {"text":"\/**\n * Function.cpp\n *\n * Implementation for the function class\n *\n * @author Emiel Bruijntjes \n * @copyright 2013 Copernica BV\n *\/\n#include \"includes.h\"\n\n\/**\n * Set up namespace\n *\/\nnamespace Php {\n\n\/**\n * Function that is called by the Zend engine every time that a function gets called\n * @param ht\n * @param return_value\n * @param return_value_ptr\n * @param this_ptr\n * @param return_value_used\n * @param tsrm_ls\n * @return integer\n *\/\nvoid Callable::invoke(INTERNAL_FUNCTION_PARAMETERS)\n{\n \/\/ find the function name\n const char *name = get_active_function_name(TSRMLS_C);\n \n \/\/ uncover the hidden pointer inside the function name\n Callable *callable = HiddenPointer(name);\n\n \/\/ construct parameters\n ParametersImpl params(this_ptr, ZEND_NUM_ARGS() TSRMLS_CC);\n\n \/\/ the function could throw an exception\n try\n {\n \/\/ get the result\n Value result(callable->invoke(params));\n \n \/\/ detach the zval (we don't want it to be destructed)\n zval *val = result.detach();\n \n \/\/ @todo php 5.6 has a RETVAL_ZVAL_FAST macro that can be used instead (and is faster)\n \n \/\/ return a full copy of the zval, and do not destruct it\n RETVAL_ZVAL(val, 1, 0);\n }\n catch (Exception &exception)\n {\n \/\/ process the exception\n process(exception TSRMLS_CC);\n }\n}\n\n\/**\n * Fill a function entry\n * \n * This method is called when the extension is registering itself, when the \n * function or method introces himself\n * \n * @param entry Entry to be filled\n * @param classname Optional class name\n * @param flags Is this a public property?\n *\/\nvoid Callable::initialize(zend_function_entry *entry, const char *classname, int flags) const\n{\n \/\/ fill the members of the entity, and hide a pointer to the current object in the name\n entry->fname = (const char *)_ptr;\n entry->handler = &Callable::invoke;\n entry->arg_info = _argv;\n entry->num_args = _argc;\n entry->flags = flags;\n\n \/\/ we should fill the first argument as well\n initialize((zend_arg_info *)entry->arg_info, classname);\n}\n\n\/**\n * Fill a function entry\n * @param info Info to be filled\n * @param classname Optional classname\n *\/\nvoid Callable::initialize(zend_arg_info *info, const char *classname) const\n{\n#if PHP_VERSION_ID >= 50400\n \/\/ up until php 5.3, the first info object is filled with alternative information,\n \/\/ later it is casted to a zend_internal_function object\n auto *finfo = (zend_internal_function_info *)info;\n \n \/\/ fill in all the members, note that return reference is false by default,\n \/\/ because we do not support returning references in PHP-CPP, although Zend\n \/\/ engine allows it. Inside the name we hide a pointer to the current object\n finfo->_name = _ptr;\n finfo->_name_len = ::strlen(_ptr);\n finfo->_class_name = classname;\n\n \/\/ number of required arguments, and the expected return type\n finfo->required_num_args = _required;\n finfo->_type_hint = (unsigned char)_return;\n\n \/\/ we do not support return-by-reference\n finfo->return_reference = false;\n \n# if PHP_VERSION_ID >= 50600\n \/\/ since php 5.6 there are _allow_null and _is_variadic properties. It's\n \/\/ not exactly clear what they do (@todo find this out) so for now we set\n \/\/ them to false\n finfo->_allow_null = false;\n finfo->_is_variadic = false;\n\n# else\n \/\/ passing by reference is not used (only for php 5.4 and php 5.5)\n finfo->pass_rest_by_reference = false;\n# endif\n\n#else\n \/\/ php 5.3 code\n info->name = nullptr;\n info->name_len = 0;\n info->class_name = nullptr;\n info->class_name_len = 0;\n info->array_type_hint = false;\n info->allow_null = false;\n info->pass_by_reference = false;\n info->return_reference = false;\n info->required_num_args = _required;\n#endif\n}\n\n\/**\n * End of namespace\n *\/\n}\n\n\ngenerate warning when a function is called with not enough parameters\/**\n * Function.cpp\n *\n * Implementation for the function class\n *\n * @author Emiel Bruijntjes \n * @copyright 2013 Copernica BV\n *\/\n#include \"includes.h\"\n\n\/**\n * Set up namespace\n *\/\nnamespace Php {\n\n\/**\n * Function that is called by the Zend engine every time that a function gets called\n * @param ht\n * @param return_value\n * @param return_value_ptr\n * @param this_ptr\n * @param return_value_used\n * @param tsrm_ls\n * @return integer\n *\/\nvoid Callable::invoke(INTERNAL_FUNCTION_PARAMETERS)\n{\n \/\/ find the function name\n const char *name = get_active_function_name(TSRMLS_C);\n \n \/\/ uncover the hidden pointer inside the function name\n Callable *callable = HiddenPointer(name);\n\n \/\/ check if sufficient parameters were passed (for some reason this check\n \/\/ is not done by Zend, so we do it here ourselves)\n if (ZEND_NUM_ARGS() < callable->_required)\n {\n \/\/ PHP itself only generates a warning when this happens, so we do the same too\n Php::warning << name << \"() expects at least \" << callable->_required << \" parameters, \" << ZEND_NUM_ARGS() << \" given\" << std::flush;\n\n \/\/ and we return null\n RETURN_NULL();\n }\n else\n {\n \/\/ construct parameters\n ParametersImpl params(this_ptr, ZEND_NUM_ARGS() TSRMLS_CC);\n\n \/\/ the function could throw an exception\n try\n {\n \/\/ get the result\n Value result(callable->invoke(params));\n \n \/\/ detach the zval (we don't want it to be destructed)\n zval *val = result.detach();\n \n \/\/ @todo php 5.6 has a RETVAL_ZVAL_FAST macro that can be used instead (and is faster)\n \n \/\/ return a full copy of the zval, and do not destruct it\n RETVAL_ZVAL(val, 1, 0);\n }\n catch (Exception &exception)\n {\n \/\/ process the exception\n process(exception TSRMLS_CC);\n }\n }\n}\n\n\/**\n * Fill a function entry\n * \n * This method is called when the extension is registering itself, when the \n * function or method introces himself\n * \n * @param entry Entry to be filled\n * @param classname Optional class name\n * @param flags Is this a public property?\n *\/\nvoid Callable::initialize(zend_function_entry *entry, const char *classname, int flags) const\n{\n \/\/ fill the members of the entity, and hide a pointer to the current object in the name\n entry->fname = (const char *)_ptr;\n entry->handler = &Callable::invoke;\n entry->arg_info = _argv;\n entry->num_args = _argc;\n entry->flags = flags;\n\n \/\/ we should fill the first argument as well\n initialize((zend_arg_info *)entry->arg_info, classname);\n}\n\n\/**\n * Fill a function entry\n * @param info Info to be filled\n * @param classname Optional classname\n *\/\nvoid Callable::initialize(zend_arg_info *info, const char *classname) const\n{\n#if PHP_VERSION_ID >= 50400\n \/\/ up until php 5.3, the first info object is filled with alternative information,\n \/\/ later it is casted to a zend_internal_function object\n auto *finfo = (zend_internal_function_info *)info;\n \n \/\/ fill in all the members, note that return reference is false by default,\n \/\/ because we do not support returning references in PHP-CPP, although Zend\n \/\/ engine allows it. Inside the name we hide a pointer to the current object\n finfo->_name = _ptr;\n finfo->_name_len = ::strlen(_ptr);\n finfo->_class_name = classname;\n\n \/\/ number of required arguments, and the expected return type\n finfo->required_num_args = _required;\n finfo->_type_hint = (unsigned char)_return;\n\n \/\/ we do not support return-by-reference\n finfo->return_reference = false;\n \n# if PHP_VERSION_ID >= 50600\n \/\/ since php 5.6 there are _allow_null and _is_variadic properties. It's\n \/\/ not exactly clear what they do (@todo find this out) so for now we set\n \/\/ them to false\n finfo->_allow_null = false;\n finfo->_is_variadic = false;\n\n# else\n \/\/ passing by reference is not used (only for php 5.4 and php 5.5)\n finfo->pass_rest_by_reference = false;\n# endif\n\n#else\n \/\/ php 5.3 code\n info->name = nullptr;\n info->name_len = 0;\n info->class_name = nullptr;\n info->class_name_len = 0;\n info->array_type_hint = false;\n info->allow_null = false;\n info->pass_by_reference = false;\n info->return_reference = false;\n info->required_num_args = _required;\n#endif\n}\n\n\/**\n * End of namespace\n *\/\n}\n\n\n<|endoftext|>"} {"text":"#include \"lexer.h\"\n\n#include \n\n#include \"lexerexception.h\"\n#include \"log.h\"\n#include \"scriptsource.h\"\n#include \"token.h\"\n#include \"tokenfactory.h\"\n\nnamespace peachy {\n\n Lexer::~Lexer() {\n logger->debug(\"Lexer destructor\");\n }\n\n Token * Lexer::nextToken() {\n logger->debug(\"Lexer::nextToken()\");\n\n Token * token;\n bool gotToken = false;\n\n while(!gotToken) {\n if(atEndOfLine()) {\n logger->debug(\"Overflowed input buffer\");\n throw LexerException(\"Overflowed input buffer\");\n }\n currentChar = currentLine[currentPos];\n switch(state) {\n case LEXER_COMPLETE:\n logger->debug(\"In state LEXER_COMPLETE\");\n token = tokenFactory->createToken(TOKEN_EOF);\n resetToken();\n gotToken = true;\n break;\n case LEXER_DEFAULT:\n logger->debug(\"In state LEXER_DEFAULT\");\n switch(currentChar) {\n case ' ':\n case '\\t':\n logger->debug(\"Whitespace\");\n consume(false);\n break;\n case '\\n':\n case '\\r':\n case NULL:\n logger->debug(\"End of line\");\n resetLine();\n break;\n case ':':\n logger->debug(\"Colon\");\n token = tokenFactory->createToken(TOKEN_COLON);\n resetToken();\n gotToken = true;\n break; \n case '{':\n logger->debug(\"Left brace\");\n token = tokenFactory->createToken(TOKEN_LEFT_BRACE);\n resetToken();\n gotToken = true;\n break;\n case '[':\n logger->debug(\"Left bracket\");\n token = tokenFactory->createToken(TOKEN_LEFT_BRACKET);\n resetToken();\n gotToken = true;\n break;\n case '(':\n logger->debug(\"Left paren\");\n token = tokenFactory->createToken(TOKEN_LEFT_PARENTHESIS);\n resetToken();\n gotToken = true;\n break;\n case '}':\n logger->debug(\"Right brace\");\n token = tokenFactory->createToken(TOKEN_RIGHT_BRACE);\n resetToken();\n gotToken = true;\n break;\n case ']':\n logger->debug(\"Right bracket\");\n token = tokenFactory->createToken(TOKEN_RIGHT_BRACKET);\n resetToken();\n gotToken = true;\n break;\n case ')':\n logger->debug(\"Right paren\");\n token = tokenFactory->createToken(TOKEN_RIGHT_PARENTHESIS);\n resetToken();\n gotToken = true;\n break;\n case '#':\n logger->debug(\"Comment line\");\n setState(LEXER_IN_COMMENT_LINE);\n consume(false);\n break;\n case '\"':\n logger->debug(\"Start of string\");\n setState(LEXER_IN_STRING);\n consume(false);\n break;\n default:\n if(isNumeric(currentChar)) {\n logger->debug(\"Current char is a number\");\n setState(LEXER_IN_NUMBER);\n consume(true);\n } else if(isLetter(currentChar)) {\n logger->debug(\"Current char is a letter\");\n setState(LEXER_IN_IDENTIFIER);\n consume(true);\n } else if(isOperatorChar(currentChar)) {\n logger->debug(\"Current char is an operator\");\n setState(LEXER_IN_OPERATOR);\n consume(true);\n } else {\n throw LexerException(\n std::string(\"Invalid character encountered: \").append(\n 1, currentChar));\n }\n }\n break;\n case LEXER_IN_STRING:\n logger->debug(\"In state LEXER_IN_STRING\");\n switch(currentChar) {\n case '\"':\n logger->debug(\"End quote\");\n token = tokenFactory->createToken(TOKEN_STRING, currentSequence);\n consume(false);\n resetToken();\n gotToken = true;\n break;\n case 0:\n logger->debug(\"Newline found\");\n currentSequence.append(1, '\\n');\n logger->debug(currentSequence);\n if(!scriptSource->hasMoreLines()) {\n logger->debug(\"End of input but still inside string\");\n throw LexerException(\"Input terminated inside open string\");\n } else {\n logger->debug(\"Getting a new line from script source\");\n setCurrentLine(scriptSource->getLine());\n currentPos = 0;\n }\n break;\n default:\n logger->debug(\"Ordinary character\");\n consume(true);\n logger->debug(currentSequence);\n break;\n }\n break;\n case LEXER_IN_NUMBER:\n logger->debug(\"In state LEXER_IN_NUMBER\");\n if(isNumeric(currentChar)) {\n logger->debug(\"Another digit of the current number\");\n consume(true);\n } else {\n logger->debug(\"End of number\");\n token = tokenFactory->createToken(TOKEN_NUMBER, currentSequence);\n resetToken();\n gotToken = true;\n }\n break;\n case LEXER_IN_IDENTIFIER:\n logger->debug(\"In state LEXER_IN_IDENTIFIER\");\n if(isIdentifier(currentChar)) {\n logger->debug(\"Another character of the current identifier\");\n consume(true);\n } else {\n logger->debug(\"End of identifier\");\n if(isKeyword(currentSequence)) {\n token = tokenFactory->createToken(TOKEN_KEYWORD, currentSequence);\n } else {\n token = tokenFactory->createToken(TOKEN_IDENTIFIER,\n currentSequence);\n }\n resetToken();\n gotToken = true;\n }\n break;\n case LEXER_IN_OPERATOR:\n logger->debug(\"In state LEXER_IN_OPERATOR\");\n if(isOperatorChar(currentChar)) {\n logger->debug(\"Another character of the current operator\");\n consume(true);\n } else if(isNumeric(currentChar) &&\n currentSequence.compare(\"-\") == 0) {\n logger->debug(\"Looks like a negative number\");\n setState(LEXER_IN_NUMBER);\n consume(true);\n } else {\n if(isOperator(currentSequence)) {\n logger->debug(\"End of operator\");\n token = tokenFactory->createToken(TOKEN_OPERATOR, currentSequence);\n resetToken();\n gotToken = true;\n } else {\n logger->debug(\"Invalid operator sequence\");\n throw LexerException(\"Invalid operator sequence\");\n }\n }\n break;\n case LEXER_IN_COMMENT_LINE:\n logger->debug(\"In state LEXER_IN_COMMENT_LINE\");\n if(isLineEnding(currentChar)) {\n logger->debug(\"End of comment\");\n token = tokenFactory->createToken(TOKEN_COMMENT_LINE,\n currentSequence);\n resetToken();\n gotToken = true;\n } else {\n logger->debug(\"Another character of the current comment\");\n consume(true);\n }\n break;\n case LEXER_NEED_INPUT:\n logger->debug(\"In state LEXER_NEED_INPUT\");\n if(!scriptSource->hasMoreLines()) {\n logger->debug(\"End of input\");\n setState(LEXER_COMPLETE);\n } else {\n setCurrentLine(scriptSource->getLine());\n logger->debug(\"Got new line from script source\");\n resetToken();\n }\n break;\n case LEXER_ERROR:\n logger->debug(\"In state LEXER_ERROR\");\n throw LexerException(\"Invalid lexer state\");\n break;\n default:\n logger->debug(\"In an unknown state\");\n setState(LEXER_ERROR);\n break;\n }\n }\n\n return token;\n }\n\n void Lexer::consume(bool appendChar) {\n logger->debug(\"Lexer::consume()\");\n if(appendChar) {\n currentSequence.append(1, currentChar);\n }\n currentPos++;\n }\n\n bool Lexer::atEndOfLine() {\n return(currentPos > currentLine.length());\n }\n\n void Lexer::resetLine() {\n logger->debug(\"Lexer::resetLine()\");\n setState(LEXER_NEED_INPUT);\n currentPos = 0;\n }\n\n void Lexer::resetToken() {\n logger->debug(\"Lexer::resetToken()\");\n setState(LEXER_DEFAULT);\n currentSequence = std::string(\"\");\n }\n\n void Lexer::setState(LexerState state) {\n logger->debug(\"Lexer::setState()\");\n this->state = state;\n }\n\n void Lexer::setCurrentLine(std::string line) {\n logger->debug(\"Lexer::setCurrentLine()\");\n this->currentLine = line;\n }\n\n LexerState Lexer::getState() {\n logger->debug(\"Lexer::getState()\");\n return this->state;\n }\n\n bool Lexer::isNumeric(char c) {\n return (\n c >= '0' &&\n c <= '9'\n );\n }\n\n bool Lexer::isLetter(char c) {\n return (\n ( c >= 'a' && c <= 'z' ) ||\n ( c >= 'A' && c <= 'Z' )\n );\n }\n\n bool Lexer::isOperatorChar(char c) {\n return (\n c == '=' ||\n c == '-' ||\n c == '+' ||\n c == '>' ||\n c == '<' ||\n c == '|'\n );\n }\n\n bool Lexer::isOperator(std::string s) {\n return (\n s.compare(\"<-\") == 0 ||\n s.compare(\"=\") == 0 ||\n s.compare(\">=\") == 0 ||\n s.compare(\"<=\") == 0 ||\n s.compare(\"<\") == 0 ||\n s.compare(\">\") == 0 ||\n s.compare(\"+\") == 0 ||\n s.compare(\"-\") == 0 ||\n s.compare(\"|\") == 0 ||\n s.compare(\"&\") == 0 \n );\n }\n\n bool Lexer::isIdentifier(char c) {\n return (\n isLetter(c) ||\n isNumeric(c) ||\n c == '_'\n );\n }\n\n bool Lexer::isKeyword(std::string s) {\n return (\n s.compare(\"while\") == 0 ||\n s.compare(\"function\") == 0 ||\n s.compare(\"return\") == 0 ||\n s.compare(\"class\") == 0 ||\n s.compare(\"for\") == 0 ||\n s.compare(\"print\") == 0\n );\n }\n\n bool Lexer::isLineEnding(char c) {\n return (\n c == '\\r' ||\n c == '\\n'\n );\n }\n}\n\nAllow multiple calls to Lexer::nextToken to return EOF once EOF is reached#include \"lexer.h\"\n\n#include \n\n#include \"lexerexception.h\"\n#include \"log.h\"\n#include \"scriptsource.h\"\n#include \"token.h\"\n#include \"tokenfactory.h\"\n\nnamespace peachy {\n\n Lexer::~Lexer() {\n logger->debug(\"Lexer destructor\");\n }\n\n Token * Lexer::nextToken() {\n logger->debug(\"Lexer::nextToken()\");\n\n Token * token;\n bool gotToken = false;\n\n while(!gotToken) {\n if(atEndOfLine()) {\n logger->debug(\"Overflowed input buffer\");\n throw LexerException(\"Overflowed input buffer\");\n }\n currentChar = currentLine[currentPos];\n switch(state) {\n case LEXER_COMPLETE:\n logger->debug(\"In state LEXER_COMPLETE\");\n token = tokenFactory->createToken(TOKEN_EOF);\n gotToken = true;\n break;\n case LEXER_DEFAULT:\n logger->debug(\"In state LEXER_DEFAULT\");\n switch(currentChar) {\n case ' ':\n case '\\t':\n logger->debug(\"Whitespace\");\n consume(false);\n break;\n case '\\n':\n case '\\r':\n case NULL:\n logger->debug(\"End of line\");\n resetLine();\n break;\n case ':':\n logger->debug(\"Colon\");\n token = tokenFactory->createToken(TOKEN_COLON);\n resetToken();\n gotToken = true;\n break; \n case '{':\n logger->debug(\"Left brace\");\n token = tokenFactory->createToken(TOKEN_LEFT_BRACE);\n resetToken();\n gotToken = true;\n break;\n case '[':\n logger->debug(\"Left bracket\");\n token = tokenFactory->createToken(TOKEN_LEFT_BRACKET);\n resetToken();\n gotToken = true;\n break;\n case '(':\n logger->debug(\"Left paren\");\n token = tokenFactory->createToken(TOKEN_LEFT_PARENTHESIS);\n resetToken();\n gotToken = true;\n break;\n case '}':\n logger->debug(\"Right brace\");\n token = tokenFactory->createToken(TOKEN_RIGHT_BRACE);\n resetToken();\n gotToken = true;\n break;\n case ']':\n logger->debug(\"Right bracket\");\n token = tokenFactory->createToken(TOKEN_RIGHT_BRACKET);\n resetToken();\n gotToken = true;\n break;\n case ')':\n logger->debug(\"Right paren\");\n token = tokenFactory->createToken(TOKEN_RIGHT_PARENTHESIS);\n resetToken();\n gotToken = true;\n break;\n case '#':\n logger->debug(\"Comment line\");\n setState(LEXER_IN_COMMENT_LINE);\n consume(false);\n break;\n case '\"':\n logger->debug(\"Start of string\");\n setState(LEXER_IN_STRING);\n consume(false);\n break;\n default:\n if(isNumeric(currentChar)) {\n logger->debug(\"Current char is a number\");\n setState(LEXER_IN_NUMBER);\n consume(true);\n } else if(isLetter(currentChar)) {\n logger->debug(\"Current char is a letter\");\n setState(LEXER_IN_IDENTIFIER);\n consume(true);\n } else if(isOperatorChar(currentChar)) {\n logger->debug(\"Current char is an operator\");\n setState(LEXER_IN_OPERATOR);\n consume(true);\n } else {\n throw LexerException(\n std::string(\"Invalid character encountered: \").append(\n 1, currentChar));\n }\n }\n break;\n case LEXER_IN_STRING:\n logger->debug(\"In state LEXER_IN_STRING\");\n switch(currentChar) {\n case '\"':\n logger->debug(\"End quote\");\n token = tokenFactory->createToken(TOKEN_STRING, currentSequence);\n consume(false);\n resetToken();\n gotToken = true;\n break;\n case 0:\n logger->debug(\"Newline found\");\n currentSequence.append(1, '\\n');\n logger->debug(currentSequence);\n if(!scriptSource->hasMoreLines()) {\n logger->debug(\"End of input but still inside string\");\n throw LexerException(\"Input terminated inside open string\");\n } else {\n logger->debug(\"Getting a new line from script source\");\n setCurrentLine(scriptSource->getLine());\n currentPos = 0;\n }\n break;\n default:\n logger->debug(\"Ordinary character\");\n consume(true);\n logger->debug(currentSequence);\n break;\n }\n break;\n case LEXER_IN_NUMBER:\n logger->debug(\"In state LEXER_IN_NUMBER\");\n if(isNumeric(currentChar)) {\n logger->debug(\"Another digit of the current number\");\n consume(true);\n } else {\n logger->debug(\"End of number\");\n token = tokenFactory->createToken(TOKEN_NUMBER, currentSequence);\n resetToken();\n gotToken = true;\n }\n break;\n case LEXER_IN_IDENTIFIER:\n logger->debug(\"In state LEXER_IN_IDENTIFIER\");\n if(isIdentifier(currentChar)) {\n logger->debug(\"Another character of the current identifier\");\n consume(true);\n } else {\n logger->debug(\"End of identifier\");\n if(isKeyword(currentSequence)) {\n token = tokenFactory->createToken(TOKEN_KEYWORD, currentSequence);\n } else {\n token = tokenFactory->createToken(TOKEN_IDENTIFIER,\n currentSequence);\n }\n resetToken();\n gotToken = true;\n }\n break;\n case LEXER_IN_OPERATOR:\n logger->debug(\"In state LEXER_IN_OPERATOR\");\n if(isOperatorChar(currentChar)) {\n logger->debug(\"Another character of the current operator\");\n consume(true);\n } else if(isNumeric(currentChar) &&\n currentSequence.compare(\"-\") == 0) {\n logger->debug(\"Looks like a negative number\");\n setState(LEXER_IN_NUMBER);\n consume(true);\n } else {\n if(isOperator(currentSequence)) {\n logger->debug(\"End of operator\");\n token = tokenFactory->createToken(TOKEN_OPERATOR, currentSequence);\n resetToken();\n gotToken = true;\n } else {\n logger->debug(\"Invalid operator sequence\");\n throw LexerException(\"Invalid operator sequence\");\n }\n }\n break;\n case LEXER_IN_COMMENT_LINE:\n logger->debug(\"In state LEXER_IN_COMMENT_LINE\");\n if(isLineEnding(currentChar)) {\n logger->debug(\"End of comment\");\n token = tokenFactory->createToken(TOKEN_COMMENT_LINE,\n currentSequence);\n resetToken();\n gotToken = true;\n } else {\n logger->debug(\"Another character of the current comment\");\n consume(true);\n }\n break;\n case LEXER_NEED_INPUT:\n logger->debug(\"In state LEXER_NEED_INPUT\");\n if(!scriptSource->hasMoreLines()) {\n logger->debug(\"End of input\");\n setState(LEXER_COMPLETE);\n } else {\n setCurrentLine(scriptSource->getLine());\n logger->debug(\"Got new line from script source\");\n resetToken();\n }\n break;\n case LEXER_ERROR:\n logger->debug(\"In state LEXER_ERROR\");\n throw LexerException(\"Invalid lexer state\");\n break;\n default:\n logger->debug(\"In an unknown state\");\n setState(LEXER_ERROR);\n break;\n }\n }\n\n return token;\n }\n\n void Lexer::consume(bool appendChar) {\n logger->debug(\"Lexer::consume()\");\n if(appendChar) {\n currentSequence.append(1, currentChar);\n }\n currentPos++;\n }\n\n bool Lexer::atEndOfLine() {\n return(currentPos > currentLine.length());\n }\n\n void Lexer::resetLine() {\n logger->debug(\"Lexer::resetLine()\");\n setState(LEXER_NEED_INPUT);\n currentPos = 0;\n }\n\n void Lexer::resetToken() {\n logger->debug(\"Lexer::resetToken()\");\n setState(LEXER_DEFAULT);\n currentSequence = std::string(\"\");\n }\n\n void Lexer::setState(LexerState state) {\n logger->debug(\"Lexer::setState()\");\n this->state = state;\n }\n\n void Lexer::setCurrentLine(std::string line) {\n logger->debug(\"Lexer::setCurrentLine()\");\n this->currentLine = line;\n }\n\n LexerState Lexer::getState() {\n logger->debug(\"Lexer::getState()\");\n return this->state;\n }\n\n bool Lexer::isNumeric(char c) {\n return (\n c >= '0' &&\n c <= '9'\n );\n }\n\n bool Lexer::isLetter(char c) {\n return (\n ( c >= 'a' && c <= 'z' ) ||\n ( c >= 'A' && c <= 'Z' )\n );\n }\n\n bool Lexer::isOperatorChar(char c) {\n return (\n c == '=' ||\n c == '-' ||\n c == '+' ||\n c == '>' ||\n c == '<' ||\n c == '|'\n );\n }\n\n bool Lexer::isOperator(std::string s) {\n return (\n s.compare(\"<-\") == 0 ||\n s.compare(\"=\") == 0 ||\n s.compare(\">=\") == 0 ||\n s.compare(\"<=\") == 0 ||\n s.compare(\"<\") == 0 ||\n s.compare(\">\") == 0 ||\n s.compare(\"+\") == 0 ||\n s.compare(\"-\") == 0 ||\n s.compare(\"|\") == 0 ||\n s.compare(\"&\") == 0 \n );\n }\n\n bool Lexer::isIdentifier(char c) {\n return (\n isLetter(c) ||\n isNumeric(c) ||\n c == '_'\n );\n }\n\n bool Lexer::isKeyword(std::string s) {\n return (\n s.compare(\"while\") == 0 ||\n s.compare(\"function\") == 0 ||\n s.compare(\"return\") == 0 ||\n s.compare(\"class\") == 0 ||\n s.compare(\"for\") == 0 ||\n s.compare(\"print\") == 0\n );\n }\n\n bool Lexer::isLineEnding(char c) {\n return (\n c == '\\r' ||\n c == '\\n'\n );\n }\n}\n\n<|endoftext|>"} {"text":"\/\/===--- SILWitnessTable.cpp - Defines the SILWitnessTable class ----------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file defines the SILWitnessTable class, which is used to map a protocol\n\/\/ conformance for a type to its implementing SILFunctions. This information is\n\/\/ (FIXME will be) used by IRGen to create witness tables for protocol dispatch.\n\/\/ It can also be used by generic specialization and existential\n\/\/ devirtualization passes to promote witness_method and protocol_method\n\/\/ instructions to static function_refs.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"swift\/SIL\/SILWitnessTable.h\"\n#include \"swift\/AST\/ASTMangler.h\"\n#include \"swift\/AST\/Module.h\"\n#include \"swift\/AST\/ProtocolConformance.h\"\n#include \"swift\/ClangImporter\/ClangModule.h\"\n#include \"swift\/SIL\/SILModule.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n\nusing namespace swift;\n\nstatic std::string mangleConstant(RootProtocolConformance *C) {\n Mangle::ASTMangler Mangler;\n return Mangler.mangleWitnessTable(C);\n}\n\nDeclContext *SILWitnessTable::getDeclContext() const {\n return getConformance()->getDeclContext();\n}\n\nProtocolDecl *SILWitnessTable::getProtocol() const {\n return getConformance()->getProtocol();\n}\n\nCanType SILWitnessTable::getConformingType() const {\n return getConformance()->getType()->getCanonicalType();\n}\n\nvoid SILWitnessTable::addWitnessTable() {\n \/\/ Make sure we have not seen this witness table yet.\n assert(Mod.WitnessTableMap.find(Conformance) ==\n Mod.WitnessTableMap.end() && \"Attempting to create duplicate \"\n \"witness table.\");\n Mod.WitnessTableMap[Conformance] = this;\n Mod.witnessTables.push_back(this);\n}\n\nSILWitnessTable *SILWitnessTable::create(\n SILModule &M, SILLinkage Linkage, IsSerialized_t Serialized,\n RootProtocolConformance *Conformance,\n ArrayRef entries,\n ArrayRef conditionalConformances) {\n assert(Conformance && \"Cannot create a witness table for a null \"\n \"conformance.\");\n\n \/\/ Create the mangled name of our witness table...\n Identifier Name = M.getASTContext().getIdentifier(mangleConstant(Conformance));\n\n \/\/ Allocate the witness table and initialize it.\n void *buf = M.allocate(sizeof(SILWitnessTable), alignof(SILWitnessTable));\n SILWitnessTable *wt = ::new (buf)\n SILWitnessTable(M, Linkage, Serialized, Name.str(), Conformance, entries,\n conditionalConformances);\n\n wt->addWitnessTable();\n\n \/\/ Return the resulting witness table.\n return wt;\n}\n\nSILWitnessTable *\nSILWitnessTable::create(SILModule &M, SILLinkage Linkage,\n RootProtocolConformance *Conformance) {\n assert(Conformance && \"Cannot create a witness table for a null \"\n \"conformance.\");\n\n \/\/ Create the mangled name of our witness table...\n Identifier Name = M.getASTContext().getIdentifier(mangleConstant(Conformance));\n\n\n \/\/ Allocate the witness table and initialize it.\n void *buf = M.allocate(sizeof(SILWitnessTable), alignof(SILWitnessTable));\n SILWitnessTable *wt = ::new (buf) SILWitnessTable(M, Linkage, Name.str(),\n Conformance);\n\n wt->addWitnessTable();\n\n \/\/ Return the resulting witness table.\n return wt;\n}\n\nSILWitnessTable::SILWitnessTable(\n SILModule &M, SILLinkage Linkage, IsSerialized_t Serialized, StringRef N,\n RootProtocolConformance *Conformance, ArrayRef entries,\n ArrayRef conditionalConformances)\n : Mod(M), Name(N), Linkage(Linkage), Conformance(Conformance), Entries(),\n ConditionalConformances(), IsDeclaration(true), Serialized(false) {\n convertToDefinition(entries, conditionalConformances, Serialized);\n}\n\nSILWitnessTable::SILWitnessTable(SILModule &M, SILLinkage Linkage, StringRef N,\n RootProtocolConformance *Conformance)\n : Mod(M), Name(N), Linkage(Linkage), Conformance(Conformance), Entries(),\n ConditionalConformances(), IsDeclaration(true), Serialized(false) {}\n\nSILWitnessTable::~SILWitnessTable() {\n if (isDeclaration())\n return;\n\n \/\/ Drop the reference count of witness functions referenced by this table.\n for (auto entry : getEntries()) {\n switch (entry.getKind()) {\n case Method:\n if (entry.getMethodWitness().Witness) {\n entry.getMethodWitness().Witness->decrementRefCount();\n }\n break;\n case AssociatedType:\n case AssociatedTypeProtocol:\n case BaseProtocol:\n case Invalid:\n break;\n }\n }\n}\n\nvoid SILWitnessTable::convertToDefinition(\n ArrayRef entries,\n ArrayRef conditionalConformances,\n IsSerialized_t isSerialized) {\n assert(isDeclaration() && \"Definitions should never call this method.\");\n IsDeclaration = false;\n assert(isSerialized != IsSerializable);\n Serialized = (isSerialized == IsSerialized);\n\n Entries = Mod.allocateCopy(entries);\n ConditionalConformances = Mod.allocateCopy(conditionalConformances);\n\n \/\/ Bump the reference count of witness functions referenced by this table.\n for (auto entry : getEntries()) {\n switch (entry.getKind()) {\n case Method:\n if (entry.getMethodWitness().Witness) {\n entry.getMethodWitness().Witness->incrementRefCount();\n }\n break;\n case AssociatedType:\n case AssociatedTypeProtocol:\n case BaseProtocol:\n case Invalid:\n break;\n }\n }\n}\n\nbool SILWitnessTable::conformanceIsSerialized(\n const RootProtocolConformance *conformance) {\n auto normalConformance = dyn_cast(conformance);\n if (normalConformance && normalConformance->isResilient())\n return false;\n\n \/\/ Serialize witness tables for conformances synthesized by\n \/\/ the ClangImporter.\n if (isa(conformance->getDeclContext()->getModuleScopeContext()))\n return true;\n\n if (conformance->getProtocol()->getEffectiveAccess() < AccessLevel::Public)\n return false;\n\n auto *nominal = conformance->getType()->getAnyNominal();\n return nominal->getEffectiveAccess() >= AccessLevel::Public;\n}\n\nbool SILWitnessTable::enumerateWitnessTableConditionalConformances(\n const ProtocolConformance *conformance,\n llvm::function_ref fn) {\n unsigned conformanceIndex = 0;\n for (auto req : conformance->getConditionalRequirements()) {\n if (req.getKind() != RequirementKind::Conformance)\n continue;\n\n auto proto = req.getSecondType()->castTo()->getDecl();\n\n if (Lowering::TypeConverter::protocolRequiresWitnessTable(proto)) {\n if (fn(conformanceIndex, req.getFirstType()->getCanonicalType(), proto))\n return true;\n\n conformanceIndex++;\n }\n }\n return false;\n}\nSIL: add a trace for the construction of witness tables\/\/===--- SILWitnessTable.cpp - Defines the SILWitnessTable class ----------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file defines the SILWitnessTable class, which is used to map a protocol\n\/\/ conformance for a type to its implementing SILFunctions. This information is\n\/\/ (FIXME will be) used by IRGen to create witness tables for protocol dispatch.\n\/\/ It can also be used by generic specialization and existential\n\/\/ devirtualization passes to promote witness_method and protocol_method\n\/\/ instructions to static function_refs.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"sil-witness-table\"\n#include \"swift\/SIL\/SILWitnessTable.h\"\n#include \"swift\/AST\/ASTMangler.h\"\n#include \"swift\/AST\/Module.h\"\n#include \"swift\/AST\/ProtocolConformance.h\"\n#include \"swift\/ClangImporter\/ClangModule.h\"\n#include \"swift\/SIL\/SILModule.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n\nusing namespace swift;\n\nstatic std::string mangleConstant(RootProtocolConformance *C) {\n Mangle::ASTMangler Mangler;\n return Mangler.mangleWitnessTable(C);\n}\n\nDeclContext *SILWitnessTable::getDeclContext() const {\n return getConformance()->getDeclContext();\n}\n\nProtocolDecl *SILWitnessTable::getProtocol() const {\n return getConformance()->getProtocol();\n}\n\nCanType SILWitnessTable::getConformingType() const {\n return getConformance()->getType()->getCanonicalType();\n}\n\nvoid SILWitnessTable::addWitnessTable() {\n \/\/ Make sure we have not seen this witness table yet.\n assert(Mod.WitnessTableMap.find(Conformance) ==\n Mod.WitnessTableMap.end() && \"Attempting to create duplicate \"\n \"witness table.\");\n Mod.WitnessTableMap[Conformance] = this;\n Mod.witnessTables.push_back(this);\n}\n\nSILWitnessTable *SILWitnessTable::create(\n SILModule &M, SILLinkage Linkage, IsSerialized_t Serialized,\n RootProtocolConformance *Conformance,\n ArrayRef entries,\n ArrayRef conditionalConformances) {\n assert(Conformance && \"Cannot create a witness table for a null \"\n \"conformance.\");\n\n \/\/ Create the mangled name of our witness table...\n Identifier Name = M.getASTContext().getIdentifier(mangleConstant(Conformance));\n\n LLVM_DEBUG(llvm::dbgs() << \"SILWitnessTable Creating: \" << Name.str() << '\\n');\n\n \/\/ Allocate the witness table and initialize it.\n void *buf = M.allocate(sizeof(SILWitnessTable), alignof(SILWitnessTable));\n SILWitnessTable *wt = ::new (buf)\n SILWitnessTable(M, Linkage, Serialized, Name.str(), Conformance, entries,\n conditionalConformances);\n\n wt->addWitnessTable();\n\n \/\/ Return the resulting witness table.\n return wt;\n}\n\nSILWitnessTable *\nSILWitnessTable::create(SILModule &M, SILLinkage Linkage,\n RootProtocolConformance *Conformance) {\n assert(Conformance && \"Cannot create a witness table for a null \"\n \"conformance.\");\n\n \/\/ Create the mangled name of our witness table...\n Identifier Name = M.getASTContext().getIdentifier(mangleConstant(Conformance));\n\n\n \/\/ Allocate the witness table and initialize it.\n void *buf = M.allocate(sizeof(SILWitnessTable), alignof(SILWitnessTable));\n SILWitnessTable *wt = ::new (buf) SILWitnessTable(M, Linkage, Name.str(),\n Conformance);\n\n wt->addWitnessTable();\n\n \/\/ Return the resulting witness table.\n return wt;\n}\n\nSILWitnessTable::SILWitnessTable(\n SILModule &M, SILLinkage Linkage, IsSerialized_t Serialized, StringRef N,\n RootProtocolConformance *Conformance, ArrayRef entries,\n ArrayRef conditionalConformances)\n : Mod(M), Name(N), Linkage(Linkage), Conformance(Conformance), Entries(),\n ConditionalConformances(), IsDeclaration(true), Serialized(false) {\n convertToDefinition(entries, conditionalConformances, Serialized);\n}\n\nSILWitnessTable::SILWitnessTable(SILModule &M, SILLinkage Linkage, StringRef N,\n RootProtocolConformance *Conformance)\n : Mod(M), Name(N), Linkage(Linkage), Conformance(Conformance), Entries(),\n ConditionalConformances(), IsDeclaration(true), Serialized(false) {}\n\nSILWitnessTable::~SILWitnessTable() {\n if (isDeclaration())\n return;\n\n \/\/ Drop the reference count of witness functions referenced by this table.\n for (auto entry : getEntries()) {\n switch (entry.getKind()) {\n case Method:\n if (entry.getMethodWitness().Witness) {\n entry.getMethodWitness().Witness->decrementRefCount();\n }\n break;\n case AssociatedType:\n case AssociatedTypeProtocol:\n case BaseProtocol:\n case Invalid:\n break;\n }\n }\n}\n\nvoid SILWitnessTable::convertToDefinition(\n ArrayRef entries,\n ArrayRef conditionalConformances,\n IsSerialized_t isSerialized) {\n assert(isDeclaration() && \"Definitions should never call this method.\");\n IsDeclaration = false;\n assert(isSerialized != IsSerializable);\n Serialized = (isSerialized == IsSerialized);\n\n Entries = Mod.allocateCopy(entries);\n ConditionalConformances = Mod.allocateCopy(conditionalConformances);\n\n \/\/ Bump the reference count of witness functions referenced by this table.\n for (auto entry : getEntries()) {\n switch (entry.getKind()) {\n case Method:\n if (entry.getMethodWitness().Witness) {\n entry.getMethodWitness().Witness->incrementRefCount();\n }\n break;\n case AssociatedType:\n case AssociatedTypeProtocol:\n case BaseProtocol:\n case Invalid:\n break;\n }\n }\n}\n\nbool SILWitnessTable::conformanceIsSerialized(\n const RootProtocolConformance *conformance) {\n auto normalConformance = dyn_cast(conformance);\n if (normalConformance && normalConformance->isResilient())\n return false;\n\n \/\/ Serialize witness tables for conformances synthesized by\n \/\/ the ClangImporter.\n if (isa(conformance->getDeclContext()->getModuleScopeContext()))\n return true;\n\n if (conformance->getProtocol()->getEffectiveAccess() < AccessLevel::Public)\n return false;\n\n auto *nominal = conformance->getType()->getAnyNominal();\n return nominal->getEffectiveAccess() >= AccessLevel::Public;\n}\n\nbool SILWitnessTable::enumerateWitnessTableConditionalConformances(\n const ProtocolConformance *conformance,\n llvm::function_ref fn) {\n unsigned conformanceIndex = 0;\n for (auto req : conformance->getConditionalRequirements()) {\n if (req.getKind() != RequirementKind::Conformance)\n continue;\n\n auto proto = req.getSecondType()->castTo()->getDecl();\n\n if (Lowering::TypeConverter::protocolRequiresWitnessTable(proto)) {\n if (fn(conformanceIndex, req.getFirstType()->getCanonicalType(), proto))\n return true;\n\n conformanceIndex++;\n }\n }\n return false;\n}\n<|endoftext|>"} {"text":"\/\/===- SystemUtils.h - Utilities to do low-level system stuff --*- C++ -*--===\/\/\n\/\/\n\/\/ This file contains functions used to do a variety of low-level, often\n\/\/ system-specific, tasks.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"Support\/SystemUtils.h\"\n#include \n#include \n#include \n#include \n#include \"Config\/sys\/types.h\"\n#include \"Config\/sys\/stat.h\"\n#include \"Config\/fcntl.h\"\n#include \"Config\/sys\/wait.h\"\n#include \"Config\/unistd.h\"\n#include \"Config\/errno.h\"\n\n\/\/\/ isExecutableFile - This function returns true if the filename specified\n\/\/\/ exists and is executable.\n\/\/\/\nbool isExecutableFile(const std::string &ExeFileName) {\n struct stat Buf;\n if (stat(ExeFileName.c_str(), &Buf))\n return false; \/\/ Must not be executable!\n\n if (!(Buf.st_mode & S_IFREG))\n return false; \/\/ Not a regular file?\n\n if (Buf.st_uid == getuid()) \/\/ Owner of file?\n return Buf.st_mode & S_IXUSR;\n else if (Buf.st_gid == getgid()) \/\/ In group of file?\n return Buf.st_mode & S_IXGRP;\n else \/\/ Unrelated to file?\n return Buf.st_mode & S_IXOTH;\n}\n\n\/\/\/ FindExecutable - Find a named executable, giving the argv[0] of program\n\/\/\/ being executed. This allows us to find another LLVM tool if it is built\n\/\/\/ into the same directory, but that directory is neither the current\n\/\/\/ directory, nor in the PATH. If the executable cannot be found, return an\n\/\/\/ empty string.\n\/\/\/ \nstd::string FindExecutable(const std::string &ExeName,\n const std::string &ProgramPath) {\n \/\/ First check the directory that bugpoint is in. We can do this if\n \/\/ BugPointPath contains at least one \/ character, indicating that it is a\n \/\/ relative path to bugpoint itself.\n \/\/\n std::string Result = ProgramPath;\n while (!Result.empty() && Result[Result.size()-1] != '\/')\n Result.erase(Result.size()-1, 1);\n\n if (!Result.empty()) {\n Result += ExeName;\n if (isExecutableFile(Result)) return Result; \/\/ Found it?\n }\n\n \/\/ Okay, if the path to the program didn't tell us anything, try using the\n \/\/ PATH environment variable.\n const char *PathStr = getenv(\"PATH\");\n if (PathStr == 0) return \"\";\n\n \/\/ Now we have a colon separated list of directories to search... try them...\n unsigned PathLen = strlen(PathStr);\n while (PathLen) {\n \/\/ Find the first colon...\n const char *Colon = std::find(PathStr, PathStr+PathLen, ':');\n \n \/\/ Check to see if this first directory contains the executable...\n std::string FilePath = std::string(PathStr, Colon) + '\/' + ExeName;\n if (isExecutableFile(FilePath))\n return FilePath; \/\/ Found the executable!\n \n \/\/ Nope it wasn't in this directory, check the next range!\n PathLen -= Colon-PathStr;\n PathStr = Colon;\n while (*PathStr == ':') { \/\/ Advance past colons\n PathStr++;\n PathLen--;\n }\n }\n\n \/\/ If we fell out, we ran out of directories in PATH to search, return failure\n return \"\";\n}\n\nstatic void RedirectFD(const std::string &File, int FD) {\n if (File.empty()) return; \/\/ Noop\n\n \/\/ Open the file\n int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);\n if (InFD == -1) {\n std::cerr << \"Error opening file '\" << File << \"' for \"\n << (FD == 0 ? \"input\" : \"output\") << \"!\\n\";\n exit(1);\n }\n\n dup2(InFD, FD); \/\/ Install it as the requested FD\n close(InFD); \/\/ Close the original FD\n}\n\n\/\/\/ RunProgramWithTimeout - This function executes the specified program, with\n\/\/\/ the specified null-terminated argument array, with the stdin\/out\/err fd's\n\/\/\/ redirected, with a timeout specified on the command line. This terminates\n\/\/\/ the calling program if there is an error executing the specified program.\n\/\/\/ It returns the return value of the program, or -1 if a timeout is detected.\n\/\/\/\nint RunProgramWithTimeout(const std::string &ProgramPath, const char **Args,\n const std::string &StdInFile,\n const std::string &StdOutFile,\n const std::string &StdErrFile) {\n\n \/\/ FIXME: install sigalarm handler here for timeout...\n\n int Child = fork();\n switch (Child) {\n case -1:\n std::cerr << \"ERROR forking!\\n\";\n exit(1);\n case 0: \/\/ Child\n RedirectFD(StdInFile, 0); \/\/ Redirect file descriptors...\n RedirectFD(StdOutFile, 1);\n RedirectFD(StdErrFile, 2);\n\n execv(ProgramPath.c_str(), (char *const *)Args);\n std::cerr << \"Error executing program '\" << ProgramPath;\n for (; *Args; ++Args)\n std::cerr << \" \" << *Args;\n exit(1);\n\n default: break;\n }\n\n \/\/ Make sure all output has been written while waiting\n std::cout << std::flush;\n\n int Status;\n if (wait(&Status) != Child) {\n if (errno == EINTR) {\n static bool FirstTimeout = true;\n if (FirstTimeout) {\n std::cout <<\n \"*** Program execution timed out! This mechanism is designed to handle\\n\"\n \" programs stuck in infinite loops gracefully. The -timeout option\\n\"\n \" can be used to change the timeout threshold or disable it completely\\n\"\n \" (with -timeout=0). This message is only displayed once.\\n\";\n FirstTimeout = false;\n }\n return -1; \/\/ Timeout detected\n }\n\n std::cerr << \"Error waiting for child process!\\n\";\n exit(1);\n }\n return Status;\n}\n\n\n\/\/\n\/\/ Function: ExecWait ()\n\/\/\n\/\/ Description:\n\/\/ This function executes a program with the specified arguments and\n\/\/ environment. It then waits for the progarm to termiante and then returns\n\/\/ to the caller.\n\/\/\n\/\/ Inputs:\n\/\/ argv - The arguments to the program as an array of C strings. The first\n\/\/ argument should be the name of the program to execute, and the\n\/\/ last argument should be a pointer to NULL.\n\/\/\n\/\/ envp - The environment passes to the program as an array of C strings in\n\/\/ the form of \"name=value\" pairs. The last element should be a\n\/\/ pointer to NULL.\n\/\/\n\/\/ Outputs:\n\/\/ None.\n\/\/\n\/\/ Return value:\n\/\/ 0 - No errors.\n\/\/ 1 - The program could not be executed.\n\/\/ 1 - The program returned a non-zero exit status.\n\/\/ 1 - The program terminated abnormally.\n\/\/\n\/\/ Notes:\n\/\/ The program will inherit the stdin, stdout, and stderr file descriptors\n\/\/ as well as other various configuration settings (umask).\n\/\/\n\/\/ This function should not print anything to stdout\/stderr on its own. It is\n\/\/ a generic library function. The caller or executed program should report\n\/\/ errors in the way it sees fit.\n\/\/\n\/\/ This function does not use $PATH to find programs.\n\/\/\nint\nExecWait (const char * const old_argv[], const char * const old_envp[])\n{\n \/\/ Child process ID\n register int child;\n\n \/\/ Status from child process when it exits\n int status;\n \n \/\/\n \/\/ Create local versions of the parameters that can be passed into execve()\n \/\/ without creating const problems.\n \/\/\n char ** const argv = (char ** const) old_argv;\n char ** const envp = (char ** const) old_envp;\n\n \/\/\n \/\/ Create a child process.\n \/\/\n switch (child=fork())\n {\n \/\/\n \/\/ An error occured: Return to the caller.\n \/\/\n case -1:\n return 1;\n break;\n\n \/\/\n \/\/ Child process: Execute the program.\n \/\/\n case 0:\n execve (argv[0], argv, envp);\n\n \/\/\n \/\/ If the execve() failed, we should exit and let the parent pick up\n \/\/ our non-zero exit status.\n \/\/\n exit (1);\n break;\n\n \/\/\n \/\/ Parent process: Break out of the switch to do our processing.\n \/\/\n default:\n break;\n }\n\n \/\/\n \/\/ Parent process: Wait for the child process to termiante.\n \/\/\n if ((wait (&status)) == -1)\n {\n return 1;\n }\n\n \/\/\n \/\/ If the program exited normally with a zero exit status, return success!\n \/\/\n if (WIFEXITED (status) && (WEXITSTATUS(status) == 0))\n {\n return 0;\n }\n\n \/\/\n \/\/ Otherwise, return failure.\n \/\/\n return 1;\n}\n\nFix up error message.\/\/===- SystemUtils.h - Utilities to do low-level system stuff --*- C++ -*--===\/\/\n\/\/\n\/\/ This file contains functions used to do a variety of low-level, often\n\/\/ system-specific, tasks.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"Support\/SystemUtils.h\"\n#include \n#include \n#include \n#include \n#include \"Config\/sys\/types.h\"\n#include \"Config\/sys\/stat.h\"\n#include \"Config\/fcntl.h\"\n#include \"Config\/sys\/wait.h\"\n#include \"Config\/unistd.h\"\n#include \"Config\/errno.h\"\n\n\/\/\/ isExecutableFile - This function returns true if the filename specified\n\/\/\/ exists and is executable.\n\/\/\/\nbool isExecutableFile(const std::string &ExeFileName) {\n struct stat Buf;\n if (stat(ExeFileName.c_str(), &Buf))\n return false; \/\/ Must not be executable!\n\n if (!(Buf.st_mode & S_IFREG))\n return false; \/\/ Not a regular file?\n\n if (Buf.st_uid == getuid()) \/\/ Owner of file?\n return Buf.st_mode & S_IXUSR;\n else if (Buf.st_gid == getgid()) \/\/ In group of file?\n return Buf.st_mode & S_IXGRP;\n else \/\/ Unrelated to file?\n return Buf.st_mode & S_IXOTH;\n}\n\n\/\/\/ FindExecutable - Find a named executable, giving the argv[0] of program\n\/\/\/ being executed. This allows us to find another LLVM tool if it is built\n\/\/\/ into the same directory, but that directory is neither the current\n\/\/\/ directory, nor in the PATH. If the executable cannot be found, return an\n\/\/\/ empty string.\n\/\/\/ \nstd::string FindExecutable(const std::string &ExeName,\n const std::string &ProgramPath) {\n \/\/ First check the directory that bugpoint is in. We can do this if\n \/\/ BugPointPath contains at least one \/ character, indicating that it is a\n \/\/ relative path to bugpoint itself.\n \/\/\n std::string Result = ProgramPath;\n while (!Result.empty() && Result[Result.size()-1] != '\/')\n Result.erase(Result.size()-1, 1);\n\n if (!Result.empty()) {\n Result += ExeName;\n if (isExecutableFile(Result)) return Result; \/\/ Found it?\n }\n\n \/\/ Okay, if the path to the program didn't tell us anything, try using the\n \/\/ PATH environment variable.\n const char *PathStr = getenv(\"PATH\");\n if (PathStr == 0) return \"\";\n\n \/\/ Now we have a colon separated list of directories to search... try them...\n unsigned PathLen = strlen(PathStr);\n while (PathLen) {\n \/\/ Find the first colon...\n const char *Colon = std::find(PathStr, PathStr+PathLen, ':');\n \n \/\/ Check to see if this first directory contains the executable...\n std::string FilePath = std::string(PathStr, Colon) + '\/' + ExeName;\n if (isExecutableFile(FilePath))\n return FilePath; \/\/ Found the executable!\n \n \/\/ Nope it wasn't in this directory, check the next range!\n PathLen -= Colon-PathStr;\n PathStr = Colon;\n while (*PathStr == ':') { \/\/ Advance past colons\n PathStr++;\n PathLen--;\n }\n }\n\n \/\/ If we fell out, we ran out of directories in PATH to search, return failure\n return \"\";\n}\n\nstatic void RedirectFD(const std::string &File, int FD) {\n if (File.empty()) return; \/\/ Noop\n\n \/\/ Open the file\n int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);\n if (InFD == -1) {\n std::cerr << \"Error opening file '\" << File << \"' for \"\n << (FD == 0 ? \"input\" : \"output\") << \"!\\n\";\n exit(1);\n }\n\n dup2(InFD, FD); \/\/ Install it as the requested FD\n close(InFD); \/\/ Close the original FD\n}\n\n\/\/\/ RunProgramWithTimeout - This function executes the specified program, with\n\/\/\/ the specified null-terminated argument array, with the stdin\/out\/err fd's\n\/\/\/ redirected, with a timeout specified on the command line. This terminates\n\/\/\/ the calling program if there is an error executing the specified program.\n\/\/\/ It returns the return value of the program, or -1 if a timeout is detected.\n\/\/\/\nint RunProgramWithTimeout(const std::string &ProgramPath, const char **Args,\n const std::string &StdInFile,\n const std::string &StdOutFile,\n const std::string &StdErrFile) {\n\n \/\/ FIXME: install sigalarm handler here for timeout...\n\n int Child = fork();\n switch (Child) {\n case -1:\n std::cerr << \"ERROR forking!\\n\";\n exit(1);\n case 0: \/\/ Child\n RedirectFD(StdInFile, 0); \/\/ Redirect file descriptors...\n RedirectFD(StdOutFile, 1);\n RedirectFD(StdErrFile, 2);\n\n execv(ProgramPath.c_str(), (char *const *)Args);\n std::cerr << \"Error executing program: '\" << ProgramPath;\n for (; *Args; ++Args)\n std::cerr << \" \" << *Args;\n std::cerr << \"'\\n\";\n exit(1);\n\n default: break;\n }\n\n \/\/ Make sure all output has been written while waiting\n std::cout << std::flush;\n\n int Status;\n if (wait(&Status) != Child) {\n if (errno == EINTR) {\n static bool FirstTimeout = true;\n if (FirstTimeout) {\n std::cout <<\n \"*** Program execution timed out! This mechanism is designed to handle\\n\"\n \" programs stuck in infinite loops gracefully. The -timeout option\\n\"\n \" can be used to change the timeout threshold or disable it completely\\n\"\n \" (with -timeout=0). This message is only displayed once.\\n\";\n FirstTimeout = false;\n }\n return -1; \/\/ Timeout detected\n }\n\n std::cerr << \"Error waiting for child process!\\n\";\n exit(1);\n }\n return Status;\n}\n\n\n\/\/\n\/\/ Function: ExecWait ()\n\/\/\n\/\/ Description:\n\/\/ This function executes a program with the specified arguments and\n\/\/ environment. It then waits for the progarm to termiante and then returns\n\/\/ to the caller.\n\/\/\n\/\/ Inputs:\n\/\/ argv - The arguments to the program as an array of C strings. The first\n\/\/ argument should be the name of the program to execute, and the\n\/\/ last argument should be a pointer to NULL.\n\/\/\n\/\/ envp - The environment passes to the program as an array of C strings in\n\/\/ the form of \"name=value\" pairs. The last element should be a\n\/\/ pointer to NULL.\n\/\/\n\/\/ Outputs:\n\/\/ None.\n\/\/\n\/\/ Return value:\n\/\/ 0 - No errors.\n\/\/ 1 - The program could not be executed.\n\/\/ 1 - The program returned a non-zero exit status.\n\/\/ 1 - The program terminated abnormally.\n\/\/\n\/\/ Notes:\n\/\/ The program will inherit the stdin, stdout, and stderr file descriptors\n\/\/ as well as other various configuration settings (umask).\n\/\/\n\/\/ This function should not print anything to stdout\/stderr on its own. It is\n\/\/ a generic library function. The caller or executed program should report\n\/\/ errors in the way it sees fit.\n\/\/\n\/\/ This function does not use $PATH to find programs.\n\/\/\nint\nExecWait (const char * const old_argv[], const char * const old_envp[])\n{\n \/\/ Child process ID\n register int child;\n\n \/\/ Status from child process when it exits\n int status;\n \n \/\/\n \/\/ Create local versions of the parameters that can be passed into execve()\n \/\/ without creating const problems.\n \/\/\n char ** const argv = (char ** const) old_argv;\n char ** const envp = (char ** const) old_envp;\n\n \/\/\n \/\/ Create a child process.\n \/\/\n switch (child=fork())\n {\n \/\/\n \/\/ An error occured: Return to the caller.\n \/\/\n case -1:\n return 1;\n break;\n\n \/\/\n \/\/ Child process: Execute the program.\n \/\/\n case 0:\n execve (argv[0], argv, envp);\n\n \/\/\n \/\/ If the execve() failed, we should exit and let the parent pick up\n \/\/ our non-zero exit status.\n \/\/\n exit (1);\n break;\n\n \/\/\n \/\/ Parent process: Break out of the switch to do our processing.\n \/\/\n default:\n break;\n }\n\n \/\/\n \/\/ Parent process: Wait for the child process to termiante.\n \/\/\n if ((wait (&status)) == -1)\n {\n return 1;\n }\n\n \/\/\n \/\/ If the program exited normally with a zero exit status, return success!\n \/\/\n if (WIFEXITED (status) && (WEXITSTATUS(status) == 0))\n {\n return 0;\n }\n\n \/\/\n \/\/ Otherwise, return failure.\n \/\/\n return 1;\n}\n\n<|endoftext|>"} {"text":"\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n\n#include \"sunversion.hxx\"\n#include \"osl\/thread.h\"\n#include \"osl\/process.h\"\n#include \"osl\/security.hxx\"\n#include \n#include \n#include \"diagnostics.h\"\nusing namespace osl;\n\nnamespace jfw_plugin { \/\/stoc_javadetect\n\n\n#if OSL_DEBUG_LEVEL >= 2\nclass SelfTest\n{\npublic:\n SelfTest();\n} test;\n#endif\n\nSunVersion::SunVersion(const OUString &usVer):\n m_nUpdateSpecial(0), m_preRelease(Rel_NONE),\n usVersion(usVer)\n{\n memset(m_arVersionParts, 0, sizeof(m_arVersionParts));\n OString sVersion= OUStringToOString(usVer, osl_getThreadTextEncoding());\n m_bValid = init(sVersion.getStr());\n}\nSunVersion::SunVersion(const char * szVer):\n m_nUpdateSpecial(0), m_preRelease(Rel_NONE)\n{\n memset(m_arVersionParts, 0, sizeof(m_arVersionParts));\n m_bValid = init(szVer);\n usVersion= OUString(szVer,strlen(szVer),osl_getThreadTextEncoding());\n}\n\n\n\/**Format major.minor.maintenance_update\n *\/\nbool SunVersion::init(const char *szVersion)\n{\n if ( ! szVersion || strlen(szVersion) == 0)\n return false;\n\n \/\/first get the major,minor,maintenance\n const char * pLast = szVersion;\n const char * pCur = szVersion;\n \/\/pEnd point to the position after the last character\n const char * pEnd = szVersion + strlen(szVersion);\n \/\/ 0 = major, 1 = minor, 2 = maintenance, 3 = update\n int nPart = 0;\n \/\/ position within part beginning with 0\n int nPartPos = 0;\n char buf[128];\n\n \/\/char must me a number 0 - 999 and no leading\n while (true)\n {\n if (pCur < pEnd && isdigit(*pCur))\n {\n if (pCur < pEnd)\n pCur ++;\n nPartPos ++;\n }\n \/\/if correct separator then form integer\n else if (\n ! (nPartPos == 0) \/\/ prevents: \".4.1\", \"..1\", part must start with digit\n && (\n \/\/separators after maintenance (1.4.1_01, 1.4.1-beta, or 1.4.1)\n ((pCur == pEnd || *pCur == '_' || *pCur == '-') && (nPart == 2 ))\n ||\n \/\/separators between major-minor and minor-maintenance\n (nPart < 2 && *pCur == '.') )\n && (\n \/\/prevent 1.4.0. 1.4.0-\n pCur + 1 == pEnd ? isdigit(*(pCur)) : 1) )\n {\n int len = pCur - pLast;\n if (len >= 127)\n return false;\n\n strncpy(buf, pLast, len);\n buf[len] = 0;\n pCur ++;\n pLast = pCur;\n\n m_arVersionParts[nPart] = atoi(buf);\n nPart ++;\n nPartPos = 0;\n if (nPart == 3)\n break;\n\n \/\/check next character\n if (! ( (pCur < pEnd)\n && ( (nPart < 3) && isdigit(*pCur))))\n return false;\n }\n else\n {\n return false;\n }\n }\n if (pCur >= pEnd)\n return true;\n \/\/We have now 1.4.1. This can be followed by _01, -beta, etc.\n \/\/ _01 (update) According to docu must not be followed by any other\n \/\/characters, but on Solaris 9 we have a 1.4.1_01a!!\n if (* (pCur - 1) == '_')\n {\/\/ _01, _02\n \/\/ update is the last part _01, _01a, part 0 is the digits parts and 1 the trailing alpha\n while (true)\n {\n if (pCur <= pEnd)\n {\n if ( ! isdigit(*pCur))\n {\n \/\/1.4.1_01-, 1.4.1_01a, the numerical part may only be 2 chars.\n int len = pCur - pLast;\n if (len > 2)\n return false;\n \/\/we've got the update: 01, 02 etc\n strncpy(buf, pLast, len);\n buf[len] = 0;\n m_arVersionParts[nPart] = atoi(buf);\n if (pCur == pEnd)\n {\n break;\n }\n if (*pCur == 'a' && (pCur + 1) == pEnd)\n {\n \/\/check if it s followed by a simple \"a\" (not specified)\n m_nUpdateSpecial = *pCur;\n break;\n }\n else if (*pCur == '-' && pCur < pEnd)\n {\n \/\/check 1.5.0_01-ea\n PreRelease pr = getPreRelease(++pCur);\n if (pr == Rel_NONE)\n return false;\n \/\/just ignore -ea because its no official release\n break;\n }\n else\n {\n return false;\n }\n }\n if (pCur < pEnd)\n pCur ++;\n else\n break;\n }\n }\n }\n \/\/ 1.4.1-ea\n else if (*(pCur - 1) == '-')\n {\n m_preRelease = getPreRelease(pCur);\n if (m_preRelease == Rel_NONE)\n return false;\n#if defined(FREEBSD)\n if (m_preRelease == Rel_FreeBSD)\n {\n pCur++; \/\/eliminate 'p'\n if (pCur < pEnd && isdigit(*pCur))\n pCur ++;\n int len = pCur - pLast -1; \/\/eliminate 'p'\n if (len >= 127)\n return false;\n strncpy(buf, (pLast+1), len); \/\/eliminate 'p'\n buf[len] = 0;\n m_nUpdateSpecial = atoi(buf)+100; \/\/hack for FBSD #i56953#\n return true;\n }\n#endif\n }\n else\n {\n return false;\n }\n return true;\n}\n\nSunVersion::PreRelease SunVersion::getPreRelease(const char *szRelease)\n{\n if (szRelease == NULL)\n return Rel_NONE;\n if( ! strcmp(szRelease,\"internal\"))\n return Rel_INTERNAL;\n else if( ! strcmp(szRelease,\"ea\"))\n return Rel_EA;\n else if( ! strcmp(szRelease,\"ea1\"))\n return Rel_EA1;\n else if( ! strcmp(szRelease,\"ea2\"))\n return Rel_EA2;\n else if( ! strcmp(szRelease,\"ea3\"))\n return Rel_EA3;\n else if ( ! strcmp(szRelease,\"beta\"))\n return Rel_BETA;\n else if ( ! strcmp(szRelease,\"beta1\"))\n return Rel_BETA1;\n else if ( ! strcmp(szRelease,\"beta2\"))\n return Rel_BETA2;\n else if ( ! strcmp(szRelease,\"beta3\"))\n return Rel_BETA3;\n else if (! strcmp(szRelease, \"rc\"))\n return Rel_RC;\n else if (! strcmp(szRelease, \"rc1\"))\n return Rel_RC1;\n else if (! strcmp(szRelease, \"rc2\"))\n return Rel_RC2;\n else if (! strcmp(szRelease, \"rc3\"))\n return Rel_RC3;\n#if defined (FREEBSD)\n else if (! strncmp(szRelease, \"p\", 1))\n return Rel_FreeBSD;\n#endif\n else\n return Rel_NONE;\n}\n\nSunVersion::~SunVersion()\n{\n\n}\n\n\/* Examples:\n a) 1.0 < 1.1\n b) 1.0 < 1.0.0\n c) 1.0 < 1.0_00\n\n returns false if both values are equal\n*\/\nbool SunVersion::operator > (const SunVersion& ver) const\n{\n if( &ver == this)\n return false;\n\n \/\/compare major.minor.maintenance\n for( int i= 0; i < 4; i ++)\n {\n \/\/ 1.4 > 1.3\n if(m_arVersionParts[i] > ver.m_arVersionParts[i])\n {\n return true;\n }\n else if (m_arVersionParts[i] < ver.m_arVersionParts[i])\n {\n return false;\n }\n }\n \/\/major.minor.maintenance_update are equal. Test for a trailing char\n if (m_nUpdateSpecial > ver.m_nUpdateSpecial)\n {\n return true;\n }\n\n \/\/Until here the versions are equal\n \/\/compare pre -release values\n if ((m_preRelease == Rel_NONE && ver.m_preRelease == Rel_NONE)\n ||\n (m_preRelease != Rel_NONE && ver.m_preRelease == Rel_NONE))\n return false;\n else if (m_preRelease == Rel_NONE && ver.m_preRelease != Rel_NONE)\n return true;\n else if (m_preRelease > ver.m_preRelease)\n return true;\n\n return false;\n}\n\nbool SunVersion::operator < (const SunVersion& ver) const\n{\n return (! operator > (ver)) && (! operator == (ver));\n}\n\nbool SunVersion::operator == (const SunVersion& ver) const\n{\n bool bRet= true;\n for(int i= 0; i < 4; i++)\n {\n if( m_arVersionParts[i] != ver.m_arVersionParts[i])\n {\n bRet= false;\n break;\n }\n }\n bRet = m_nUpdateSpecial == ver.m_nUpdateSpecial && bRet;\n bRet = m_preRelease == ver.m_preRelease && bRet;\n return bRet;\n}\n\n\n#if OSL_DEBUG_LEVEL >= 2\nSelfTest::SelfTest()\n{\n bool bRet = true;\n\n char const * versions[] = {\"1.4.0\", \"1.4.1\", \"1.0.0\", \"10.0.0\", \"10.10.0\",\n \"10.2.2\", \"10.10.0\", \"10.10.10\", \"111.0.999\",\n \"1.4.1_01\", \"9.90.99_09\", \"1.4.1_99\",\n \"1.4.1_00a\",\n \"1.4.1-ea\", \"1.4.1-beta\", \"1.4.1-rc1\",\n \"1.5.0_01-ea\", \"1.5.0_01-rc2\"};\n char const * badVersions[] = {\".4.0\", \"..1\", \"\", \"10.0\", \"10.10.0.\", \"10.10.0-\", \"10.10.0.\",\n \"10.2-2\", \"10_10.0\", \"10..10\",\"10.10\", \"a.0.999\",\n \"1.4b.1_01\", \"9.90.-99_09\", \"1.4.1_99-\",\n \"1.4.1_00a2\", \"1.4.0_z01z\", \"1.4.1__99A\",\n \"1.4.1-1ea\", \"1.5.0_010\", \"1.5.0._01-\", \"1.5.0_01-eac\"};\n char const * orderedVer[] = { \"1.3.1-ea\", \"1.3.1-beta\", \"1.3.1-rc1\",\n \"1.3.1\", \"1.3.1_00a\", \"1.3.1_01\", \"1.3.1_01a\",\n \"1.3.2\", \"1.4.0\", \"1.5.0_01-ea\", \"2.0.0\"};\n\n int num = sizeof (versions) \/ sizeof(char*);\n int numBad = sizeof (badVersions) \/ sizeof(char*);\n int numOrdered = sizeof (orderedVer) \/ sizeof(char*);\n \/\/parsing test (positive)\n for (int i = 0; i < num; i++)\n {\n SunVersion ver(versions[i]);\n if ( ! ver)\n {\n bRet = false;\n break;\n }\n }\n OSL_ENSURE(bRet, \"SunVersion selftest failed\");\n \/\/Parsing test (negative)\n for ( int i = 0; i < numBad; i++)\n {\n SunVersion ver(badVersions[i]);\n if (ver)\n {\n bRet = false;\n break;\n }\n }\n OSL_ENSURE(bRet, \"SunVersion selftest failed\");\n\n \/\/ Ordering test\n bRet = true;\n int j = 0;\n for (int i = 0; i < numOrdered; i ++)\n {\n SunVersion curVer(orderedVer[i]);\n if ( ! curVer)\n {\n bRet = false;\n break;\n }\n for (j = 0; j < numOrdered; j++)\n {\n SunVersion compVer(orderedVer[j]);\n if (i < j)\n {\n if ( !(curVer < compVer))\n {\n bRet = false;\n break;\n }\n }\n else if ( i == j)\n {\n if (! (curVer == compVer\n && ! (curVer > compVer)\n && ! (curVer < compVer)))\n {\n bRet = false;\n break;\n }\n }\n else if (i > j)\n {\n if ( !(curVer > compVer))\n {\n bRet = false;\n break;\n }\n }\n }\n if ( ! bRet)\n break;\n }\n if (bRet)\n JFW_TRACE2(\"Testing class SunVersion succeeded.\");\n else\n OSL_ENSURE(bRet, \"[Java framework] sunjavaplugin: SunVersion self test failed.\\n\");\n}\n#endif\n\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\nfix higher debug level build\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n\n#include \"sunversion.hxx\"\n#include \"osl\/diagnose.h\"\n#include \"osl\/thread.h\"\n#include \"osl\/process.h\"\n#include \"osl\/security.hxx\"\n#include \n#include \n#include \"diagnostics.h\"\nusing namespace osl;\n\nnamespace jfw_plugin { \/\/stoc_javadetect\n\n\n#if OSL_DEBUG_LEVEL >= 2\nclass SelfTest\n{\npublic:\n SelfTest();\n} test;\n#endif\n\nSunVersion::SunVersion(const OUString &usVer):\n m_nUpdateSpecial(0), m_preRelease(Rel_NONE),\n usVersion(usVer)\n{\n memset(m_arVersionParts, 0, sizeof(m_arVersionParts));\n OString sVersion= OUStringToOString(usVer, osl_getThreadTextEncoding());\n m_bValid = init(sVersion.getStr());\n}\nSunVersion::SunVersion(const char * szVer):\n m_nUpdateSpecial(0), m_preRelease(Rel_NONE)\n{\n memset(m_arVersionParts, 0, sizeof(m_arVersionParts));\n m_bValid = init(szVer);\n usVersion= OUString(szVer,strlen(szVer),osl_getThreadTextEncoding());\n}\n\n\n\/**Format major.minor.maintenance_update\n *\/\nbool SunVersion::init(const char *szVersion)\n{\n if ( ! szVersion || strlen(szVersion) == 0)\n return false;\n\n \/\/first get the major,minor,maintenance\n const char * pLast = szVersion;\n const char * pCur = szVersion;\n \/\/pEnd point to the position after the last character\n const char * pEnd = szVersion + strlen(szVersion);\n \/\/ 0 = major, 1 = minor, 2 = maintenance, 3 = update\n int nPart = 0;\n \/\/ position within part beginning with 0\n int nPartPos = 0;\n char buf[128];\n\n \/\/char must me a number 0 - 999 and no leading\n while (true)\n {\n if (pCur < pEnd && isdigit(*pCur))\n {\n if (pCur < pEnd)\n pCur ++;\n nPartPos ++;\n }\n \/\/if correct separator then form integer\n else if (\n ! (nPartPos == 0) \/\/ prevents: \".4.1\", \"..1\", part must start with digit\n && (\n \/\/separators after maintenance (1.4.1_01, 1.4.1-beta, or 1.4.1)\n ((pCur == pEnd || *pCur == '_' || *pCur == '-') && (nPart == 2 ))\n ||\n \/\/separators between major-minor and minor-maintenance\n (nPart < 2 && *pCur == '.') )\n && (\n \/\/prevent 1.4.0. 1.4.0-\n pCur + 1 == pEnd ? isdigit(*(pCur)) : 1) )\n {\n int len = pCur - pLast;\n if (len >= 127)\n return false;\n\n strncpy(buf, pLast, len);\n buf[len] = 0;\n pCur ++;\n pLast = pCur;\n\n m_arVersionParts[nPart] = atoi(buf);\n nPart ++;\n nPartPos = 0;\n if (nPart == 3)\n break;\n\n \/\/check next character\n if (! ( (pCur < pEnd)\n && ( (nPart < 3) && isdigit(*pCur))))\n return false;\n }\n else\n {\n return false;\n }\n }\n if (pCur >= pEnd)\n return true;\n \/\/We have now 1.4.1. This can be followed by _01, -beta, etc.\n \/\/ _01 (update) According to docu must not be followed by any other\n \/\/characters, but on Solaris 9 we have a 1.4.1_01a!!\n if (* (pCur - 1) == '_')\n {\/\/ _01, _02\n \/\/ update is the last part _01, _01a, part 0 is the digits parts and 1 the trailing alpha\n while (true)\n {\n if (pCur <= pEnd)\n {\n if ( ! isdigit(*pCur))\n {\n \/\/1.4.1_01-, 1.4.1_01a, the numerical part may only be 2 chars.\n int len = pCur - pLast;\n if (len > 2)\n return false;\n \/\/we've got the update: 01, 02 etc\n strncpy(buf, pLast, len);\n buf[len] = 0;\n m_arVersionParts[nPart] = atoi(buf);\n if (pCur == pEnd)\n {\n break;\n }\n if (*pCur == 'a' && (pCur + 1) == pEnd)\n {\n \/\/check if it s followed by a simple \"a\" (not specified)\n m_nUpdateSpecial = *pCur;\n break;\n }\n else if (*pCur == '-' && pCur < pEnd)\n {\n \/\/check 1.5.0_01-ea\n PreRelease pr = getPreRelease(++pCur);\n if (pr == Rel_NONE)\n return false;\n \/\/just ignore -ea because its no official release\n break;\n }\n else\n {\n return false;\n }\n }\n if (pCur < pEnd)\n pCur ++;\n else\n break;\n }\n }\n }\n \/\/ 1.4.1-ea\n else if (*(pCur - 1) == '-')\n {\n m_preRelease = getPreRelease(pCur);\n if (m_preRelease == Rel_NONE)\n return false;\n#if defined(FREEBSD)\n if (m_preRelease == Rel_FreeBSD)\n {\n pCur++; \/\/eliminate 'p'\n if (pCur < pEnd && isdigit(*pCur))\n pCur ++;\n int len = pCur - pLast -1; \/\/eliminate 'p'\n if (len >= 127)\n return false;\n strncpy(buf, (pLast+1), len); \/\/eliminate 'p'\n buf[len] = 0;\n m_nUpdateSpecial = atoi(buf)+100; \/\/hack for FBSD #i56953#\n return true;\n }\n#endif\n }\n else\n {\n return false;\n }\n return true;\n}\n\nSunVersion::PreRelease SunVersion::getPreRelease(const char *szRelease)\n{\n if (szRelease == NULL)\n return Rel_NONE;\n if( ! strcmp(szRelease,\"internal\"))\n return Rel_INTERNAL;\n else if( ! strcmp(szRelease,\"ea\"))\n return Rel_EA;\n else if( ! strcmp(szRelease,\"ea1\"))\n return Rel_EA1;\n else if( ! strcmp(szRelease,\"ea2\"))\n return Rel_EA2;\n else if( ! strcmp(szRelease,\"ea3\"))\n return Rel_EA3;\n else if ( ! strcmp(szRelease,\"beta\"))\n return Rel_BETA;\n else if ( ! strcmp(szRelease,\"beta1\"))\n return Rel_BETA1;\n else if ( ! strcmp(szRelease,\"beta2\"))\n return Rel_BETA2;\n else if ( ! strcmp(szRelease,\"beta3\"))\n return Rel_BETA3;\n else if (! strcmp(szRelease, \"rc\"))\n return Rel_RC;\n else if (! strcmp(szRelease, \"rc1\"))\n return Rel_RC1;\n else if (! strcmp(szRelease, \"rc2\"))\n return Rel_RC2;\n else if (! strcmp(szRelease, \"rc3\"))\n return Rel_RC3;\n#if defined (FREEBSD)\n else if (! strncmp(szRelease, \"p\", 1))\n return Rel_FreeBSD;\n#endif\n else\n return Rel_NONE;\n}\n\nSunVersion::~SunVersion()\n{\n\n}\n\n\/* Examples:\n a) 1.0 < 1.1\n b) 1.0 < 1.0.0\n c) 1.0 < 1.0_00\n\n returns false if both values are equal\n*\/\nbool SunVersion::operator > (const SunVersion& ver) const\n{\n if( &ver == this)\n return false;\n\n \/\/compare major.minor.maintenance\n for( int i= 0; i < 4; i ++)\n {\n \/\/ 1.4 > 1.3\n if(m_arVersionParts[i] > ver.m_arVersionParts[i])\n {\n return true;\n }\n else if (m_arVersionParts[i] < ver.m_arVersionParts[i])\n {\n return false;\n }\n }\n \/\/major.minor.maintenance_update are equal. Test for a trailing char\n if (m_nUpdateSpecial > ver.m_nUpdateSpecial)\n {\n return true;\n }\n\n \/\/Until here the versions are equal\n \/\/compare pre -release values\n if ((m_preRelease == Rel_NONE && ver.m_preRelease == Rel_NONE)\n ||\n (m_preRelease != Rel_NONE && ver.m_preRelease == Rel_NONE))\n return false;\n else if (m_preRelease == Rel_NONE && ver.m_preRelease != Rel_NONE)\n return true;\n else if (m_preRelease > ver.m_preRelease)\n return true;\n\n return false;\n}\n\nbool SunVersion::operator < (const SunVersion& ver) const\n{\n return (! operator > (ver)) && (! operator == (ver));\n}\n\nbool SunVersion::operator == (const SunVersion& ver) const\n{\n bool bRet= true;\n for(int i= 0; i < 4; i++)\n {\n if( m_arVersionParts[i] != ver.m_arVersionParts[i])\n {\n bRet= false;\n break;\n }\n }\n bRet = m_nUpdateSpecial == ver.m_nUpdateSpecial && bRet;\n bRet = m_preRelease == ver.m_preRelease && bRet;\n return bRet;\n}\n\n\n#if OSL_DEBUG_LEVEL >= 2\nSelfTest::SelfTest()\n{\n bool bRet = true;\n\n char const * versions[] = {\"1.4.0\", \"1.4.1\", \"1.0.0\", \"10.0.0\", \"10.10.0\",\n \"10.2.2\", \"10.10.0\", \"10.10.10\", \"111.0.999\",\n \"1.4.1_01\", \"9.90.99_09\", \"1.4.1_99\",\n \"1.4.1_00a\",\n \"1.4.1-ea\", \"1.4.1-beta\", \"1.4.1-rc1\",\n \"1.5.0_01-ea\", \"1.5.0_01-rc2\"};\n char const * badVersions[] = {\".4.0\", \"..1\", \"\", \"10.0\", \"10.10.0.\", \"10.10.0-\", \"10.10.0.\",\n \"10.2-2\", \"10_10.0\", \"10..10\",\"10.10\", \"a.0.999\",\n \"1.4b.1_01\", \"9.90.-99_09\", \"1.4.1_99-\",\n \"1.4.1_00a2\", \"1.4.0_z01z\", \"1.4.1__99A\",\n \"1.4.1-1ea\", \"1.5.0_010\", \"1.5.0._01-\", \"1.5.0_01-eac\"};\n char const * orderedVer[] = { \"1.3.1-ea\", \"1.3.1-beta\", \"1.3.1-rc1\",\n \"1.3.1\", \"1.3.1_00a\", \"1.3.1_01\", \"1.3.1_01a\",\n \"1.3.2\", \"1.4.0\", \"1.5.0_01-ea\", \"2.0.0\"};\n\n int num = sizeof (versions) \/ sizeof(char*);\n int numBad = sizeof (badVersions) \/ sizeof(char*);\n int numOrdered = sizeof (orderedVer) \/ sizeof(char*);\n \/\/parsing test (positive)\n for (int i = 0; i < num; i++)\n {\n SunVersion ver(versions[i]);\n if ( ! ver)\n {\n bRet = false;\n break;\n }\n }\n OSL_ENSURE(bRet, \"SunVersion selftest failed\");\n \/\/Parsing test (negative)\n for ( int i = 0; i < numBad; i++)\n {\n SunVersion ver(badVersions[i]);\n if (ver)\n {\n bRet = false;\n break;\n }\n }\n OSL_ENSURE(bRet, \"SunVersion selftest failed\");\n\n \/\/ Ordering test\n bRet = true;\n int j = 0;\n for (int i = 0; i < numOrdered; i ++)\n {\n SunVersion curVer(orderedVer[i]);\n if ( ! curVer)\n {\n bRet = false;\n break;\n }\n for (j = 0; j < numOrdered; j++)\n {\n SunVersion compVer(orderedVer[j]);\n if (i < j)\n {\n if ( !(curVer < compVer))\n {\n bRet = false;\n break;\n }\n }\n else if ( i == j)\n {\n if (! (curVer == compVer\n && ! (curVer > compVer)\n && ! (curVer < compVer)))\n {\n bRet = false;\n break;\n }\n }\n else if (i > j)\n {\n if ( !(curVer > compVer))\n {\n bRet = false;\n break;\n }\n }\n }\n if ( ! bRet)\n break;\n }\n if (bRet)\n JFW_TRACE2(\"Testing class SunVersion succeeded.\");\n else\n OSL_ENSURE(bRet, \"[Java framework] sunjavaplugin: SunVersion self test failed.\\n\");\n}\n#endif\n\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright 2020 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n#include \"src\/linter.h\"\n\n#include \n#include \n#include \n#include \n\n#include \"absl\/strings\/string_view.h\"\n#include \"absl\/strings\/str_cat.h\"\n#include \"zetasql\/parser\/parse_tree_visitor.h\"\n#include \"zetasql\/parser\/parser.h\"\n#include \"zetasql\/public\/parse_helpers.h\"\n\nnamespace zetasql {\n\nnamespace linter {\n\n\nabsl::Status printASTTree(absl::string_view sql) {\n absl::Status return_status;\n std::unique_ptr output;\n\n return_status = zetasql::ParseStatement(sql,\n zetasql::ParserOptions(), &output);\n\n std::cout << \"Status for sql \\\" \" << sql << \"\\\" = \"\n << return_status.ToString() << std::endl;\n\n if ( return_status.ok() ) {\n std::cout << output -> statement() -> DebugString() << std::endl;\n }\n\n return return_status;\n}\n\nabsl::Status checkStatement(absl::string_view sql) {\n std::unique_ptr output;\n return zetasql::ParseStatement(sql,\n zetasql::ParserOptions(), &output);\n}\n\n\nabsl::Status checkLineLength(absl::string_view sql, int lineLimit,\n const char delimeter) {\n int lineSize = 0;\n int lineNumber = 1;\n for (int i=0; i(sql.size()); i++) {\n if ( sql[i] == delimeter ) {\n lineSize = 0;\n lineNumber++;\n } else {\n lineSize++;\n }\n if ( lineSize > lineLimit ) {\n return absl::Status(\n absl::StatusCode::kFailedPrecondition,\n absl::StrCat(\"Lines should be <= \", std::to_string(lineLimit),\n \" characters long [\", std::to_string(lineNumber), \",1]\") );\n }\n }\n return absl::OkStatus();\n}\n\nvoid KeywordExtractor::extract() {\n \/\/ TODO(orhan_uysal): Implement a keyword extractor\n \/\/ that pushes all keyword nodes to vector \"keywords\"\n}\n\nbool allUpperCase(const zetasql::ASTNode* x) {\n \/\/ TODO(orhan_uysal): Implement a function checking\n \/\/ if all characters in ASTNode(keyword node) is uppercase\n return true;\n}\n\nabsl::Status checkUppercaseKeywords(absl::string_view sql) {\n std::vector *keywords;\n *keywords = std::vector();\n\n std::unique_ptr output;\n\n absl::Status parser_status = zetasql::ParseStatement(sql,\n zetasql::ParserOptions(), &output);\n\n if ( !parser_status.ok() )\n return parser_status;\n\n \/\/ KeywordExtractor(output->statement(), keywords).extract();\n\n for (const zetasql::ASTNode *keyword : *keywords) {\n if ( !allUpperCase(keyword) ) {\n return absl::Status(\n absl::StatusCode::kFailedPrecondition, \"\");\n }\n }\n\n return absl::OkStatus();\n}\n\n} \/\/ namespace linter\n} \/\/ namespace zetasql\nUpdate keywords to be a vector instear of a pointer to vector. This will fix build error: keyword is uninitialized when used here...\/\/\n\/\/ Copyright 2020 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n#include \"src\/linter.h\"\n\n#include \n#include \n#include \n#include \n\n#include \"absl\/strings\/string_view.h\"\n#include \"absl\/strings\/str_cat.h\"\n#include \"zetasql\/parser\/parse_tree_visitor.h\"\n#include \"zetasql\/parser\/parser.h\"\n#include \"zetasql\/public\/parse_helpers.h\"\n\nnamespace zetasql {\n\nnamespace linter {\n\n\nabsl::Status printASTTree(absl::string_view sql) {\n absl::Status return_status;\n std::unique_ptr output;\n\n return_status = zetasql::ParseStatement(sql,\n zetasql::ParserOptions(), &output);\n\n std::cout << \"Status for sql \\\" \" << sql << \"\\\" = \"\n << return_status.ToString() << std::endl;\n\n if ( return_status.ok() ) {\n std::cout << output -> statement() -> DebugString() << std::endl;\n }\n\n return return_status;\n}\n\nabsl::Status checkStatement(absl::string_view sql) {\n std::unique_ptr output;\n return zetasql::ParseStatement(sql,\n zetasql::ParserOptions(), &output);\n}\n\n\nabsl::Status checkLineLength(absl::string_view sql, int lineLimit,\n const char delimeter) {\n int lineSize = 0;\n int lineNumber = 1;\n for (int i=0; i(sql.size()); i++) {\n if ( sql[i] == delimeter ) {\n lineSize = 0;\n lineNumber++;\n } else {\n lineSize++;\n }\n if ( lineSize > lineLimit ) {\n return absl::Status(\n absl::StatusCode::kFailedPrecondition,\n absl::StrCat(\"Lines should be <= \", std::to_string(lineLimit),\n \" characters long [\", std::to_string(lineNumber), \",1]\") );\n }\n }\n return absl::OkStatus();\n}\n\nvoid KeywordExtractor::extract() {\n \/\/ TODO(orhan_uysal): Implement a keyword extractor\n \/\/ that pushes all keyword nodes to vector \"keywords\"\n}\n\nbool allUpperCase(const zetasql::ASTNode* x) {\n \/\/ TODO(orhan_uysal): Implement a function checking\n \/\/ if all characters in ASTNode(keyword node) is uppercase\n return true;\n}\n\nabsl::Status checkUppercaseKeywords(absl::string_view sql) {\n std::vector keywords{};\n\n std::unique_ptr output;\n\n absl::Status parser_status = zetasql::ParseStatement(sql,\n zetasql::ParserOptions(), &output);\n\n if ( !parser_status.ok() )\n return parser_status;\n \/\/ TODO(orhan_uysal): Implement KeywordExtractor.\n\n for (const zetasql::ASTNode *keyword : keywords) {\n if ( !allUpperCase(keyword) ) {\n return absl::Status(\n absl::StatusCode::kFailedPrecondition, \"\");\n }\n }\n\n return absl::OkStatus();\n}\n\n} \/\/ namespace linter\n} \/\/ namespace zetasql\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright (C) Zbigniew Zagorski ,\n\/\/ licensed to the public under the terms of the GNU GPL (>= 2)\n\/\/ see the file COPYING for details\n\/\/ I.e., do what you like, but keep copyright and there's NO WARRANTY.\n\/\/\n\n#include \"tinfra\/symbol.h\"\n\n#include \n\n#include \"tinfra\/mo.h\"\n\nnamespace tinfra_mo_test {\n TINFRA_SYMBOL_IMPL(x);\n TINFRA_SYMBOL_IMPL(y);\n TINFRA_SYMBOL_IMPL(top_left);\n TINFRA_SYMBOL_IMPL(bottom_right);\n struct point {\n int x;\n int y;\n TINFRA_MO_MANIFEST(point) {\n TINFRA_MO_FIELD(x);\n TINFRA_MO_FIELD(y);\n }\n };\n \n struct rect {\n point top_left;\n point bottom_right;\n \n TINFRA_MO_MANIFEST(rect) {\n TINFRA_MO_FIELD(top_left);\n TINFRA_MO_FIELD(bottom_right);\n }\n };\n \n class point_bean {\n int x;\n int y;\n \n public:\n int getX() const { return x; }\n int getY() const { return y; }\n \n void setX(int v) { x = v; }\n void setY(int v) { y = v; }\n \n template \n void apply(F& f) const\n {\n f(S::x, &point_bean::getX, &point_bean::setX);\n f(S::y, &point_bean::getY, &point_bean::setY);\n }\n };\n}\n\nnamespace tinfra {\n template<> \n struct mo_traits: public tinfra::struct_mo_traits {};\n \n template<> \n struct mo_traits: public tinfra::struct_mo_traits {};\n \n template \n struct mo_bean_processor_adapter {\n MO const& mo;\n F& f;\n template \n void operator()(tinfra::symbol const& sym, T (MO::*getter)() const, X)\n {\n f(sym, (mo.*getter)());\n }\n };\n \n template \n struct mo_bean_mutator_adapter {\n MO& mo;\n F& f;\n template \n void operator()(tinfra::symbol const& sym, T (MO::*getter)() const, void (MO::*setter)(T const& v))\n {\n T orig = (mo.*getter)();\n T victim(orig);\n f(sym, victim);\n if( !(victim == orig) ) {\n mo.*setter(victim);\n }\n }\n \n template \n void operator()(tinfra::symbol const& sym, T (MO::*getter)() const, void (MO::*setter)(T v))\n {\n T orig = (mo.*getter)();\n T victim(orig);\n f(sym, victim);\n if( !(victim == orig) ) {\n (mo.*setter)(victim);\n }\n }\n };\n \n template \n void mo_process(tinfra_mo_test::point_bean const& v, F& f)\n {\n mo_bean_processor_adapter adapter = {v, f};\n v.apply(adapter);\n }\n \n template \n void mo_mutate(tinfra_mo_test::point_bean& v, F& f)\n {\n mo_bean_mutator_adapter adapter = { v, f };\n v.apply(adapter);\n }\n}\n\nSUITE(tinfra)\n{\n using tinfra_mo_test::point;\n using tinfra_mo_test::rect;\n using tinfra_mo_test::point_bean;\n using tinfra::symbol;\n \n struct dummy_functor {\n int sum;\n int count;\n void operator()(symbol const&, int const& v) {\n sum+=v;\n count++;\n }\n template \n void mstruct(symbol const&, T const& v) {\n tinfra::mo_process(v, *this);\n }\n };\n \n TEST(mo_process_api)\n {\n dummy_functor f = {0,0};\n const point a = { 3,-2};\n tinfra::mo_process(a, f);\n CHECK_EQUAL(1, f.sum);\n CHECK_EQUAL(2, f.count);\n }\n \n TEST(mo_process_complex)\n {\n dummy_functor f = {0};\n const rect r = { { 3,-2} , {4, -3} };\n tinfra::mo_process(r, f);\n CHECK_EQUAL(2, f.sum);\n CHECK_EQUAL(4, f.count);\n }\n \n TEST(mo_process_bean_api)\n {\n dummy_functor f = {0};\n point_bean a;\n a.setX(1);\n a.setY(2);\n tinfra::mo_process(a, f);\n CHECK_EQUAL(3, f.sum);\n }\n \n struct foo_modifier {\n int count;\n void operator()(symbol const&, int& v ) { \n v = 1; \n count++;\n }\n \n template \n void mstruct(symbol const&, T& v) {\n tinfra::mo_mutate(v, *this);\n }\n };\n \n TEST(mo_mutate_api)\n {\n foo_modifier f = {0};\n point a = { 0, 0 };\n tinfra::mo_mutate(a, f);\n \n CHECK_EQUAL(1, a.x);\n CHECK_EQUAL(1, a.y);\n CHECK_EQUAL(2, f.count);\n }\n \n TEST(mo_mutate_complex)\n {\n foo_modifier f = {0};\n rect r = { {0, 0}, {2,2} };\n tinfra::mo_mutate(r, f);\n \n CHECK_EQUAL(1, r.top_left.x);\n CHECK_EQUAL(1, r.top_left.y);\n CHECK_EQUAL(1, r.bottom_right.x);\n CHECK_EQUAL(1, r.bottom_right.y);\n CHECK_EQUAL(4, f.count);\n }\n \n TEST(mo_mutate_bean_api)\n {\n foo_modifier f;\n point_bean a;\n a.setX(0);\n a.setY(2);\n \n tinfra::mo_mutate(a, f);\n \n CHECK_EQUAL(1, a.getX());\n CHECK_EQUAL(1, a.getY());\n }\n}\n\n\/\/ jedit: :tabSize=8:indentSize=4:noTabs=true:mode=c++:\ntest_mo: added proof of concept for SFINAE based matching of MO objects in functor (works on gcc 3.4.5)\/\/\n\/\/ Copyright (C) Zbigniew Zagorski ,\n\/\/ licensed to the public under the terms of the GNU GPL (>= 2)\n\/\/ see the file COPYING for details\n\/\/ I.e., do what you like, but keep copyright and there's NO WARRANTY.\n\/\/\n\n#include \"tinfra\/symbol.h\"\n\n#include \n\n#include \"tinfra\/mo.h\"\n\nstruct true_type { enum { value = 1 } ; };\n\nstruct false_type { enum { value = 1 } ; };\n\nnamespace tinfra_mo_test {\n TINFRA_SYMBOL_IMPL(x);\n TINFRA_SYMBOL_IMPL(y);\n TINFRA_SYMBOL_IMPL(z);\n TINFRA_SYMBOL_IMPL(top_left);\n TINFRA_SYMBOL_IMPL(bottom_right);\n \n \n struct point {\n int x;\n int y;\n TINFRA_MO_MANIFEST(point) {\n TINFRA_MO_FIELD(x);\n TINFRA_MO_FIELD(y);\n }\n };\n \n struct point3d {\n typedef true_type tinfra_is_mo;\n int x;\n int y;\n int z;\n TINFRA_MO_MANIFEST(point) {\n TINFRA_MO_FIELD(x);\n TINFRA_MO_FIELD(y);\n TINFRA_MO_FIELD(z);\n }\n };\n \n struct rect {\n point top_left;\n point bottom_right;\n \n TINFRA_MO_MANIFEST(rect) {\n TINFRA_MO_FIELD(top_left);\n TINFRA_MO_FIELD(bottom_right);\n }\n };\n \n class point_bean {\n int x;\n int y;\n \n public:\n int getX() const { return x; }\n int getY() const { return y; }\n \n void setX(int v) { x = v; }\n void setY(int v) { y = v; }\n \n template \n void apply(F& f) const\n {\n f(S::x, &point_bean::getX, &point_bean::setX);\n f(S::y, &point_bean::getY, &point_bean::setY);\n }\n };\n}\n\nnamespace tinfra {\n template<> \n struct mo_traits: public tinfra::struct_mo_traits {};\n \n template<> \n struct mo_traits: public tinfra::struct_mo_traits {};\n \n template \n struct mo_bean_processor_adapter {\n MO const& mo;\n F& f;\n template \n void operator()(tinfra::symbol const& sym, T (MO::*getter)() const, X)\n {\n f(sym, (mo.*getter)());\n }\n };\n \n template \n struct mo_bean_mutator_adapter {\n MO& mo;\n F& f;\n template \n void operator()(tinfra::symbol const& sym, T (MO::*getter)() const, void (MO::*setter)(T const& v))\n {\n T orig = (mo.*getter)();\n T victim(orig);\n f(sym, victim);\n if( !(victim == orig) ) {\n mo.*setter(victim);\n }\n }\n \n template \n void operator()(tinfra::symbol const& sym, T (MO::*getter)() const, void (MO::*setter)(T v))\n {\n T orig = (mo.*getter)();\n T victim(orig);\n f(sym, victim);\n if( !(victim == orig) ) {\n (mo.*setter)(victim);\n }\n }\n };\n \n template \n void mo_process(tinfra_mo_test::point_bean const& v, F& f)\n {\n mo_bean_processor_adapter adapter = {v, f};\n v.apply(adapter);\n }\n \n template \n void mo_mutate(tinfra_mo_test::point_bean& v, F& f)\n {\n mo_bean_mutator_adapter adapter = { v, f };\n v.apply(adapter);\n }\n}\n\nSUITE(tinfra)\n{\n using tinfra_mo_test::point;\n using tinfra_mo_test::rect;\n using tinfra_mo_test::point_bean;\n using tinfra::symbol;\n \n struct dummy_functor {\n int sum;\n int count;\n void operator()(symbol const&, int const& v) {\n sum+=v;\n count++;\n }\n template \n void mstruct(symbol const&, T const& v) {\n tinfra::mo_process(v, *this);\n }\n };\n \n TEST(mo_process_api)\n {\n dummy_functor f = {0,0};\n const point a = { 3,-2};\n tinfra::mo_process(a, f);\n CHECK_EQUAL(1, f.sum);\n CHECK_EQUAL(2, f.count);\n }\n \n TEST(mo_process_complex)\n {\n dummy_functor f = {0};\n const rect r = { { 3,-2} , {4, -3} };\n tinfra::mo_process(r, f);\n CHECK_EQUAL(2, f.sum);\n CHECK_EQUAL(4, f.count);\n }\n \n TEST(mo_process_bean_api)\n {\n dummy_functor f = {0};\n point_bean a;\n a.setX(1);\n a.setY(2);\n tinfra::mo_process(a, f);\n CHECK_EQUAL(3, f.sum);\n }\n \n struct foo_modifier {\n int count;\n void operator()(symbol const&, int& v ) { \n v = 1; \n count++;\n }\n \n template \n void mstruct(symbol const&, T& v) {\n tinfra::mo_mutate(v, *this);\n }\n };\n \n TEST(mo_mutate_api)\n {\n foo_modifier f = {0};\n point a = { 0, 0 };\n tinfra::mo_mutate(a, f);\n \n CHECK_EQUAL(1, a.x);\n CHECK_EQUAL(1, a.y);\n CHECK_EQUAL(2, f.count);\n }\n \n TEST(mo_mutate_complex)\n {\n foo_modifier f = {0};\n rect r = { {0, 0}, {2,2} };\n tinfra::mo_mutate(r, f);\n \n CHECK_EQUAL(1, r.top_left.x);\n CHECK_EQUAL(1, r.top_left.y);\n CHECK_EQUAL(1, r.bottom_right.x);\n CHECK_EQUAL(1, r.bottom_right.y);\n CHECK_EQUAL(4, f.count);\n }\n \n TEST(mo_mutate_bean_api)\n {\n foo_modifier f;\n point_bean a;\n a.setX(0);\n a.setY(2);\n \n tinfra::mo_mutate(a, f);\n \n CHECK_EQUAL(1, a.getX());\n CHECK_EQUAL(1, a.getY());\n }\n \n struct sfinae_functor {\n int sum;\n void operator()(symbol const&, int const& v ) {\n sum += v;\n }\n \n bool sfinae_matched;\n template \n void operator()(symbol const&, T const& v, typename T::tinfra_is_mo = true_type()) {\n sfinae_matched = true;\n tinfra::mo_process(v, *this);\n }\n };\n \n TEST(mo_sfinae_processor)\n {\n sfinae_functor functor = {0, false};\n const tinfra_mo_test::point3d foo = { 1,2,3 };\n \n tinfra::process(tinfra::symbol(\"a\"), foo, functor);\n \n CHECK( functor.sfinae_matched);\n \n CHECK_EQUAL(6, functor.sum); \n }\n \n struct sfinae_mutator {\n void operator()(symbol const&, int& v ) {\n v = 0;\n }\n \n bool sfinae_matched;\n template \n void operator()(symbol const&, T& v, typename T::tinfra_is_mo = true_type()) {\n sfinae_matched = true;\n \/\/v.foo =2; uncomment to see how unreadable error is\n tinfra::mo_mutate(v, *this);\n }\n };\n \n TEST(mo_sfinae_mutator)\n {\n sfinae_mutator functor = {false};\n tinfra_mo_test::point3d foo = { 1,2,3 };\n \n tinfra::mutate(tinfra::symbol(\"a\"), foo, functor);\n \n CHECK( functor.sfinae_matched);\n \n CHECK_EQUAL(0, foo.x);\n CHECK_EQUAL(0, foo.y);\n CHECK_EQUAL(0, foo.z);\n }\n}\n\n\/\/ jedit: :tabSize=8:indentSize=4:noTabs=true:mode=c++:\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors\n\/\/ Licensed under the MIT License:\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\n#include \"io.h\"\n#include \"debug.h\"\n#include \"miniposix.h\"\n#include \n#include \n\n#if !_WIN32\n#include \n#endif\n\nnamespace kj {\n\nInputStream::~InputStream() noexcept(false) {}\nOutputStream::~OutputStream() noexcept(false) {}\nBufferedInputStream::~BufferedInputStream() noexcept(false) {}\nBufferedOutputStream::~BufferedOutputStream() noexcept(false) {}\n\nsize_t InputStream::read(void* buffer, size_t minBytes, size_t maxBytes) {\n size_t n = tryRead(buffer, minBytes, maxBytes);\n KJ_REQUIRE(n >= minBytes, \"Premature EOF\") {\n \/\/ Pretend we read zeros from the input.\n memset(reinterpret_cast(buffer) + n, 0, minBytes - n);\n return minBytes;\n }\n return n;\n}\n\nvoid InputStream::skip(size_t bytes) {\n char scratch[8192];\n while (bytes > 0) {\n size_t amount = std::min(bytes, sizeof(scratch));\n read(scratch, amount);\n bytes -= amount;\n }\n}\n\nvoid OutputStream::write(ArrayPtr> pieces) {\n for (auto piece: pieces) {\n write(piece.begin(), piece.size());\n }\n}\n\nArrayPtr BufferedInputStream::getReadBuffer() {\n auto result = tryGetReadBuffer();\n KJ_REQUIRE(result.size() > 0, \"Premature EOF\");\n return result;\n}\n\n\/\/ =======================================================================================\n\nBufferedInputStreamWrapper::BufferedInputStreamWrapper(InputStream& inner, ArrayPtr buffer)\n : inner(inner), ownedBuffer(buffer == nullptr ? heapArray(8192) : nullptr),\n buffer(buffer == nullptr ? ownedBuffer : buffer) {}\n\nBufferedInputStreamWrapper::~BufferedInputStreamWrapper() noexcept(false) {}\n\nArrayPtr BufferedInputStreamWrapper::tryGetReadBuffer() {\n if (bufferAvailable.size() == 0) {\n size_t n = inner.tryRead(buffer.begin(), 1, buffer.size());\n bufferAvailable = buffer.slice(0, n);\n }\n\n return bufferAvailable;\n}\n\nsize_t BufferedInputStreamWrapper::tryRead(void* dst, size_t minBytes, size_t maxBytes) {\n if (minBytes <= bufferAvailable.size()) {\n \/\/ Serve from current buffer.\n size_t n = std::min(bufferAvailable.size(), maxBytes);\n memcpy(dst, bufferAvailable.begin(), n);\n bufferAvailable = bufferAvailable.slice(n, bufferAvailable.size());\n return n;\n } else {\n \/\/ Copy current available into destination.\n memcpy(dst, bufferAvailable.begin(), bufferAvailable.size());\n size_t fromFirstBuffer = bufferAvailable.size();\n\n dst = reinterpret_cast(dst) + fromFirstBuffer;\n minBytes -= fromFirstBuffer;\n maxBytes -= fromFirstBuffer;\n\n if (maxBytes <= buffer.size()) {\n \/\/ Read the next buffer-full.\n size_t n = inner.read(buffer.begin(), minBytes, buffer.size());\n size_t fromSecondBuffer = std::min(n, maxBytes);\n memcpy(dst, buffer.begin(), fromSecondBuffer);\n bufferAvailable = buffer.slice(fromSecondBuffer, n);\n return fromFirstBuffer + fromSecondBuffer;\n } else {\n \/\/ Forward large read to the underlying stream.\n bufferAvailable = nullptr;\n return fromFirstBuffer + inner.read(dst, minBytes, maxBytes);\n }\n }\n}\n\nvoid BufferedInputStreamWrapper::skip(size_t bytes) {\n if (bytes <= bufferAvailable.size()) {\n bufferAvailable = bufferAvailable.slice(bytes, bufferAvailable.size());\n } else {\n bytes -= bufferAvailable.size();\n if (bytes <= buffer.size()) {\n \/\/ Read the next buffer-full.\n size_t n = inner.read(buffer.begin(), bytes, buffer.size());\n bufferAvailable = buffer.slice(bytes, n);\n } else {\n \/\/ Forward large skip to the underlying stream.\n bufferAvailable = nullptr;\n inner.skip(bytes);\n }\n }\n}\n\n\/\/ -------------------------------------------------------------------\n\nBufferedOutputStreamWrapper::BufferedOutputStreamWrapper(OutputStream& inner, ArrayPtr buffer)\n : inner(inner),\n ownedBuffer(buffer == nullptr ? heapArray(8192) : nullptr),\n buffer(buffer == nullptr ? ownedBuffer : buffer),\n bufferPos(this->buffer.begin()) {}\n\nBufferedOutputStreamWrapper::~BufferedOutputStreamWrapper() noexcept(false) {\n unwindDetector.catchExceptionsIfUnwinding([&]() {\n flush();\n });\n}\n\nvoid BufferedOutputStreamWrapper::flush() {\n if (bufferPos > buffer.begin()) {\n inner.write(buffer.begin(), bufferPos - buffer.begin());\n bufferPos = buffer.begin();\n }\n}\n\nArrayPtr BufferedOutputStreamWrapper::getWriteBuffer() {\n return arrayPtr(bufferPos, buffer.end());\n}\n\nvoid BufferedOutputStreamWrapper::write(const void* src, size_t size) {\n if (src == bufferPos) {\n \/\/ Oh goody, the caller wrote directly into our buffer.\n bufferPos += size;\n } else {\n size_t available = buffer.end() - bufferPos;\n\n if (size <= available) {\n memcpy(bufferPos, src, size);\n bufferPos += size;\n } else if (size <= buffer.size()) {\n \/\/ Too much for this buffer, but not a full buffer's worth, so we'll go ahead and copy.\n memcpy(bufferPos, src, available);\n inner.write(buffer.begin(), buffer.size());\n\n size -= available;\n src = reinterpret_cast(src) + available;\n\n memcpy(buffer.begin(), src, size);\n bufferPos = buffer.begin() + size;\n } else {\n \/\/ Writing so much data that we might as well write directly to avoid a copy.\n inner.write(buffer.begin(), bufferPos - buffer.begin());\n bufferPos = buffer.begin();\n inner.write(src, size);\n }\n }\n}\n\n\/\/ =======================================================================================\n\nArrayInputStream::ArrayInputStream(ArrayPtr array): array(array) {}\nArrayInputStream::~ArrayInputStream() noexcept(false) {}\n\nArrayPtr ArrayInputStream::tryGetReadBuffer() {\n return array;\n}\n\nsize_t ArrayInputStream::tryRead(void* dst, size_t minBytes, size_t maxBytes) {\n size_t n = std::min(maxBytes, array.size());\n memcpy(dst, array.begin(), n);\n array = array.slice(n, array.size());\n return n;\n}\n\nvoid ArrayInputStream::skip(size_t bytes) {\n KJ_REQUIRE(array.size() >= bytes, \"ArrayInputStream ended prematurely.\") {\n bytes = array.size();\n break;\n }\n array = array.slice(bytes, array.size());\n}\n\n\/\/ -------------------------------------------------------------------\n\nArrayOutputStream::ArrayOutputStream(ArrayPtr array): array(array), fillPos(array.begin()) {}\nArrayOutputStream::~ArrayOutputStream() noexcept(false) {}\n\nArrayPtr ArrayOutputStream::getWriteBuffer() {\n return arrayPtr(fillPos, array.end());\n}\n\nvoid ArrayOutputStream::write(const void* src, size_t size) {\n if (src == fillPos) {\n \/\/ Oh goody, the caller wrote directly into our buffer.\n KJ_REQUIRE(size <= array.end() - fillPos);\n fillPos += size;\n } else {\n KJ_REQUIRE(size <= (size_t)(array.end() - fillPos),\n \"ArrayOutputStream's backing array was not large enough for the data written.\");\n memcpy(fillPos, src, size);\n fillPos += size;\n }\n}\n\n\/\/ -------------------------------------------------------------------\n\nVectorOutputStream::VectorOutputStream(size_t initialCapacity)\n : vector(heapArray(initialCapacity)), fillPos(vector.begin()) {}\nVectorOutputStream::~VectorOutputStream() noexcept(false) {}\n\nArrayPtr VectorOutputStream::getWriteBuffer() {\n \/\/ Grow if needed.\n if (fillPos == vector.end()) {\n grow(vector.size() + 1);\n }\n\n return arrayPtr(fillPos, vector.end());\n}\n\nvoid VectorOutputStream::write(const void* src, size_t size) {\n if (src == fillPos) {\n \/\/ Oh goody, the caller wrote directly into our buffer.\n KJ_REQUIRE(size <= vector.end() - fillPos);\n fillPos += size;\n } else {\n if (vector.end() - fillPos < size) {\n grow(fillPos - vector.begin() + size);\n }\n\n memcpy(fillPos, src, size);\n fillPos += size;\n }\n}\n\nvoid VectorOutputStream::grow(size_t minSize) {\n size_t newSize = vector.size() * 2;\n while (newSize < minSize) newSize *= 2;\n auto newVector = heapArray(newSize);\n memcpy(newVector.begin(), vector.begin(), fillPos - vector.begin());\n fillPos = fillPos - vector.begin() + newVector.begin();\n vector = kj::mv(newVector);\n}\n\n\/\/ =======================================================================================\n\nAutoCloseFd::~AutoCloseFd() noexcept(false) {\n if (fd >= 0) {\n unwindDetector.catchExceptionsIfUnwinding([&]() {\n \/\/ Don't use SYSCALL() here because close() should not be repeated on EINTR.\n if (miniposix::close(fd) < 0) {\n KJ_FAIL_SYSCALL(\"close\", errno, fd) {\n break;\n }\n }\n });\n }\n}\n\nFdInputStream::~FdInputStream() noexcept(false) {}\n\nsize_t FdInputStream::tryRead(void* buffer, size_t minBytes, size_t maxBytes) {\n byte* pos = reinterpret_cast(buffer);\n byte* min = pos + minBytes;\n byte* max = pos + maxBytes;\n\n while (pos < min) {\n miniposix::ssize_t n;\n KJ_SYSCALL(n = miniposix::read(fd, pos, max - pos), fd);\n if (n == 0) {\n break;\n }\n pos += n;\n }\n\n return pos - reinterpret_cast(buffer);\n}\n\nFdOutputStream::~FdOutputStream() noexcept(false) {}\n\nvoid FdOutputStream::write(const void* buffer, size_t size) {\n const char* pos = reinterpret_cast(buffer);\n\n while (size > 0) {\n miniposix::ssize_t n;\n KJ_SYSCALL(n = miniposix::write(fd, pos, size), fd);\n KJ_ASSERT(n > 0, \"write() returned zero.\");\n pos += n;\n size -= n;\n }\n}\n\nvoid FdOutputStream::write(ArrayPtr> pieces) {\n#if _WIN32\n \/\/ Windows has no reasonable writev(). It has WriteFileGather, but this call has the unreasonable\n \/\/ restriction that each segment must be page-aligned. So, fall back to write().\n\n for (auto piece: pieces) {\n write(piece.begin(), piece.size());\n }\n\n#else\n const size_t iovmax = miniposix::iovMax(pieces.size());\n while (pieces.size() > iovmax) {\n write(pieces.slice(0, iovmax));\n pieces = pieces.slice(iovmax, pieces.size());\n }\n\n KJ_STACK_ARRAY(struct iovec, iov, pieces.size(), 16, 128);\n\n for (uint i = 0; i < pieces.size(); i++) {\n \/\/ writev() interface is not const-correct. :(\n iov[i].iov_base = const_cast(pieces[i].begin());\n iov[i].iov_len = pieces[i].size();\n }\n\n struct iovec* current = iov.begin();\n\n \/\/ Advance past any leading empty buffers so that a write full of only empty buffers does not\n \/\/ cause a syscall at all.\n while (current < iov.end() && current->iov_len == 0) {\n ++current;\n }\n\n while (current < iov.end()) {\n \/\/ Issue the write.\n ssize_t n = 0;\n KJ_SYSCALL(n = ::writev(fd, current, iov.end() - current), fd);\n KJ_ASSERT(n > 0, \"writev() returned zero.\");\n\n \/\/ Advance past all buffers that were fully-written.\n while (current < iov.end() && static_cast(n) >= current->iov_len) {\n n -= current->iov_len;\n ++current;\n }\n\n \/\/ If we only partially-wrote one of the buffers, adjust the pointer and size to include only\n \/\/ the unwritten part.\n if (n > 0) {\n current->iov_base = reinterpret_cast(current->iov_base) + n;\n current->iov_len -= n;\n }\n }\n#endif\n}\n\n} \/\/ namespace kj\nkj\/io: Make FdOutputStream::write fallback to OutputStream::write.\/\/ Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors\n\/\/ Licensed under the MIT License:\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\n#include \"io.h\"\n#include \"debug.h\"\n#include \"miniposix.h\"\n#include \n#include \n\n#if !_WIN32\n#include \n#endif\n\nnamespace kj {\n\nInputStream::~InputStream() noexcept(false) {}\nOutputStream::~OutputStream() noexcept(false) {}\nBufferedInputStream::~BufferedInputStream() noexcept(false) {}\nBufferedOutputStream::~BufferedOutputStream() noexcept(false) {}\n\nsize_t InputStream::read(void* buffer, size_t minBytes, size_t maxBytes) {\n size_t n = tryRead(buffer, minBytes, maxBytes);\n KJ_REQUIRE(n >= minBytes, \"Premature EOF\") {\n \/\/ Pretend we read zeros from the input.\n memset(reinterpret_cast(buffer) + n, 0, minBytes - n);\n return minBytes;\n }\n return n;\n}\n\nvoid InputStream::skip(size_t bytes) {\n char scratch[8192];\n while (bytes > 0) {\n size_t amount = std::min(bytes, sizeof(scratch));\n read(scratch, amount);\n bytes -= amount;\n }\n}\n\nvoid OutputStream::write(ArrayPtr> pieces) {\n for (auto piece: pieces) {\n write(piece.begin(), piece.size());\n }\n}\n\nArrayPtr BufferedInputStream::getReadBuffer() {\n auto result = tryGetReadBuffer();\n KJ_REQUIRE(result.size() > 0, \"Premature EOF\");\n return result;\n}\n\n\/\/ =======================================================================================\n\nBufferedInputStreamWrapper::BufferedInputStreamWrapper(InputStream& inner, ArrayPtr buffer)\n : inner(inner), ownedBuffer(buffer == nullptr ? heapArray(8192) : nullptr),\n buffer(buffer == nullptr ? ownedBuffer : buffer) {}\n\nBufferedInputStreamWrapper::~BufferedInputStreamWrapper() noexcept(false) {}\n\nArrayPtr BufferedInputStreamWrapper::tryGetReadBuffer() {\n if (bufferAvailable.size() == 0) {\n size_t n = inner.tryRead(buffer.begin(), 1, buffer.size());\n bufferAvailable = buffer.slice(0, n);\n }\n\n return bufferAvailable;\n}\n\nsize_t BufferedInputStreamWrapper::tryRead(void* dst, size_t minBytes, size_t maxBytes) {\n if (minBytes <= bufferAvailable.size()) {\n \/\/ Serve from current buffer.\n size_t n = std::min(bufferAvailable.size(), maxBytes);\n memcpy(dst, bufferAvailable.begin(), n);\n bufferAvailable = bufferAvailable.slice(n, bufferAvailable.size());\n return n;\n } else {\n \/\/ Copy current available into destination.\n memcpy(dst, bufferAvailable.begin(), bufferAvailable.size());\n size_t fromFirstBuffer = bufferAvailable.size();\n\n dst = reinterpret_cast(dst) + fromFirstBuffer;\n minBytes -= fromFirstBuffer;\n maxBytes -= fromFirstBuffer;\n\n if (maxBytes <= buffer.size()) {\n \/\/ Read the next buffer-full.\n size_t n = inner.read(buffer.begin(), minBytes, buffer.size());\n size_t fromSecondBuffer = std::min(n, maxBytes);\n memcpy(dst, buffer.begin(), fromSecondBuffer);\n bufferAvailable = buffer.slice(fromSecondBuffer, n);\n return fromFirstBuffer + fromSecondBuffer;\n } else {\n \/\/ Forward large read to the underlying stream.\n bufferAvailable = nullptr;\n return fromFirstBuffer + inner.read(dst, minBytes, maxBytes);\n }\n }\n}\n\nvoid BufferedInputStreamWrapper::skip(size_t bytes) {\n if (bytes <= bufferAvailable.size()) {\n bufferAvailable = bufferAvailable.slice(bytes, bufferAvailable.size());\n } else {\n bytes -= bufferAvailable.size();\n if (bytes <= buffer.size()) {\n \/\/ Read the next buffer-full.\n size_t n = inner.read(buffer.begin(), bytes, buffer.size());\n bufferAvailable = buffer.slice(bytes, n);\n } else {\n \/\/ Forward large skip to the underlying stream.\n bufferAvailable = nullptr;\n inner.skip(bytes);\n }\n }\n}\n\n\/\/ -------------------------------------------------------------------\n\nBufferedOutputStreamWrapper::BufferedOutputStreamWrapper(OutputStream& inner, ArrayPtr buffer)\n : inner(inner),\n ownedBuffer(buffer == nullptr ? heapArray(8192) : nullptr),\n buffer(buffer == nullptr ? ownedBuffer : buffer),\n bufferPos(this->buffer.begin()) {}\n\nBufferedOutputStreamWrapper::~BufferedOutputStreamWrapper() noexcept(false) {\n unwindDetector.catchExceptionsIfUnwinding([&]() {\n flush();\n });\n}\n\nvoid BufferedOutputStreamWrapper::flush() {\n if (bufferPos > buffer.begin()) {\n inner.write(buffer.begin(), bufferPos - buffer.begin());\n bufferPos = buffer.begin();\n }\n}\n\nArrayPtr BufferedOutputStreamWrapper::getWriteBuffer() {\n return arrayPtr(bufferPos, buffer.end());\n}\n\nvoid BufferedOutputStreamWrapper::write(const void* src, size_t size) {\n if (src == bufferPos) {\n \/\/ Oh goody, the caller wrote directly into our buffer.\n bufferPos += size;\n } else {\n size_t available = buffer.end() - bufferPos;\n\n if (size <= available) {\n memcpy(bufferPos, src, size);\n bufferPos += size;\n } else if (size <= buffer.size()) {\n \/\/ Too much for this buffer, but not a full buffer's worth, so we'll go ahead and copy.\n memcpy(bufferPos, src, available);\n inner.write(buffer.begin(), buffer.size());\n\n size -= available;\n src = reinterpret_cast(src) + available;\n\n memcpy(buffer.begin(), src, size);\n bufferPos = buffer.begin() + size;\n } else {\n \/\/ Writing so much data that we might as well write directly to avoid a copy.\n inner.write(buffer.begin(), bufferPos - buffer.begin());\n bufferPos = buffer.begin();\n inner.write(src, size);\n }\n }\n}\n\n\/\/ =======================================================================================\n\nArrayInputStream::ArrayInputStream(ArrayPtr array): array(array) {}\nArrayInputStream::~ArrayInputStream() noexcept(false) {}\n\nArrayPtr ArrayInputStream::tryGetReadBuffer() {\n return array;\n}\n\nsize_t ArrayInputStream::tryRead(void* dst, size_t minBytes, size_t maxBytes) {\n size_t n = std::min(maxBytes, array.size());\n memcpy(dst, array.begin(), n);\n array = array.slice(n, array.size());\n return n;\n}\n\nvoid ArrayInputStream::skip(size_t bytes) {\n KJ_REQUIRE(array.size() >= bytes, \"ArrayInputStream ended prematurely.\") {\n bytes = array.size();\n break;\n }\n array = array.slice(bytes, array.size());\n}\n\n\/\/ -------------------------------------------------------------------\n\nArrayOutputStream::ArrayOutputStream(ArrayPtr array): array(array), fillPos(array.begin()) {}\nArrayOutputStream::~ArrayOutputStream() noexcept(false) {}\n\nArrayPtr ArrayOutputStream::getWriteBuffer() {\n return arrayPtr(fillPos, array.end());\n}\n\nvoid ArrayOutputStream::write(const void* src, size_t size) {\n if (src == fillPos) {\n \/\/ Oh goody, the caller wrote directly into our buffer.\n KJ_REQUIRE(size <= array.end() - fillPos);\n fillPos += size;\n } else {\n KJ_REQUIRE(size <= (size_t)(array.end() - fillPos),\n \"ArrayOutputStream's backing array was not large enough for the data written.\");\n memcpy(fillPos, src, size);\n fillPos += size;\n }\n}\n\n\/\/ -------------------------------------------------------------------\n\nVectorOutputStream::VectorOutputStream(size_t initialCapacity)\n : vector(heapArray(initialCapacity)), fillPos(vector.begin()) {}\nVectorOutputStream::~VectorOutputStream() noexcept(false) {}\n\nArrayPtr VectorOutputStream::getWriteBuffer() {\n \/\/ Grow if needed.\n if (fillPos == vector.end()) {\n grow(vector.size() + 1);\n }\n\n return arrayPtr(fillPos, vector.end());\n}\n\nvoid VectorOutputStream::write(const void* src, size_t size) {\n if (src == fillPos) {\n \/\/ Oh goody, the caller wrote directly into our buffer.\n KJ_REQUIRE(size <= vector.end() - fillPos);\n fillPos += size;\n } else {\n if (vector.end() - fillPos < size) {\n grow(fillPos - vector.begin() + size);\n }\n\n memcpy(fillPos, src, size);\n fillPos += size;\n }\n}\n\nvoid VectorOutputStream::grow(size_t minSize) {\n size_t newSize = vector.size() * 2;\n while (newSize < minSize) newSize *= 2;\n auto newVector = heapArray(newSize);\n memcpy(newVector.begin(), vector.begin(), fillPos - vector.begin());\n fillPos = fillPos - vector.begin() + newVector.begin();\n vector = kj::mv(newVector);\n}\n\n\/\/ =======================================================================================\n\nAutoCloseFd::~AutoCloseFd() noexcept(false) {\n if (fd >= 0) {\n unwindDetector.catchExceptionsIfUnwinding([&]() {\n \/\/ Don't use SYSCALL() here because close() should not be repeated on EINTR.\n if (miniposix::close(fd) < 0) {\n KJ_FAIL_SYSCALL(\"close\", errno, fd) {\n break;\n }\n }\n });\n }\n}\n\nFdInputStream::~FdInputStream() noexcept(false) {}\n\nsize_t FdInputStream::tryRead(void* buffer, size_t minBytes, size_t maxBytes) {\n byte* pos = reinterpret_cast(buffer);\n byte* min = pos + minBytes;\n byte* max = pos + maxBytes;\n\n while (pos < min) {\n miniposix::ssize_t n;\n KJ_SYSCALL(n = miniposix::read(fd, pos, max - pos), fd);\n if (n == 0) {\n break;\n }\n pos += n;\n }\n\n return pos - reinterpret_cast(buffer);\n}\n\nFdOutputStream::~FdOutputStream() noexcept(false) {}\n\nvoid FdOutputStream::write(const void* buffer, size_t size) {\n const char* pos = reinterpret_cast(buffer);\n\n while (size > 0) {\n miniposix::ssize_t n;\n KJ_SYSCALL(n = miniposix::write(fd, pos, size), fd);\n KJ_ASSERT(n > 0, \"write() returned zero.\");\n pos += n;\n size -= n;\n }\n}\n\nvoid FdOutputStream::write(ArrayPtr> pieces) {\n#if _WIN32\n \/\/ Windows has no reasonable writev(). It has WriteFileGather, but this call has the unreasonable\n \/\/ restriction that each segment must be page-aligned. So, fall back to the default implementation\n\n OutputStream::write(pieces);\n\n#else\n const size_t iovmax = miniposix::iovMax(pieces.size());\n while (pieces.size() > iovmax) {\n write(pieces.slice(0, iovmax));\n pieces = pieces.slice(iovmax, pieces.size());\n }\n\n KJ_STACK_ARRAY(struct iovec, iov, pieces.size(), 16, 128);\n\n for (uint i = 0; i < pieces.size(); i++) {\n \/\/ writev() interface is not const-correct. :(\n iov[i].iov_base = const_cast(pieces[i].begin());\n iov[i].iov_len = pieces[i].size();\n }\n\n struct iovec* current = iov.begin();\n\n \/\/ Advance past any leading empty buffers so that a write full of only empty buffers does not\n \/\/ cause a syscall at all.\n while (current < iov.end() && current->iov_len == 0) {\n ++current;\n }\n\n while (current < iov.end()) {\n \/\/ Issue the write.\n ssize_t n = 0;\n KJ_SYSCALL(n = ::writev(fd, current, iov.end() - current), fd);\n KJ_ASSERT(n > 0, \"writev() returned zero.\");\n\n \/\/ Advance past all buffers that were fully-written.\n while (current < iov.end() && static_cast(n) >= current->iov_len) {\n n -= current->iov_len;\n ++current;\n }\n\n \/\/ If we only partially-wrote one of the buffers, adjust the pointer and size to include only\n \/\/ the unwritten part.\n if (n > 0) {\n current->iov_base = reinterpret_cast(current->iov_base) + n;\n current->iov_len -= n;\n }\n }\n#endif\n}\n\n} \/\/ namespace kj\n<|endoftext|>"} {"text":"\/\/===-- SelectionDAGPrinter.cpp - Implement SelectionDAG::viewGraph() -----===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This implements the SelectionDAG::viewGraph method.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Constants.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/Assembly\/Writer.h\"\n#include \"llvm\/CodeGen\/SelectionDAG.h\"\n#include \"llvm\/CodeGen\/ScheduleDAGSDNodes.h\"\n#include \"llvm\/CodeGen\/MachineConstantPool.h\"\n#include \"llvm\/CodeGen\/MachineFunction.h\"\n#include \"llvm\/CodeGen\/MachineModuleInfo.h\"\n#include \"llvm\/CodeGen\/PseudoSourceValue.h\"\n#include \"llvm\/Target\/TargetRegisterInfo.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/GraphWriter.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/ADT\/DenseSet.h\"\n#include \"llvm\/ADT\/StringExtras.h\"\n#include \"llvm\/Config\/config.h\"\n#include \nusing namespace llvm;\n\nnamespace llvm {\n template<>\n struct DOTGraphTraits : public DefaultDOTGraphTraits {\n static bool hasEdgeDestLabels() {\n return true;\n }\n\n static unsigned numEdgeDestLabels(const void *Node) {\n return ((const SDNode *) Node)->getNumValues();\n }\n\n static std::string getEdgeDestLabel(const void *Node, unsigned i) {\n return ((const SDNode *) Node)->getValueType(i).getMVTString();\n }\n\n \/\/\/ edgeTargetsEdgeSource - This method returns true if this outgoing edge\n \/\/\/ should actually target another edge source, not a node. If this method is\n \/\/\/ implemented, getEdgeTarget should be implemented.\n template\n static bool edgeTargetsEdgeSource(const void *Node, EdgeIter I) {\n return true;\n }\n\n \/\/\/ getEdgeTarget - If edgeTargetsEdgeSource returns true, this method is\n \/\/\/ called to determine which outgoing edge of Node is the target of this\n \/\/\/ edge.\n template\n static EdgeIter getEdgeTarget(const void *Node, EdgeIter I) {\n SDNode *TargetNode = *I;\n SDNodeIterator NI = SDNodeIterator::begin(TargetNode);\n std::advance(NI, I.getNode()->getOperand(I.getOperand()).getResNo());\n return NI;\n }\n\n static std::string getGraphName(const SelectionDAG *G) {\n return G->getMachineFunction().getFunction()->getName();\n }\n\n static bool renderGraphFromBottomUp() {\n return true;\n }\n \n static bool hasNodeAddressLabel(const SDNode *Node,\n const SelectionDAG *Graph) {\n return true;\n }\n \n \/\/\/ If you want to override the dot attributes printed for a particular\n \/\/\/ edge, override this method.\n template\n static std::string getEdgeAttributes(const void *Node, EdgeIter EI) {\n SDValue Op = EI.getNode()->getOperand(EI.getOperand());\n MVT VT = Op.getValueType();\n if (VT == MVT::Flag)\n return \"color=red,style=bold\";\n else if (VT == MVT::Other)\n return \"color=blue,style=dashed\";\n return \"\";\n }\n \n\n static std::string getNodeLabel(const SDNode *Node,\n const SelectionDAG *Graph);\n static std::string getNodeAttributes(const SDNode *N,\n const SelectionDAG *Graph) {\n#ifndef NDEBUG\n const std::string &Attrs = Graph->getGraphAttrs(N);\n if (!Attrs.empty()) {\n if (Attrs.find(\"shape=\") == std::string::npos)\n return std::string(\"shape=Mrecord,\") + Attrs;\n else\n return Attrs;\n }\n#endif\n return \"shape=Mrecord\";\n }\n\n static void addCustomGraphFeatures(SelectionDAG *G,\n GraphWriter &GW) {\n GW.emitSimpleNode(0, \"plaintext=circle\", \"GraphRoot\");\n if (G->getRoot().getNode())\n GW.emitEdge(0, -1, G->getRoot().getNode(), G->getRoot().getResNo(),\n \"color=blue,style=dashed\");\n }\n };\n}\n\nstd::string DOTGraphTraits::getNodeLabel(const SDNode *Node,\n const SelectionDAG *G) {\n std::string Op = Node->getOperationName(G);\n\n if (const ConstantSDNode *CSDN = dyn_cast(Node)) {\n Op += \": \" + utostr(CSDN->getZExtValue());\n } else if (const ConstantFPSDNode *CSDN = dyn_cast(Node)) {\n Op += \": \" + ftostr(CSDN->getValueAPF());\n } else if (const GlobalAddressSDNode *GADN =\n dyn_cast(Node)) {\n Op += \": \" + GADN->getGlobal()->getName();\n if (int64_t Offset = GADN->getOffset()) {\n if (Offset > 0)\n Op += \"+\" + itostr(Offset);\n else\n Op += itostr(Offset);\n }\n } else if (const FrameIndexSDNode *FIDN = dyn_cast(Node)) {\n Op += \" \" + itostr(FIDN->getIndex());\n } else if (const JumpTableSDNode *JTDN = dyn_cast(Node)) {\n Op += \" \" + itostr(JTDN->getIndex());\n } else if (const ConstantPoolSDNode *CP = dyn_cast(Node)){\n if (CP->isMachineConstantPoolEntry()) {\n Op += '<';\n {\n raw_string_ostream OSS(Op);\n OSS << *CP->getMachineCPVal();\n }\n Op += '>';\n } else {\n if (ConstantFP *CFP = dyn_cast(CP->getConstVal()))\n Op += \"<\" + ftostr(CFP->getValueAPF()) + \">\";\n else if (ConstantInt *CI = dyn_cast(CP->getConstVal()))\n Op += \"<\" + utostr(CI->getZExtValue()) + \">\";\n else {\n Op += '<';\n {\n raw_string_ostream OSS(Op);\n WriteAsOperand(OSS, CP->getConstVal(), false);\n }\n Op += '>';\n }\n }\n Op += \" A=\" + itostr(1 << CP->getAlignment());\n } else if (const BasicBlockSDNode *BBDN = dyn_cast(Node)) {\n Op = \"BB: \";\n const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();\n if (LBB)\n Op += LBB->getName();\n \/\/Op += \" \" + (const void*)BBDN->getBasicBlock();\n } else if (const RegisterSDNode *R = dyn_cast(Node)) {\n if (G && R->getReg() != 0 &&\n TargetRegisterInfo::isPhysicalRegister(R->getReg())) {\n Op = Op + \" \" +\n G->getTarget().getRegisterInfo()->getName(R->getReg());\n } else {\n Op += \" #\" + utostr(R->getReg());\n }\n } else if (const DbgStopPointSDNode *D = dyn_cast(Node)) {\n Op += \": \" + D->getCompileUnit()->getFileName();\n Op += \":\" + utostr(D->getLine());\n if (D->getColumn() != 0)\n Op += \":\" + utostr(D->getColumn());\n } else if (const LabelSDNode *L = dyn_cast(Node)) {\n Op += \": LabelID=\" + utostr(L->getLabelID());\n } else if (const CallSDNode *C = dyn_cast(Node)) {\n Op += \": CallingConv=\" + utostr(C->getCallingConv());\n if (C->isVarArg())\n Op += \", isVarArg\";\n if (C->isTailCall())\n Op += \", isTailCall\";\n } else if (const ExternalSymbolSDNode *ES =\n dyn_cast(Node)) {\n Op += \"'\" + std::string(ES->getSymbol()) + \"'\";\n } else if (const SrcValueSDNode *M = dyn_cast(Node)) {\n if (M->getValue())\n Op += \"<\" + M->getValue()->getName() + \">\";\n else\n Op += \"\";\n } else if (const MemOperandSDNode *M = dyn_cast(Node)) {\n const Value *V = M->MO.getValue();\n Op += '<';\n if (!V) {\n Op += \"(unknown)\";\n } else if (isa(V)) {\n \/\/ PseudoSourceValues don't have names, so use their print method.\n {\n raw_string_ostream OSS(Op);\n OSS << *M->MO.getValue();\n }\n } else {\n Op += V->getName();\n }\n Op += '+' + itostr(M->MO.getOffset()) + '>';\n } else if (const ARG_FLAGSSDNode *N = dyn_cast(Node)) {\n Op = Op + \" AF=\" + N->getArgFlags().getArgFlagsString();\n } else if (const VTSDNode *N = dyn_cast(Node)) {\n Op = Op + \" VT=\" + N->getVT().getMVTString();\n } else if (const LoadSDNode *LD = dyn_cast(Node)) {\n bool doExt = true;\n switch (LD->getExtensionType()) {\n default: doExt = false; break;\n case ISD::EXTLOAD:\n Op = Op + \"getMemoryVT().getMVTString() + \">\";\n if (LD->isVolatile())\n Op += \"\";\n Op += LD->getIndexedModeName(LD->getAddressingMode());\n if (LD->getAlignment() > 1)\n Op += \" A=\" + utostr(LD->getAlignment());\n } else if (const StoreSDNode *ST = dyn_cast(Node)) {\n if (ST->isTruncatingStore())\n Op += \"getMemoryVT().getMVTString() + \">\";\n if (ST->isVolatile())\n Op += \"\";\n Op += ST->getIndexedModeName(ST->getAddressingMode());\n if (ST->getAlignment() > 1)\n Op += \" A=\" + utostr(ST->getAlignment());\n }\n\n#if 0\n Op += \" Id=\" + itostr(Node->getNodeId());\n#endif\n \n return Op;\n}\n\n\n\/\/\/ viewGraph - Pop up a ghostview window with the reachable parts of the DAG\n\/\/\/ rendered using 'dot'.\n\/\/\/\nvoid SelectionDAG::viewGraph(const std::string &Title) {\n\/\/ This code is only for debugging!\n#ifndef NDEBUG\n ViewGraph(this, \"dag.\" + getMachineFunction().getFunction()->getName(),\n Title);\n#else\n cerr << \"SelectionDAG::viewGraph is only available in debug builds on \"\n << \"systems with Graphviz or gv!\\n\";\n#endif \/\/ NDEBUG\n}\n\n\/\/ This overload is defined out-of-line here instead of just using a\n\/\/ default parameter because this is easiest for gdb to call.\nvoid SelectionDAG::viewGraph() {\n viewGraph(\"\");\n}\n\n\/\/\/ clearGraphAttrs - Clear all previously defined node graph attributes.\n\/\/\/ Intended to be used from a debugging tool (eg. gdb).\nvoid SelectionDAG::clearGraphAttrs() {\n#ifndef NDEBUG\n NodeGraphAttrs.clear();\n#else\n cerr << \"SelectionDAG::clearGraphAttrs is only available in debug builds\"\n << \" on systems with Graphviz or gv!\\n\";\n#endif\n}\n\n\n\/\/\/ setGraphAttrs - Set graph attributes for a node. (eg. \"color=red\".)\n\/\/\/\nvoid SelectionDAG::setGraphAttrs(const SDNode *N, const char *Attrs) {\n#ifndef NDEBUG\n NodeGraphAttrs[N] = Attrs;\n#else\n cerr << \"SelectionDAG::setGraphAttrs is only available in debug builds\"\n << \" on systems with Graphviz or gv!\\n\";\n#endif\n}\n\n\n\/\/\/ getGraphAttrs - Get graph attributes for a node. (eg. \"color=red\".)\n\/\/\/ Used from getNodeAttributes.\nconst std::string SelectionDAG::getGraphAttrs(const SDNode *N) const {\n#ifndef NDEBUG\n std::map::const_iterator I =\n NodeGraphAttrs.find(N);\n \n if (I != NodeGraphAttrs.end())\n return I->second;\n else\n return \"\";\n#else\n cerr << \"SelectionDAG::getGraphAttrs is only available in debug builds\"\n << \" on systems with Graphviz or gv!\\n\";\n return std::string(\"\");\n#endif\n}\n\n\/\/\/ setGraphColor - Convenience for setting node color attribute.\n\/\/\/\nvoid SelectionDAG::setGraphColor(const SDNode *N, const char *Color) {\n#ifndef NDEBUG\n NodeGraphAttrs[N] = std::string(\"color=\") + Color;\n#else\n cerr << \"SelectionDAG::setGraphColor is only available in debug builds\"\n << \" on systems with Graphviz or gv!\\n\";\n#endif\n}\n\n\/\/\/ setSubgraphColorHelper - Implement setSubgraphColor. Return\n\/\/\/ whether we truncated the search.\n\/\/\/\nbool SelectionDAG::setSubgraphColorHelper(SDNode *N, const char *Color, DenseSet &visited,\n int level, bool &printed) {\n bool hit_limit = false;\n\n#ifndef NDEBUG\n if (level >= 20) {\n if (!printed) {\n printed = true;\n DOUT << \"setSubgraphColor hit max level\\n\";\n }\n return true;\n }\n\n unsigned oldSize = visited.size();\n visited.insert(N);\n if (visited.size() != oldSize) {\n setGraphColor(N, Color);\n for(SDNodeIterator i = SDNodeIterator::begin(N), iend = SDNodeIterator::end(N);\n i != iend;\n ++i) {\n hit_limit = setSubgraphColorHelper(*i, Color, visited, level+1, printed) || hit_limit;\n }\n }\n#else\n cerr << \"SelectionDAG::setSubgraphColor is only available in debug builds\"\n << \" on systems with Graphviz or gv!\\n\";\n#endif\n return hit_limit;\n}\n\n\/\/\/ setSubgraphColor - Convenience for setting subgraph color attribute.\n\/\/\/\nvoid SelectionDAG::setSubgraphColor(SDNode *N, const char *Color) {\n#ifndef NDEBUG\n DenseSet visited;\n bool printed = false;\n if (setSubgraphColorHelper(N, Color, visited, 0, printed)) {\n \/\/ Visually mark that we hit the limit\n if (strcmp(Color, \"red\") == 0) {\n setSubgraphColorHelper(N, \"blue\", visited, 0, printed);\n }\n else if (strcmp(Color, \"yellow\") == 0) {\n setSubgraphColorHelper(N, \"green\", visited, 0, printed);\n }\n }\n\n#else\n cerr << \"SelectionDAG::setSubgraphColor is only available in debug builds\"\n << \" on systems with Graphviz or gv!\\n\";\n#endif\n}\n\nstd::string ScheduleDAGSDNodes::getGraphNodeLabel(const SUnit *SU) const {\n std::string s;\n raw_string_ostream O(s);\n O << \"SU(\" << SU->NodeNum << \"): \";\n if (SU->getNode()) {\n SmallVector FlaggedNodes;\n for (SDNode *N = SU->getNode(); N; N = N->getFlaggedNode())\n FlaggedNodes.push_back(N);\n while (!FlaggedNodes.empty()) {\n O << DOTGraphTraits::getNodeLabel(FlaggedNodes.back(), DAG);\n FlaggedNodes.pop_back();\n if (!FlaggedNodes.empty())\n O << \"\\n \";\n }\n } else {\n O << \"CROSS RC COPY\";\n }\n return O.str();\n}\n\nvoid ScheduleDAGSDNodes::getCustomGraphFeatures(GraphWriter &GW) const {\n if (DAG) {\n \/\/ Draw a special \"GraphRoot\" node to indicate the root of the graph.\n GW.emitSimpleNode(0, \"plaintext=circle\", \"GraphRoot\");\n const SDNode *N = DAG->getRoot().getNode();\n if (N && N->getNodeId() != -1)\n GW.emitEdge(0, -1, &SUnits[N->getNodeId()], -1,\n \"color=blue,style=dashed\");\n }\n}\nFix printing of PseudoSourceValues in SDNode graphs.\/\/===-- SelectionDAGPrinter.cpp - Implement SelectionDAG::viewGraph() -----===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This implements the SelectionDAG::viewGraph method.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Constants.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/Assembly\/Writer.h\"\n#include \"llvm\/CodeGen\/SelectionDAG.h\"\n#include \"llvm\/CodeGen\/ScheduleDAGSDNodes.h\"\n#include \"llvm\/CodeGen\/MachineConstantPool.h\"\n#include \"llvm\/CodeGen\/MachineFunction.h\"\n#include \"llvm\/CodeGen\/MachineModuleInfo.h\"\n#include \"llvm\/CodeGen\/PseudoSourceValue.h\"\n#include \"llvm\/Target\/TargetRegisterInfo.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/GraphWriter.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/ADT\/DenseSet.h\"\n#include \"llvm\/ADT\/StringExtras.h\"\n#include \"llvm\/Config\/config.h\"\n#include \nusing namespace llvm;\n\nnamespace llvm {\n template<>\n struct DOTGraphTraits : public DefaultDOTGraphTraits {\n static bool hasEdgeDestLabels() {\n return true;\n }\n\n static unsigned numEdgeDestLabels(const void *Node) {\n return ((const SDNode *) Node)->getNumValues();\n }\n\n static std::string getEdgeDestLabel(const void *Node, unsigned i) {\n return ((const SDNode *) Node)->getValueType(i).getMVTString();\n }\n\n \/\/\/ edgeTargetsEdgeSource - This method returns true if this outgoing edge\n \/\/\/ should actually target another edge source, not a node. If this method is\n \/\/\/ implemented, getEdgeTarget should be implemented.\n template\n static bool edgeTargetsEdgeSource(const void *Node, EdgeIter I) {\n return true;\n }\n\n \/\/\/ getEdgeTarget - If edgeTargetsEdgeSource returns true, this method is\n \/\/\/ called to determine which outgoing edge of Node is the target of this\n \/\/\/ edge.\n template\n static EdgeIter getEdgeTarget(const void *Node, EdgeIter I) {\n SDNode *TargetNode = *I;\n SDNodeIterator NI = SDNodeIterator::begin(TargetNode);\n std::advance(NI, I.getNode()->getOperand(I.getOperand()).getResNo());\n return NI;\n }\n\n static std::string getGraphName(const SelectionDAG *G) {\n return G->getMachineFunction().getFunction()->getName();\n }\n\n static bool renderGraphFromBottomUp() {\n return true;\n }\n \n static bool hasNodeAddressLabel(const SDNode *Node,\n const SelectionDAG *Graph) {\n return true;\n }\n \n \/\/\/ If you want to override the dot attributes printed for a particular\n \/\/\/ edge, override this method.\n template\n static std::string getEdgeAttributes(const void *Node, EdgeIter EI) {\n SDValue Op = EI.getNode()->getOperand(EI.getOperand());\n MVT VT = Op.getValueType();\n if (VT == MVT::Flag)\n return \"color=red,style=bold\";\n else if (VT == MVT::Other)\n return \"color=blue,style=dashed\";\n return \"\";\n }\n \n\n static std::string getNodeLabel(const SDNode *Node,\n const SelectionDAG *Graph);\n static std::string getNodeAttributes(const SDNode *N,\n const SelectionDAG *Graph) {\n#ifndef NDEBUG\n const std::string &Attrs = Graph->getGraphAttrs(N);\n if (!Attrs.empty()) {\n if (Attrs.find(\"shape=\") == std::string::npos)\n return std::string(\"shape=Mrecord,\") + Attrs;\n else\n return Attrs;\n }\n#endif\n return \"shape=Mrecord\";\n }\n\n static void addCustomGraphFeatures(SelectionDAG *G,\n GraphWriter &GW) {\n GW.emitSimpleNode(0, \"plaintext=circle\", \"GraphRoot\");\n if (G->getRoot().getNode())\n GW.emitEdge(0, -1, G->getRoot().getNode(), G->getRoot().getResNo(),\n \"color=blue,style=dashed\");\n }\n };\n}\n\nstd::string DOTGraphTraits::getNodeLabel(const SDNode *Node,\n const SelectionDAG *G) {\n std::string Op = Node->getOperationName(G);\n\n if (const ConstantSDNode *CSDN = dyn_cast(Node)) {\n Op += \": \" + utostr(CSDN->getZExtValue());\n } else if (const ConstantFPSDNode *CSDN = dyn_cast(Node)) {\n Op += \": \" + ftostr(CSDN->getValueAPF());\n } else if (const GlobalAddressSDNode *GADN =\n dyn_cast(Node)) {\n Op += \": \" + GADN->getGlobal()->getName();\n if (int64_t Offset = GADN->getOffset()) {\n if (Offset > 0)\n Op += \"+\" + itostr(Offset);\n else\n Op += itostr(Offset);\n }\n } else if (const FrameIndexSDNode *FIDN = dyn_cast(Node)) {\n Op += \" \" + itostr(FIDN->getIndex());\n } else if (const JumpTableSDNode *JTDN = dyn_cast(Node)) {\n Op += \" \" + itostr(JTDN->getIndex());\n } else if (const ConstantPoolSDNode *CP = dyn_cast(Node)){\n if (CP->isMachineConstantPoolEntry()) {\n Op += '<';\n {\n raw_string_ostream OSS(Op);\n OSS << *CP->getMachineCPVal();\n }\n Op += '>';\n } else {\n if (ConstantFP *CFP = dyn_cast(CP->getConstVal()))\n Op += \"<\" + ftostr(CFP->getValueAPF()) + \">\";\n else if (ConstantInt *CI = dyn_cast(CP->getConstVal()))\n Op += \"<\" + utostr(CI->getZExtValue()) + \">\";\n else {\n Op += '<';\n {\n raw_string_ostream OSS(Op);\n WriteAsOperand(OSS, CP->getConstVal(), false);\n }\n Op += '>';\n }\n }\n Op += \" A=\" + itostr(1 << CP->getAlignment());\n } else if (const BasicBlockSDNode *BBDN = dyn_cast(Node)) {\n Op = \"BB: \";\n const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();\n if (LBB)\n Op += LBB->getName();\n \/\/Op += \" \" + (const void*)BBDN->getBasicBlock();\n } else if (const RegisterSDNode *R = dyn_cast(Node)) {\n if (G && R->getReg() != 0 &&\n TargetRegisterInfo::isPhysicalRegister(R->getReg())) {\n Op = Op + \" \" +\n G->getTarget().getRegisterInfo()->getName(R->getReg());\n } else {\n Op += \" #\" + utostr(R->getReg());\n }\n } else if (const DbgStopPointSDNode *D = dyn_cast(Node)) {\n Op += \": \" + D->getCompileUnit()->getFileName();\n Op += \":\" + utostr(D->getLine());\n if (D->getColumn() != 0)\n Op += \":\" + utostr(D->getColumn());\n } else if (const LabelSDNode *L = dyn_cast(Node)) {\n Op += \": LabelID=\" + utostr(L->getLabelID());\n } else if (const CallSDNode *C = dyn_cast(Node)) {\n Op += \": CallingConv=\" + utostr(C->getCallingConv());\n if (C->isVarArg())\n Op += \", isVarArg\";\n if (C->isTailCall())\n Op += \", isTailCall\";\n } else if (const ExternalSymbolSDNode *ES =\n dyn_cast(Node)) {\n Op += \"'\" + std::string(ES->getSymbol()) + \"'\";\n } else if (const SrcValueSDNode *M = dyn_cast(Node)) {\n if (M->getValue())\n Op += \"<\" + M->getValue()->getName() + \">\";\n else\n Op += \"\";\n } else if (const MemOperandSDNode *M = dyn_cast(Node)) {\n const Value *V = M->MO.getValue();\n Op += '<';\n if (!V) {\n Op += \"(unknown)\";\n } else if (const PseudoSourceValue *PSV = dyn_cast(V)) {\n \/\/ PseudoSourceValues don't have names, so use their print method.\n raw_string_ostream OSS(Op);\n PSV->print(OSS);\n } else {\n Op += V->getName();\n }\n Op += '+' + itostr(M->MO.getOffset()) + '>';\n } else if (const ARG_FLAGSSDNode *N = dyn_cast(Node)) {\n Op = Op + \" AF=\" + N->getArgFlags().getArgFlagsString();\n } else if (const VTSDNode *N = dyn_cast(Node)) {\n Op = Op + \" VT=\" + N->getVT().getMVTString();\n } else if (const LoadSDNode *LD = dyn_cast(Node)) {\n bool doExt = true;\n switch (LD->getExtensionType()) {\n default: doExt = false; break;\n case ISD::EXTLOAD:\n Op = Op + \"getMemoryVT().getMVTString() + \">\";\n if (LD->isVolatile())\n Op += \"\";\n Op += LD->getIndexedModeName(LD->getAddressingMode());\n if (LD->getAlignment() > 1)\n Op += \" A=\" + utostr(LD->getAlignment());\n } else if (const StoreSDNode *ST = dyn_cast(Node)) {\n if (ST->isTruncatingStore())\n Op += \"getMemoryVT().getMVTString() + \">\";\n if (ST->isVolatile())\n Op += \"\";\n Op += ST->getIndexedModeName(ST->getAddressingMode());\n if (ST->getAlignment() > 1)\n Op += \" A=\" + utostr(ST->getAlignment());\n }\n\n#if 0\n Op += \" Id=\" + itostr(Node->getNodeId());\n#endif\n \n return Op;\n}\n\n\n\/\/\/ viewGraph - Pop up a ghostview window with the reachable parts of the DAG\n\/\/\/ rendered using 'dot'.\n\/\/\/\nvoid SelectionDAG::viewGraph(const std::string &Title) {\n\/\/ This code is only for debugging!\n#ifndef NDEBUG\n ViewGraph(this, \"dag.\" + getMachineFunction().getFunction()->getName(),\n Title);\n#else\n cerr << \"SelectionDAG::viewGraph is only available in debug builds on \"\n << \"systems with Graphviz or gv!\\n\";\n#endif \/\/ NDEBUG\n}\n\n\/\/ This overload is defined out-of-line here instead of just using a\n\/\/ default parameter because this is easiest for gdb to call.\nvoid SelectionDAG::viewGraph() {\n viewGraph(\"\");\n}\n\n\/\/\/ clearGraphAttrs - Clear all previously defined node graph attributes.\n\/\/\/ Intended to be used from a debugging tool (eg. gdb).\nvoid SelectionDAG::clearGraphAttrs() {\n#ifndef NDEBUG\n NodeGraphAttrs.clear();\n#else\n cerr << \"SelectionDAG::clearGraphAttrs is only available in debug builds\"\n << \" on systems with Graphviz or gv!\\n\";\n#endif\n}\n\n\n\/\/\/ setGraphAttrs - Set graph attributes for a node. (eg. \"color=red\".)\n\/\/\/\nvoid SelectionDAG::setGraphAttrs(const SDNode *N, const char *Attrs) {\n#ifndef NDEBUG\n NodeGraphAttrs[N] = Attrs;\n#else\n cerr << \"SelectionDAG::setGraphAttrs is only available in debug builds\"\n << \" on systems with Graphviz or gv!\\n\";\n#endif\n}\n\n\n\/\/\/ getGraphAttrs - Get graph attributes for a node. (eg. \"color=red\".)\n\/\/\/ Used from getNodeAttributes.\nconst std::string SelectionDAG::getGraphAttrs(const SDNode *N) const {\n#ifndef NDEBUG\n std::map::const_iterator I =\n NodeGraphAttrs.find(N);\n \n if (I != NodeGraphAttrs.end())\n return I->second;\n else\n return \"\";\n#else\n cerr << \"SelectionDAG::getGraphAttrs is only available in debug builds\"\n << \" on systems with Graphviz or gv!\\n\";\n return std::string(\"\");\n#endif\n}\n\n\/\/\/ setGraphColor - Convenience for setting node color attribute.\n\/\/\/\nvoid SelectionDAG::setGraphColor(const SDNode *N, const char *Color) {\n#ifndef NDEBUG\n NodeGraphAttrs[N] = std::string(\"color=\") + Color;\n#else\n cerr << \"SelectionDAG::setGraphColor is only available in debug builds\"\n << \" on systems with Graphviz or gv!\\n\";\n#endif\n}\n\n\/\/\/ setSubgraphColorHelper - Implement setSubgraphColor. Return\n\/\/\/ whether we truncated the search.\n\/\/\/\nbool SelectionDAG::setSubgraphColorHelper(SDNode *N, const char *Color, DenseSet &visited,\n int level, bool &printed) {\n bool hit_limit = false;\n\n#ifndef NDEBUG\n if (level >= 20) {\n if (!printed) {\n printed = true;\n DOUT << \"setSubgraphColor hit max level\\n\";\n }\n return true;\n }\n\n unsigned oldSize = visited.size();\n visited.insert(N);\n if (visited.size() != oldSize) {\n setGraphColor(N, Color);\n for(SDNodeIterator i = SDNodeIterator::begin(N), iend = SDNodeIterator::end(N);\n i != iend;\n ++i) {\n hit_limit = setSubgraphColorHelper(*i, Color, visited, level+1, printed) || hit_limit;\n }\n }\n#else\n cerr << \"SelectionDAG::setSubgraphColor is only available in debug builds\"\n << \" on systems with Graphviz or gv!\\n\";\n#endif\n return hit_limit;\n}\n\n\/\/\/ setSubgraphColor - Convenience for setting subgraph color attribute.\n\/\/\/\nvoid SelectionDAG::setSubgraphColor(SDNode *N, const char *Color) {\n#ifndef NDEBUG\n DenseSet visited;\n bool printed = false;\n if (setSubgraphColorHelper(N, Color, visited, 0, printed)) {\n \/\/ Visually mark that we hit the limit\n if (strcmp(Color, \"red\") == 0) {\n setSubgraphColorHelper(N, \"blue\", visited, 0, printed);\n }\n else if (strcmp(Color, \"yellow\") == 0) {\n setSubgraphColorHelper(N, \"green\", visited, 0, printed);\n }\n }\n\n#else\n cerr << \"SelectionDAG::setSubgraphColor is only available in debug builds\"\n << \" on systems with Graphviz or gv!\\n\";\n#endif\n}\n\nstd::string ScheduleDAGSDNodes::getGraphNodeLabel(const SUnit *SU) const {\n std::string s;\n raw_string_ostream O(s);\n O << \"SU(\" << SU->NodeNum << \"): \";\n if (SU->getNode()) {\n SmallVector FlaggedNodes;\n for (SDNode *N = SU->getNode(); N; N = N->getFlaggedNode())\n FlaggedNodes.push_back(N);\n while (!FlaggedNodes.empty()) {\n O << DOTGraphTraits::getNodeLabel(FlaggedNodes.back(), DAG);\n FlaggedNodes.pop_back();\n if (!FlaggedNodes.empty())\n O << \"\\n \";\n }\n } else {\n O << \"CROSS RC COPY\";\n }\n return O.str();\n}\n\nvoid ScheduleDAGSDNodes::getCustomGraphFeatures(GraphWriter &GW) const {\n if (DAG) {\n \/\/ Draw a special \"GraphRoot\" node to indicate the root of the graph.\n GW.emitSimpleNode(0, \"plaintext=circle\", \"GraphRoot\");\n const SDNode *N = DAG->getRoot().getNode();\n if (N && N->getNodeId() != -1)\n GW.emitEdge(0, -1, &SUnits[N->getNodeId()], -1,\n \"color=blue,style=dashed\");\n }\n}\n<|endoftext|>"} {"text":"\/\/\/\n\/\/\/ @file pod_vector.hpp\n\/\/\/\n\/\/\/ Copyright (C) 2022 Kim Walisch, \n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#ifndef POD_VECTOR_HPP\n#define POD_VECTOR_HPP\n\n#include \"macros.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace primesieve {\n\n\/\/\/ pod_vector is a dynamically growing array.\n\/\/\/ It has the same API (though not complete) as std::vector but its\n\/\/\/ resize() method does not default initialize memory for built-in\n\/\/\/ integer types. It does however default initialize classes and\n\/\/\/ struct types if they have a constructor. It also prevents\n\/\/\/ bounds checks which is important for primesieve's performance, e.g.\n\/\/\/ the Fedora Linux distribution compiles with -D_GLIBCXX_ASSERTIONS\n\/\/\/ which enables std::vector bounds checks.\n\/\/\/\ntemplate \nclass pod_vector\n{\npublic:\n static_assert(std::is_trivially_destructible::value,\n \"pod_vector only supports types with trivial destructors!\");\n\n pod_vector() noexcept = default;\n\n pod_vector(std::size_t size)\n {\n resize(size);\n }\n\n ~pod_vector()\n {\n delete [] array_;\n }\n\n \/\/\/ Free all memory, the pod_vector\n \/\/\/ can be reused afterwards.\n void free() noexcept\n {\n delete [] array_;\n array_ = nullptr;\n end_ = nullptr;\n capacity_ = nullptr;\n }\n\n \/\/\/ Reset the pod_vector, but do not free its\n \/\/\/ memory. Same as std::vector.clear().\n void clear() noexcept\n {\n end_ = array_;\n }\n\n \/\/\/ Copying is slow, we prevent it\n pod_vector(const pod_vector&) = delete;\n pod_vector& operator=(const pod_vector&) = delete;\n\n \/\/\/ Move constructor\n pod_vector(pod_vector&& other) noexcept\n {\n this->swap(other);\n }\n\n \/\/\/ Move assignment operator\n pod_vector& operator=(pod_vector&& other) noexcept\n {\n if (this != &other)\n this->swap(other);\n\n return *this;\n }\n\n void swap(pod_vector& other) noexcept\n {\n std::swap(array_, other.array_);\n std::swap(end_, other.end_);\n std::swap(capacity_, other.capacity_);\n }\n\n bool empty() const noexcept\n {\n return array_ == end_;\n }\n\n T& operator[] (std::size_t pos) noexcept\n {\n return array_[pos];\n }\n\n T& operator[] (std::size_t pos) const noexcept\n {\n return array_[pos];\n }\n\n T* data() noexcept\n {\n return array_;\n }\n\n T* data() const noexcept\n {\n return array_;\n }\n\n std::size_t size() const noexcept\n {\n assert(end_ >= array_);\n return (std::size_t)(end_ - array_);\n }\n\n std::size_t capacity() const noexcept\n {\n assert(capacity_ >= array_);\n return (std::size_t)(capacity_ - array_);\n }\n\n T* begin() noexcept\n {\n return array_;\n }\n\n T* begin() const noexcept\n {\n return array_;\n }\n\n T* end() noexcept\n {\n return end_;\n }\n\n T* end() const noexcept\n {\n return end_;\n }\n\n T& front() noexcept\n {\n return *array_;\n }\n\n T& front() const noexcept\n {\n return *array_;\n }\n\n T& back() noexcept\n {\n assert(end_ != nullptr);\n return *(end_ - 1);\n }\n\n T& back() const noexcept\n {\n assert(end_ != nullptr);\n return *(end_ - 1);\n }\n\n ALWAYS_INLINE void push_back(const T& value)\n {\n if_unlikely(end_ >= capacity_)\n reserve(std::max((std::size_t) 1, capacity() * 2));\n *end_++ = value;\n }\n\n ALWAYS_INLINE void push_back(T&& value)\n {\n if_unlikely(end_ >= capacity_)\n reserve(std::max((std::size_t) 1, capacity() * 2));\n *end_++ = value;\n }\n\n template \n ALWAYS_INLINE void emplace_back(Args&&... args)\n {\n if_unlikely(end_ >= capacity_)\n reserve(std::max((std::size_t) 1, capacity() * 2));\n *end_++ = T(std::forward(args)...);\n }\n\n template \n ALWAYS_INLINE typename std::enable_if::value>::type\n default_initialize_range(TT*, TT*)\n { }\n\n template \n ALWAYS_INLINE typename std::enable_if::value>::type\n default_initialize_range(TT* first, TT* last)\n {\n std::fill(first, last, TT());\n }\n\n void reserve(std::size_t n)\n {\n if (n > capacity())\n {\n \/\/ GCC & Clang's std::vector grow the capacity by at least\n \/\/ 2x for every call to resize() with n > capacity(). We\n \/\/ grow by at least 1.5x as we tend to accurately calculate\n \/\/ the amount of memory we need upfront.\n n = std::max(n, (std::size_t)(capacity() * 1.5));\n std::size_t old_size = size();\n\n \/\/ This default initializes memory of classes and\n \/\/ structs with constructors. But it does not default\n \/\/ initialize memory for POD types like int, long.\n T* new_array = new T[n];\n\n if (array_)\n {\n std::copy(array_, end_, new_array);\n delete [] array_;\n }\n\n array_ = new_array;\n end_ = array_ + old_size;\n capacity_ = array_ + n;\n }\n }\n\n \/\/\/ Resize without default initializing memory.\n \/\/\/ If the pod_vector is not empty the current content\n \/\/\/ will be copied into the new array.\n \/\/\/\n void resize(std::size_t n)\n {\n if (n == size())\n return;\n else if (n <= capacity())\n {\n assert(capacity() > 0);\n\n \/\/ This will only be used for classes\n \/\/ and structs with constructors.\n if (n > size())\n default_initialize_range(end_, array_ + n);\n\n end_ = array_ + n;\n }\n else\n {\n \/\/ GCC & Clang's std::vector grow the capacity by at least\n \/\/ 2x for every call to resize() with n > capacity(). We\n \/\/ grow by at least 1.5x as we tend to accurately calculate\n \/\/ the amount of memory we need upfront.\n assert(n > capacity());\n n = std::max(n, (std::size_t)(capacity() * 1.5));\n\n \/\/ This default initializes memory of classes and\n \/\/ structs with constructors. But it does not default\n \/\/ initialize memory for POD types like int, long.\n T* new_array = new T[n];\n\n if (array_)\n {\n std::copy(array_, end_, new_array);\n delete [] array_;\n }\n\n array_ = new_array;\n end_ = array_ + n;\n capacity_ = end_;\n }\n }\n\n using value_type = T;\n\nprivate:\n T* array_ = nullptr;\n T* end_ = nullptr;\n T* capacity_ = nullptr;\n};\n\n} \/\/ namespace\n\n#endif\nFix resize()\/\/\/\n\/\/\/ @file pod_vector.hpp\n\/\/\/\n\/\/\/ Copyright (C) 2022 Kim Walisch, \n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#ifndef POD_VECTOR_HPP\n#define POD_VECTOR_HPP\n\n#include \"macros.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace primesieve {\n\n\/\/\/ pod_vector is a dynamically growing array.\n\/\/\/ It has the same API (though not complete) as std::vector but its\n\/\/\/ resize() method does not default initialize memory for built-in\n\/\/\/ integer types. It does however default initialize classes and\n\/\/\/ struct types if they have a constructor. It also prevents\n\/\/\/ bounds checks which is important for primesieve's performance, e.g.\n\/\/\/ the Fedora Linux distribution compiles with -D_GLIBCXX_ASSERTIONS\n\/\/\/ which enables std::vector bounds checks.\n\/\/\/\ntemplate \nclass pod_vector\n{\npublic:\n static_assert(std::is_trivially_destructible::value,\n \"pod_vector only supports types with trivial destructors!\");\n\n pod_vector() noexcept = default;\n\n pod_vector(std::size_t size)\n {\n resize(size);\n }\n\n ~pod_vector()\n {\n delete [] array_;\n }\n\n \/\/\/ Free all memory, the pod_vector\n \/\/\/ can be reused afterwards.\n void free() noexcept\n {\n delete [] array_;\n array_ = nullptr;\n end_ = nullptr;\n capacity_ = nullptr;\n }\n\n \/\/\/ Reset the pod_vector, but do not free its\n \/\/\/ memory. Same as std::vector.clear().\n void clear() noexcept\n {\n end_ = array_;\n }\n\n \/\/\/ Copying is slow, we prevent it\n pod_vector(const pod_vector&) = delete;\n pod_vector& operator=(const pod_vector&) = delete;\n\n \/\/\/ Move constructor\n pod_vector(pod_vector&& other) noexcept\n {\n std::swap(array_, other.array_);\n std::swap(end_, other.end_);\n std::swap(capacity_, other.capacity_);\n }\n\n \/\/\/ Move assignment operator\n pod_vector& operator=(pod_vector&& other) noexcept\n {\n if (this != &other)\n {\n std::swap(array_, other.array_);\n std::swap(end_, other.end_);\n std::swap(capacity_, other.capacity_);\n }\n\n return *this;\n }\n\n bool empty() const noexcept\n {\n return array_ == end_;\n }\n\n T& operator[] (std::size_t pos) noexcept\n {\n return array_[pos];\n }\n\n T& operator[] (std::size_t pos) const noexcept\n {\n return array_[pos];\n }\n\n T* data() noexcept\n {\n return array_;\n }\n\n T* data() const noexcept\n {\n return array_;\n }\n\n std::size_t size() const noexcept\n {\n assert(end_ >= array_);\n return (std::size_t)(end_ - array_);\n }\n\n std::size_t capacity() const noexcept\n {\n assert(capacity_ >= array_);\n return (std::size_t)(capacity_ - array_);\n }\n\n T* begin() noexcept\n {\n return array_;\n }\n\n T* begin() const noexcept\n {\n return array_;\n }\n\n T* end() noexcept\n {\n return end_;\n }\n\n T* end() const noexcept\n {\n return end_;\n }\n\n T& front() noexcept\n {\n return *array_;\n }\n\n T& front() const noexcept\n {\n return *array_;\n }\n\n T& back() noexcept\n {\n assert(end_ != nullptr);\n return *(end_ - 1);\n }\n\n T& back() const noexcept\n {\n assert(end_ != nullptr);\n return *(end_ - 1);\n }\n\n ALWAYS_INLINE void push_back(const T& value)\n {\n if_unlikely(end_ >= capacity_)\n reserve(std::max((std::size_t) 1, capacity() * 2));\n *end_++ = value;\n }\n\n ALWAYS_INLINE void push_back(T&& value)\n {\n if_unlikely(end_ >= capacity_)\n reserve(std::max((std::size_t) 1, capacity() * 2));\n *end_++ = value;\n }\n\n template \n ALWAYS_INLINE void emplace_back(Args&&... args)\n {\n if_unlikely(end_ >= capacity_)\n reserve(std::max((std::size_t) 1, capacity() * 2));\n *end_++ = T(std::forward(args)...);\n }\n\n template \n ALWAYS_INLINE typename std::enable_if::value>::type\n default_initialize_range(U*, U*)\n { }\n\n template \n ALWAYS_INLINE typename std::enable_if::value>::type\n default_initialize_range(U* first, U* last)\n {\n std::fill(first, last, U());\n }\n\n template \n ALWAYS_INLINE typename std::enable_if::value, std::size_t>::type\n get_new_capacity(std::size_t size)\n {\n \/\/ GCC & Clang's std::vector grow the capacity by at least\n \/\/ 2x for every call to resize() with n > capacity(). We\n \/\/ grow by at least 1.5x as we tend to accurately calculate\n \/\/ the amount of memory we need upfront.\n assert(size > 0);\n std::size_t new_capacity = (std::size_t)(capacity() * 1.5);\n constexpr std::size_t min_alignment = (sizeof(long) * 2) \/ sizeof(U);\n return std::max({min_alignment, size, new_capacity});\n }\n\n template \n ALWAYS_INLINE typename std::enable_if::value, std::size_t>::type\n get_new_capacity(std::size_t size)\n {\n \/\/ GCC & Clang's std::vector grow the capacity by at least\n \/\/ 2x for every call to resize() with n > capacity(). We\n \/\/ grow by at least 1.5x as we tend to accurately calculate\n \/\/ the amount of memory we need upfront.\n assert(size > 0);\n std::size_t new_capacity = (std::size_t)(capacity() * 1.5);\n return std::max(size, new_capacity);\n }\n\n void reserve(std::size_t n)\n {\n if (n > capacity())\n {\n std::size_t old_size = size();\n std::size_t new_capacity = get_new_capacity(n);\n assert(new_capacity >= n);\n assert(new_capacity > old_size);\n\n \/\/ This default initializes memory of classes and\n \/\/ structs with constructors. But it does not default\n \/\/ initialize memory for POD types like int, long.\n T* new_array = new T[new_capacity];\n\n if (array_)\n {\n std::copy(array_, end_, new_array);\n delete [] array_;\n }\n\n array_ = new_array;\n end_ = array_ + old_size;\n capacity_ = array_ + new_capacity;\n }\n }\n\n \/\/\/ Resize without default initializing memory.\n \/\/\/ If the pod_vector is not empty the current content\n \/\/\/ will be copied into the new array.\n \/\/\/\n void resize(std::size_t n)\n {\n if (n == size())\n return;\n else if (n <= capacity())\n {\n assert(capacity() > 0);\n\n \/\/ This will only be used for classes\n \/\/ and structs with constructors.\n if (n > size())\n default_initialize_range(end_, array_ + n);\n\n end_ = array_ + n;\n }\n else\n {\n std::size_t new_capacity = get_new_capacity(n);\n assert(new_capacity >= n);\n assert(new_capacity > size());\n\n \/\/ This default initializes memory of classes and\n \/\/ structs with constructors. But it does not default\n \/\/ initialize memory for POD types like int, long.\n T* new_array = new T[new_capacity];\n\n if (array_)\n {\n std::copy(array_, end_, new_array);\n delete [] array_;\n }\n\n array_ = new_array;\n end_ = array_ + n;\n capacity_ = array_ + new_capacity;\n }\n }\n\n using value_type = T;\n\nprivate:\n T* array_ = nullptr;\n T* end_ = nullptr;\n T* capacity_ = nullptr;\n};\n\n} \/\/ namespace\n\n#endif\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2008 Nokia Corporation.\n *\n * Contact: Marius Vollmer \n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public License\n * version 2.1 as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA\n *\n *\/\n\n#include \"contextregistryinfo.h\"\n#include \"infobackend.h\"\n#include \"sconnect.h\"\n#include \n#include \n#include \n\n\/*!\n \\class ContextRegistryInfo\n\n \\brief A class to introspect the registry contents.\n\n This is a singelton class used to obtain information about the keys (properties)\n in the registry database. The information can be provided either from xml files\n or from a cdb database. It's possible to list all the keys in the registry and\n also list all keys belonging to a one particular provider.\n*\/\n\nContextRegistryInfo* ContextRegistryInfo::registryInstance = NULL;\n\n\/* Public *\/\n\n\/\/\/ Returns the singleton instance of the ContextRegistryInfo. The object\n\/\/\/ is constructed automaticall on first access.\n\/\/\/ \\param backendName the optional name of the backend to use (force).\n\nContextRegistryInfo* ContextRegistryInfo::instance(const QString &backendName)\n{\n static QMutex mutex;\n QMutexLocker locker(&mutex);\n if (! registryInstance) {\n InfoBackend::instance(backendName);\n registryInstance = new ContextRegistryInfo;\n\n InfoBackend* infoBackend = InfoBackend::instance();\n\n sconnect(infoBackend, SIGNAL(keysChanged(QStringList)),\n registryInstance, SLOT(onKeysChanged(QStringList)));\n\n sconnect(infoBackend, SIGNAL(keysAdded(QStringList)),\n registryInstance, SLOT(onKeysAdded(QStringList)));\n\n sconnect(infoBackend, SIGNAL(keysRemoved(QStringList)),\n registryInstance, SLOT(onKeysRemoved(QStringList)));\n\n \/\/ Move the backend to the main thread\n registryInstance->moveToThread(QCoreApplication::instance()->thread());\n }\n\n return registryInstance;\n}\n\n\/\/\/ Returns the list of all the keys currently availible in the registry.\nQStringList ContextRegistryInfo::listKeys() const\n{\n return InfoBackend::instance()->listKeys();\n}\n\n\/\/\/ Returns the list of all the keys associated with the given provider.\nQStringList ContextRegistryInfo::listKeys(QString providerName) const\n{\n \/\/ TBD: obsolete this?\n QStringList keys = InfoBackend::instance()->listKeysForPlugin(\"contextkit-dbus\");\n QStringList toReturn;\n foreach (const QString& key, keys) {\n QString constructionString = InfoBackend::instance()->constructionStringForKey(key);\n if (constructionString.split(\":\").last() == providerName) {\n toReturn << key;\n }\n }\n return toReturn;\n}\n\n\/\/\/ Returns the list of all the keys associated with the given plugin\nQStringList ContextRegistryInfo::listKeysForPlugin(QString plugin) const\n{\n return InfoBackend::instance()->listKeysForPlugin(plugin);\n}\n\n\/\/\/ Returns the list of all unique providers in the registry.\n\/\/\/ The lists consist of strings with dbus names of the providers.\nQStringList ContextRegistryInfo::listProviders() const\n{\n \/\/ TBD: obsolete this?\n QStringList keys = InfoBackend::instance()->listKeysForPlugin(\"contextkit-dbus\");\n QSet foundProviders;\n foreach (const QString& key, keys) {\n QString constructionString = InfoBackend::instance()->constructionStringForKey(key);\n foundProviders.insert(constructionString.split(\":\").last());\n }\n QStringList toReturn(foundProviders.toList());\n return toReturn;\n}\n\n\/\/\/ Returns the list of all unique plugins in the registry.\nQStringList ContextRegistryInfo::listPlugins() const\n{\n return InfoBackend::instance()->listPlugins();\n}\n\n\/\/\/ Returns the name of the currently used registry backend. Ie. \"cdb\" or \"xml\".\nQString ContextRegistryInfo::backendName() const\n{\n return InfoBackend::instance()->name();\n}\n\n\/* Slots *\/\n\n\/\/\/ This is connected to the \\a onKeysChanged of the actual info backend instance.\nvoid ContextRegistryInfo::onKeysChanged(const QStringList& currentKeys)\n{\n emit(keysChanged(currentKeys));\n}\n\n\/\/\/ This is connected to the \\a onKeysAdded of the actual info backend instance.\nvoid ContextRegistryInfo::onKeysAdded(const QStringList& newKeys)\n{\n emit(keysAdded(newKeys));\n}\n\n\/\/\/ This is connected to the \\a onKeysRemoved of the actual info backend instance.\nvoid ContextRegistryInfo::onKeysRemoved(const QStringList& removedKeys)\n{\n emit(keysRemoved(removedKeys));\n}\n\nDeprecating ContextRegistryInfo::listKeysForPlugin()\/*\n * Copyright (C) 2008 Nokia Corporation.\n *\n * Contact: Marius Vollmer \n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public License\n * version 2.1 as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA\n *\n *\/\n\n#include \"contextregistryinfo.h\"\n#include \"infobackend.h\"\n#include \"sconnect.h\"\n#include \"logging.h\"\n#include \"loggingfeatures.h\"\n#include \"contextproviderinfo.h\"\n#include \n#include \n#include \n\n\/*!\n \\class ContextRegistryInfo\n\n \\brief A class to introspect the registry contents.\n\n This is a singelton class used to obtain information about the keys (properties)\n in the registry database. The information can be provided either from xml files\n or from a cdb database. It's possible to list all the keys in the registry and\n also list all keys belonging to a one particular provider.\n*\/\n\nContextRegistryInfo* ContextRegistryInfo::registryInstance = NULL;\n\n\/* Public *\/\n\n\/\/\/ Returns the singleton instance of the ContextRegistryInfo. The object\n\/\/\/ is constructed automaticall on first access.\n\/\/\/ \\param backendName the optional name of the backend to use (force).\n\nContextRegistryInfo* ContextRegistryInfo::instance(const QString &backendName)\n{\n static QMutex mutex;\n QMutexLocker locker(&mutex);\n if (! registryInstance) {\n InfoBackend::instance(backendName);\n registryInstance = new ContextRegistryInfo;\n\n InfoBackend* infoBackend = InfoBackend::instance();\n\n sconnect(infoBackend, SIGNAL(keysChanged(QStringList)),\n registryInstance, SLOT(onKeysChanged(QStringList)));\n\n sconnect(infoBackend, SIGNAL(keysAdded(QStringList)),\n registryInstance, SLOT(onKeysAdded(QStringList)));\n\n sconnect(infoBackend, SIGNAL(keysRemoved(QStringList)),\n registryInstance, SLOT(onKeysRemoved(QStringList)));\n\n \/\/ Move the backend to the main thread\n registryInstance->moveToThread(QCoreApplication::instance()->thread());\n }\n\n return registryInstance;\n}\n\n\/\/\/ Returns the list of all the keys currently availible in the registry.\nQStringList ContextRegistryInfo::listKeys() const\n{\n return InfoBackend::instance()->listKeys();\n}\n\n\/\/\/ Returns the list of all the keys associated with the given provider.\nQStringList ContextRegistryInfo::listKeys(QString providerName) const\n{\n \/\/ TBD: obsolete this?\n QStringList keys = InfoBackend::instance()->listKeysForPlugin(\"contextkit-dbus\");\n QStringList toReturn;\n foreach (const QString& key, keys) {\n QString constructionString = InfoBackend::instance()->constructionStringForKey(key);\n if (constructionString.split(\":\").last() == providerName) {\n toReturn << key;\n }\n }\n return toReturn;\n}\n\n\/\/\/ Returns the list of all the keys associated with the given plugin\nQStringList ContextRegistryInfo::listKeysForPlugin(QString plugin) const\n{\n contextWarning() << F_DEPRECATION << \"ContextRegistryInfo::listKeysForPlugin() is deprecated.\";\n\n QStringList keys;\n\n foreach (QString key, listKeys()) {\n QList providers = InfoBackend::instance()->listProviders(key);\n foreach (ContextProviderInfo info, providers) {\n if (info.plugin == plugin) {\n keys << key;\n break;\n }\n }\n\n }\n\n return keys;\n}\n\n\/\/\/ Returns the list of all unique providers in the registry.\n\/\/\/ The lists consist of strings with dbus names of the providers.\nQStringList ContextRegistryInfo::listProviders() const\n{\n \/\/ TBD: obsolete this?\n QStringList keys = InfoBackend::instance()->listKeysForPlugin(\"contextkit-dbus\");\n QSet foundProviders;\n foreach (const QString& key, keys) {\n QString constructionString = InfoBackend::instance()->constructionStringForKey(key);\n foundProviders.insert(constructionString.split(\":\").last());\n }\n QStringList toReturn(foundProviders.toList());\n return toReturn;\n}\n\n\/\/\/ Returns the list of all unique plugins in the registry.\nQStringList ContextRegistryInfo::listPlugins() const\n{\n return InfoBackend::instance()->listPlugins();\n}\n\n\/\/\/ Returns the name of the currently used registry backend. Ie. \"cdb\" or \"xml\".\nQString ContextRegistryInfo::backendName() const\n{\n return InfoBackend::instance()->name();\n}\n\n\/* Slots *\/\n\n\/\/\/ This is connected to the \\a onKeysChanged of the actual info backend instance.\nvoid ContextRegistryInfo::onKeysChanged(const QStringList& currentKeys)\n{\n emit(keysChanged(currentKeys));\n}\n\n\/\/\/ This is connected to the \\a onKeysAdded of the actual info backend instance.\nvoid ContextRegistryInfo::onKeysAdded(const QStringList& newKeys)\n{\n emit(keysAdded(newKeys));\n}\n\n\/\/\/ This is connected to the \\a onKeysRemoved of the actual info backend instance.\nvoid ContextRegistryInfo::onKeysRemoved(const QStringList& removedKeys)\n{\n emit(keysRemoved(removedKeys));\n}\n\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2014-2016 Pelagicore AB\n * All rights reserved.\n *\/\n#include \"dbusgateway.h\"\n\nDBusGateway::DBusGateway(ProxyType type\n , const std::string &gatewayDir\n , const std::string &name)\n : Gateway(ID)\n , m_type(type)\n{\n m_state = GatewayState::CREATED;\n m_socket = gatewayDir \n + (m_type == SessionProxy ? \"\/sess_\" : \"\/sys_\")\n + name \n + \".sock\";\n\n m_sessionBusConfig = json_array();\n m_systemBusConfig = json_array();\n}\n\nDBusGateway::~DBusGateway()\n{\n if (m_state == GatewayState::ACTIVATED) {\n teardown();\n }\n}\n\nstatic constexpr const char *SESSION_CONFIG = \"dbus-gateway-config-session\";\nstatic constexpr const char *SYSTEM_CONFIG = \"dbus-gateway-config-system\";\n\nReturnCode DBusGateway::readConfigElement(const JSonElement &element)\n{\n JSonElement sessionConfig = element[SESSION_CONFIG];\n if (sessionConfig.isValid() && sessionConfig.isArray()) {\n for(unsigned int i = 0; i < sessionConfig.elementCount(); i++) {\n JSonElement child = sessionConfig.arrayElementAt(i);\n json_array_append(m_sessionBusConfig, (json_t*)child.root());\n }\n }\n\n JSonElement systemConfig = element[SYSTEM_CONFIG];\n if (systemConfig.isValid() && systemConfig.isArray()) {\n for(unsigned int i = 0; i < systemConfig.elementCount(); i++) {\n JSonElement child = systemConfig.arrayElementAt(i);\n json_array_append(m_systemBusConfig, (json_t*)child.root());\n }\n }\n\n m_state = GatewayState::CONFIGURED;\n return ReturnCode::SUCCESS;\n}\n\nbool DBusGateway::activateGateway()\n{\n \/\/ set DBUS_{SESSION,SYSTEM}_BUS_ADDRESS env variable\n std::string variable = std::string(\"DBUS_\")\n + (m_type == SessionProxy ? \"SESSION\" : \"SYSTEM\")\n + std::string(\"_BUS_ADDRESS\");\n std::string value = \"unix:path=\/gateways\/\" + socketName();\n setEnvironmentVariable(variable, value);\n\n std::vector commandVec = { \"dbus-proxy\"\n , m_socket\n , m_type == SessionProxy ? \"session\" : \"system\" };\n\n \/\/ Give the dbus-proxy access to the real dbus bus address.\n std::vector envVec;\n if (char *envValue = getenv(variable.c_str())) {\n envVec.push_back(variable + \"=\" + envValue);\n } else if (m_type == SessionProxy) {\n log_error() << \"Using DBus gateway in session mode\"\n << \" and no \" + variable + \" set in host environment, dbus-proxy won't work\";\n return false;\n } else {\n log_warn() << \"Using DBus gateway in system mode\"\n << \" and no \" + variable + \" set in host environment, this could be a problem\";\n }\n\n if (!startDBusProxy(commandVec, envVec)) {\n return false;\n }\n\n \/\/ Write configuration\n json_t *jsonConfig = json_object();\n json_object_set(jsonConfig, SESSION_CONFIG, m_sessionBusConfig);\n json_object_set(jsonConfig, SYSTEM_CONFIG, m_systemBusConfig);\n std::string config = std::string(json_dumps(jsonConfig, JSON_COMPACT));\n\n return testDBusConnection(config);\n}\n\nbool DBusGateway::testDBusConnection(const std::string &config)\n{\n log_debug() << \"Sending config \" << config;\n unsigned int count = sizeof(char) * config.length();\n ssize_t written = write(m_infp, config.c_str(), count);\n\n \/\/ writing didn't work at all\n if (written == -1) {\n log_error() << \"Failed to write to STDIN of dbus-proxy: \" << strerror(errno);\n return false;\n } else if (written == (ssize_t)count) {\n \/\/ writing has written exact amout of bytes\n close(m_infp);\n m_infp = INVALID_FD;\n \/\/ dbus-proxy might take some time to create the bus socket\n if (isSocketCreated()) {\n log_debug() << \"Found D-Bus socket: \" << m_socket;\n return true;\n } else {\n log_error() << \"Did not find any D-Bus socket: \" << m_socket;\n return false;\n }\n } else {\n \/\/ something went wrong during the write\n log_error() << \"Failed to write to STDIN of dbus-proxy!\";\n return false;\n }\n}\n\nbool DBusGateway::startDBusProxy(const std::vector &commandVec, const std::vector &envVec)\n{\n \/\/ Spawn dbus-proxy with access to its stdin.\n try {\n Glib::spawn_async_with_pipes( \".\"\n , commandVec\n , envVec\n , Glib::SPAWN_STDOUT_TO_DEV_NULL \/\/ Redirect stdout\n | Glib::SPAWN_STDERR_TO_DEV_NULL \/\/ Redirect stderr\n | Glib::SPAWN_SEARCH_PATH \/\/ Search $PATH\n | Glib::SPAWN_DO_NOT_REAP_CHILD \/\/ Lets us do waitpid\n , sigc::slot() \/\/ child setup\n , &m_pid\n , &m_infp \/\/ stdin\n );\n } catch (const Glib::Error &ex) {\n log_error() << \"Failed to launch dbus-proxy\";\n return false;\n }\n\n log_debug() << \"Started dbus-proxy: \" << m_pid;\n m_state = GatewayState::ACTIVATED;\n\n return true;\n}\n\nbool DBusGateway::isSocketCreated() const\n{\n int maxCount = 1000;\n int count = 0;\n do {\n if (count >= maxCount) {\n return false;\n }\n count++;\n usleep(1000 * 10);\n } while (access(m_socket.c_str(), F_OK) == -1);\n return true;\n}\n\nbool DBusGateway::teardownGateway()\n{\n bool success = true;\n\n if (m_pid != INVALID_PID) {\n log_debug() << \"Killing dbus-proxy with pid \" << m_pid;\n \/*\n * For some reason, it does not work using SIGTERM, as that causes\n * the system to hang on waitpid - even if Glib::SPAWN_DO_NOT_REAP_CHILD\n * is set. It seems dbus-proxy does not react to SIGTERM.\n *\/\n kill(m_pid, SIGTERM);\n waitpid(m_pid, nullptr, 0); \/\/ Wait until it exits\n Glib::spawn_close_pid(m_pid);\n } else {\n log_debug() << \"dbus-proxy pid not set or already dead: \" << m_pid;\n }\n\n if (access(m_socket.c_str(), F_OK) != -1) {\n if (unlink(m_socket.c_str()) == -1) {\n log_error() << \"Could not remove \" << m_socket << \": \" << strerror(errno);\n success = false;\n }\n } else {\n log_debug() << \"Socket not accessible, has it been removed already?\";\n }\n\n return success;\n}\n\nstd::string DBusGateway::socketName()\n{\n \/\/ Return the filename after stripping directory info\n std::string socket(m_socket.c_str());\n return socket.substr(socket.rfind('\/') + 1);\n}\n\n\ndbusgateway.cpp: use SIGKILL, some configs fail with SIGTERM\/*\n * Copyright (C) 2014-2016 Pelagicore AB\n * All rights reserved.\n *\/\n#include \"dbusgateway.h\"\n\nDBusGateway::DBusGateway(ProxyType type\n , const std::string &gatewayDir\n , const std::string &name)\n : Gateway(ID)\n , m_type(type)\n{\n m_state = GatewayState::CREATED;\n m_socket = gatewayDir \n + (m_type == SessionProxy ? \"\/sess_\" : \"\/sys_\")\n + name \n + \".sock\";\n\n m_sessionBusConfig = json_array();\n m_systemBusConfig = json_array();\n}\n\nDBusGateway::~DBusGateway()\n{\n if (m_state == GatewayState::ACTIVATED) {\n teardown();\n }\n}\n\nstatic constexpr const char *SESSION_CONFIG = \"dbus-gateway-config-session\";\nstatic constexpr const char *SYSTEM_CONFIG = \"dbus-gateway-config-system\";\n\nReturnCode DBusGateway::readConfigElement(const JSonElement &element)\n{\n JSonElement sessionConfig = element[SESSION_CONFIG];\n if (sessionConfig.isValid() && sessionConfig.isArray()) {\n for(unsigned int i = 0; i < sessionConfig.elementCount(); i++) {\n JSonElement child = sessionConfig.arrayElementAt(i);\n json_array_append(m_sessionBusConfig, (json_t*)child.root());\n }\n }\n\n JSonElement systemConfig = element[SYSTEM_CONFIG];\n if (systemConfig.isValid() && systemConfig.isArray()) {\n for(unsigned int i = 0; i < systemConfig.elementCount(); i++) {\n JSonElement child = systemConfig.arrayElementAt(i);\n json_array_append(m_systemBusConfig, (json_t*)child.root());\n }\n }\n\n m_state = GatewayState::CONFIGURED;\n return ReturnCode::SUCCESS;\n}\n\nbool DBusGateway::activateGateway()\n{\n \/\/ set DBUS_{SESSION,SYSTEM}_BUS_ADDRESS env variable\n std::string variable = std::string(\"DBUS_\")\n + (m_type == SessionProxy ? \"SESSION\" : \"SYSTEM\")\n + std::string(\"_BUS_ADDRESS\");\n std::string value = \"unix:path=\/gateways\/\" + socketName();\n setEnvironmentVariable(variable, value);\n\n std::vector commandVec = { \"dbus-proxy\"\n , m_socket\n , m_type == SessionProxy ? \"session\" : \"system\" };\n\n \/\/ Give the dbus-proxy access to the real dbus bus address.\n std::vector envVec;\n if (char *envValue = getenv(variable.c_str())) {\n envVec.push_back(variable + \"=\" + envValue);\n } else if (m_type == SessionProxy) {\n log_error() << \"Using DBus gateway in session mode\"\n << \" and no \" + variable + \" set in host environment, dbus-proxy won't work\";\n return false;\n } else {\n log_warn() << \"Using DBus gateway in system mode\"\n << \" and no \" + variable + \" set in host environment, this could be a problem\";\n }\n\n if (!startDBusProxy(commandVec, envVec)) {\n return false;\n }\n\n \/\/ Write configuration\n json_t *jsonConfig = json_object();\n json_object_set(jsonConfig, SESSION_CONFIG, m_sessionBusConfig);\n json_object_set(jsonConfig, SYSTEM_CONFIG, m_systemBusConfig);\n std::string config = std::string(json_dumps(jsonConfig, JSON_COMPACT));\n\n return testDBusConnection(config);\n}\n\nbool DBusGateway::testDBusConnection(const std::string &config)\n{\n log_debug() << \"Sending config \" << config;\n unsigned int count = sizeof(char) * config.length();\n ssize_t written = write(m_infp, config.c_str(), count);\n\n \/\/ writing didn't work at all\n if (written == -1) {\n log_error() << \"Failed to write to STDIN of dbus-proxy: \" << strerror(errno);\n return false;\n } else if (written == (ssize_t)count) {\n \/\/ writing has written exact amout of bytes\n close(m_infp);\n m_infp = INVALID_FD;\n \/\/ dbus-proxy might take some time to create the bus socket\n if (isSocketCreated()) {\n log_debug() << \"Found D-Bus socket: \" << m_socket;\n return true;\n } else {\n log_error() << \"Did not find any D-Bus socket: \" << m_socket;\n return false;\n }\n } else {\n \/\/ something went wrong during the write\n log_error() << \"Failed to write to STDIN of dbus-proxy!\";\n return false;\n }\n}\n\nbool DBusGateway::startDBusProxy(const std::vector &commandVec, const std::vector &envVec)\n{\n \/\/ Spawn dbus-proxy with access to its stdin.\n try {\n Glib::spawn_async_with_pipes( \".\"\n , commandVec\n , envVec\n , Glib::SPAWN_STDOUT_TO_DEV_NULL \/\/ Redirect stdout\n | Glib::SPAWN_STDERR_TO_DEV_NULL \/\/ Redirect stderr\n | Glib::SPAWN_SEARCH_PATH \/\/ Search $PATH\n | Glib::SPAWN_DO_NOT_REAP_CHILD \/\/ Lets us do waitpid\n , sigc::slot() \/\/ child setup\n , &m_pid\n , &m_infp \/\/ stdin\n );\n } catch (const Glib::Error &ex) {\n log_error() << \"Failed to launch dbus-proxy\";\n return false;\n }\n\n log_debug() << \"Started dbus-proxy: \" << m_pid;\n m_state = GatewayState::ACTIVATED;\n\n return true;\n}\n\nbool DBusGateway::isSocketCreated() const\n{\n int maxCount = 1000;\n int count = 0;\n do {\n if (count >= maxCount) {\n return false;\n }\n count++;\n usleep(1000 * 10);\n } while (access(m_socket.c_str(), F_OK) == -1);\n return true;\n}\n\nbool DBusGateway::teardownGateway()\n{\n bool success = true;\n\n if (m_pid != INVALID_PID) {\n log_debug() << \"Killing dbus-proxy with pid \" << m_pid;\n\n kill(m_pid, SIGKILL); \/\/ In some configurations, hangs if using SIGTERM instead\n waitpid(m_pid, nullptr, 0); \/\/ Wait until it exits\n Glib::spawn_close_pid(m_pid);\n } else {\n log_debug() << \"dbus-proxy pid not set or already dead: \" << m_pid;\n }\n\n if (access(m_socket.c_str(), F_OK) != -1) {\n if (unlink(m_socket.c_str()) == -1) {\n log_error() << \"Could not remove \" << m_socket << \": \" << strerror(errno);\n success = false;\n }\n } else {\n log_debug() << \"Socket not accessible, has it been removed already?\";\n }\n\n return success;\n}\n\nstd::string DBusGateway::socketName()\n{\n \/\/ Return the filename after stripping directory info\n std::string socket(m_socket.c_str());\n return socket.substr(socket.rfind('\/') + 1);\n}\n\n\n<|endoftext|>"} {"text":"#include \"config_manager.h\"\n\nusing namespace std;\nusing namespace TOOLS;\n\nConfigDataKeeper::ConfigDataKeeper(const ConfigDataKeeper& obj) \n : storage(obj.storage), tinfo(obj.tinfo) { }\n\n\nConfigDataKeeper::ConfigDataKeeper(void* data, const string& tinfo) \n : storage(data), tinfo(tinfo) { }\n\nConfigDataKeeper::ConfigDataKeeper(const string& tinfo) \n : storage(nullptr), tinfo(tinfo) { }\n\n\/\/ return verbose type string\nstring ConfigDataKeeper::verbose_type() const {\n if(tinfo == typeid(int).name())\n return \"integer\";\n else if(tinfo == typeid(double).name())\n return \"float\";\n else if(tinfo == typeid(string).name())\n return \"string\";\n else if(tinfo == typeid(tStringList).name())\n return \"string list\";\n else if(tinfo == typeid(tStringMap).name())\n return \"string map\";\n else if(tinfo == typeid(bool).name())\n return \"boolean\";\n return \"unknown data type!!! \";\n}\n\n\/\/ return verbose data string representation\nstring ConfigDataKeeper::verbose_data(void* raw_data) const {\n string out;\n const ConfigDataKeeper* cdk;\n if(raw_data != nullptr)\n cdk = new ConfigDataKeeper(raw_data, tinfo);\n else\n cdk = this;\n\n if(tinfo == typeid(int).name())\n out = str(cdk->get());\n else if(tinfo == typeid(double).name())\n out = str(cdk->get());\n else if(tinfo == typeid(string).name())\n out = cdk->get();\n else if(tinfo == typeid(tStringList).name())\n out = XString(\",\").join(cdk->get());\n else if(tinfo == typeid(tStringMap).name()) {\n tStringList tmp;\n for(auto& key_val : cdk->get())\n tmp.push_back(key_val.first + \":\" + key_val.second);\n out = XString(\",\").join(tmp);\n } else if(tinfo == typeid(bool).name())\n out = (cdk->get()) ? \"true\" : \"false\";\n else\n out = \"unknown data\";\n\n if(raw_data != nullptr)\n delete cdk;\n return out;\n}\n\nConfigOption::ConfigOption(const std::string& id, const std::string& desc, \\\n const std::string& tinfo, const std::string& scmd)\n : data(tinfo), default_data(tinfo), id(id), cmd_short(scmd), desc(desc), \n was_set(false), has_default(false), parent(NULL) { }\n\n\nstring ConfigOption::verbose_type() const {\n return data.verbose_type();\n}\n\nstring ConfigOption::verbose_data() const {\n return data.verbose_data();\n}\n\nstring ConfigOption::verbose_default() const {\n if(has_default)\n return default_data.verbose_data();\n return \"\";\n}\n\nConfigGroup::ConfigGroup(const std::string& name, ConfigManager* par)\n : name(name), parent(par) {}\n\nConfigGroup::iterator ConfigGroup::begin() {\n return members.begin();\n}\n\nConfigGroup::const_iterator ConfigGroup::begin() const { \n return members.begin();\n}\n\nConfigGroup::iterator ConfigGroup::end() { \n return members.end();\n}\n\nConfigGroup::const_iterator ConfigGroup::end() const { \n return members.end();\n}\n\nConfigOption& ConfigGroup::get_option(const std::string& id) {\n tOptionIter it = members.find(id);\n if(it != members.end())\n return *it->second;\n throw OptionNotFound(id);\n}\n\nConfigGroup& ConfigManager::new_group(const std::string& name) {\n groups[name] = new ConfigGroup(name, this);\n return *groups[name];\n}\n\nConfigGroup& ConfigManager::get_group(const string& name) {\n tGroupIter it = groups.find(name);\n if(it == groups.end())\n throw GroupNotFound(name);\n return *it->second;\n}\n\nConfigGroup& ConfigManager::get_group_from_option(const string& name) {\n return *(get_option(name).parent);\n}\n\nConfigOption& ConfigManager::get_option(const std::string& id) {\n tOptionIter it = members.find(id);\n if(it == members.end())\n throw OptionNotFound(id);\n return *(it->second);\n}\n\nConfigManager::iterator ConfigManager::begin() { \n return groups.begin(); \n}\n\nConfigManager::const_iterator ConfigManager::begin() const { \n return groups.begin();\n}\n\nConfigManager::iterator ConfigManager::end() { \n return groups.end();\n}\n\nConfigManager::const_iterator ConfigManager::end() const { \n return groups.end();\n}\n\n\nConfigManager::ConfigManager(const std::string& start_command)\n : command(start_command) { }\n\nvoid ConfigManager::parse(tStringList* args) {\n string cmd = args->at(0);\n\n if(cmdmap.find(cmd) == cmdmap.end())\n throw UnknownParameter(cmd);\n\n string id = cmdmap[cmd];\n ConfigDataKeeper* tmp = &members[id]->data;\n\n \/\/ catch boolean value as this doesn't need an arg\n if(tmp->same_data_types()) {\n \/\/ even if possible, a arg for bools may be passed\n if(args->size() > 1) {\n bool explicit_set = false;\n if(args->at(1) == \"true\") {\n explicit_set = true;\n set(id, true);\n } else if(args->at(1) == \"false\") {\n explicit_set = true;\n set(id, false);\n }\n if(explicit_set) \n args->erase(args->begin(), args->begin()+2);\n \n } else {\n \/\/ if not passed, just toggle or set to true\n if(members[id]->has_default)\n set(id, !get(id));\n else\n set(id, true);\n args->erase(args->begin());\n }\n return;\n }\n\n if(args->size() < 2)\n throw MissingParameter(cmd + \" - found no more args\");\n\n string arg = args->at(1);\n\n \/\/ check for integer and double\n try {\n if(tmp->same_data_types()) {\n set(id, integer(arg));\n args->erase(args->begin(), args->begin()+2);\n return;\n } else if(tmp->same_data_types()) {\n set(id, real(arg));\n args->erase(args->begin(), args->begin()+2);\n return;\n }\n } catch(ConvertValueError e) {\n throw IncompatibleDataTypes(\"data: \" + tmp->verbose_type() + \" passed: \" + arg);\n }\n\n \/\/ get string\n if(tmp->same_data_types()) {\n set(id, str(arg));\n args->erase(args->begin(), args->begin()+2);\n return;\n }\n\n \/\/ build tStringList from \",\" separated input\n if(tmp->same_data_types()) {\n set(id, XString(arg).split(\",\"));\n args->erase(args->begin(), args->begin()+2);\n return;\n \/\/ build tStringMap from \",\" and \":\" separated input\n }\n if(tmp->same_data_types()) {\n tStringList tmp = XString(arg).split(\",\");\n tStringMap tmpmap;\n for(tStringIter i=tmp.begin(); i!=tmp.end(); ++i) {\n tStringList two = XString(*i).split(\":\");\n tmpmap[two[0]] = two[1];\n }\n set(id, tmpmap);\n args->erase(args->begin(), args->begin()+2);\n return;\n }\n throw IncompatibleDataTypes(\"data: \" + tmp->verbose_type() + \" passed: \" + arg);\n}\n\nvoid ConfigManager::parse_cmdline(int argc, char* argv[]) {\n tStringList args;\n for(int i=1; i 0)\n parse(&args);\n}\n\nvoid ConfigManager::write_config_file(ostream& fd, bool shorter) {\n fd << endl;\n fd << \"###\" << endl;\n fd << \"### config file for: \" << command << endl;\n fd << \"###\" << endl;\n fd << endl;\n for(tGroupPair& grp : groups) {\n if(!shorter)\n fd << \"####################################################\" << endl;\n else\n fd << endl;\n fd << \"# [ \" << grp.first << \" ]\" << endl;\n for(tOptionPair& opt : *grp.second) {\n const ConfigOption* c = opt.second;\n const string& id = opt.first;\n\n \/\/ write desc\/help text\n if(!shorter) {\n fd << \"# \" << c->desc << \" [\" << c->verbose_type() << \"]\"; \n \/\/ write if ConfigOption has default\n if(c->has_default)\n fd << \" default: \" << c->verbose_default();\n fd << endl;\n }\n\n \/\/ ConfigOption was set, output its value\n if(c->was_set) {\n fd << id << \" = \" << c->verbose_data() << endl;\n \/\/ ConfigOption was _not_ set, output commented out line and default\n } else if(c->has_default) {\n fd << \"# \" << id << \" = \" << c->verbose_default() << endl;\n \/\/ ConfigOption was neither set nor has a default value\n } else {\n if(!shorter)\n fd << \"# \" << id << \" = \" << \"\" << endl;\n }\n if(!shorter)\n fd << endl;\n }\n }\n}\n\nvoid ConfigManager::parse_config_file(const string& fn) {\n ifstream fd(fn.c_str(), ios::in);\n XString line;\n tStringList tokens;\n while(fd.good()) {\n getline(fd, line);\n line.strip().strip(\"\\n\");\n if(line.length() == 0)\n continue;\n\n if(line.startswith(\"#\"))\n continue;\n\n if(line.find(\"=\") == string::npos) {\n tokens.push_back(\"--\" + line);\n continue;\n }\n\n tStringList lr = line.split(\"=\");\n XString left(lr[0]), right(lr[1]);\n left.strip();\n right.strip();\n\n tokens.push_back(\"--\" + left);\n tokens.push_back(right);\n }\n fd.close();\n\n try {\n while(tokens.size() > 0) \n parse(&tokens);\n \n } catch(IncompatibleDataTypes& e) {\n e.message += \" (inside configfile)\";\n throw e;\n }\n}\n\nbool ConfigManager::is_group_active(const std::string& name) {\n tOptionMap& opts = groups[name]->members;\n for(tOptionIter i=opts.begin(); i!=opts.end(); ++i)\n if(i->second->was_set)\n return true;\n return false;\n}\n\nbool ConfigManager::is_option_set(const std::string& id) {\n return (get_option(id).was_set || get_option(id).has_default);\n}\n\nvoid ConfigManager::usage(ostream& ss) {\n ss << \"Usage: \" << command << \" \" << endl;\n ss << endl << \"Options:\" << endl;\n\n string::size_type id_len = 0, scmd_len = 0, desc_len = 0;\n for(tStringMapIter i=cmdmap.begin(); i!=cmdmap.end(); ++i) {\n ConfigOption* opt = members[i->second];\n if(i->first.find(\"--\") != string::npos)\n id_len = max(opt->id.length(), id_len);\n else\n scmd_len = max(opt->cmd_short.length(), scmd_len);\n desc_len = max(opt->desc.length(), desc_len);\n }\n\n for(tGroupIter g=groups.begin(); g!=groups.end(); ++g) {\n ConfigGroup* grp = g->second;\n ss << endl << \"--- Group: \" << grp->name << endl;\n for(tOptionIter i=grp->members.begin(); i!=grp->members.end(); ++i) {\n ConfigOption* opt = grp->members[i->first];\n\n ss << right << setw(scmd_len+1) << ((opt->cmd_short.size() > 0) ? \\\n (\"-\" + opt->cmd_short) : \"\") << \" | \" << flush;\n ss << left << setw(id_len+2) << (\"--\" + opt->id) << \" \" << opt->desc;\n ss << \" [\" << opt->data.verbose_type() << \"]\";\n ss << endl;\n }\n }\n ss << endl;\n}\nConfigManager catching case two bools without args in cmdline#include \"config_manager.h\"\n\nusing namespace std;\nusing namespace TOOLS;\n\nConfigDataKeeper::ConfigDataKeeper(const ConfigDataKeeper& obj) \n : storage(obj.storage), tinfo(obj.tinfo) { }\n\n\nConfigDataKeeper::ConfigDataKeeper(void* data, const string& tinfo) \n : storage(data), tinfo(tinfo) { }\n\nConfigDataKeeper::ConfigDataKeeper(const string& tinfo) \n : storage(nullptr), tinfo(tinfo) { }\n\n\/\/ return verbose type string\nstring ConfigDataKeeper::verbose_type() const {\n if(tinfo == typeid(int).name())\n return \"integer\";\n else if(tinfo == typeid(double).name())\n return \"float\";\n else if(tinfo == typeid(string).name())\n return \"string\";\n else if(tinfo == typeid(tStringList).name())\n return \"string list\";\n else if(tinfo == typeid(tStringMap).name())\n return \"string map\";\n else if(tinfo == typeid(bool).name())\n return \"boolean\";\n return \"unknown data type!!! \";\n}\n\n\/\/ return verbose data string representation\nstring ConfigDataKeeper::verbose_data(void* raw_data) const {\n string out;\n const ConfigDataKeeper* cdk;\n if(raw_data != nullptr)\n cdk = new ConfigDataKeeper(raw_data, tinfo);\n else\n cdk = this;\n\n if(tinfo == typeid(int).name())\n out = str(cdk->get());\n else if(tinfo == typeid(double).name())\n out = str(cdk->get());\n else if(tinfo == typeid(string).name())\n out = cdk->get();\n else if(tinfo == typeid(tStringList).name())\n out = XString(\",\").join(cdk->get());\n else if(tinfo == typeid(tStringMap).name()) {\n tStringList tmp;\n for(auto& key_val : cdk->get())\n tmp.push_back(key_val.first + \":\" + key_val.second);\n out = XString(\",\").join(tmp);\n } else if(tinfo == typeid(bool).name())\n out = (cdk->get()) ? \"true\" : \"false\";\n else\n out = \"unknown data\";\n\n if(raw_data != nullptr)\n delete cdk;\n return out;\n}\n\nConfigOption::ConfigOption(const std::string& id, const std::string& desc, \\\n const std::string& tinfo, const std::string& scmd)\n : data(tinfo), default_data(tinfo), id(id), cmd_short(scmd), desc(desc), \n was_set(false), has_default(false), parent(NULL) { }\n\n\nstring ConfigOption::verbose_type() const {\n return data.verbose_type();\n}\n\nstring ConfigOption::verbose_data() const {\n return data.verbose_data();\n}\n\nstring ConfigOption::verbose_default() const {\n if(has_default)\n return default_data.verbose_data();\n return \"\";\n}\n\nConfigGroup::ConfigGroup(const std::string& name, ConfigManager* par)\n : name(name), parent(par) {}\n\nConfigGroup::iterator ConfigGroup::begin() {\n return members.begin();\n}\n\nConfigGroup::const_iterator ConfigGroup::begin() const { \n return members.begin();\n}\n\nConfigGroup::iterator ConfigGroup::end() { \n return members.end();\n}\n\nConfigGroup::const_iterator ConfigGroup::end() const { \n return members.end();\n}\n\nConfigOption& ConfigGroup::get_option(const std::string& id) {\n tOptionIter it = members.find(id);\n if(it != members.end())\n return *it->second;\n throw OptionNotFound(id);\n}\n\nConfigGroup& ConfigManager::new_group(const std::string& name) {\n groups[name] = new ConfigGroup(name, this);\n return *groups[name];\n}\n\nConfigGroup& ConfigManager::get_group(const string& name) {\n tGroupIter it = groups.find(name);\n if(it == groups.end())\n throw GroupNotFound(name);\n return *it->second;\n}\n\nConfigGroup& ConfigManager::get_group_from_option(const string& name) {\n return *(get_option(name).parent);\n}\n\nConfigOption& ConfigManager::get_option(const std::string& id) {\n tOptionIter it = members.find(id);\n if(it == members.end())\n throw OptionNotFound(id);\n return *(it->second);\n}\n\nConfigManager::iterator ConfigManager::begin() { \n return groups.begin(); \n}\n\nConfigManager::const_iterator ConfigManager::begin() const { \n return groups.begin();\n}\n\nConfigManager::iterator ConfigManager::end() { \n return groups.end();\n}\n\nConfigManager::const_iterator ConfigManager::end() const { \n return groups.end();\n}\n\n\nConfigManager::ConfigManager(const std::string& start_command)\n : command(start_command) { }\n\nvoid ConfigManager::parse(tStringList* args) {\n string cmd = args->at(0);\n\n if(cmdmap.find(cmd) == cmdmap.end())\n throw UnknownParameter(cmd);\n\n string id = cmdmap[cmd];\n ConfigDataKeeper* tmp = &members[id]->data;\n\n \/\/ catch boolean value as this doesn't need an arg\n if(tmp->same_data_types()) {\n \/\/ even if possible, a arg for bools may be passed\n if(args->size() > 1) {\n bool explicit_set = false;\n if(args->at(1) == \"true\") {\n explicit_set = true;\n set(id, true);\n } else if(args->at(1) == \"false\") {\n explicit_set = true;\n set(id, false);\n }\n if(explicit_set) {\n args->erase(args->begin(), args->begin()+2);\n return;\n }\n }\n \n \/\/ if not passed, just toggle or set to true\n if(members[id]->has_default)\n set(id, !get(id));\n else\n set(id, true);\n args->erase(args->begin());\n return;\n }\n\n if(args->size() < 2)\n throw MissingParameter(cmd + \" - found no more args\");\n\n string arg = args->at(1);\n\n \/\/ check for integer and double\n try {\n if(tmp->same_data_types()) {\n set(id, integer(arg));\n args->erase(args->begin(), args->begin()+2);\n return;\n } else if(tmp->same_data_types()) {\n set(id, real(arg));\n args->erase(args->begin(), args->begin()+2);\n return;\n }\n } catch(ConvertValueError e) {\n throw IncompatibleDataTypes(\"data: \" + tmp->verbose_type() + \" passed: \" + arg);\n }\n\n \/\/ get string\n if(tmp->same_data_types()) {\n set(id, str(arg));\n args->erase(args->begin(), args->begin()+2);\n return;\n }\n\n \/\/ build tStringList from \",\" separated input\n if(tmp->same_data_types()) {\n set(id, XString(arg).split(\",\"));\n args->erase(args->begin(), args->begin()+2);\n return;\n \/\/ build tStringMap from \",\" and \":\" separated input\n }\n if(tmp->same_data_types()) {\n tStringList tmp = XString(arg).split(\",\");\n tStringMap tmpmap;\n for(tStringIter i=tmp.begin(); i!=tmp.end(); ++i) {\n tStringList two = XString(*i).split(\":\");\n tmpmap[two[0]] = two[1];\n }\n set(id, tmpmap);\n args->erase(args->begin(), args->begin()+2);\n return;\n }\n throw IncompatibleDataTypes(\"data: \" + tmp->verbose_type() + \" passed: \" + arg);\n}\n\nvoid ConfigManager::parse_cmdline(int argc, char* argv[]) {\n tStringList args;\n for(int i=1; i 0)\n parse(&args);\n}\n\nvoid ConfigManager::write_config_file(ostream& fd, bool shorter) {\n fd << endl;\n fd << \"###\" << endl;\n fd << \"### config file for: \" << command << endl;\n fd << \"###\" << endl;\n fd << endl;\n for(tGroupPair& grp : groups) {\n if(!shorter)\n fd << \"####################################################\" << endl;\n else\n fd << endl;\n fd << \"# [ \" << grp.first << \" ]\" << endl;\n for(tOptionPair& opt : *grp.second) {\n const ConfigOption* c = opt.second;\n const string& id = opt.first;\n\n \/\/ write desc\/help text\n if(!shorter) {\n fd << \"# \" << c->desc << \" [\" << c->verbose_type() << \"]\"; \n \/\/ write if ConfigOption has default\n if(c->has_default)\n fd << \" default: \" << c->verbose_default();\n fd << endl;\n }\n\n \/\/ ConfigOption was set, output its value\n if(c->was_set) {\n fd << id << \" = \" << c->verbose_data() << endl;\n \/\/ ConfigOption was _not_ set, output commented out line and default\n } else if(c->has_default) {\n fd << \"# \" << id << \" = \" << c->verbose_default() << endl;\n \/\/ ConfigOption was neither set nor has a default value\n } else {\n if(!shorter)\n fd << \"# \" << id << \" = \" << \"\" << endl;\n }\n if(!shorter)\n fd << endl;\n }\n }\n}\n\nvoid ConfigManager::parse_config_file(const string& fn) {\n ifstream fd(fn.c_str(), ios::in);\n XString line;\n tStringList tokens;\n while(fd.good()) {\n getline(fd, line);\n line.strip().strip(\"\\n\");\n if(line.length() == 0)\n continue;\n\n if(line.startswith(\"#\"))\n continue;\n\n if(line.find(\"=\") == string::npos) {\n tokens.push_back(\"--\" + line);\n continue;\n }\n\n tStringList lr = line.split(\"=\");\n XString left(lr[0]), right(lr[1]);\n left.strip();\n right.strip();\n\n tokens.push_back(\"--\" + left);\n tokens.push_back(right);\n }\n fd.close();\n\n try {\n while(tokens.size() > 0) \n parse(&tokens);\n \n } catch(IncompatibleDataTypes& e) {\n e.message += \" (inside configfile)\";\n throw e;\n }\n}\n\nbool ConfigManager::is_group_active(const std::string& name) {\n tOptionMap& opts = groups[name]->members;\n for(tOptionIter i=opts.begin(); i!=opts.end(); ++i)\n if(i->second->was_set)\n return true;\n return false;\n}\n\nbool ConfigManager::is_option_set(const std::string& id) {\n return (get_option(id).was_set || get_option(id).has_default);\n}\n\nvoid ConfigManager::usage(ostream& ss) {\n ss << \"Usage: \" << command << \" \" << endl;\n ss << endl << \"Options:\" << endl;\n\n string::size_type id_len = 0, scmd_len = 0, desc_len = 0;\n for(tStringMapIter i=cmdmap.begin(); i!=cmdmap.end(); ++i) {\n ConfigOption* opt = members[i->second];\n if(i->first.find(\"--\") != string::npos)\n id_len = max(opt->id.length(), id_len);\n else\n scmd_len = max(opt->cmd_short.length(), scmd_len);\n desc_len = max(opt->desc.length(), desc_len);\n }\n\n for(tGroupIter g=groups.begin(); g!=groups.end(); ++g) {\n ConfigGroup* grp = g->second;\n ss << endl << \"--- Group: \" << grp->name << endl;\n for(tOptionIter i=grp->members.begin(); i!=grp->members.end(); ++i) {\n ConfigOption* opt = grp->members[i->first];\n\n ss << right << setw(scmd_len+1) << ((opt->cmd_short.size() > 0) ? \\\n (\"-\" + opt->cmd_short) : \"\") << \" | \" << flush;\n ss << left << setw(id_len+2) << (\"--\" + opt->id) << \" \" << opt->desc;\n ss << \" [\" << opt->data.verbose_type() << \"]\";\n ss << endl;\n }\n }\n ss << endl;\n}\n<|endoftext|>"} {"text":"\n\n\/\/ This file contains definition of C++ new\/delete operators\n\n\n#include \n#include \n#include \"stdexcept.h\"\n\nnamespace std {\n void terminate();\n}\n\ntypedef void (*new_handler)();\nstatic new_handler new_handl = &std::terminate;\n\n\nnamespace std {\n new_handler set_new_handler(new_handler handl) {\n new_handler old = new_handl;\n new_handl = handl;\n return old;\n }\n}\n\n\n__attribute__((weak))\nvoid * operator new(size_t size) {\n\n void * mem = malloc(size);\n while(mem == NULL) {\n new_handl();\n mem = malloc(size);\n }\n\n return mem;\n}\n\n\n__attribute__((weak))\nvoid operator delete(void * ptr) {\n free(ptr);\n}\n\n\n__attribute__((weak))\nvoid * operator new[](size_t size) {\n return ::operator new(size);\n}\n\n\n__attribute__((weak))\nvoid operator delete[](void * ptr) {\n ::operator delete(ptr);\n}\n\n\nfix for COMPILER-8905: operator new should throw std::bad_alloc if new handler is not set\n\n\/\/ This file contains definition of C++ new\/delete operators\n\n\n#include \n#include \n#include \"stdexcept.h\"\n\nnamespace std {\n void terminate();\n}\n\ntypedef void (*new_handler)();\nstatic new_handler new_handl = &std::terminate;\n\n\nnamespace std {\n new_handler set_new_handler(new_handler handl) {\n new_handler old = new_handl;\n new_handl = handl;\n return old;\n }\n}\n\n\n__attribute__((weak))\nvoid * operator new(size_t size) {\n\n void * mem = malloc(size);\n while(mem == NULL) {\n if(new_handl != NULL) {\n new_handl();\n } else {\n throw std::bad_alloc();\n }\n mem = malloc(size);\n }\n\n return mem;\n}\n\n\n__attribute__((weak))\nvoid operator delete(void * ptr) {\n free(ptr);\n}\n\n\n__attribute__((weak))\nvoid * operator new[](size_t size) {\n return ::operator new(size);\n}\n\n\n__attribute__((weak))\nvoid operator delete[](void * ptr) {\n ::operator delete(ptr);\n}\n\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"media\/video\/capture\/fake_video_capture_device.h\"\n\n#include \n\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/stringprintf.h\"\n\nnamespace media {\n\nstatic const int kFakeCaptureTimeoutMs = 100;\nenum { kNumberOfFakeDevices = 2 };\n\nvoid FakeVideoCaptureDevice::GetDeviceNames(Names* const device_names) {\n \/\/ Empty the name list.\n device_names->erase(device_names->begin(), device_names->end());\n\n for (int n = 0; n < kNumberOfFakeDevices; n++) {\n Name name;\n name.unique_id = StringPrintf(\"\/dev\/video%d\", n);\n name.device_name = StringPrintf(\"fake_device_%d\", n);\n device_names->push_back(name);\n }\n}\n\nVideoCaptureDevice* FakeVideoCaptureDevice::Create(const Name& device_name) {\n for (int n = 0; n < kNumberOfFakeDevices; ++n) {\n std::string possible_id = StringPrintf(\"\/dev\/video%d\", n);\n if (device_name.unique_id.compare(possible_id) == 0) {\n return new FakeVideoCaptureDevice(device_name);\n }\n }\n return NULL;\n}\n\nFakeVideoCaptureDevice::FakeVideoCaptureDevice(const Name& device_name)\n : device_name_(device_name),\n state_(kIdle),\n capture_thread_(\"CaptureThread\") {\n}\n\nFakeVideoCaptureDevice::~FakeVideoCaptureDevice() {\n \/\/ Check if the thread is running.\n \/\/ This means that the device have not been DeAllocated properly.\n DCHECK(!capture_thread_.IsRunning());\n}\n\nvoid FakeVideoCaptureDevice::Allocate(int width,\n int height,\n int frame_rate,\n EventHandler* observer) {\n if (state_ != kIdle) {\n return; \/\/ Wrong state.\n }\n\n observer_ = observer;\n Capability current_settings;\n current_settings.color = kI420;\n if (width > 320) { \/\/ VGA\n current_settings.width = 640;\n current_settings.height = 480;\n current_settings.frame_rate = 30;\n } else { \/\/ QVGA\n current_settings.width = 320;\n current_settings.height = 240;\n current_settings.frame_rate = 30;\n }\n\n fake_frame_.reset(new uint8[current_settings.width *\n current_settings.height * 3 \/ 2]);\n memset(fake_frame_.get(), 0, sizeof(fake_frame_.get()));\n\n state_ = kAllocated;\n observer_->OnFrameInfo(current_settings);\n}\n\nvoid FakeVideoCaptureDevice::Start() {\n if (state_ != kAllocated) {\n return; \/\/ Wrong state.\n }\n state_ = kCapturing;\n capture_thread_.Start();\n capture_thread_.message_loop()->PostTask(\n FROM_HERE,\n NewRunnableMethod(this, &FakeVideoCaptureDevice::OnCaptureTask));\n}\n\nvoid FakeVideoCaptureDevice::Stop() {\n if (state_ != kCapturing) {\n return; \/\/ Wrong state.\n }\n capture_thread_.Stop();\n state_ = kAllocated;\n}\n\nvoid FakeVideoCaptureDevice::DeAllocate() {\n if (state_ != kAllocated && state_ != kCapturing) {\n return; \/\/ Wrong state.\n }\n capture_thread_.Stop();\n state_ = kIdle;\n}\n\nconst VideoCaptureDevice::Name& FakeVideoCaptureDevice::device_name() {\n return device_name_;\n}\n\nvoid FakeVideoCaptureDevice::OnCaptureTask() {\n if (state_ != kCapturing) {\n return;\n }\n \/\/ Give the captured frame to the observer.\n observer_->OnIncomingCapturedFrame(fake_frame_.get(),\n sizeof(fake_frame_.get()),\n base::Time::Now());\n \/\/ Reschedule next CaptureTask.\n capture_thread_.message_loop()->PostDelayedTask(\n FROM_HERE,\n NewRunnableMethod(this, &FakeVideoCaptureDevice::OnCaptureTask),\n kFakeCaptureTimeoutMs);\n}\n\n} \/\/ namespace media\nUninitialized member in FakeVideoCaptureDevice.\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"media\/video\/capture\/fake_video_capture_device.h\"\n\n#include \n\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/stringprintf.h\"\n\nnamespace media {\n\nstatic const int kFakeCaptureTimeoutMs = 100;\nenum { kNumberOfFakeDevices = 2 };\n\nvoid FakeVideoCaptureDevice::GetDeviceNames(Names* const device_names) {\n \/\/ Empty the name list.\n device_names->erase(device_names->begin(), device_names->end());\n\n for (int n = 0; n < kNumberOfFakeDevices; n++) {\n Name name;\n name.unique_id = StringPrintf(\"\/dev\/video%d\", n);\n name.device_name = StringPrintf(\"fake_device_%d\", n);\n device_names->push_back(name);\n }\n}\n\nVideoCaptureDevice* FakeVideoCaptureDevice::Create(const Name& device_name) {\n for (int n = 0; n < kNumberOfFakeDevices; ++n) {\n std::string possible_id = StringPrintf(\"\/dev\/video%d\", n);\n if (device_name.unique_id.compare(possible_id) == 0) {\n return new FakeVideoCaptureDevice(device_name);\n }\n }\n return NULL;\n}\n\nFakeVideoCaptureDevice::FakeVideoCaptureDevice(const Name& device_name)\n : device_name_(device_name),\n observer_(NULL),\n state_(kIdle),\n capture_thread_(\"CaptureThread\") {\n}\n\nFakeVideoCaptureDevice::~FakeVideoCaptureDevice() {\n \/\/ Check if the thread is running.\n \/\/ This means that the device have not been DeAllocated properly.\n DCHECK(!capture_thread_.IsRunning());\n}\n\nvoid FakeVideoCaptureDevice::Allocate(int width,\n int height,\n int frame_rate,\n EventHandler* observer) {\n if (state_ != kIdle) {\n return; \/\/ Wrong state.\n }\n\n observer_ = observer;\n Capability current_settings;\n current_settings.color = kI420;\n if (width > 320) { \/\/ VGA\n current_settings.width = 640;\n current_settings.height = 480;\n current_settings.frame_rate = 30;\n } else { \/\/ QVGA\n current_settings.width = 320;\n current_settings.height = 240;\n current_settings.frame_rate = 30;\n }\n\n fake_frame_.reset(new uint8[current_settings.width *\n current_settings.height * 3 \/ 2]);\n memset(fake_frame_.get(), 0, sizeof(fake_frame_.get()));\n\n state_ = kAllocated;\n observer_->OnFrameInfo(current_settings);\n}\n\nvoid FakeVideoCaptureDevice::Start() {\n if (state_ != kAllocated) {\n return; \/\/ Wrong state.\n }\n state_ = kCapturing;\n capture_thread_.Start();\n capture_thread_.message_loop()->PostTask(\n FROM_HERE,\n NewRunnableMethod(this, &FakeVideoCaptureDevice::OnCaptureTask));\n}\n\nvoid FakeVideoCaptureDevice::Stop() {\n if (state_ != kCapturing) {\n return; \/\/ Wrong state.\n }\n capture_thread_.Stop();\n state_ = kAllocated;\n}\n\nvoid FakeVideoCaptureDevice::DeAllocate() {\n if (state_ != kAllocated && state_ != kCapturing) {\n return; \/\/ Wrong state.\n }\n capture_thread_.Stop();\n state_ = kIdle;\n}\n\nconst VideoCaptureDevice::Name& FakeVideoCaptureDevice::device_name() {\n return device_name_;\n}\n\nvoid FakeVideoCaptureDevice::OnCaptureTask() {\n if (state_ != kCapturing) {\n return;\n }\n \/\/ Give the captured frame to the observer.\n observer_->OnIncomingCapturedFrame(fake_frame_.get(),\n sizeof(fake_frame_.get()),\n base::Time::Now());\n \/\/ Reschedule next CaptureTask.\n capture_thread_.message_loop()->PostDelayedTask(\n FROM_HERE,\n NewRunnableMethod(this, &FakeVideoCaptureDevice::OnCaptureTask),\n kFakeCaptureTimeoutMs);\n}\n\n} \/\/ namespace media\n<|endoftext|>"} {"text":"\/\/\n\/\/ ex9_31.cpp\n\/\/ Exercise 9.31 \n\/\/\n\/\/ Created by pezy on 12\/3\/14.\n\/\/\n\/\/ @Brief The program on page 354 to remove even-valued elements and \n\/\/ duplicate odd ones will not work on a list or forward_list. Why? \n\/\/ Revise the program so that it works on these types as well. \n\/\/ @forward_list 1. vi.insert -> vi.insert_after\n\/\/ 2. iter += 2; -> advance(iter, 2);\n\/\/ 3. vi.erase -> vi.erase_after\n\/\/ 4. added iterator prev, and edit some detail\n\n#include \n#include \n\nusing std::forward_list; using std::cout; using std::endl; using std::advance;\n\nint main()\n{\n forward_list vi = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n auto iter = vi.begin(), prev = vi.before_begin();\n while (iter != vi.end()) {\n if (*iter % 2) {\n iter = vi.insert_after(prev, *iter);\n advance(iter, 2);\n advance(prev, 2);\n }\n else\n iter = vi.erase_after(prev);\n }\n\n for (auto i : vi)\n cout << i << \" \";\n\n return 0;\n}\nUpdate ex9_31_2.cpp\/\/\n\/\/ ex9_31.cpp\n\/\/ Exercise 9.31 \n\/\/\n\/\/ Created by pezy on 12\/3\/14.\n\/\/\n\/\/ @Brief The program on page 354 to remove even-valued elements and \n\/\/ duplicate odd ones will not work on a list or forward_list. Why? \n\/\/ Revise the program so that it works on these types as well. \n\/\/ \n\/\/ Refactored by Yue Wang Oct 2015 \n\/\/\n\n#include \n#include \n\nusing std::forward_list;\nusing std::cout;\nusing std::advance;\n\nauto remove_evens_and_double_odds(forward_list& data)\n{\n for(auto cur = data.begin(), prv = data.before_begin(); cur != data.end();)\n if (*cur & 0x1)\n cur = data.insert_after(prv, *cur),\n advance(cur, 2),\n advance(prv, 2);\n else\n cur = data.erase_after(prv);\n}\n\nint main()\n{\n forward_list data { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n remove_evens_and_double_odds(data);\n for (auto i : data)\n cout << i << \" \";\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ Amiga.cpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 16\/07\/2021.\n\/\/ Copyright © 2021 Thomas Harte. All rights reserved.\n\/\/\n\n#include \"Amiga.hpp\"\n\n#include \"..\/MachineTypes.hpp\"\n\n#include \"..\/..\/Processors\/68000\/68000.hpp\"\n\n#include \"..\/..\/Analyser\/Static\/Amiga\/Target.hpp\"\n\n#include \"..\/Utility\/MemoryPacker.hpp\"\n#include \"..\/Utility\/MemoryFuzzer.hpp\"\n\nnamespace Amiga {\n\nclass ConcreteMachine:\n\tpublic CPU::MC68000::BusHandler,\n\tpublic MachineTypes::ScanProducer,\n\tpublic MachineTypes::TimedMachine,\n\tpublic Machine {\n\tpublic:\n\t\tConcreteMachine(const Analyser::Static::Amiga::Target &target, const ROMMachine::ROMFetcher &rom_fetcher) :\n\t\t\tmc68000_(*this)\n\t\t{\n\t\t\t(void)target;\n\n\t\t\t\/\/ Temporary: use a hard-coded Kickstart selection.\n\t\t\tconstexpr ROM::Name rom_name = ROM::Name::AmigaA500Kickstart13;\n\t\t\tROM::Request request(rom_name);\n\t\t\tauto roms = rom_fetcher(request);\n\t\t\tif(!request.validate(roms)) {\n\t\t\t\tthrow ROMMachine::Error::MissingROMs;\n\t\t\t}\n\t\t\tMemory::PackBigEndian16(roms.find(rom_name)->second, kickstart_.data());\n\n\t\t\t\/\/ NTSC clock rate: 2*3.579545 = 7.15909Mhz.\n\t\t\t\/\/ PAL clock rate: 7.09379Mhz.\n\t\t\tset_clock_rate(7'093'790.0);\n\t\t}\n\n\t\t\/\/ MARK: - MC68000::BusHandler.\n\t\tusing Microcycle = CPU::MC68000::Microcycle;\n\t\tHalfCycles perform_bus_operation(const CPU::MC68000::Microcycle &cycle, int) {\n\t\t\t\/\/ Do nothing if no address is exposed.\n\t\t\tif(!(cycle.operation & (Microcycle::NewAddress | Microcycle::SameAddress))) return HalfCycles(0);\n\n\t\t\t\/\/ TODO: interrupt acknowledgement though?\n\n\t\t\t\/\/ Grab the target address to pick a memory source.\n\t\t\tconst uint32_t address = cycle.host_endian_byte_address();\n\t\t\t(void)address;\n\n\t\t\t\/\/ Address spaces that matter:\n\t\t\t\/\/\n\t\t\t\/\/\t00'0000 – 08'0000:\tchip RAM.\t[or overlayed KickStart]\n\t\t\t\/\/\t– 10'0000: extended chip ram for ECS.\n\t\t\t\/\/\t– 20'0000: auto-config space (\/fast RAM).\n\t\t\t\/\/\t...\n\t\t\t\/\/\tbf'd000 – c0'0000: 8250s.\n\t\t\t\/\/\tc0'0000 – d8'0000: pseudo-fast RAM.\n\t\t\t\/\/\t...\n\t\t\t\/\/\tdc'0000 – dd'0000: optional real-time clock.\n\t\t\t\/\/\tdf'f000 - e0'0000: custom chip registers.\n\t\t\t\/\/\t...\n\t\t\t\/\/\tf0'0000 — : 512kb Kickstart (or possibly just an extra 512kb reserved for hypothetical 1mb Kickstart?).\n\t\t\t\/\/\tf8'0000 — : 256kb Kickstart if 2.04 or higher.\n\t\t\t\/\/\tfc'0000 – : 256kb Kickstart otherwise.\n\n\t\t\treturn HalfCycles(0);\n\t\t}\n\n\tprivate:\n\t\tCPU::MC68000::Processor mc68000_;\n\n\t\t\/\/ MARK: - Memory map.\n\t\tstd::array ram_;\n\t\tstd::array kickstart_;\n\n\t\tstruct MemoryRegion {\n\n\t\t} regions_[64];\t\/\/ i.e. top six bits are used as an index.\n\n\t\t\/\/ MARK: - MachineTypes::ScanProducer.\n\n\t\tvoid set_scan_target(Outputs::Display::ScanTarget *scan_target) final {\n\t\t\t(void)scan_target;\n\t\t}\n\n\t\tOutputs::Display::ScanStatus get_scaled_scan_status() const {\n\t\t\treturn Outputs::Display::ScanStatus();\n\t\t}\n\n\t\t\/\/ MARK: - MachineTypes::TimedMachine.\n\n\t\tvoid run_for(const Cycles cycles) {\n\t\t\tmc68000_.run_for(cycles);\n\t\t}\n};\n\n}\n\n\nusing namespace Amiga;\n\nMachine *Machine::Amiga(const Analyser::Static::Target *target, const ROMMachine::ROMFetcher &rom_fetcher) {\n\tusing Target = Analyser::Static::Amiga::Target;\n\tconst Target *const amiga_target = dynamic_cast(target);\n\treturn new Amiga::ConcreteMachine(*amiga_target, rom_fetcher);\n}\n\nMachine::~Machine() {}\nBegins sketching out a memory mapper.\/\/\n\/\/ Amiga.cpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 16\/07\/2021.\n\/\/ Copyright © 2021 Thomas Harte. All rights reserved.\n\/\/\n\n#include \"Amiga.hpp\"\n\n#include \"..\/MachineTypes.hpp\"\n\n#include \"..\/..\/Processors\/68000\/68000.hpp\"\n\n#include \"..\/..\/Analyser\/Static\/Amiga\/Target.hpp\"\n\n#include \"..\/Utility\/MemoryPacker.hpp\"\n#include \"..\/Utility\/MemoryFuzzer.hpp\"\n\nnamespace Amiga {\n\nclass ConcreteMachine:\n\tpublic CPU::MC68000::BusHandler,\n\tpublic MachineTypes::ScanProducer,\n\tpublic MachineTypes::TimedMachine,\n\tpublic Machine {\n\tpublic:\n\t\tConcreteMachine(const Analyser::Static::Amiga::Target &target, const ROMMachine::ROMFetcher &rom_fetcher) :\n\t\t\tmc68000_(*this)\n\t\t{\n\t\t\t(void)target;\n\n\t\t\t\/\/ Temporary: use a hard-coded Kickstart selection.\n\t\t\tconstexpr ROM::Name rom_name = ROM::Name::AmigaA500Kickstart13;\n\t\t\tROM::Request request(rom_name);\n\t\t\tauto roms = rom_fetcher(request);\n\t\t\tif(!request.validate(roms)) {\n\t\t\t\tthrow ROMMachine::Error::MissingROMs;\n\t\t\t}\n\t\t\tMemory::PackBigEndian16(roms.find(rom_name)->second, kickstart_.data());\n\n\t\t\t\/\/ Address spaces that matter:\n\t\t\t\/\/\n\t\t\t\/\/\t00'0000 – 08'0000:\tchip RAM.\t[or overlayed KickStart]\n\t\t\t\/\/\t– 10'0000: extended chip ram for ECS.\n\t\t\t\/\/\t– 20'0000: auto-config space (\/fast RAM).\n\t\t\t\/\/\t...\n\t\t\t\/\/\tbf'd000 – c0'0000: 8250s.\n\t\t\t\/\/\tc0'0000 – d8'0000: pseudo-fast RAM.\n\t\t\t\/\/\t...\n\t\t\t\/\/\tdc'0000 – dd'0000: optional real-time clock.\n\t\t\t\/\/\tdf'f000 - e0'0000: custom chip registers.\n\t\t\t\/\/\t...\n\t\t\t\/\/\tf0'0000 — : 512kb Kickstart (or possibly just an extra 512kb reserved for hypothetical 1mb Kickstart?).\n\t\t\t\/\/\tf8'0000 — : 256kb Kickstart if 2.04 or higher.\n\t\t\t\/\/\tfc'0000 – : 256kb Kickstart otherwise.\n\t\t\tset_region(0x00'0000, 0x08'00000, kickstart_.data(), CPU::MC68000::Microcycle::PermitRead);\n\t\t\tset_region(0xfc'0000, 0x1'00'0000, kickstart_.data(), CPU::MC68000::Microcycle::PermitRead);\n\n\t\t\t\/\/ NTSC clock rate: 2*3.579545 = 7.15909Mhz.\n\t\t\t\/\/ PAL clock rate: 7.09379Mhz.\n\t\t\tset_clock_rate(7'093'790.0);\n\t\t}\n\n\t\t\/\/ MARK: - MC68000::BusHandler.\n\t\tusing Microcycle = CPU::MC68000::Microcycle;\n\t\tHalfCycles perform_bus_operation(const CPU::MC68000::Microcycle &cycle, int) {\n\t\t\t\/\/ Do nothing if no address is exposed.\n\t\t\tif(!(cycle.operation & (Microcycle::NewAddress | Microcycle::SameAddress))) return HalfCycles(0);\n\n\t\t\t\/\/ Otherwise, intended 1-2 step here is:\n\t\t\t\/\/\n\t\t\t\/\/\t(1) determine when this CPU access will be scheduled;\n\t\t\t\/\/\t(2)\tdo all the other actions prior to this CPU access being scheduled.\n\t\t\t\/\/\n\t\t\t\/\/ (or at least enqueue them, JIT-wise).\n\n\t\t\t\/\/ TODO: interrupt acknowledgement.\n\n\t\t\t\/\/ Grab the target address to pick a memory source.\n\t\t\tconst uint32_t address = cycle.host_endian_byte_address();\n\t\t\tif(!regions_[address >> 18].read_write_mask) {\n\t\t\t\t\/\/ TODO: registers, etc, here.\n\t\t\t\tassert(false);\n\t\t\t}\n\t\t\tcycle.apply(®ions_[address >> 18].contents[address], regions_[address >> 18].read_write_mask);\n\n\t\t\treturn HalfCycles(0);\n\t\t}\n\n\tprivate:\n\t\tCPU::MC68000::Processor mc68000_;\n\n\t\t\/\/ MARK: - Memory map.\n\t\tstd::array ram_;\n\t\tstd::array kickstart_;\n\n\t\tstruct MemoryRegion {\n\t\t\tuint8_t *contents = nullptr;\n\t\t\tint read_write_mask = 0;\n\t\t} regions_[64];\t\/\/ i.e. top six bits are used as an index.\n\n\t\tvoid set_region(int start, int end, uint8_t *base, int read_write_mask) {\n\t\t\tassert(!(start & ~0xfc'0000));\n\t\t\tassert(!((end - (1 << 18)) & ~0xfc'0000));\n\n\t\t\tfor(int c = start >> 18; c < end >> 18; c++) {\n\t\t\t\tregions_[c].contents = base - (c << 18);\n\t\t\t\tregions_[c].read_write_mask = read_write_mask;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ MARK: - MachineTypes::ScanProducer.\n\n\t\tvoid set_scan_target(Outputs::Display::ScanTarget *scan_target) final {\n\t\t\t(void)scan_target;\n\t\t}\n\n\t\tOutputs::Display::ScanStatus get_scaled_scan_status() const {\n\t\t\treturn Outputs::Display::ScanStatus();\n\t\t}\n\n\t\t\/\/ MARK: - MachineTypes::TimedMachine.\n\n\t\tvoid run_for(const Cycles cycles) {\n\t\t\tmc68000_.run_for(cycles);\n\t\t}\n};\n\n}\n\n\nusing namespace Amiga;\n\nMachine *Machine::Amiga(const Analyser::Static::Target *target, const ROMMachine::ROMFetcher &rom_fetcher) {\n\tusing Target = Analyser::Static::Amiga::Target;\n\tconst Target *const amiga_target = dynamic_cast(target);\n\treturn new Amiga::ConcreteMachine(*amiga_target, rom_fetcher);\n}\n\nMachine::~Machine() {}\n<|endoftext|>"} {"text":"\/\/===--- LangOptions.cpp - Language & configuration options ---------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file defines the LangOptions class, which provides various\n\/\/ language and configuration flags.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"swift\/Basic\/LangOptions.h\"\n#include \"swift\/Basic\/Platform.h\"\n#include \"swift\/Basic\/Range.h\"\n#include \"swift\/Config.h\"\n#include \"llvm\/ADT\/Hashing.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \n\nusing namespace swift;\n\nstruct SupportedConditionalValue {\n StringRef value;\n\n \/\/\/ If the value has been deprecated, the new value to replace it with.\n StringRef replacement = \"\";\n\n SupportedConditionalValue(const char *value) : value(value) {}\n SupportedConditionalValue(const char *value, const char *replacement)\n : value(value), replacement(replacement) {}\n};\n\nstatic const SupportedConditionalValue SupportedConditionalCompilationOSs[] = {\n \"OSX\",\n \"macOS\",\n \"tvOS\",\n \"watchOS\",\n \"iOS\",\n \"Linux\",\n \"FreeBSD\",\n \"OpenBSD\",\n \"Windows\",\n \"Android\",\n \"PS4\",\n \"Cygwin\",\n \"Haiku\",\n \"WASI\",\n};\n\nstatic const SupportedConditionalValue SupportedConditionalCompilationArches[] = {\n \"arm\",\n \"arm64\",\n \"i386\",\n \"x86_64\",\n \"powerpc64\",\n \"powerpc64le\",\n \"s390x\",\n \"wasm32\",\n};\n\nstatic const SupportedConditionalValue SupportedConditionalCompilationEndianness[] = {\n \"little\",\n \"big\"\n};\n\nstatic const SupportedConditionalValue SupportedConditionalCompilationRuntimes[] = {\n \"_ObjC\",\n \"_Native\",\n};\n\nstatic const SupportedConditionalValue SupportedConditionalCompilationTargetEnvironments[] = {\n \"simulator\",\n { \"macabi\", \"macCatalyst\" },\n \"macCatalyst\", \/\/ A synonym for \"macabi\" when compiling for iOS\n};\n\nstatic const SupportedConditionalValue SupportedConditionalCompilationPtrAuthSchemes[] = {\n \"_none\",\n \"_arm64e\",\n};\n\nstatic const PlatformConditionKind AllPublicPlatformConditionKinds[] = {\n#define PLATFORM_CONDITION(LABEL, IDENTIFIER) PlatformConditionKind::LABEL,\n#define PLATFORM_CONDITION_(LABEL, IDENTIFIER)\n#include \"swift\/AST\/PlatformConditionKinds.def\"\n};\n\nArrayRef getSupportedConditionalCompilationValues(const PlatformConditionKind &Kind) {\n switch (Kind) {\n case PlatformConditionKind::OS:\n return SupportedConditionalCompilationOSs;\n case PlatformConditionKind::Arch:\n return SupportedConditionalCompilationArches;\n case PlatformConditionKind::Endianness:\n return SupportedConditionalCompilationEndianness;\n case PlatformConditionKind::Runtime:\n return SupportedConditionalCompilationRuntimes;\n case PlatformConditionKind::CanImport:\n return { };\n case PlatformConditionKind::TargetEnvironment:\n return SupportedConditionalCompilationTargetEnvironments;\n case PlatformConditionKind::PtrAuth:\n return SupportedConditionalCompilationPtrAuthSchemes;\n }\n llvm_unreachable(\"Unhandled PlatformConditionKind in switch\");\n}\n\nPlatformConditionKind suggestedPlatformConditionKind(PlatformConditionKind Kind, const StringRef &V,\n std::vector &suggestedValues) {\n std::string lower = V.lower();\n for (const PlatformConditionKind& candidateKind : AllPublicPlatformConditionKinds) {\n if (candidateKind != Kind) {\n auto supportedValues = getSupportedConditionalCompilationValues(candidateKind);\n for (const SupportedConditionalValue& candidateValue : supportedValues) {\n if (candidateValue.value.lower() == lower) {\n suggestedValues.clear();\n if (candidateValue.value != V) {\n suggestedValues.emplace_back(candidateValue.value);\n }\n return candidateKind;\n }\n }\n }\n }\n return Kind;\n}\n\nbool isMatching(PlatformConditionKind Kind, const StringRef &V,\n PlatformConditionKind &suggestedKind, std::vector &suggestions) {\n \/\/ Compare against known values, ignoring case to avoid penalizing\n \/\/ characters with incorrect case.\n unsigned minDistance = std::numeric_limits::max();\n std::string lower = V.lower();\n auto supportedValues = getSupportedConditionalCompilationValues(Kind);\n for (const SupportedConditionalValue& candidate : supportedValues) {\n if (candidate.value == V) {\n suggestedKind = Kind;\n suggestions.clear();\n if (!candidate.replacement.empty())\n suggestions.push_back(candidate.replacement);\n return true;\n }\n unsigned distance = StringRef(lower).edit_distance(candidate.value.lower());\n if (distance < minDistance) {\n suggestions.clear();\n minDistance = distance;\n }\n if (distance == minDistance)\n suggestions.emplace_back(candidate.value);\n }\n suggestedKind = suggestedPlatformConditionKind(Kind, V, suggestions);\n return false;\n}\n\nbool LangOptions::\ncheckPlatformConditionSupported(PlatformConditionKind Kind, StringRef Value,\n PlatformConditionKind &suggestedKind,\n std::vector &suggestedValues) {\n switch (Kind) {\n case PlatformConditionKind::OS:\n case PlatformConditionKind::Arch:\n case PlatformConditionKind::Endianness:\n case PlatformConditionKind::Runtime:\n case PlatformConditionKind::TargetEnvironment:\n case PlatformConditionKind::PtrAuth:\n return isMatching(Kind, Value, suggestedKind, suggestedValues);\n case PlatformConditionKind::CanImport:\n \/\/ All importable names are valid.\n \/\/ FIXME: Perform some kind of validation of the string?\n return true;\n }\n llvm_unreachable(\"Unhandled enum value\");\n}\n\nStringRef\nLangOptions::getPlatformConditionValue(PlatformConditionKind Kind) const {\n \/\/ Last one wins.\n for (auto &Opt : llvm::reverse(PlatformConditionValues)) {\n if (Opt.first == Kind)\n return Opt.second;\n }\n return StringRef();\n}\n\nbool LangOptions::\ncheckPlatformCondition(PlatformConditionKind Kind, StringRef Value) const {\n \/\/ Check a special case that \"macOS\" is an alias of \"OSX\".\n if (Kind == PlatformConditionKind::OS && Value == \"macOS\")\n return checkPlatformCondition(Kind, \"OSX\");\n\n \/\/ When compiling for iOS we consider \"macCatalyst\" to be a\n \/\/ synonym of \"macabi\". This enables the use of\n \/\/ #if targetEnvironment(macCatalyst) as a compilation\n \/\/ condition for macCatalyst.\n\n if (Kind == PlatformConditionKind::TargetEnvironment &&\n Value == \"macCatalyst\" && Target.isiOS()) {\n return checkPlatformCondition(Kind, \"macabi\");\n }\n\n for (auto &Opt : llvm::reverse(PlatformConditionValues)) {\n if (Opt.first == Kind)\n if (Opt.second == Value)\n return true;\n }\n\n return false;\n}\n\nbool LangOptions::isCustomConditionalCompilationFlagSet(StringRef Name) const {\n return std::find(CustomConditionalCompilationFlags.begin(),\n CustomConditionalCompilationFlags.end(), Name)\n != CustomConditionalCompilationFlags.end();\n}\n\nstd::pair LangOptions::setTarget(llvm::Triple triple) {\n clearAllPlatformConditionValues();\n\n if (triple.getOS() == llvm::Triple::Darwin &&\n triple.getVendor() == llvm::Triple::Apple) {\n \/\/ Rewrite darwinX.Y triples to macosx10.X'.Y ones.\n \/\/ It affects code generation on our platform.\n llvm::SmallString<16> osxBuf;\n llvm::raw_svector_ostream osx(osxBuf);\n osx << llvm::Triple::getOSTypeName(llvm::Triple::MacOSX);\n\n unsigned major, minor, micro;\n triple.getMacOSXVersion(major, minor, micro);\n osx << major << \".\" << minor;\n if (micro != 0)\n osx << \".\" << micro;\n\n triple.setOSName(osx.str());\n }\n Target = std::move(triple);\n\n bool UnsupportedOS = false;\n\n \/\/ Set the \"os\" platform condition.\n switch (Target.getOS()) {\n case llvm::Triple::Darwin:\n case llvm::Triple::MacOSX:\n addPlatformConditionValue(PlatformConditionKind::OS, \"OSX\");\n break;\n case llvm::Triple::TvOS:\n addPlatformConditionValue(PlatformConditionKind::OS, \"tvOS\");\n break;\n case llvm::Triple::WatchOS:\n addPlatformConditionValue(PlatformConditionKind::OS, \"watchOS\");\n break;\n case llvm::Triple::IOS:\n addPlatformConditionValue(PlatformConditionKind::OS, \"iOS\");\n break;\n case llvm::Triple::Linux:\n if (Target.getEnvironment() == llvm::Triple::Android)\n addPlatformConditionValue(PlatformConditionKind::OS, \"Android\");\n else\n addPlatformConditionValue(PlatformConditionKind::OS, \"Linux\");\n break;\n case llvm::Triple::FreeBSD:\n addPlatformConditionValue(PlatformConditionKind::OS, \"FreeBSD\");\n break;\n case llvm::Triple::OpenBSD:\n addPlatformConditionValue(PlatformConditionKind::OS, \"OpenBSD\");\n break;\n case llvm::Triple::Win32:\n if (Target.getEnvironment() == llvm::Triple::Cygnus)\n addPlatformConditionValue(PlatformConditionKind::OS, \"Cygwin\");\n else\n addPlatformConditionValue(PlatformConditionKind::OS, \"Windows\");\n break;\n case llvm::Triple::PS4:\n if (Target.getVendor() == llvm::Triple::SCEI)\n addPlatformConditionValue(PlatformConditionKind::OS, \"PS4\");\n else\n UnsupportedOS = false;\n break;\n case llvm::Triple::Haiku:\n addPlatformConditionValue(PlatformConditionKind::OS, \"Haiku\");\n break;\n case llvm::Triple::WASI:\n addPlatformConditionValue(PlatformConditionKind::OS, \"WASI\");\n break;\n default:\n UnsupportedOS = true;\n break;\n }\n\n bool UnsupportedArch = false;\n\n \/\/ Set the \"arch\" platform condition.\n switch (Target.getArch()) {\n case llvm::Triple::ArchType::arm:\n case llvm::Triple::ArchType::thumb:\n addPlatformConditionValue(PlatformConditionKind::Arch, \"arm\");\n break;\n case llvm::Triple::ArchType::aarch64:\n addPlatformConditionValue(PlatformConditionKind::Arch, \"arm64\");\n break;\n case llvm::Triple::ArchType::ppc64:\n addPlatformConditionValue(PlatformConditionKind::Arch, \"powerpc64\");\n break;\n case llvm::Triple::ArchType::ppc64le:\n addPlatformConditionValue(PlatformConditionKind::Arch, \"powerpc64le\");\n break;\n case llvm::Triple::ArchType::x86:\n addPlatformConditionValue(PlatformConditionKind::Arch, \"i386\");\n break;\n case llvm::Triple::ArchType::x86_64:\n addPlatformConditionValue(PlatformConditionKind::Arch, \"x86_64\");\n break;\n case llvm::Triple::ArchType::systemz:\n addPlatformConditionValue(PlatformConditionKind::Arch, \"s390x\");\n break;\n case llvm::Triple::ArchType::wasm32:\n addPlatformConditionValue(PlatformConditionKind::Arch, \"wasm32\");\n break;\n default:\n UnsupportedArch = true;\n }\n\n if (UnsupportedOS || UnsupportedArch)\n return { UnsupportedOS, UnsupportedArch };\n\n \/\/ Set the \"_endian\" platform condition.\n switch (Target.getArch()) {\n default: llvm_unreachable(\"undefined architecture endianness\");\n case llvm::Triple::ArchType::arm:\n case llvm::Triple::ArchType::thumb:\n case llvm::Triple::ArchType::aarch64:\n case llvm::Triple::ArchType::ppc64le:\n case llvm::Triple::ArchType::wasm32:\n case llvm::Triple::ArchType::x86:\n case llvm::Triple::ArchType::x86_64:\n addPlatformConditionValue(PlatformConditionKind::Endianness, \"little\");\n break;\n case llvm::Triple::ArchType::ppc64:\n case llvm::Triple::ArchType::systemz:\n addPlatformConditionValue(PlatformConditionKind::Endianness, \"big\");\n break;\n }\n\n \/\/ Set the \"runtime\" platform condition.\n addPlatformConditionValue(PlatformConditionKind::Runtime,\n EnableObjCInterop ? \"_ObjC\" : \"_Native\");\n\n \/\/ Set the pointer authentication scheme.\n if (Target.getArchName() == \"arm64e\") {\n addPlatformConditionValue(PlatformConditionKind::PtrAuth, \"_arm64e\");\n } else {\n addPlatformConditionValue(PlatformConditionKind::PtrAuth, \"_none\");\n }\n\n \/\/ Set the \"targetEnvironment\" platform condition if targeting a simulator\n \/\/ environment. Otherwise _no_ value is present for targetEnvironment; it's\n \/\/ an optional disambiguating refinement of the triple.\n if (swift::tripleIsAnySimulator(Target))\n addPlatformConditionValue(PlatformConditionKind::TargetEnvironment,\n \"simulator\");\n\n if (tripleIsMacCatalystEnvironment(Target))\n addPlatformConditionValue(PlatformConditionKind::TargetEnvironment,\n \"macabi\");\n\n \/\/ If you add anything to this list, change the default size of\n \/\/ PlatformConditionValues to not require an extra allocation\n \/\/ in the common case.\n\n return { false, false };\n}\n\nbool LangOptions::doesTargetSupportObjCMetadataUpdateCallback() const {\n if (Target.getArchName() == \"arm64e\")\n return true;\n if (Target.isMacOSX())\n return !Target.isMacOSXVersionLT(10, 14, 4);\n if (Target.isiOS()) \/\/ also returns true on tvOS\n return !Target.isOSVersionLT(12, 2);\n if (Target.isWatchOS())\n return !Target.isOSVersionLT(5, 2);\n\n \/\/ Don't assert if we're running on a non-Apple platform; we still\n \/\/ want to allow running tests that -enable-objc-interop.\n return false;\n}\n\nbool LangOptions::doesTargetSupportObjCGetClassHook() const {\n return doesTargetSupportObjCMetadataUpdateCallback();\n}\n\nbool LangOptions::doesTargetSupportObjCClassStubs() const {\n if (Target.getArchName() == \"arm64e\")\n return true;\n if (Target.isMacOSX())\n return !Target.isMacOSXVersionLT(10, 15);\n if (Target.isiOS()) \/\/ also returns true on tvOS\n return !Target.isOSVersionLT(13);\n if (Target.isWatchOS())\n return !Target.isOSVersionLT(6);\n\n \/\/ Don't assert if we're running on a non-Apple platform; we still\n \/\/ want to allow running tests that -enable-objc-interop.\n return false;\n}\nFixup for 3904fe83f (AST: Centralize ABI-related deployment target checks)\/\/===--- LangOptions.cpp - Language & configuration options ---------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file defines the LangOptions class, which provides various\n\/\/ language and configuration flags.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"swift\/Basic\/LangOptions.h\"\n#include \"swift\/Basic\/Platform.h\"\n#include \"swift\/Basic\/Range.h\"\n#include \"swift\/Config.h\"\n#include \"llvm\/ADT\/Hashing.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \n\nusing namespace swift;\n\nstruct SupportedConditionalValue {\n StringRef value;\n\n \/\/\/ If the value has been deprecated, the new value to replace it with.\n StringRef replacement = \"\";\n\n SupportedConditionalValue(const char *value) : value(value) {}\n SupportedConditionalValue(const char *value, const char *replacement)\n : value(value), replacement(replacement) {}\n};\n\nstatic const SupportedConditionalValue SupportedConditionalCompilationOSs[] = {\n \"OSX\",\n \"macOS\",\n \"tvOS\",\n \"watchOS\",\n \"iOS\",\n \"Linux\",\n \"FreeBSD\",\n \"OpenBSD\",\n \"Windows\",\n \"Android\",\n \"PS4\",\n \"Cygwin\",\n \"Haiku\",\n \"WASI\",\n};\n\nstatic const SupportedConditionalValue SupportedConditionalCompilationArches[] = {\n \"arm\",\n \"arm64\",\n \"i386\",\n \"x86_64\",\n \"powerpc64\",\n \"powerpc64le\",\n \"s390x\",\n \"wasm32\",\n};\n\nstatic const SupportedConditionalValue SupportedConditionalCompilationEndianness[] = {\n \"little\",\n \"big\"\n};\n\nstatic const SupportedConditionalValue SupportedConditionalCompilationRuntimes[] = {\n \"_ObjC\",\n \"_Native\",\n};\n\nstatic const SupportedConditionalValue SupportedConditionalCompilationTargetEnvironments[] = {\n \"simulator\",\n { \"macabi\", \"macCatalyst\" },\n \"macCatalyst\", \/\/ A synonym for \"macabi\" when compiling for iOS\n};\n\nstatic const SupportedConditionalValue SupportedConditionalCompilationPtrAuthSchemes[] = {\n \"_none\",\n \"_arm64e\",\n};\n\nstatic const PlatformConditionKind AllPublicPlatformConditionKinds[] = {\n#define PLATFORM_CONDITION(LABEL, IDENTIFIER) PlatformConditionKind::LABEL,\n#define PLATFORM_CONDITION_(LABEL, IDENTIFIER)\n#include \"swift\/AST\/PlatformConditionKinds.def\"\n};\n\nArrayRef getSupportedConditionalCompilationValues(const PlatformConditionKind &Kind) {\n switch (Kind) {\n case PlatformConditionKind::OS:\n return SupportedConditionalCompilationOSs;\n case PlatformConditionKind::Arch:\n return SupportedConditionalCompilationArches;\n case PlatformConditionKind::Endianness:\n return SupportedConditionalCompilationEndianness;\n case PlatformConditionKind::Runtime:\n return SupportedConditionalCompilationRuntimes;\n case PlatformConditionKind::CanImport:\n return { };\n case PlatformConditionKind::TargetEnvironment:\n return SupportedConditionalCompilationTargetEnvironments;\n case PlatformConditionKind::PtrAuth:\n return SupportedConditionalCompilationPtrAuthSchemes;\n }\n llvm_unreachable(\"Unhandled PlatformConditionKind in switch\");\n}\n\nPlatformConditionKind suggestedPlatformConditionKind(PlatformConditionKind Kind, const StringRef &V,\n std::vector &suggestedValues) {\n std::string lower = V.lower();\n for (const PlatformConditionKind& candidateKind : AllPublicPlatformConditionKinds) {\n if (candidateKind != Kind) {\n auto supportedValues = getSupportedConditionalCompilationValues(candidateKind);\n for (const SupportedConditionalValue& candidateValue : supportedValues) {\n if (candidateValue.value.lower() == lower) {\n suggestedValues.clear();\n if (candidateValue.value != V) {\n suggestedValues.emplace_back(candidateValue.value);\n }\n return candidateKind;\n }\n }\n }\n }\n return Kind;\n}\n\nbool isMatching(PlatformConditionKind Kind, const StringRef &V,\n PlatformConditionKind &suggestedKind, std::vector &suggestions) {\n \/\/ Compare against known values, ignoring case to avoid penalizing\n \/\/ characters with incorrect case.\n unsigned minDistance = std::numeric_limits::max();\n std::string lower = V.lower();\n auto supportedValues = getSupportedConditionalCompilationValues(Kind);\n for (const SupportedConditionalValue& candidate : supportedValues) {\n if (candidate.value == V) {\n suggestedKind = Kind;\n suggestions.clear();\n if (!candidate.replacement.empty())\n suggestions.push_back(candidate.replacement);\n return true;\n }\n unsigned distance = StringRef(lower).edit_distance(candidate.value.lower());\n if (distance < minDistance) {\n suggestions.clear();\n minDistance = distance;\n }\n if (distance == minDistance)\n suggestions.emplace_back(candidate.value);\n }\n suggestedKind = suggestedPlatformConditionKind(Kind, V, suggestions);\n return false;\n}\n\nbool LangOptions::\ncheckPlatformConditionSupported(PlatformConditionKind Kind, StringRef Value,\n PlatformConditionKind &suggestedKind,\n std::vector &suggestedValues) {\n switch (Kind) {\n case PlatformConditionKind::OS:\n case PlatformConditionKind::Arch:\n case PlatformConditionKind::Endianness:\n case PlatformConditionKind::Runtime:\n case PlatformConditionKind::TargetEnvironment:\n case PlatformConditionKind::PtrAuth:\n return isMatching(Kind, Value, suggestedKind, suggestedValues);\n case PlatformConditionKind::CanImport:\n \/\/ All importable names are valid.\n \/\/ FIXME: Perform some kind of validation of the string?\n return true;\n }\n llvm_unreachable(\"Unhandled enum value\");\n}\n\nStringRef\nLangOptions::getPlatformConditionValue(PlatformConditionKind Kind) const {\n \/\/ Last one wins.\n for (auto &Opt : llvm::reverse(PlatformConditionValues)) {\n if (Opt.first == Kind)\n return Opt.second;\n }\n return StringRef();\n}\n\nbool LangOptions::\ncheckPlatformCondition(PlatformConditionKind Kind, StringRef Value) const {\n \/\/ Check a special case that \"macOS\" is an alias of \"OSX\".\n if (Kind == PlatformConditionKind::OS && Value == \"macOS\")\n return checkPlatformCondition(Kind, \"OSX\");\n\n \/\/ When compiling for iOS we consider \"macCatalyst\" to be a\n \/\/ synonym of \"macabi\". This enables the use of\n \/\/ #if targetEnvironment(macCatalyst) as a compilation\n \/\/ condition for macCatalyst.\n\n if (Kind == PlatformConditionKind::TargetEnvironment &&\n Value == \"macCatalyst\" && Target.isiOS()) {\n return checkPlatformCondition(Kind, \"macabi\");\n }\n\n for (auto &Opt : llvm::reverse(PlatformConditionValues)) {\n if (Opt.first == Kind)\n if (Opt.second == Value)\n return true;\n }\n\n return false;\n}\n\nbool LangOptions::isCustomConditionalCompilationFlagSet(StringRef Name) const {\n return std::find(CustomConditionalCompilationFlags.begin(),\n CustomConditionalCompilationFlags.end(), Name)\n != CustomConditionalCompilationFlags.end();\n}\n\nstd::pair LangOptions::setTarget(llvm::Triple triple) {\n clearAllPlatformConditionValues();\n\n if (triple.getOS() == llvm::Triple::Darwin &&\n triple.getVendor() == llvm::Triple::Apple) {\n \/\/ Rewrite darwinX.Y triples to macosx10.X'.Y ones.\n \/\/ It affects code generation on our platform.\n llvm::SmallString<16> osxBuf;\n llvm::raw_svector_ostream osx(osxBuf);\n osx << llvm::Triple::getOSTypeName(llvm::Triple::MacOSX);\n\n unsigned major, minor, micro;\n triple.getMacOSXVersion(major, minor, micro);\n osx << major << \".\" << minor;\n if (micro != 0)\n osx << \".\" << micro;\n\n triple.setOSName(osx.str());\n }\n Target = std::move(triple);\n\n bool UnsupportedOS = false;\n\n \/\/ Set the \"os\" platform condition.\n switch (Target.getOS()) {\n case llvm::Triple::Darwin:\n case llvm::Triple::MacOSX:\n addPlatformConditionValue(PlatformConditionKind::OS, \"OSX\");\n break;\n case llvm::Triple::TvOS:\n addPlatformConditionValue(PlatformConditionKind::OS, \"tvOS\");\n break;\n case llvm::Triple::WatchOS:\n addPlatformConditionValue(PlatformConditionKind::OS, \"watchOS\");\n break;\n case llvm::Triple::IOS:\n addPlatformConditionValue(PlatformConditionKind::OS, \"iOS\");\n break;\n case llvm::Triple::Linux:\n if (Target.getEnvironment() == llvm::Triple::Android)\n addPlatformConditionValue(PlatformConditionKind::OS, \"Android\");\n else\n addPlatformConditionValue(PlatformConditionKind::OS, \"Linux\");\n break;\n case llvm::Triple::FreeBSD:\n addPlatformConditionValue(PlatformConditionKind::OS, \"FreeBSD\");\n break;\n case llvm::Triple::OpenBSD:\n addPlatformConditionValue(PlatformConditionKind::OS, \"OpenBSD\");\n break;\n case llvm::Triple::Win32:\n if (Target.getEnvironment() == llvm::Triple::Cygnus)\n addPlatformConditionValue(PlatformConditionKind::OS, \"Cygwin\");\n else\n addPlatformConditionValue(PlatformConditionKind::OS, \"Windows\");\n break;\n case llvm::Triple::PS4:\n if (Target.getVendor() == llvm::Triple::SCEI)\n addPlatformConditionValue(PlatformConditionKind::OS, \"PS4\");\n else\n UnsupportedOS = false;\n break;\n case llvm::Triple::Haiku:\n addPlatformConditionValue(PlatformConditionKind::OS, \"Haiku\");\n break;\n case llvm::Triple::WASI:\n addPlatformConditionValue(PlatformConditionKind::OS, \"WASI\");\n break;\n default:\n UnsupportedOS = true;\n break;\n }\n\n bool UnsupportedArch = false;\n\n \/\/ Set the \"arch\" platform condition.\n switch (Target.getArch()) {\n case llvm::Triple::ArchType::arm:\n case llvm::Triple::ArchType::thumb:\n addPlatformConditionValue(PlatformConditionKind::Arch, \"arm\");\n break;\n case llvm::Triple::ArchType::aarch64:\n addPlatformConditionValue(PlatformConditionKind::Arch, \"arm64\");\n break;\n case llvm::Triple::ArchType::ppc64:\n addPlatformConditionValue(PlatformConditionKind::Arch, \"powerpc64\");\n break;\n case llvm::Triple::ArchType::ppc64le:\n addPlatformConditionValue(PlatformConditionKind::Arch, \"powerpc64le\");\n break;\n case llvm::Triple::ArchType::x86:\n addPlatformConditionValue(PlatformConditionKind::Arch, \"i386\");\n break;\n case llvm::Triple::ArchType::x86_64:\n addPlatformConditionValue(PlatformConditionKind::Arch, \"x86_64\");\n break;\n case llvm::Triple::ArchType::systemz:\n addPlatformConditionValue(PlatformConditionKind::Arch, \"s390x\");\n break;\n case llvm::Triple::ArchType::wasm32:\n addPlatformConditionValue(PlatformConditionKind::Arch, \"wasm32\");\n break;\n default:\n UnsupportedArch = true;\n }\n\n if (UnsupportedOS || UnsupportedArch)\n return { UnsupportedOS, UnsupportedArch };\n\n \/\/ Set the \"_endian\" platform condition.\n switch (Target.getArch()) {\n default: llvm_unreachable(\"undefined architecture endianness\");\n case llvm::Triple::ArchType::arm:\n case llvm::Triple::ArchType::thumb:\n case llvm::Triple::ArchType::aarch64:\n case llvm::Triple::ArchType::ppc64le:\n case llvm::Triple::ArchType::wasm32:\n case llvm::Triple::ArchType::x86:\n case llvm::Triple::ArchType::x86_64:\n addPlatformConditionValue(PlatformConditionKind::Endianness, \"little\");\n break;\n case llvm::Triple::ArchType::ppc64:\n case llvm::Triple::ArchType::systemz:\n addPlatformConditionValue(PlatformConditionKind::Endianness, \"big\");\n break;\n }\n\n \/\/ Set the \"runtime\" platform condition.\n addPlatformConditionValue(PlatformConditionKind::Runtime,\n EnableObjCInterop ? \"_ObjC\" : \"_Native\");\n\n \/\/ Set the pointer authentication scheme.\n if (Target.getArchName() == \"arm64e\") {\n addPlatformConditionValue(PlatformConditionKind::PtrAuth, \"_arm64e\");\n } else {\n addPlatformConditionValue(PlatformConditionKind::PtrAuth, \"_none\");\n }\n\n \/\/ Set the \"targetEnvironment\" platform condition if targeting a simulator\n \/\/ environment. Otherwise _no_ value is present for targetEnvironment; it's\n \/\/ an optional disambiguating refinement of the triple.\n if (swift::tripleIsAnySimulator(Target))\n addPlatformConditionValue(PlatformConditionKind::TargetEnvironment,\n \"simulator\");\n\n if (tripleIsMacCatalystEnvironment(Target))\n addPlatformConditionValue(PlatformConditionKind::TargetEnvironment,\n \"macabi\");\n\n \/\/ If you add anything to this list, change the default size of\n \/\/ PlatformConditionValues to not require an extra allocation\n \/\/ in the common case.\n\n return { false, false };\n}\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief json helper functions\n\/\/\/\n\/\/\/ @file\n\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2004-2013 triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\/ you may not use this file except in compliance with the License.\n\/\/\/ You may obtain a copy of the License at\n\/\/\/\n\/\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\/\n\/\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\/ See the License for the specific language governing permissions and\n\/\/\/ limitations under the License.\n\/\/\/\n\/\/\/ Copyright holder is triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Jan Steemann\n\/\/\/ @author Copyright 2012-2013, triAGENS GmbH, Cologne, Germany\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"Basics\/JsonHelper.h\"\n\n#include \"BasicsC\/conversions.h\"\n#include \"BasicsC\/string-buffer.h\"\n\nusing namespace triagens::basics;\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- class JsonHelper\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- public static methods\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief convert a uint64 into a JSON string \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nTRI_json_t* JsonHelper::uint64String (TRI_memory_zone_t* zone,\n uint64_t value) {\n char buffer[21];\n size_t len;\n\n len = TRI_StringUInt64InPlace(value, (char*) &buffer);\n\n return TRI_CreateString2CopyJson(zone, buffer, len);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief convert a uint64 into a JSON string \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nuint64_t JsonHelper::stringUInt64 (TRI_json_t const* json) {\n if (json != 0) {\n if (json->_type == TRI_JSON_STRING) {\n return TRI_UInt64String2(json->_value._string.data, json->_value._string.length - 1);\n }\n else if (json->_type == TRI_JSON_NUMBER) {\n return (uint64_t) json->_value._number;\n }\n }\n\n return 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief convert a uint64 into a JSON string \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nuint64_t JsonHelper::stringUInt64 (TRI_json_t const* json,\n char const* name) {\n\n if (json == 0) {\n return 0;\n }\n\n TRI_json_t const* element = TRI_LookupArrayJson(json, name);\n return stringUInt64(element);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief creates a JSON key\/value object from a list of strings\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nTRI_json_t* JsonHelper::stringObject (TRI_memory_zone_t* zone,\n std::map const& values) {\n TRI_json_t* json = TRI_CreateArray2Json(zone, values.size());\n\n if (json == 0) {\n return 0;\n }\n\n std::map::const_iterator it;\n for (it = values.begin(); it != values.end(); ++it) {\n const std::string key = (*it).first;\n const std::string value = (*it).second;\n\n TRI_json_t* v = TRI_CreateString2CopyJson(zone, value.c_str(), value.size());\n if (v != 0) {\n TRI_Insert3ArrayJson(zone, json, key.c_str(), v);\n }\n }\n\n return json;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief creates a key\/value object of strings from a JSON (sub-) object\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstd::map JsonHelper::stringObject (TRI_json_t const* json) {\n std::map result;\n\n if (isArray(json)) {\n for (size_t i = 0, n = json->_value._objects._length; i < n; i += 2) {\n TRI_json_t const* k = (TRI_json_t const*) TRI_AtVector(&json->_value._objects, i);\n TRI_json_t const* v = (TRI_json_t const*) TRI_AtVector(&json->_value._objects, i + 1);\n\n if (isString(k) && isString(v)) {\n const std::string key = std::string(k->_value._string.data, k->_value._string.length - 1);\n const std::string value = std::string(v->_value._string.data, v->_value._string.length - 1);\n result.insert(std::pair(key, value));\n }\n }\n }\n\n return result;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief creates a JSON object from a list of strings\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nTRI_json_t* JsonHelper::stringList (TRI_memory_zone_t* zone,\n std::vector const& values) {\n TRI_json_t* json = TRI_CreateList2Json(zone, values.size());\n\n if (json == 0) {\n return 0;\n }\n\n for (size_t i = 0, n = values.size(); i < n; ++i) {\n TRI_json_t* v = TRI_CreateString2CopyJson(zone, values[i].c_str(), values[i].size());\n if (v != 0) {\n TRI_PushBack3ListJson(zone, json, v);\n }\n }\n\n return json;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief creates a list of strings from a JSON (sub-) object\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstd::vector JsonHelper::stringList (TRI_json_t const* json) {\n std::vector result;\n\n if (isList(json)) {\n for (size_t i = 0, n = json->_value._objects._length; i < n; ++i) {\n TRI_json_t const* v = (TRI_json_t const*) TRI_AtVector(&json->_value._objects, i);\n\n if (isString(v)) {\n result.push_back(std::string(v->_value._string.data, v->_value._string.length - 1));\n }\n }\n }\n\n return result;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief create JSON from string\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \nTRI_json_t* JsonHelper::fromString (std::string const& data) {\n TRI_json_t* json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, data.c_str());\n\n return json;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief create JSON from string\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \nTRI_json_t* JsonHelper::fromString (char const* data,\n size_t length) {\n TRI_json_t* json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, data);\n\n return json;\n}\n \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief stringify json\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \nstd::string JsonHelper::toString (TRI_json_t const* json) {\n TRI_string_buffer_t buffer;\n\n TRI_InitStringBuffer(&buffer, TRI_UNKNOWN_MEM_ZONE);\n int res = TRI_StringifyJson(&buffer, json);\n\n if (res != TRI_ERROR_NO_ERROR) {\n return \"\";\n }\n\n string out(TRI_BeginStringBuffer(&buffer), TRI_LengthStringBuffer(&buffer));\n TRI_DestroyStringBuffer(&buffer);\n\n return out;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief returns an array sub-element\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \nTRI_json_t* JsonHelper::getArrayElement (TRI_json_t const* json, \n const char* name) {\n if (! isArray(json)) {\n return 0;\n }\n\n return TRI_LookupArrayJson(json, name);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief returns a string element, or a default it is does not exist\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \nstd::string JsonHelper::getStringValue (TRI_json_t const* json, \n const std::string& defaultValue) {\n if (isString(json)) {\n return string(json->_value._string.data, json->_value._string.length - 1);\n }\n return defaultValue;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief returns a string sub-element, or a default it is does not exist\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \nstd::string JsonHelper::getStringValue (TRI_json_t const* json, \n const char* name, \n const std::string& defaultValue) {\n TRI_json_t const* sub = getArrayElement(json, name);\n\n if (isString(sub)) {\n return string(sub->_value._string.data, sub->_value._string.length - 1);\n }\n return defaultValue;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief returns a boolean sub-element, or a default it is does not exist\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \nbool JsonHelper::getBooleanValue (TRI_json_t const* json, \n const char* name, \n bool defaultValue) {\n TRI_json_t const* sub = getArrayElement(json, name);\n\n if (isBoolean(sub)) {\n return sub->_value._boolean;\n }\n\n return defaultValue;\n}\n\n\/\/ Local Variables:\n\/\/ mode: outline-minor\n\/\/ outline-regexp: \"\/\/\/ @brief\\\\|\/\/\/ {@inheritDoc}\\\\|\/\/\/ @addtogroup\\\\|\/\/\/ @page\\\\|\/\/ --SECTION--\\\\|\/\/\/ @\\\\}\"\n\/\/ End:\nFix a description of two methods.\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief json helper functions\n\/\/\/\n\/\/\/ @file\n\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2004-2013 triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\/ you may not use this file except in compliance with the License.\n\/\/\/ You may obtain a copy of the License at\n\/\/\/\n\/\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\/\n\/\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\/ See the License for the specific language governing permissions and\n\/\/\/ limitations under the License.\n\/\/\/\n\/\/\/ Copyright holder is triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Jan Steemann\n\/\/\/ @author Copyright 2012-2013, triAGENS GmbH, Cologne, Germany\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"Basics\/JsonHelper.h\"\n\n#include \"BasicsC\/conversions.h\"\n#include \"BasicsC\/string-buffer.h\"\n\nusing namespace triagens::basics;\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- class JsonHelper\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- public static methods\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief convert a uint64 into a JSON string \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nTRI_json_t* JsonHelper::uint64String (TRI_memory_zone_t* zone,\n uint64_t value) {\n char buffer[21];\n size_t len;\n\n len = TRI_StringUInt64InPlace(value, (char*) &buffer);\n\n return TRI_CreateString2CopyJson(zone, buffer, len);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief convert a JSON strong or number into a uint64\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nuint64_t JsonHelper::stringUInt64 (TRI_json_t const* json) {\n if (json != 0) {\n if (json->_type == TRI_JSON_STRING) {\n return TRI_UInt64String2(json->_value._string.data, json->_value._string.length - 1);\n }\n else if (json->_type == TRI_JSON_NUMBER) {\n return (uint64_t) json->_value._number;\n }\n }\n\n return 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief convert a JSON strong or number into a uint64\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nuint64_t JsonHelper::stringUInt64 (TRI_json_t const* json,\n char const* name) {\n\n if (json == 0) {\n return 0;\n }\n\n TRI_json_t const* element = TRI_LookupArrayJson(json, name);\n return stringUInt64(element);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief creates a JSON key\/value object from a list of strings\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nTRI_json_t* JsonHelper::stringObject (TRI_memory_zone_t* zone,\n std::map const& values) {\n TRI_json_t* json = TRI_CreateArray2Json(zone, values.size());\n\n if (json == 0) {\n return 0;\n }\n\n std::map::const_iterator it;\n for (it = values.begin(); it != values.end(); ++it) {\n const std::string key = (*it).first;\n const std::string value = (*it).second;\n\n TRI_json_t* v = TRI_CreateString2CopyJson(zone, value.c_str(), value.size());\n if (v != 0) {\n TRI_Insert3ArrayJson(zone, json, key.c_str(), v);\n }\n }\n\n return json;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief creates a key\/value object of strings from a JSON (sub-) object\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstd::map JsonHelper::stringObject (TRI_json_t const* json) {\n std::map result;\n\n if (isArray(json)) {\n for (size_t i = 0, n = json->_value._objects._length; i < n; i += 2) {\n TRI_json_t const* k = (TRI_json_t const*) TRI_AtVector(&json->_value._objects, i);\n TRI_json_t const* v = (TRI_json_t const*) TRI_AtVector(&json->_value._objects, i + 1);\n\n if (isString(k) && isString(v)) {\n const std::string key = std::string(k->_value._string.data, k->_value._string.length - 1);\n const std::string value = std::string(v->_value._string.data, v->_value._string.length - 1);\n result.insert(std::pair(key, value));\n }\n }\n }\n\n return result;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief creates a JSON object from a list of strings\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nTRI_json_t* JsonHelper::stringList (TRI_memory_zone_t* zone,\n std::vector const& values) {\n TRI_json_t* json = TRI_CreateList2Json(zone, values.size());\n\n if (json == 0) {\n return 0;\n }\n\n for (size_t i = 0, n = values.size(); i < n; ++i) {\n TRI_json_t* v = TRI_CreateString2CopyJson(zone, values[i].c_str(), values[i].size());\n if (v != 0) {\n TRI_PushBack3ListJson(zone, json, v);\n }\n }\n\n return json;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief creates a list of strings from a JSON (sub-) object\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstd::vector JsonHelper::stringList (TRI_json_t const* json) {\n std::vector result;\n\n if (isList(json)) {\n for (size_t i = 0, n = json->_value._objects._length; i < n; ++i) {\n TRI_json_t const* v = (TRI_json_t const*) TRI_AtVector(&json->_value._objects, i);\n\n if (isString(v)) {\n result.push_back(std::string(v->_value._string.data, v->_value._string.length - 1));\n }\n }\n }\n\n return result;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief create JSON from string\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \nTRI_json_t* JsonHelper::fromString (std::string const& data) {\n TRI_json_t* json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, data.c_str());\n\n return json;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief create JSON from string\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \nTRI_json_t* JsonHelper::fromString (char const* data,\n size_t length) {\n TRI_json_t* json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, data);\n\n return json;\n}\n \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief stringify json\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \nstd::string JsonHelper::toString (TRI_json_t const* json) {\n TRI_string_buffer_t buffer;\n\n TRI_InitStringBuffer(&buffer, TRI_UNKNOWN_MEM_ZONE);\n int res = TRI_StringifyJson(&buffer, json);\n\n if (res != TRI_ERROR_NO_ERROR) {\n return \"\";\n }\n\n string out(TRI_BeginStringBuffer(&buffer), TRI_LengthStringBuffer(&buffer));\n TRI_DestroyStringBuffer(&buffer);\n\n return out;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief returns an array sub-element\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \nTRI_json_t* JsonHelper::getArrayElement (TRI_json_t const* json, \n const char* name) {\n if (! isArray(json)) {\n return 0;\n }\n\n return TRI_LookupArrayJson(json, name);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief returns a string element, or a default it is does not exist\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \nstd::string JsonHelper::getStringValue (TRI_json_t const* json, \n const std::string& defaultValue) {\n if (isString(json)) {\n return string(json->_value._string.data, json->_value._string.length - 1);\n }\n return defaultValue;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief returns a string sub-element, or a default it is does not exist\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \nstd::string JsonHelper::getStringValue (TRI_json_t const* json, \n const char* name, \n const std::string& defaultValue) {\n TRI_json_t const* sub = getArrayElement(json, name);\n\n if (isString(sub)) {\n return string(sub->_value._string.data, sub->_value._string.length - 1);\n }\n return defaultValue;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief returns a boolean sub-element, or a default it is does not exist\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \nbool JsonHelper::getBooleanValue (TRI_json_t const* json, \n const char* name, \n bool defaultValue) {\n TRI_json_t const* sub = getArrayElement(json, name);\n\n if (isBoolean(sub)) {\n return sub->_value._boolean;\n }\n\n return defaultValue;\n}\n\n\/\/ Local Variables:\n\/\/ mode: outline-minor\n\/\/ outline-regexp: \"\/\/\/ @brief\\\\|\/\/\/ {@inheritDoc}\\\\|\/\/\/ @addtogroup\\\\|\/\/\/ @page\\\\|\/\/ --SECTION--\\\\|\/\/\/ @\\\\}\"\n\/\/ End:\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \"number.hh\"\n\nusing namespace std;\n\n\/\/ number class definitions.\ntemplate <>\nNumber::complex_type Number::coerce() const{\n switch(type_){\n case Type::complex:\n return z_;\n case Type::real:\n return complex_type{f_};\n case Type::integer:\n return complex_type{static_cast(i_)};\n case Type::uninitialized:\n default:\n UNEXP_CONVERSION(\"complex\");\n }\n}\n\ntemplate <>\nNumber::real_type Number::coerce() const{\n switch(type_){\n case Type::real:\n return f_;\n case Type::integer:\n return static_cast(i_);\n case Type::complex:\n case Type::uninitialized:\n default:\n UNEXP_CONVERSION(\"real\");\n }\n}\n\ntemplate <>\nNumber::integer_type Number::coerce() const{\n switch(type_){\n case Type::integer:\n return i_;\n case Type::complex:\n case Type::real:\n case Type::uninitialized:\n default:\n UNEXP_CONVERSION(\"integer\");\n }\n}\n\n\n\/\/ number parsers\nnamespace {\n\nenum class Exactness{\n exact, inexact, unspecified\n };\n\nstruct PrefixValue {\n const int radix;\n const Exactness ex;\n\n constexpr PrefixValue() \/\/ error value\n : radix(0), ex(Exactness::unspecified){}\n\n constexpr PrefixValue(int r, Exactness e)\n : radix(r), ex(e){}\n\n explicit operator bool() const {\n return (radix != 0);\n }\n};\n\nPrefixValue parse_number_prefix(FILE* f){\n int r = 10;\n Exactness e = Exactness::unspecified;\n bool r_appeared = false, e_appeared = false;\n\n for(int loop = 0; loop < 2; ++loop){\n decltype(fgetc(f)) c = fgetc(f);\n\n if(c != '#'){\n ungetc(c, f);\n return {r, e};\n }\n\n switch(c = fgetc(f)){\n case 'i': case 'e':\n if(e_appeared) return {};\n e_appeared = true;\n e = (c == 'i') ? Exactness::inexact \n : Exactness::exact;\n break;\n case 'b': case 'o': case 'd': case 'x':\n if(r_appeared) return {};\n r_appeared = true;\n r = (c == 'b') ? 2\n : (c == 'o') ? 8\n : (c == 'd') ? 10\n : 16;\n break;\n default:\n fprintf(stderr, \"reader error: unknown number prefix '%c' appeared!\\n\", c);\n return {};\n }\n } \n \n return {r, e};\n}\n\n\ninline\nbool is_number_char(int radix, char c){\n switch(radix){\n case 16:\n return isxdigit(c);\n\n case 10:\n return isdigit(c);\n\n case 8:\n switch(c){\n case '0': case '1':\n case '2': case '3': case '4':\n case '5': case '6': case '7':\n return true;\n default:\n return false;\n }\n\n case 2:\n switch(c){\n case '0': case '1':\n return true;\n default:\n return false;\n }\n \n default:\n UNEXP_DEFAULT();\n }\n}\n\nint eat_sharp(FILE* f, string& o){\n decltype(fgetc(f)) c;\n int sharps = 0;\n\n while((c = fgetc(f)) == '#'){\n o.push_back('0');\n ++sharps;\n }\n ungetc(c, f);\n\n return sharps;\n}\n\n\nstruct ParserRet {\n const Number number;\n const Exactness ex;\n\n constexpr ParserRet() \/\/ error value\n : number(), ex(Exactness::unspecified){}\n\n constexpr ParserRet(const Number& n, Exactness e)\n : number(n), ex(e){}\n\n explicit operator bool() const {\n return static_cast(number);\n }\n};\n\nParserRet parse_unsigned(int radix, FILE* f, string& s){\n decltype(fgetc(f)) c;\n\n while(is_number_char(radix, c = fgetc(f)))\n s.push_back(c);\n ungetc(c, f);\n\n if(s.empty()){\n return {};\n }\n \n Exactness e;\n\n if(eat_sharp(f, s) > 0){\n e = Exactness::inexact;\n }else{\n e = Exactness::exact;\n }\n\n errno = 0;\n long l = strtol(s.c_str(), nullptr, radix);\n if(errno) return {};\n\n return {Number{l}, e};\n}\n\ninline\nbool check_decimal_suffix(char c){\n switch(c){\n case 'e': case 's': case 'f': case 'd': case 'l':\n return true;\n default:\n return false;\n }\n}\n\nParserRet parse_decimal(FILE* f, string& s){\n decltype(fgetc(f)) c;\n bool dot_start = false;\n int sharps_before_dot = 0;\n\n if(s.empty()){\n if((c = fgetc(f)) == '.'){\n ungetc(c, f);\n dot_start = true;\n }else{\n return {};\n }\n }else{\n sharps_before_dot = eat_sharp(f, s);\n }\n\n if((c = fgetc(f)) != '.'){\n goto end; \/\/ 1. no frac part\n }\n s.push_back('.');\n \n if(sharps_before_dot > 0){\n eat_sharp(f, s);\n goto end; \/\/ 4. only sharps after dot\n }\n\n {\n bool digits_after_dot = false;\n\n while(is_number_char(10, c = fgetc(f))){\n digits_after_dot = true;\n s.push_back(c);\n }\n ungetc(c, f);\n\n if(dot_start && !digits_after_dot)\n return {}; \/\/ 2. dot start should have digits\n\n eat_sharp(f, s);\n }\n \n end:\n if(check_decimal_suffix(c = fgetc(f))){\n s.push_back('e');\n\n switch(c = fgetc(f)){\n case '+': case '-':\n s.push_back(c); break;\n default:\n ungetc(c, f); break;\n }\n\n {\n bool exp_digits = false;\n\n while(is_number_char(10, c = fgetc(f))){\n exp_digits = true;\n s.push_back(c);\n }\n ungetc(c, f);\n\n if(!exp_digits)\n return {}; \/\/ no number on exp. part\n }\n }else{\n ungetc(c, f);\n }\n\n return {Number{strtod(s.c_str(), nullptr)},\n Exactness::inexact};\n}\n\nParserRet parse_real_number(int radix, FILE* f){\n decltype(fgetc(f)) c;\n int sign = 1;\n\n switch(c = fgetc(f)){\n case '+':\n sign = 1;\n break;\n case '-':\n sign = -1;\n break;\n default:\n sign = 1;\n ungetc(c, f);\n break;\n }\n\n string s;\n\n auto u1 = parse_unsigned(radix, f, s);\n c = fgetc(f);\n\n if((c == '.') || (u1 && check_decimal_suffix(c))){\n \/\/ decimal float\n if(radix == 10){\n ungetc(c, f);\n auto n = parse_decimal(f, s);\n\n if(n.number.type() == Number::Type::real){\n return {Number{n.number.coerce() * sign},\n Exactness::inexact};\n }\n }\n return {};\n }else if(!u1){\n return {};\n }else if(c == '\/'){\n \/\/ rational\n string s2;\n auto u2 = parse_unsigned(radix, f, s2);\n if(!u2) return {};\n\n return {Number(sign * u1.number.coerce() \/ u2.number.coerce()),\n Exactness::inexact};\n }else{\n \/\/ integer?\n ungetc(c, f);\n \/\/ FIXME: inexact or super-big integer can be fall into float.\n return {Number(sign * u1.number.coerce()), u1.ex};\n }\n}\n\nParserRet parse_complex(int radix, FILE* f){\n const auto first_char = fgetc(f);\n ungetc(first_char, f);\n\n \/\/ has real part\n auto real = parse_real_number(radix, f);\n if(!real) return {};\n\n switch(auto c = fgetc(f)){\n case '@': {\/\/ polar literal\n auto deg = parse_real_number(radix, f);\n if(!deg) return {};\n \n return {Number{polar(real.number.coerce(), deg.number.coerce())},\n Exactness::inexact};\n }\n case '+': case '-': {\n const int sign = (c == '+') ? 1 : -1;\n\n if((c = fgetc(f)) == 'i'){\n return {Number{real.number.coerce(), static_cast(sign)},\n Exactness::inexact};\n }\n ungetc(c, f);\n \n auto imag = parse_real_number(radix, f);\n if(!imag || fgetc(f) != 'i')\n return {};\n\n return {Number{real.number.coerce(), imag.number.coerce() * sign},\n Exactness::inexact};\n }\n case 'i':\n if(first_char == '+' || first_char == '-'){\n return {Number{0, real.number.coerce()},\n Exactness::inexact};\n }else{\n return {};\n }\n default:\n ungetc(c, f);\n return real;\n }\n}\n\n} \/\/ namespace\n\nNumber parse_number(FILE* f){\n const auto prefix_info = parse_number_prefix(f);\n if(!prefix_info) return {};\n\n const auto r = parse_complex(prefix_info.radix, f);\n if(!r) return {};\n\n if(prefix_info.ex == Exactness::unspecified\n || prefix_info.ex == r.ex){\n return r.number;\n }else if(prefix_info.ex == Exactness::exact){\n return to_exact(r.number);\n }else{\n return to_inexact(r.number);\n }\n}\n\nbool eql(const Number& n, const Number& m){\n if(n.type() != m.type()) return false;\n\n switch(n.type()){\n case Number::Type::uninitialized:\n return false;\n case Number::Type::complex:\n return n.get() == m.get();\n case Number::Type::real:\n return n.get() == m.get();\n case Number::Type::integer:\n return n.get() == m.get();\n default:\n UNEXP_DEFAULT();\n }\n}\n\nvoid print(FILE* f, const Number& n){\n switch(n.type()){\n case Number::Type::uninitialized:\n fprintf(f, \"(uninitialied number)\");\n break;\n case Number::Type::complex: {\n auto&& z = n.get();\n fprintf(f, \"%g+%gi\", z.real(), z.imag());\n }\n break;\n case Number::Type::real:\n fprintf(f, \"%g\", n.get());\n break;\n case Number::Type::integer:\n fprintf(f, \"%ld\", n.get());\n break;\n default:\n UNEXP_DEFAULT();\n }\n}\n\nNumber to_exact(const Number& n){\n switch(n.type()){\n case Number::Type::complex:\n return {}; \/\/ not supported\n case Number::Type::real:\n return {}; \/\/ not supported\n case Number::Type::integer:\n return n;\n case Number::Type::uninitialized:\n default:\n return {};\n }\n}\n\nNumber to_inexact(const Number& n){\n switch(n.type()){\n case Number::Type::complex:\n return n;\n case Number::Type::real:\n return n;\n case Number::Type::integer:\n return Number{static_cast\n (n.get())};\n case Number::Type::uninitialized:\n default:\n return {};\n }\n}\n\nconst char* stringify(Number::Type t){\n switch(t){\n case Number::Type::uninitialized:\n return \"uninitialized\";\n case Number::Type::complex:\n return \"complex\";\n case Number::Type::real:\n return \"real\";\n case Number::Type::integer:\n return \"integer\";\n default:\n return \"(unknown number type)\";\n }\n}\n\nvoid describe(FILE* f, Number::Type t){\n fputs(stringify(t), f);\n}\n\nvoid describe(FILE* f, const Number& n){\n const auto t = n.type();\n\n fprintf(f, \"Number: %s(\", stringify(t));\n print(f, n);\n fputc(')', f);\n}\n\nbitly number parser change#include \n#include \n\n#include \"number.hh\"\n\nusing namespace std;\n\n\/\/ number class definitions.\ntemplate <>\nNumber::complex_type Number::coerce() const{\n switch(type_){\n case Type::complex:\n return z_;\n case Type::real:\n return complex_type{f_};\n case Type::integer:\n return complex_type{static_cast(i_)};\n case Type::uninitialized:\n default:\n UNEXP_CONVERSION(\"complex\");\n }\n}\n\ntemplate <>\nNumber::real_type Number::coerce() const{\n switch(type_){\n case Type::real:\n return f_;\n case Type::integer:\n return static_cast(i_);\n case Type::complex:\n case Type::uninitialized:\n default:\n UNEXP_CONVERSION(\"real\");\n }\n}\n\ntemplate <>\nNumber::integer_type Number::coerce() const{\n switch(type_){\n case Type::integer:\n return i_;\n case Type::complex:\n case Type::real:\n case Type::uninitialized:\n default:\n UNEXP_CONVERSION(\"integer\");\n }\n}\n\n\n\/\/ number parsers\nnamespace {\n\nenum class Exactness{\n exact, inexact, unspecified\n };\n\nstruct PrefixValue {\n const int radix;\n const Exactness ex;\n\n constexpr PrefixValue() \/\/ error value\n : radix(0), ex(Exactness::unspecified){}\n\n constexpr PrefixValue(int r, Exactness e)\n : radix(r), ex(e){}\n\n explicit operator bool() const {\n return (radix != 0);\n }\n};\n\nPrefixValue parse_number_prefix(FILE* f){\n int r = 10;\n Exactness e = Exactness::unspecified;\n bool r_appeared = false, e_appeared = false;\n\n for(int loop = 0; loop < 2; ++loop){\n decltype(fgetc(f)) c = fgetc(f);\n\n if(c != '#'){\n ungetc(c, f);\n return {r, e};\n }\n\n switch(c = fgetc(f)){\n case 'i': case 'e':\n if(e_appeared) return {};\n e_appeared = true;\n e = (c == 'i') ? Exactness::inexact \n : Exactness::exact;\n break;\n case 'b': case 'o': case 'd': case 'x':\n if(r_appeared) return {};\n r_appeared = true;\n r = (c == 'b') ? 2\n : (c == 'o') ? 8\n : (c == 'd') ? 10\n : 16;\n break;\n default:\n fprintf(stderr, \"reader error: unknown number prefix '%c' appeared!\\n\", c);\n return {};\n }\n } \n \n return {r, e};\n}\n\n\ninline\nbool is_number_char(int radix, char c){\n switch(radix){\n case 16:\n return isxdigit(c);\n\n case 10:\n return isdigit(c);\n\n case 8:\n switch(c){\n case '0': case '1':\n case '2': case '3': case '4':\n case '5': case '6': case '7':\n return true;\n default:\n return false;\n }\n\n case 2:\n switch(c){\n case '0': case '1':\n return true;\n default:\n return false;\n }\n \n default:\n UNEXP_DEFAULT();\n }\n}\n\nint eat_sharp(FILE* f, string& o){\n decltype(fgetc(f)) c;\n int sharps = 0;\n\n while((c = fgetc(f)) == '#'){\n o.push_back('0');\n ++sharps;\n }\n ungetc(c, f);\n\n return sharps;\n}\n\n\nstruct ParserRet {\n const Number number;\n const Exactness ex;\n\n constexpr ParserRet() \/\/ error value\n : number(), ex(Exactness::unspecified){}\n\n constexpr ParserRet(const Number& n, Exactness e)\n : number(n), ex(e){}\n\n explicit operator bool() const {\n return static_cast(number);\n }\n};\n\nParserRet parse_unsigned(int radix, FILE* f, string& s){\n decltype(fgetc(f)) c;\n\n while(is_number_char(radix, c = fgetc(f)))\n s.push_back(c);\n ungetc(c, f);\n\n if(s.empty()){\n return {};\n }\n \n Exactness e;\n\n if(eat_sharp(f, s) > 0){\n e = Exactness::inexact;\n }else{\n e = Exactness::exact;\n }\n\n errno = 0;\n long l = strtol(s.c_str(), nullptr, radix);\n if(errno) return {};\n\n return {Number{l}, e};\n}\n\ninline\nbool check_decimal_suffix(char c){\n switch(c){\n case 'e': case 's': case 'f': case 'd': case 'l':\n return true;\n default:\n return false;\n }\n}\n\nParserRet parse_decimal(FILE* f, string& s){\n decltype(fgetc(f)) c;\n bool dot_start = false;\n int sharps_before_dot = 0;\n\n if(s.empty()){\n if((c = fgetc(f)) == '.'){\n ungetc(c, f);\n dot_start = true;\n }else{\n return {};\n }\n }else{\n sharps_before_dot = eat_sharp(f, s);\n }\n\n if((c = fgetc(f)) != '.'){\n goto end; \/\/ 1. no frac part\n }\n s.push_back('.');\n \n if(sharps_before_dot > 0){\n eat_sharp(f, s);\n goto end; \/\/ 4. only sharps after dot\n }\n\n {\n bool digits_after_dot = false;\n\n while(isdigit(c = fgetc(f))){\n digits_after_dot = true;\n s.push_back(c);\n }\n ungetc(c, f);\n\n if(dot_start && !digits_after_dot)\n return {}; \/\/ 2. dot start should have digits\n\n eat_sharp(f, s);\n }\n \n end:\n if(check_decimal_suffix(c = fgetc(f))){\n s.push_back('e');\n\n switch(c = fgetc(f)){\n case '+': case '-':\n s.push_back(c); break;\n default:\n ungetc(c, f); break;\n }\n\n {\n bool exp_digits = false;\n\n while(isdigit(c = fgetc(f))){\n exp_digits = true;\n s.push_back(c);\n }\n ungetc(c, f);\n\n if(!exp_digits)\n return {}; \/\/ no number on exp. part\n }\n }else{\n ungetc(c, f);\n }\n\n return {Number{strtod(s.c_str(), nullptr)},\n Exactness::inexact};\n}\n\nParserRet parse_real_number(int radix, FILE* f){\n decltype(fgetc(f)) c;\n int sign = 1;\n\n switch(c = fgetc(f)){\n case '+':\n sign = 1;\n break;\n case '-':\n sign = -1;\n break;\n default:\n sign = 1;\n ungetc(c, f);\n break;\n }\n\n string s;\n\n auto u1 = parse_unsigned(radix, f, s);\n c = fgetc(f);\n\n if((c == '.') || (u1 && check_decimal_suffix(c))){\n \/\/ decimal float\n if(radix == 10){\n ungetc(c, f);\n auto n = parse_decimal(f, s);\n\n if(n.number.type() == Number::Type::real){\n return {Number{n.number.coerce() * sign},\n Exactness::inexact};\n }\n }\n return {};\n }else if(!u1){\n return {};\n }else if(c == '\/'){\n \/\/ rational\n string s2;\n auto u2 = parse_unsigned(radix, f, s2);\n if(!u2) return {};\n\n return {Number(sign * u1.number.coerce() \/ u2.number.coerce()),\n Exactness::inexact};\n }else{\n \/\/ integer?\n ungetc(c, f);\n \/\/ FIXME: inexact or super-big integer can be fall into float.\n return {Number(sign * u1.number.coerce()), u1.ex};\n }\n}\n\nParserRet parse_complex(int radix, FILE* f){\n const auto first_char = fgetc(f);\n ungetc(first_char, f);\n\n \/\/ has real part\n auto real = parse_real_number(radix, f);\n if(!real) return {};\n\n switch(auto c = fgetc(f)){\n case '@': {\/\/ polar literal\n auto deg = parse_real_number(radix, f);\n if(!deg) return {};\n \n return {Number{polar(real.number.coerce(), deg.number.coerce())},\n Exactness::inexact};\n }\n case '+': case '-': {\n const int sign = (c == '+') ? 1 : -1;\n\n if((c = fgetc(f)) == 'i'){\n return {Number{real.number.coerce(), static_cast(sign)},\n Exactness::inexact};\n }\n ungetc(c, f);\n \n auto imag = parse_real_number(radix, f);\n if(!imag || fgetc(f) != 'i')\n return {};\n\n return {Number{real.number.coerce(), imag.number.coerce() * sign},\n Exactness::inexact};\n }\n case 'i':\n if(first_char == '+' || first_char == '-'){\n return {Number{0, real.number.coerce()},\n Exactness::inexact};\n }else{\n return {};\n }\n default:\n ungetc(c, f);\n return real;\n }\n}\n\n} \/\/ namespace\n\nNumber parse_number(FILE* f){\n const auto prefix_info = parse_number_prefix(f);\n if(!prefix_info) return {};\n\n const auto r = parse_complex(prefix_info.radix, f);\n if(!r) return {};\n\n if(prefix_info.ex == Exactness::unspecified\n || prefix_info.ex == r.ex){\n return r.number;\n }else if(prefix_info.ex == Exactness::exact){\n return to_exact(r.number);\n }else{\n return to_inexact(r.number);\n }\n}\n\nbool eql(const Number& n, const Number& m){\n if(n.type() != m.type()) return false;\n\n switch(n.type()){\n case Number::Type::uninitialized:\n return false;\n case Number::Type::complex:\n return n.get() == m.get();\n case Number::Type::real:\n return n.get() == m.get();\n case Number::Type::integer:\n return n.get() == m.get();\n default:\n UNEXP_DEFAULT();\n }\n}\n\nvoid print(FILE* f, const Number& n){\n switch(n.type()){\n case Number::Type::uninitialized:\n fprintf(f, \"(uninitialied number)\");\n break;\n case Number::Type::complex: {\n auto&& z = n.get();\n fprintf(f, \"%g+%gi\", z.real(), z.imag());\n }\n break;\n case Number::Type::real:\n fprintf(f, \"%g\", n.get());\n break;\n case Number::Type::integer:\n fprintf(f, \"%ld\", n.get());\n break;\n default:\n UNEXP_DEFAULT();\n }\n}\n\nNumber to_exact(const Number& n){\n switch(n.type()){\n case Number::Type::complex:\n return {}; \/\/ not supported\n case Number::Type::real:\n return {}; \/\/ not supported\n case Number::Type::integer:\n return n;\n case Number::Type::uninitialized:\n default:\n return {};\n }\n}\n\nNumber to_inexact(const Number& n){\n switch(n.type()){\n case Number::Type::complex:\n return n;\n case Number::Type::real:\n return n;\n case Number::Type::integer:\n return Number{static_cast\n (n.get())};\n case Number::Type::uninitialized:\n default:\n return {};\n }\n}\n\nconst char* stringify(Number::Type t){\n switch(t){\n case Number::Type::uninitialized:\n return \"uninitialized\";\n case Number::Type::complex:\n return \"complex\";\n case Number::Type::real:\n return \"real\";\n case Number::Type::integer:\n return \"integer\";\n default:\n return \"(unknown number type)\";\n }\n}\n\nvoid describe(FILE* f, Number::Type t){\n fputs(stringify(t), f);\n}\n\nvoid describe(FILE* f, const Number& n){\n const auto t = n.type();\n\n fprintf(f, \"Number: %s(\", stringify(t));\n print(f, n);\n fputc(')', f);\n}\n\n<|endoftext|>"} {"text":"\/*\n * IceWM\n *\n * Copyright (C) 1999-2002 Marko Macek\n *\/\n#include \"config.h\"\n#include \"objmenu.h\"\n#include \"objbar.h\"\n#include \"objbutton.h\"\n#include \"ybutton.h\"\n#include \"prefs.h\"\n#include \"wmtaskbar.h\"\n#include \"wmapp.h\"\n#include \"wpixmaps.h\"\n#include \"yrect.h\"\n#include \"yicon.h\"\n\nref ObjectButton::font;\nYColor * ObjectButton::bgColor(NULL);\nYColor * ObjectButton::fgColor(NULL);\n\nObjectBar::ObjectBar(YWindow *parent): YWindow(parent) {\n setSize(1, 1);\n}\n\nObjectBar::~ObjectBar() {\n}\n\nvoid ObjectBar::addButton(const ustring &name, ref icon, YButton *button) {\n button->setToolTip(name);\n if (icon != null) {\n button->setIcon(icon, YIcon::smallSize());\n button->setSize(button->width() + 4, button->width() + 4);\n } else\n button->setText(name);\n\n button->setPosition(width(), 0);\n int h = button->height();\n if (h < height())\n h = height();\n\n if (h < height())\n h = height();\n\n button->setSize(button->width(), h);\n setSize(width() + button->width(), h);\n button->show();\n\n objects.append(button);\n}\n\nvoid ObjectBar::paint(Graphics &g, const YRect &\/*r*\/) {\n ref gradient(parent()->getGradient());\n\n if (gradient != null)\n g.drawImage(gradient, this->x(), this->y(), width(), height(), 0, 0);\n else\n if (taskbackPixmap != null)\n g.fillPixmap(taskbackPixmap, 0, 0, width(), height());\n else {\n g.setColor(getTaskBarBg());\n g.fillRect(0, 0, width(), height());\n }\n}\n\nvoid ObjectBar::addObject(DObject *object) {\n YButton *button = new ObjectButton(this, object);\n addButton(object->getName(), object->getIcon(), button);\n}\n\nvoid ObjectBar::addSeparator() {\n setSize(width() + 4, height());\n objects.append(0);\n}\n\nvoid ObjectBar::addContainer(const ustring &name, ref icon, ObjectContainer *container) {\n if (container) {\n YButton *button = new ObjectButton(this, (YMenu*) container);\n addButton(name, icon, button);\n }\n}\n\nvoid ObjectBar::configure(const YRect &r) {\n YWindow::configure(r);\n\n\n int left = 0;\n for (int i = 0; i < objects.getCount(); i++) {\n YButton *obj = objects[i];\n if (obj) {\n obj->setGeometry(YRect(left, 0, obj->width(), height()));\n left += obj->width();\n } else\n left += 4;\n }\n}\n\nref ObjectButton::getFont() {\n return font != null ? font : font =\n (*toolButtonFontName ? YFont::getFont(XFA(toolButtonFontName))\n : YButton::getFont());\n}\n\nYColor * ObjectButton::getColor() {\n return *clrToolButtonText\n ? fgColor ? fgColor : fgColor = new YColor(clrToolButtonText)\n : YButton::getColor();\n}\n\nYSurface ObjectButton::getSurface() {\n if (bgColor == 0)\n bgColor = new YColor(*clrToolButton ? clrToolButton : clrNormalButton);\n\n return YSurface(bgColor, toolbuttonPixmap, toolbuttonPixbuf);\n}\n\nvoid ObjectButton::actionPerformed(YAction action, unsigned modifiers) {\n wmapp->signalGuiEvent(geLaunchApp);\n if (fObject) fObject->open();\n else YButton::actionPerformed(action, modifiers);\n}\n\nObjectMenu *rootMenu(NULL);\n\n\/\/ vim: set sw=4 ts=4 et:\nUse dynamic_cast for downcast from container to menu and check the result for issue #195.\/*\n * IceWM\n *\n * Copyright (C) 1999-2002 Marko Macek\n *\/\n#include \"config.h\"\n#include \"objmenu.h\"\n#include \"objbar.h\"\n#include \"objbutton.h\"\n#include \"ybutton.h\"\n#include \"prefs.h\"\n#include \"wmtaskbar.h\"\n#include \"wmapp.h\"\n#include \"wpixmaps.h\"\n#include \"yrect.h\"\n#include \"yicon.h\"\n\nref ObjectButton::font;\nYColor * ObjectButton::bgColor(NULL);\nYColor * ObjectButton::fgColor(NULL);\n\nObjectBar::ObjectBar(YWindow *parent): YWindow(parent) {\n setSize(1, 1);\n}\n\nObjectBar::~ObjectBar() {\n}\n\nvoid ObjectBar::addButton(const ustring &name, ref icon, YButton *button) {\n button->setToolTip(name);\n if (icon != null) {\n button->setIcon(icon, YIcon::smallSize());\n button->setSize(button->width() + 4, button->width() + 4);\n } else\n button->setText(name);\n\n button->setPosition(width(), 0);\n int h = button->height();\n if (h < height())\n h = height();\n\n if (h < height())\n h = height();\n\n button->setSize(button->width(), h);\n setSize(width() + button->width(), h);\n button->show();\n\n objects.append(button);\n}\n\nvoid ObjectBar::paint(Graphics &g, const YRect &\/*r*\/) {\n ref gradient(parent()->getGradient());\n\n if (gradient != null)\n g.drawImage(gradient, this->x(), this->y(), width(), height(), 0, 0);\n else\n if (taskbackPixmap != null)\n g.fillPixmap(taskbackPixmap, 0, 0, width(), height());\n else {\n g.setColor(getTaskBarBg());\n g.fillRect(0, 0, width(), height());\n }\n}\n\nvoid ObjectBar::addObject(DObject *object) {\n YButton *button = new ObjectButton(this, object);\n addButton(object->getName(), object->getIcon(), button);\n}\n\nvoid ObjectBar::addSeparator() {\n setSize(width() + 4, height());\n objects.append(0);\n}\n\nvoid ObjectBar::addContainer(const ustring &name, ref icon, ObjectContainer *container) {\n if (container) {\n ObjectMenu* menu = dynamic_cast(container);\n PRECONDITION(menu);\n if (!menu) return CARP(Bad menu);\n YButton *button = new ObjectButton(this, menu);\n addButton(name, icon, button);\n }\n}\n\nvoid ObjectBar::configure(const YRect &r) {\n YWindow::configure(r);\n\n\n int left = 0;\n for (int i = 0; i < objects.getCount(); i++) {\n YButton *obj = objects[i];\n if (obj) {\n obj->setGeometry(YRect(left, 0, obj->width(), height()));\n left += obj->width();\n } else\n left += 4;\n }\n}\n\nref ObjectButton::getFont() {\n return font != null ? font : font =\n (*toolButtonFontName ? YFont::getFont(XFA(toolButtonFontName))\n : YButton::getFont());\n}\n\nYColor * ObjectButton::getColor() {\n return *clrToolButtonText\n ? fgColor ? fgColor : fgColor = new YColor(clrToolButtonText)\n : YButton::getColor();\n}\n\nYSurface ObjectButton::getSurface() {\n if (bgColor == 0)\n bgColor = new YColor(*clrToolButton ? clrToolButton : clrNormalButton);\n\n return YSurface(bgColor, toolbuttonPixmap, toolbuttonPixbuf);\n}\n\nvoid ObjectButton::actionPerformed(YAction action, unsigned modifiers) {\n wmapp->signalGuiEvent(geLaunchApp);\n if (fObject) fObject->open();\n else YButton::actionPerformed(action, modifiers);\n}\n\nObjectMenu *rootMenu(NULL);\n\n\/\/ vim: set sw=4 ts=4 et:\n<|endoftext|>"} {"text":"\/\/ Copyright 2015 Chris Sattinger\n#include \"ofApp.h\"\n#include \"ofMain.h\"\n#include \n#include \"style.h\"\n\n\/\/--------------------------------------------------------------\nvoid ofApp::setup() {\n ofSetVerticalSync(true);\n ofSetFrameRate(60);\n\n ofAddListener(dataSource.didLoadEvent, this, &ofApp::dataSourceDidLoad);\n\n windowResized(ofGetWidth(), ofGetHeight());\n\n setupGui();\n}\n\nvoid ofApp::setupGui() {\n gui = new ofxDatGui(ofxDatGuiAnchor::TOP_RIGHT);\n controls.loadButton = gui->addButton(\"Click to load dataset\");\n controls.selectSound = gui->addDropdown(\"Sound\", superCollider.defNames());\n controls.selectSound->select(0); \/\/ what is actual index of current sound ?\n controls.pointRadius = gui->addSlider(\"Point radius\", 1, 6, scatterPlots.pointRadius);\n controls.brushWidth = gui->addSlider(\"Brush Width\", 1, 15, scatterPlots.brush.brushWidth);\n controls.brushHeight = gui->addSlider(\"Brush Height\", 1, 15, scatterPlots.brush.brushHeight);\n controls.amp = gui->addSlider(\"Amp\", 0.0, 1.0, sonifier.amp);\n controls.sustain = gui->addSlider(\"Sustain\", 0.005, 1.0, sonifier.sustain);\n controls.freqBase = gui->addSlider(\"Freq\", 220, 3520, sonifier.freqBase);\n\n \/\/ gui->addColorPicker(\"Brush Color\", engagedPointColor);\n gui->addFRM(1.0f);\n\n gui->onButtonEvent(this, &ofApp::onOfxDatGuiButtonEvent);\n gui->onSliderEvent(this, &ofApp::onOfxDatGuiSliderEvent);\n gui->onDropdownEvent(this, &ofApp::onOfxDatGuiDropdownEvent);\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::update() {\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::draw() {\n ofBackground(settingsBackground);\n scatterPlots.draw();\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::keyPressed(int key) {\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::keyReleased(int key) {\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseMoved(int x, int y) {\n scatterPlots.brush.mouseMoved(x, ofGetHeight() - y);\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseDragged(int x, int y, int button) {\n scatterPlots.brush.mouseDragged(x, ofGetHeight() - y, button);\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mousePressed(int x, int y, int button) {\n scatterPlots.brush.mousePressed(x, ofGetHeight() - y, button);\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseReleased(int x, int y, int button) {\n scatterPlots.brush.mouseReleased(x, ofGetHeight() - y, button);\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseEntered(int x, int y) {\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseExited(int x, int y) {\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::windowResized(int w, int h) {\n const double panelWidth = 310;\n auto rect = ofRectangle(0, 0, w - panelWidth - gutter - gutter, h);\n scatterPlots.setFrame(rect);\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::gotMessage(ofMessage msg) {\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::dragEvent(ofDragInfo dragInfo) {\n auto path = dragInfo.files.at(dragInfo.files.size() - 1);\n dataSource.load(path);\n}\n\nvoid ofApp::dataSourceDidLoad() {\n scatterPlots.setData(dataSource);\n controls.loadButton->setLabel(dataSource.title);\n}\n\n\nvoid ofApp::onOfxDatGuiButtonEvent(ofxDatGuiButtonEvent e) {\n if (e.target == controls.loadButton) {\n \/\/ initial load file dialog\n }\n}\n\nvoid ofApp::onOfxDatGuiDropdownEvent(ofxDatGuiDropdownEvent e) {\n if (e.target == controls.selectSound) {\n sonifier.selectSynthDef(e.child);\n }\n}\n\nvoid ofApp::onOfxDatGuiSliderEvent(ofxDatGuiSliderEvent e) {\n if (e.target == controls.brushHeight) {\n scatterPlots.brush.brushHeight = e.value;\n } else if (e.target == controls.brushWidth) {\n scatterPlots.brush.brushWidth = e.value;\n } else if (e.target == controls.pointRadius) {\n scatterPlots.pointRadius = e.value;\n scatterPlots.redrawPlotter();\n } else if (e.target == controls.amp) {\n sonifier.amp = e.value;\n } else if (e.target == controls.sustain) {\n sonifier.sustain = e.value;\n } else if (e.target == controls.freqBase) {\n sonifier.freqBase = e.value;\n }\n}\nprevent auto-selecting the first sound if there are none loaded\/\/ Copyright 2015 Chris Sattinger\n#include \"ofApp.h\"\n#include \"ofMain.h\"\n#include \n#include \"style.h\"\n\n\/\/--------------------------------------------------------------\nvoid ofApp::setup() {\n ofSetVerticalSync(true);\n ofSetFrameRate(60);\n\n ofAddListener(dataSource.didLoadEvent, this, &ofApp::dataSourceDidLoad);\n\n windowResized(ofGetWidth(), ofGetHeight());\n\n if (sonifier.sound() == \"\") {\n if (superCollider.synthDefs.size() > 0) {\n sonifier.selectSynthDef(0);\n }\n }\n \n setupGui();\n}\n\nvoid ofApp::setupGui() {\n gui = new ofxDatGui(ofxDatGuiAnchor::TOP_RIGHT);\n controls.loadButton = gui->addButton(\"Click to load dataset\");\n controls.selectSound = gui->addDropdown(\"Sound\", superCollider.defNames());\n controls.selectSound->select(0); \/\/ what is actual index of current sound ?\n controls.pointRadius = gui->addSlider(\"Point radius\", 1, 6, scatterPlots.pointRadius);\n controls.brushWidth = gui->addSlider(\"Brush Width\", 1, 15, scatterPlots.brush.brushWidth);\n controls.brushHeight = gui->addSlider(\"Brush Height\", 1, 15, scatterPlots.brush.brushHeight);\n controls.amp = gui->addSlider(\"Amp\", 0.0, 1.0, sonifier.amp);\n controls.sustain = gui->addSlider(\"Sustain\", 0.005, 1.0, sonifier.sustain);\n controls.freqBase = gui->addSlider(\"Freq\", 220, 3520, sonifier.freqBase);\n\n \/\/ gui->addColorPicker(\"Brush Color\", engagedPointColor);\n gui->addFRM(1.0f);\n\n gui->onButtonEvent(this, &ofApp::onOfxDatGuiButtonEvent);\n gui->onSliderEvent(this, &ofApp::onOfxDatGuiSliderEvent);\n gui->onDropdownEvent(this, &ofApp::onOfxDatGuiDropdownEvent);\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::update() {\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::draw() {\n ofBackground(settingsBackground);\n scatterPlots.draw();\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::keyPressed(int key) {\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::keyReleased(int key) {\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseMoved(int x, int y) {\n scatterPlots.brush.mouseMoved(x, ofGetHeight() - y);\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseDragged(int x, int y, int button) {\n scatterPlots.brush.mouseDragged(x, ofGetHeight() - y, button);\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mousePressed(int x, int y, int button) {\n scatterPlots.brush.mousePressed(x, ofGetHeight() - y, button);\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseReleased(int x, int y, int button) {\n scatterPlots.brush.mouseReleased(x, ofGetHeight() - y, button);\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseEntered(int x, int y) {\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseExited(int x, int y) {\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::windowResized(int w, int h) {\n const double panelWidth = 310;\n auto rect = ofRectangle(0, 0, w - panelWidth - gutter - gutter, h);\n scatterPlots.setFrame(rect);\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::gotMessage(ofMessage msg) {\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::dragEvent(ofDragInfo dragInfo) {\n auto path = dragInfo.files.at(dragInfo.files.size() - 1);\n dataSource.load(path);\n}\n\nvoid ofApp::dataSourceDidLoad() {\n scatterPlots.setData(dataSource);\n controls.loadButton->setLabel(dataSource.title);\n}\n\n\nvoid ofApp::onOfxDatGuiButtonEvent(ofxDatGuiButtonEvent e) {\n if (e.target == controls.loadButton) {\n \/\/ initial load file dialog\n }\n}\n\nvoid ofApp::onOfxDatGuiDropdownEvent(ofxDatGuiDropdownEvent e) {\n if (e.target == controls.selectSound) {\n sonifier.selectSynthDef(e.child);\n }\n}\n\nvoid ofApp::onOfxDatGuiSliderEvent(ofxDatGuiSliderEvent e) {\n if (e.target == controls.brushHeight) {\n scatterPlots.brush.brushHeight = e.value;\n } else if (e.target == controls.brushWidth) {\n scatterPlots.brush.brushWidth = e.value;\n } else if (e.target == controls.pointRadius) {\n scatterPlots.pointRadius = e.value;\n scatterPlots.redrawPlotter();\n } else if (e.target == controls.amp) {\n sonifier.amp = e.value;\n } else if (e.target == controls.sustain) {\n sonifier.sustain = e.value;\n } else if (e.target == controls.freqBase) {\n sonifier.freqBase = e.value;\n }\n}\n<|endoftext|>"} {"text":"#include \n#include \"btree.h\"\n\nusing namespace std;\n\nint main(int argc, char** argv)\n{\n {\n btree index;\n for (int i = 0; i < 8; i++)\n {\n index.insert(8 - i, i + 1);\n index.print();\n cout << \"====================\" << endl;\n }\n\n index.remove(5);\n\n cout << \"After remove\" << endl;\n index.print();\n\n }\n\n return 0;\n}Randomized testing found interesting access violation#include \n#include \n#include \n#include \n#include \"btree.h\"\n\nusing namespace std;\n\nint main(int argc, char** argv)\n{\n map reference;\n btree tree;\n srand(0);\n int min_key = -30;\n int max_key = 30;\n for (int i = 0; i < 1000; i++)\n {\n int operation = rand() % 3;\n switch (operation)\n {\n case 0:\n {\n int key_to_insert = rand() % (max_key - min_key) + min_key;\n int val_to_insert = rand() % (max_key - min_key) + min_key;\n bool insertion_result = tree.insert(key_to_insert, val_to_insert);\n if (reference.find(key_to_insert) == reference.end())\n {\n reference.insert(make_pair(key_to_insert, val_to_insert));\n assert(insertion_result);\n }\n else\n {\n assert(!insertion_result);\n }\n }\n break;\n case 1:\n {\n int key_to_remove = rand() % (max_key - min_key) + min_key;\n bool remove_result = tree.remove(key_to_remove);\n if (reference.find(key_to_remove) != reference.end())\n {\n reference.erase(key_to_remove);\n assert(remove_result);\n }\n else\n {\n assert(!remove_result);\n }\n }\n break;\n case 2:\n {\n int select_answer;\n int key_to_select = rand() % (max_key - min_key) + min_key;\n bool select_result = tree.select(key_to_select, &select_answer);\n if (reference.find(key_to_select) != reference.end())\n {\n assert(select_result);\n assert(reference[key_to_select] == select_answer);\n }\n else\n {\n assert(!select_result);\n }\n\n break;\n }\n }\n\n }\n\n return 0;\n}<|endoftext|>"} {"text":"\/\/ statTemplates.cpp : Defines the entry point for the DLL application.\n\/\/\n\n#include \"statTemplates.h\"\n#include \"bzfsAPI.h\"\n#include \"plugin_utils.h\"\n\ndouble start;\nstd::string getFileHeader ( void )\n{\n start = bz_getCurrentTime();\n std::string page =\"<\/HEAD>\\n
\\n\";\n\n std::string publicAddr = bz_getPublicAddr().c_str();\n page = \"Stats for\";\n page += publicAddr + \"
\\n\";\n\n return page;\n}\n\nstd::string getFileFooter ( void )\n{\n return format(\"


Page generated by webstats in %f seconds\\n\",bz_getCurrentTime()-start);\n}\n\n\n\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\nAdd blank before servername\/\/ statTemplates.cpp : Defines the entry point for the DLL application.\n\/\/\n\n#include \"statTemplates.h\"\n#include \"bzfsAPI.h\"\n#include \"plugin_utils.h\"\n\ndouble start;\nstd::string getFileHeader ( void )\n{\n start = bz_getCurrentTime();\n std::string page =\"<\/HEAD>\\n
\\n\";\n\n std::string publicAddr = bz_getPublicAddr().c_str();\n page = \"Stats for \";\n page += publicAddr + \"
\\n\";\n\n return page;\n}\n\nstd::string getFileFooter ( void )\n{\n return format(\"

Page generated by webstats in %f seconds\\n\",bz_getCurrentTime()-start);\n}\n\n\n\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<|endoftext|>"} {"text":"#define EXTERN_DLL_EXPORT \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\nconst int PATH_MAXIMUM_LENGTH = 260;\n\nenum class RequestFunction\n{\n\tIsProcessValid,\n\tOpenRemoteProcess,\n\tCloseRemoteProcess,\n\tReadRemoteMemory,\n\tWriteRemoteMemory,\n\tEnumerateProcesses,\n\tEnumerateRemoteSectionsAndModules\n};\n\ntypedef LPVOID(__stdcall *RequestFunctionPtrCallback)(RequestFunction request);\nRequestFunctionPtrCallback requestFunction;\n\nEXTERN_DLL_EXPORT VOID __stdcall Initialize(RequestFunctionPtrCallback requestCallback)\n{\n\trequestFunction = requestCallback;\n}\n\nDWORD lastError = 0;\nEXTERN_DLL_EXPORT DWORD __stdcall GetLastErrorCode()\n{\n\treturn lastError;\n}\n\nEXTERN_DLL_EXPORT BOOL __stdcall IsProcessValid(HANDLE process)\n{\n\tif (!process)\n\t{\n\t\treturn FALSE;\n\t}\n\n\tauto retn = WaitForSingleObject(process, 0);\n\tif (retn == WAIT_FAILED)\n\t{\n\t\treturn FALSE;\n\t}\n\treturn retn == WAIT_TIMEOUT;\n}\n\nEXTERN_DLL_EXPORT LPVOID __stdcall OpenRemoteProcess(DWORD pid, DWORD desiredAccess)\n{\n\treturn OpenProcess(desiredAccess, FALSE, pid);\n}\n\nEXTERN_DLL_EXPORT VOID __stdcall CloseRemoteProcess(HANDLE process)\n{\n\tCloseHandle(process);\n}\n\nEXTERN_DLL_EXPORT BOOL __stdcall ReadRemoteMemory(HANDLE process, LPCVOID address, LPVOID buffer, SIZE_T size)\n{\n\tif (ReadProcessMemory(process, address, buffer, size, nullptr))\n\t{\n\t\tlastError = 0;\n\n\t\treturn TRUE;\n\t}\n\n\tlastError = GetLastError();\n\n\treturn FALSE;\n}\n\nEXTERN_DLL_EXPORT BOOL __stdcall WriteRemoteMemory(HANDLE process, LPVOID address, LPCVOID buffer, SIZE_T size)\n{\n\tDWORD oldProtect;\n\tif (VirtualProtectEx(process, address, size, PAGE_EXECUTE_READWRITE, &oldProtect))\n\t{\n\t\tif (WriteProcessMemory(process, address, buffer, size, nullptr))\n\t\t{\n\t\t\tVirtualProtectEx(process, address, size, oldProtect, nullptr);\n\n\t\t\tlastError = 0;\n\n\t\t\treturn TRUE;\n\t\t}\n\t}\n\n\tlastError = GetLastError();\n\n\treturn FALSE;\n}\n\nenum class Platform\n{\n\tUnknown,\n\tX86,\n\tX64\n};\n\nPlatform GetProcessPlatform(HANDLE process)\n{\n\tauto GetProcessorArchitecture = []()\n\t{\n\t\tstatic USHORT processorArchitecture = PROCESSOR_ARCHITECTURE_UNKNOWN;\n\t\tif (processorArchitecture == PROCESSOR_ARCHITECTURE_UNKNOWN)\n\t\t{\n\t\t\tSYSTEM_INFO info = {};\n\t\t\tGetNativeSystemInfo(&info);\n\n\t\t\tprocessorArchitecture = info.wProcessorArchitecture;\n\t\t}\n\t\treturn processorArchitecture;\n\t};\n\n\tswitch (GetProcessorArchitecture())\n\t{\n\t\tcase PROCESSOR_ARCHITECTURE_INTEL:\n\t\t\treturn Platform::X86;\n\t\tcase PROCESSOR_ARCHITECTURE_AMD64:\n\t\t\tBOOL isWow64 = FALSE;\n\t\t\tif (IsWow64Process(process, &isWow64))\n\t\t\t{\n\t\t\t\treturn isWow64 ? Platform::X86 : Platform::X64;\n\t\t\t}\n\n#ifdef _WIN64\n\t\t\treturn Platform::X64;\n#else\n\t\t\treturn Platform::X86;\n#endif\n\t}\n\treturn Platform::Unknown;\n}\n\ntypedef VOID(__stdcall EnumerateProcessCallback)(DWORD pid, WCHAR modulePath[PATH_MAXIMUM_LENGTH]);\n\nEXTERN_DLL_EXPORT VOID __stdcall EnumerateProcesses(EnumerateProcessCallback callbackProcess)\n{\n\tif (callbackProcess == nullptr)\n\t{\n\t\treturn;\n\t}\n\n\tauto handle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);\n\tif (handle != INVALID_HANDLE_VALUE)\n\t{\n\t\tPROCESSENTRY32W pe32 = {};\n\t\tpe32.dwSize = sizeof(PROCESSENTRY32W);\n\t\tif (Process32FirstW(handle, &pe32))\n\t\t{\n\t\t\tauto openRemoteProcess = reinterpret_cast(requestFunction(RequestFunction::OpenRemoteProcess));\n\t\t\tauto closeRemoteProcess = reinterpret_cast(requestFunction(RequestFunction::CloseRemoteProcess));\n\n\t\t\tdo\n\t\t\t{\n\t\t\t\tauto process = openRemoteProcess(pe32.th32ProcessID, PROCESS_QUERY_INFORMATION | PROCESS_VM_READ);\n\t\t\t\tif (process != nullptr && process != INVALID_HANDLE_VALUE)\n\t\t\t\t{\n\t\t\t\t\tauto platform = GetProcessPlatform(process);\n\t\t\t\t\t\n#ifdef _WIN64\n\t\t\t\t\tif (platform == Platform::X64)\n#else\n\t\t\t\t\tif (platform == Platform::X86)\n#endif\n\t\t\t\t\t{\n\t\t\t\t\t\tWCHAR process_path[MAX_PATH] = { };\n\t\t\t\t\t\tGetModuleFileNameExW(process, NULL, process_path, MAX_PATH);\n\n\t\t\t\t\t\tcallbackProcess(pe32.th32ProcessID, process_path);\n\t\t\t\t\t}\n\n\t\t\t\t\tcloseRemoteProcess(process);\n\t\t\t\t}\n\t\t\t} while (Process32NextW(handle, &pe32));\n\t\t}\n\n\t\tCloseHandle(handle);\n\n\t\tlastError = 0;\n\n\t\treturn;\n\t}\n\n\tlastError = GetLastError();\n}\n\ntypedef VOID(__stdcall EnumerateRemoteSectionsCallback)(LPVOID baseAddress, SIZE_T regionSize, BYTE name[IMAGE_SIZEOF_SHORT_NAME + 2], DWORD state, DWORD protection, DWORD type, WCHAR modulePath[PATH_MAXIMUM_LENGTH]);\ntypedef VOID(__stdcall EnumerateRemoteModulesCallback)(LPVOID baseAddress, SIZE_T regionSize, WCHAR modulePath[PATH_MAXIMUM_LENGTH]);\n\nEXTERN_DLL_EXPORT VOID __stdcall EnumerateRemoteSectionsAndModules(HANDLE process, EnumerateRemoteSectionsCallback callbackSection, EnumerateRemoteModulesCallback callbackModule)\n{\n\tif (callbackSection == nullptr && callbackModule == nullptr)\n\t{\n\t\treturn;\n\t}\n\n\tstruct SectionInfo\n\t{\n\t\tLPVOID BaseAddress;\n\t\tSIZE_T RegionSize;\n\t\tBYTE Name[IMAGE_SIZEOF_SHORT_NAME + 2];\n\t\tDWORD State;\n\t\tDWORD Protection;\n\t\tDWORD Type;\n\t\tWCHAR ModulePath[PATH_MAXIMUM_LENGTH];\n\t};\n\tstd::vector sections;\n\n\tSYSTEM_INFO sysInfo;\n\tGetSystemInfo(&sysInfo);\n\n\tMEMORY_BASIC_INFORMATION memInfo;\n\tsize_t address = (size_t)sysInfo.lpMinimumApplicationAddress;\n\twhile (address < (size_t)sysInfo.lpMaximumApplicationAddress)\n\t{\n\t\tif (VirtualQueryEx(process, (LPCVOID)address, &memInfo, sizeof(MEMORY_BASIC_INFORMATION)) != 0)\n\t\t{\n\t\t\tif (memInfo.State == MEM_COMMIT \/*&& memInfo.Type == MEM_PRIVATE*\/)\n\t\t\t{\n\t\t\t\tSectionInfo section = {};\n\t\t\t\tsection.BaseAddress = memInfo.BaseAddress;\n\t\t\t\tsection.RegionSize = memInfo.RegionSize;\n\t\t\t\tsection.State = memInfo.State;\n\t\t\t\tsection.Protection = memInfo.Protect;\n\t\t\t\tsection.Type = memInfo.Type;\n\n\t\t\t\tsections.push_back(std::move(section));\n\t\t\t}\n\t\t\taddress = (ULONG_PTR)memInfo.BaseAddress + memInfo.RegionSize;\n\t\t}\n\t\telse\n\t\t{\n\t\t\taddress += 1024;\n\t\t}\n\t}\n\n\tauto handle = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, GetProcessId(process));\n\tif (handle != INVALID_HANDLE_VALUE)\n\t{\n\t\tMODULEENTRY32W me32 = {};\n\t\tme32.dwSize = sizeof(MODULEENTRY32W);\n\t\tif (Module32FirstW(handle, &me32))\n\t\t{\n\t\t\tauto readRemoteMemory = reinterpret_cast(requestFunction(RequestFunction::ReadRemoteMemory));\n\n\t\t\tdo\n\t\t\t{\n\t\t\t\tif (callbackModule != nullptr)\n\t\t\t\t{\n\t\t\t\t\tcallbackModule(me32.modBaseAddr, me32.modBaseSize, me32.szExePath);\n\t\t\t\t}\n\n\t\t\t\tif (callbackSection != nullptr)\n\t\t\t\t{\n\t\t\t\t\tauto it = std::lower_bound(std::begin(sections), std::end(sections), (LPVOID)me32.modBaseAddr, [§ions](const SectionInfo& lhs, const LPVOID& rhs)\n\t\t\t\t\t{\n\t\t\t\t\t\treturn lhs.BaseAddress < rhs;\n\t\t\t\t\t});\n\n\t\t\t\t\tIMAGE_DOS_HEADER DosHdr = {};\n\t\t\t\t\tIMAGE_NT_HEADERS NtHdr = {};\n\n\t\t\t\t\treadRemoteMemory(process, me32.modBaseAddr, &DosHdr, sizeof(IMAGE_DOS_HEADER));\n\t\t\t\t\treadRemoteMemory(process, me32.modBaseAddr + DosHdr.e_lfanew, &NtHdr, sizeof(IMAGE_NT_HEADERS));\n\n\t\t\t\t\tstd::vector sectionHeaders(NtHdr.FileHeader.NumberOfSections);\n\t\t\t\t\treadRemoteMemory(process, me32.modBaseAddr + DosHdr.e_lfanew + sizeof(IMAGE_NT_HEADERS), sectionHeaders.data(), NtHdr.FileHeader.NumberOfSections * sizeof(IMAGE_SECTION_HEADER));\n\t\t\t\t\tfor (int i = 0; i < NtHdr.FileHeader.NumberOfSections; ++i)\n\t\t\t\t\t{\n\t\t\t\t\t\tauto&& section = sectionHeaders[i];\n\n\t\t\t\t\t\tauto sectionAddress = (size_t)me32.modBaseAddr + section.VirtualAddress;\n\t\t\t\t\t\tfor (auto j = it; j != std::end(sections); ++j)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (sectionAddress >= (size_t)j->BaseAddress && sectionAddress <= (size_t)j->BaseAddress + (size_t)j->RegionSize)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tstd::memcpy(j->Name, section.Name, IMAGE_SIZEOF_SHORT_NAME);\n\t\t\t\t\t\t\t\tstd::memcpy(j->ModulePath, me32.szExePath, sizeof(SectionInfo::ModulePath));\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} while (Module32NextW(handle, &me32));\n\t\t}\n\n\t\tCloseHandle(handle);\n\n\t\tif (callbackSection != nullptr)\n\t\t{\n\t\t\tfor (auto&& section : sections)\n\t\t\t{\n\t\t\t\tcallbackSection(section.BaseAddress, section.RegionSize, section.Name, section.State, section.Protection, section.Type, section.ModulePath);\n\t\t\t}\n\t\t}\n\n\t\tlastError = 0;\n\n\t\treturn;\n\t}\n\n\tlastError = GetLastError();\n}\n\ntypedef VOID(__stdcall DisassembleRemoteCodeCallback)(LPVOID address, DWORD length, CHAR instruction[64]);\n\nEXTERN_DLL_EXPORT VOID __stdcall DisassembleRemoteCode(HANDLE process, LPVOID address, int length, DisassembleRemoteCodeCallback callbackDisassembledCode)\n{\n\tif (callbackDisassembledCode == nullptr)\n\t{\n\t\treturn;\n\t}\n\n\tUIntPtr start = (UIntPtr)address;\n\tUIntPtr end = start + length;\n\tif (end <= start)\n\t{\n\t\treturn;\n\t}\n\n\tDISASM disasm;\n\tstd::memset(&disasm, 0, sizeof(DISASM));\n\tdisasm.Options = NasmSyntax + PrefixedNumeral;\n#ifdef _WIN64\n\tdisasm.Archi = 64;\n#endif\n\n\tauto readRemoteMemory = reinterpret_cast(requestFunction(RequestFunction::ReadRemoteMemory));\n\n\tstd::vector buffer(length);\n\treadRemoteMemory(process, address, buffer.data(), buffer.size());\n\n\tdisasm.EIP = (UIntPtr)buffer.data();\n\tdisasm.VirtualAddr = start;\n\n\twhile (true)\n\t{\n\t\tdisasm.SecurityBlock = ((UIntPtr)buffer.data() + buffer.size()) - disasm.EIP;\n\n\t\tauto disamLength = Disasm(&disasm);\n\t\tif (disamLength == OUT_OF_BLOCK || disamLength == UNKNOWN_OPCODE)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\n\t\tcallbackDisassembledCode((LPVOID)disasm.VirtualAddr, disamLength, disasm.CompleteInstr);\n\n\t\tdisasm.EIP += disamLength;\n\t\tif (disasm.EIP >= end)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t\tdisasm.VirtualAddr += disamLength;\n\t}\n}\nFixed wrong section mapping.#define EXTERN_DLL_EXPORT \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\nconst int PATH_MAXIMUM_LENGTH = 260;\n\nenum class RequestFunction\n{\n\tIsProcessValid,\n\tOpenRemoteProcess,\n\tCloseRemoteProcess,\n\tReadRemoteMemory,\n\tWriteRemoteMemory,\n\tEnumerateProcesses,\n\tEnumerateRemoteSectionsAndModules\n};\n\ntypedef LPVOID(__stdcall *RequestFunctionPtrCallback)(RequestFunction request);\nRequestFunctionPtrCallback requestFunction;\n\nEXTERN_DLL_EXPORT VOID __stdcall Initialize(RequestFunctionPtrCallback requestCallback)\n{\n\trequestFunction = requestCallback;\n}\n\nDWORD lastError = 0;\nEXTERN_DLL_EXPORT DWORD __stdcall GetLastErrorCode()\n{\n\treturn lastError;\n}\n\nEXTERN_DLL_EXPORT BOOL __stdcall IsProcessValid(HANDLE process)\n{\n\tif (!process)\n\t{\n\t\treturn FALSE;\n\t}\n\n\tauto retn = WaitForSingleObject(process, 0);\n\tif (retn == WAIT_FAILED)\n\t{\n\t\treturn FALSE;\n\t}\n\treturn retn == WAIT_TIMEOUT;\n}\n\nEXTERN_DLL_EXPORT LPVOID __stdcall OpenRemoteProcess(DWORD pid, DWORD desiredAccess)\n{\n\treturn OpenProcess(desiredAccess, FALSE, pid);\n}\n\nEXTERN_DLL_EXPORT VOID __stdcall CloseRemoteProcess(HANDLE process)\n{\n\tCloseHandle(process);\n}\n\nEXTERN_DLL_EXPORT BOOL __stdcall ReadRemoteMemory(HANDLE process, LPCVOID address, LPVOID buffer, SIZE_T size)\n{\n\tif (ReadProcessMemory(process, address, buffer, size, nullptr))\n\t{\n\t\tlastError = 0;\n\n\t\treturn TRUE;\n\t}\n\n\tlastError = GetLastError();\n\n\treturn FALSE;\n}\n\nEXTERN_DLL_EXPORT BOOL __stdcall WriteRemoteMemory(HANDLE process, LPVOID address, LPCVOID buffer, SIZE_T size)\n{\n\tDWORD oldProtect;\n\tif (VirtualProtectEx(process, address, size, PAGE_EXECUTE_READWRITE, &oldProtect))\n\t{\n\t\tif (WriteProcessMemory(process, address, buffer, size, nullptr))\n\t\t{\n\t\t\tVirtualProtectEx(process, address, size, oldProtect, nullptr);\n\n\t\t\tlastError = 0;\n\n\t\t\treturn TRUE;\n\t\t}\n\t}\n\n\tlastError = GetLastError();\n\n\treturn FALSE;\n}\n\nenum class Platform\n{\n\tUnknown,\n\tX86,\n\tX64\n};\n\nPlatform GetProcessPlatform(HANDLE process)\n{\n\tauto GetProcessorArchitecture = []()\n\t{\n\t\tstatic USHORT processorArchitecture = PROCESSOR_ARCHITECTURE_UNKNOWN;\n\t\tif (processorArchitecture == PROCESSOR_ARCHITECTURE_UNKNOWN)\n\t\t{\n\t\t\tSYSTEM_INFO info = {};\n\t\t\tGetNativeSystemInfo(&info);\n\n\t\t\tprocessorArchitecture = info.wProcessorArchitecture;\n\t\t}\n\t\treturn processorArchitecture;\n\t};\n\n\tswitch (GetProcessorArchitecture())\n\t{\n\t\tcase PROCESSOR_ARCHITECTURE_INTEL:\n\t\t\treturn Platform::X86;\n\t\tcase PROCESSOR_ARCHITECTURE_AMD64:\n\t\t\tBOOL isWow64 = FALSE;\n\t\t\tif (IsWow64Process(process, &isWow64))\n\t\t\t{\n\t\t\t\treturn isWow64 ? Platform::X86 : Platform::X64;\n\t\t\t}\n\n#ifdef _WIN64\n\t\t\treturn Platform::X64;\n#else\n\t\t\treturn Platform::X86;\n#endif\n\t}\n\treturn Platform::Unknown;\n}\n\ntypedef VOID(__stdcall EnumerateProcessCallback)(DWORD pid, WCHAR modulePath[PATH_MAXIMUM_LENGTH]);\n\nEXTERN_DLL_EXPORT VOID __stdcall EnumerateProcesses(EnumerateProcessCallback callbackProcess)\n{\n\tif (callbackProcess == nullptr)\n\t{\n\t\treturn;\n\t}\n\n\tauto handle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);\n\tif (handle != INVALID_HANDLE_VALUE)\n\t{\n\t\tPROCESSENTRY32W pe32 = {};\n\t\tpe32.dwSize = sizeof(PROCESSENTRY32W);\n\t\tif (Process32FirstW(handle, &pe32))\n\t\t{\n\t\t\tauto openRemoteProcess = reinterpret_cast(requestFunction(RequestFunction::OpenRemoteProcess));\n\t\t\tauto closeRemoteProcess = reinterpret_cast(requestFunction(RequestFunction::CloseRemoteProcess));\n\n\t\t\tdo\n\t\t\t{\n\t\t\t\tauto process = openRemoteProcess(pe32.th32ProcessID, PROCESS_QUERY_INFORMATION | PROCESS_VM_READ);\n\t\t\t\tif (process != nullptr && process != INVALID_HANDLE_VALUE)\n\t\t\t\t{\n\t\t\t\t\tauto platform = GetProcessPlatform(process);\n\t\t\t\t\t\n#ifdef _WIN64\n\t\t\t\t\tif (platform == Platform::X64)\n#else\n\t\t\t\t\tif (platform == Platform::X86)\n#endif\n\t\t\t\t\t{\n\t\t\t\t\t\tWCHAR process_path[MAX_PATH] = { };\n\t\t\t\t\t\tGetModuleFileNameExW(process, NULL, process_path, MAX_PATH);\n\n\t\t\t\t\t\tcallbackProcess(pe32.th32ProcessID, process_path);\n\t\t\t\t\t}\n\n\t\t\t\t\tcloseRemoteProcess(process);\n\t\t\t\t}\n\t\t\t} while (Process32NextW(handle, &pe32));\n\t\t}\n\n\t\tCloseHandle(handle);\n\n\t\tlastError = 0;\n\n\t\treturn;\n\t}\n\n\tlastError = GetLastError();\n}\n\ntypedef VOID(__stdcall EnumerateRemoteSectionsCallback)(LPVOID baseAddress, SIZE_T regionSize, BYTE name[IMAGE_SIZEOF_SHORT_NAME + 2], DWORD state, DWORD protection, DWORD type, WCHAR modulePath[PATH_MAXIMUM_LENGTH]);\ntypedef VOID(__stdcall EnumerateRemoteModulesCallback)(LPVOID baseAddress, SIZE_T regionSize, WCHAR modulePath[PATH_MAXIMUM_LENGTH]);\n\nEXTERN_DLL_EXPORT VOID __stdcall EnumerateRemoteSectionsAndModules(HANDLE process, EnumerateRemoteSectionsCallback callbackSection, EnumerateRemoteModulesCallback callbackModule)\n{\n\tif (callbackSection == nullptr && callbackModule == nullptr)\n\t{\n\t\treturn;\n\t}\n\n\tstruct SectionInfo\n\t{\n\t\tLPVOID BaseAddress;\n\t\tSIZE_T RegionSize;\n\t\tBYTE Name[IMAGE_SIZEOF_SHORT_NAME + 2];\n\t\tDWORD State;\n\t\tDWORD Protection;\n\t\tDWORD Type;\n\t\tWCHAR ModulePath[PATH_MAXIMUM_LENGTH];\n\t};\n\tstd::vector sections;\n\n\tSYSTEM_INFO sysInfo;\n\tGetSystemInfo(&sysInfo);\n\n\tMEMORY_BASIC_INFORMATION memInfo;\n\tsize_t address = (size_t)sysInfo.lpMinimumApplicationAddress;\n\twhile (address < (size_t)sysInfo.lpMaximumApplicationAddress)\n\t{\n\t\tif (VirtualQueryEx(process, (LPCVOID)address, &memInfo, sizeof(MEMORY_BASIC_INFORMATION)) != 0)\n\t\t{\n\t\t\tif (memInfo.State == MEM_COMMIT \/*&& memInfo.Type == MEM_PRIVATE*\/)\n\t\t\t{\n\t\t\t\tSectionInfo section = {};\n\t\t\t\tsection.BaseAddress = memInfo.BaseAddress;\n\t\t\t\tsection.RegionSize = memInfo.RegionSize;\n\t\t\t\tsection.State = memInfo.State;\n\t\t\t\tsection.Protection = memInfo.Protect;\n\t\t\t\tsection.Type = memInfo.Type;\n\n\t\t\t\tsections.push_back(std::move(section));\n\t\t\t}\n\t\t\taddress = (ULONG_PTR)memInfo.BaseAddress + memInfo.RegionSize;\n\t\t}\n\t\telse\n\t\t{\n\t\t\taddress += 1024;\n\t\t}\n\t}\n\n\tauto handle = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, GetProcessId(process));\n\tif (handle != INVALID_HANDLE_VALUE)\n\t{\n\t\tMODULEENTRY32W me32 = {};\n\t\tme32.dwSize = sizeof(MODULEENTRY32W);\n\t\tif (Module32FirstW(handle, &me32))\n\t\t{\n\t\t\tauto readRemoteMemory = reinterpret_cast(requestFunction(RequestFunction::ReadRemoteMemory));\n\n\t\t\tdo\n\t\t\t{\n\t\t\t\tif (callbackModule != nullptr)\n\t\t\t\t{\n\t\t\t\t\tcallbackModule(me32.modBaseAddr, me32.modBaseSize, me32.szExePath);\n\t\t\t\t}\n\n\t\t\t\tif (callbackSection != nullptr)\n\t\t\t\t{\n\t\t\t\t\tauto it = std::lower_bound(std::begin(sections), std::end(sections), (LPVOID)me32.modBaseAddr, [§ions](const SectionInfo& lhs, const LPVOID& rhs)\n\t\t\t\t\t{\n\t\t\t\t\t\treturn lhs.BaseAddress < rhs;\n\t\t\t\t\t});\n\n\t\t\t\t\tIMAGE_DOS_HEADER DosHdr = {};\n\t\t\t\t\tIMAGE_NT_HEADERS NtHdr = {};\n\n\t\t\t\t\treadRemoteMemory(process, me32.modBaseAddr, &DosHdr, sizeof(IMAGE_DOS_HEADER));\n\t\t\t\t\treadRemoteMemory(process, me32.modBaseAddr + DosHdr.e_lfanew, &NtHdr, sizeof(IMAGE_NT_HEADERS));\n\n\t\t\t\t\tstd::vector sectionHeaders(NtHdr.FileHeader.NumberOfSections);\n\t\t\t\t\treadRemoteMemory(process, me32.modBaseAddr + DosHdr.e_lfanew + sizeof(IMAGE_NT_HEADERS), sectionHeaders.data(), NtHdr.FileHeader.NumberOfSections * sizeof(IMAGE_SECTION_HEADER));\n\t\t\t\t\tfor (int i = 0; i < NtHdr.FileHeader.NumberOfSections; ++i)\n\t\t\t\t\t{\n\t\t\t\t\t\tauto&& section = sectionHeaders[i];\n\n\t\t\t\t\t\tauto sectionAddress = (size_t)me32.modBaseAddr + section.VirtualAddress;\n\t\t\t\t\t\tfor (auto j = it; j != std::end(sections); ++j)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (sectionAddress >= (size_t)j->BaseAddress && sectionAddress < (size_t)j->BaseAddress + (size_t)j->RegionSize)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tstd::memcpy(j->Name, section.Name, IMAGE_SIZEOF_SHORT_NAME);\n\t\t\t\t\t\t\t\tstd::memcpy(j->ModulePath, me32.szExePath, sizeof(SectionInfo::ModulePath));\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} while (Module32NextW(handle, &me32));\n\t\t}\n\n\t\tCloseHandle(handle);\n\n\t\tif (callbackSection != nullptr)\n\t\t{\n\t\t\tfor (auto&& section : sections)\n\t\t\t{\n\t\t\t\tcallbackSection(section.BaseAddress, section.RegionSize, section.Name, section.State, section.Protection, section.Type, section.ModulePath);\n\t\t\t}\n\t\t}\n\n\t\tlastError = 0;\n\n\t\treturn;\n\t}\n\n\tlastError = GetLastError();\n}\n\ntypedef VOID(__stdcall DisassembleRemoteCodeCallback)(LPVOID address, DWORD length, CHAR instruction[64]);\n\nEXTERN_DLL_EXPORT VOID __stdcall DisassembleRemoteCode(HANDLE process, LPVOID address, int length, DisassembleRemoteCodeCallback callbackDisassembledCode)\n{\n\tif (callbackDisassembledCode == nullptr)\n\t{\n\t\treturn;\n\t}\n\n\tUIntPtr start = (UIntPtr)address;\n\tUIntPtr end = start + length;\n\tif (end <= start)\n\t{\n\t\treturn;\n\t}\n\n\tDISASM disasm;\n\tstd::memset(&disasm, 0, sizeof(DISASM));\n\tdisasm.Options = NasmSyntax + PrefixedNumeral;\n#ifdef _WIN64\n\tdisasm.Archi = 64;\n#endif\n\n\tauto readRemoteMemory = reinterpret_cast(requestFunction(RequestFunction::ReadRemoteMemory));\n\n\tstd::vector buffer(length);\n\treadRemoteMemory(process, address, buffer.data(), buffer.size());\n\n\tdisasm.EIP = (UIntPtr)buffer.data();\n\tdisasm.VirtualAddr = start;\n\n\twhile (true)\n\t{\n\t\tdisasm.SecurityBlock = ((UIntPtr)buffer.data() + buffer.size()) - disasm.EIP;\n\n\t\tauto disamLength = Disasm(&disasm);\n\t\tif (disamLength == OUT_OF_BLOCK || disamLength == UNKNOWN_OPCODE)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\n\t\tcallbackDisassembledCode((LPVOID)disasm.VirtualAddr, disamLength, disasm.CompleteInstr);\n\n\t\tdisasm.EIP += disamLength;\n\t\tif (disasm.EIP >= end)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t\tdisasm.VirtualAddr += disamLength;\n\t}\n}\n<|endoftext|>"} {"text":"\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n(Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\/\n\nCopyright (c) 2000-2006 Torus Knot Software Ltd\nAlso see acknowledgements in Readme.html\n\nThis program is free software; you can redistribute it and\/or modify it under\nthe terms of the GNU Lesser General Public License as published by the Free Software\nFoundation; either version 2 of the License, or (at your option) any later\nversion.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT\nANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\nFOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License along with\nthis program; if not, write to the Free Software Foundation, Inc., 59 Temple\nPlace - Suite 330, Boston, MA 02111-1307, USA, or go to\nhttp:\/\/www.gnu.org\/copyleft\/lesser.txt.\n\nYou may alternatively use this source under the terms of a specific version of\nthe OGRE Unrestricted License provided you have obtained such a license from\nTorus Knot Software Ltd.\n-----------------------------------------------------------------------------\n*\/\n#include \"OgreStableHeaders.h\"\n\n#include \"OgreZip.h\"\n\n#include \"OgreLogManager.h\"\n#include \"OgreException.h\"\n#include \"OgreStringVector.h\"\n#include \"OgreRoot.h\"\n\n#include \n\n\nnamespace Ogre {\n\n \/\/\/ Utility method to format out zzip errors\n String getZzipErrorDescription(zzip_error_t zzipError) \n {\n String errorMsg;\n switch (zzipError)\n {\n case ZZIP_NO_ERROR:\n break;\n case ZZIP_OUTOFMEM:\n errorMsg = \"Out of memory.\";\n break; \n case ZZIP_DIR_OPEN:\n case ZZIP_DIR_STAT: \n case ZZIP_DIR_SEEK:\n case ZZIP_DIR_READ:\n errorMsg = \"Unable to read zip file.\";\n break; \n case ZZIP_UNSUPP_COMPR:\n errorMsg = \"Unsupported compression format.\";\n break; \n case ZZIP_CORRUPTED:\n errorMsg = \"Corrupted archive.\";\n break; \n default:\n errorMsg = \"Unknown error.\";\n break; \n };\n\n return errorMsg;\n }\n \/\/-----------------------------------------------------------------------\n ZipArchive::ZipArchive(const String& name, const String& archType )\n : Archive(name, archType), mZzipDir(0)\n {\n }\n \/\/-----------------------------------------------------------------------\n ZipArchive::~ZipArchive()\n {\n unload();\n }\n \/\/-----------------------------------------------------------------------\n void ZipArchive::load()\n {\n if (!mZzipDir)\n {\n zzip_error_t zzipError;\n mZzipDir = zzip_dir_open(mName.c_str(), &zzipError);\n checkZzipError(zzipError, \"opening archive\");\n\n \/\/ Cache names\n ZZIP_DIRENT zzipEntry;\n while (zzip_dir_read(mZzipDir, &zzipEntry))\n {\n FileInfo info;\n\t\t\t\tinfo.archive = this;\n \/\/ Get basename \/ path\n StringUtil::splitFilename(zzipEntry.d_name, info.basename, info.path);\n info.filename = zzipEntry.d_name;\n \/\/ Get sizes\n info.compressedSize = static_cast(zzipEntry.d_csize);\n info.uncompressedSize = static_cast(zzipEntry.st_size);\n \/\/ folder entries\n if (info.basename.empty())\n {\n info.filename = info.filename.substr (0, info.filename.length () - 1);\n StringUtil::splitFilename(info.filename, info.basename, info.path);\n \/\/ Set compressed size to -1 for folders; anyway nobody will check\n \/\/ the compressed size of a folder, and if he does, its useless anyway\n info.compressedSize = size_t (-1);\n }\n\n mFileList.push_back(info);\n\n }\n\n }\n }\n \/\/-----------------------------------------------------------------------\n void ZipArchive::unload()\n {\n if (mZzipDir)\n {\n zzip_dir_close(mZzipDir);\n mZzipDir = 0;\n mFileList.clear();\n }\n \n }\n \/\/-----------------------------------------------------------------------\n\tDataStreamPtr ZipArchive::open(const String& filename) const\n {\n\n \/\/ Format not used here (always binary)\n ZZIP_FILE* zzipFile = \n zzip_file_open(mZzipDir, filename.c_str(), ZZIP_ONLYZIP | ZZIP_CASELESS);\n if (!zzipFile)\n\t\t{\n int zerr = zzip_error(mZzipDir);\n String zzDesc = getZzipErrorDescription((zzip_error_t)zerr);\n LogManager::getSingleton().logMessage(\n mName + \" - Unable to open file \" + filename + \", error was '\" + zzDesc + \"'\");\n \n\t\t\t\/\/ return null pointer\n\t\t\treturn DataStreamPtr();\n\t\t}\n\n\t\t\/\/ Get uncompressed size too\n\t\tZZIP_STAT zstat;\n\t\tzzip_dir_stat(mZzipDir, filename.c_str(), &zstat, ZZIP_CASEINSENSITIVE);\n\n \/\/ Construct & return stream\n return DataStreamPtr(OGRE_NEW ZipDataStream(filename, zzipFile, static_cast(zstat.st_size)));\n\n }\n \/\/-----------------------------------------------------------------------\n StringVectorPtr ZipArchive::list(bool recursive, bool dirs)\n {\n StringVectorPtr ret = StringVectorPtr(OGRE_NEW_T(StringVector, MEMCATEGORY_GENERAL)(), SPFM_DELETE_T);\n\n FileInfoList::iterator i, iend;\n iend = mFileList.end();\n for (i = mFileList.begin(); i != iend; ++i)\n if ((dirs == (i->compressedSize == size_t (-1))) &&\n (recursive || i->path.empty()))\n ret->push_back(i->filename);\n\n return ret;\n }\n \/\/-----------------------------------------------------------------------\n FileInfoListPtr ZipArchive::listFileInfo(bool recursive, bool dirs)\n {\n FileInfoList* fil = OGRE_NEW_T(FileInfoList, MEMCATEGORY_GENERAL)();\n FileInfoList::const_iterator i, iend;\n iend = mFileList.end();\n for (i = mFileList.begin(); i != iend; ++i)\n if ((dirs == (i->compressedSize == size_t (-1))) &&\n (recursive || i->path.empty()))\n fil->push_back(*i);\n\n return FileInfoListPtr(fil, SPFM_DELETE_T);\n }\n \/\/-----------------------------------------------------------------------\n StringVectorPtr ZipArchive::find(const String& pattern, bool recursive, bool dirs)\n {\n StringVectorPtr ret = StringVectorPtr(OGRE_NEW_T(StringVector, MEMCATEGORY_GENERAL)(), SPFM_DELETE_T);\n \/\/ If pattern contains a directory name, do a full match\n bool full_match = (pattern.find ('\/') != String::npos) ||\n (pattern.find ('\\\\') != String::npos);\n\n FileInfoList::iterator i, iend;\n iend = mFileList.end();\n for (i = mFileList.begin(); i != iend; ++i)\n if ((dirs == (i->compressedSize == size_t (-1))) &&\n (recursive || full_match || i->path.empty()))\n \/\/ Check basename matches pattern (zip is case insensitive)\n if (StringUtil::match(full_match ? i->filename : i->basename, pattern, false))\n ret->push_back(i->filename);\n\n return ret;\n }\n \/\/-----------------------------------------------------------------------\n\tFileInfoListPtr ZipArchive::findFileInfo(const String& pattern, \n bool recursive, bool dirs)\n {\n FileInfoListPtr ret = FileInfoListPtr(OGRE_NEW_T(FileInfoList, MEMCATEGORY_GENERAL)(), SPFM_DELETE_T);\n \/\/ If pattern contains a directory name, do a full match\n bool full_match = (pattern.find ('\/') != String::npos) ||\n (pattern.find ('\\\\') != String::npos);\n\n FileInfoList::iterator i, iend;\n iend = mFileList.end();\n for (i = mFileList.begin(); i != iend; ++i)\n if ((dirs == (i->compressedSize == size_t (-1))) &&\n (recursive || full_match || i->path.empty()))\n \/\/ Check name matches pattern (zip is case insensitive)\n if (StringUtil::match(full_match ? i->filename : i->basename, pattern, false))\n ret->push_back(*i);\n\n return ret;\n }\n \/\/-----------------------------------------------------------------------\n\tbool ZipArchive::exists(const String& filename)\n\t{\n\t\tZZIP_STAT zstat;\n\t\tint res = zzip_dir_stat(mZzipDir, filename.c_str(), &zstat, ZZIP_CASEINSENSITIVE);\n\n\t\treturn (res == ZZIP_NO_ERROR);\n\n\t}\n\t\/\/-----------------------------------------------------------------------\n void ZipArchive::checkZzipError(int zzipError, const String& operation) const\n {\n if (zzipError != ZZIP_NO_ERROR)\n {\n String errorMsg = getZzipErrorDescription(static_cast(zzipError));\n\n OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, \n mName + \" - error whilst \" + operation + \": \" + errorMsg,\n \"ZipArchive::checkZzipError\");\n }\n }\n \/\/-----------------------------------------------------------------------\n \/\/-----------------------------------------------------------------------\n \/\/-----------------------------------------------------------------------\n ZipDataStream::ZipDataStream(ZZIP_FILE* zzipFile, size_t uncompressedSize)\n : mZzipFile(zzipFile)\n {\n\t\tmSize = uncompressedSize;\n }\n \/\/-----------------------------------------------------------------------\n ZipDataStream::ZipDataStream(const String& name, ZZIP_FILE* zzipFile, size_t uncompressedSize)\n :DataStream(name), mZzipFile(zzipFile)\n {\n\t\tmSize = uncompressedSize;\n }\n \/\/-----------------------------------------------------------------------\n\tZipDataStream::~ZipDataStream()\n\t{\n\t\tclose();\n\t}\n \/\/-----------------------------------------------------------------------\n size_t ZipDataStream::read(void* buf, size_t count)\n {\n zzip_ssize_t r = zzip_file_read(mZzipFile, (char*)buf, count);\n if (r<0) {\n ZZIP_DIR *dir = zzip_dirhandle(mZzipFile);\n String msg = zzip_strerror_of(dir);\n OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR,\n mName+\" - error from zziplib: \"+msg,\n \"ZipDataStream::read\");\n }\n return (size_t) r;\n }\n \/\/-----------------------------------------------------------------------\n void ZipDataStream::skip(long count)\n {\n zzip_seek(mZzipFile, static_cast(count), SEEK_CUR);\n }\n \/\/-----------------------------------------------------------------------\n void ZipDataStream::seek( size_t pos )\n {\n\t\tzzip_seek(mZzipFile, static_cast(pos), SEEK_SET);\n }\n \/\/-----------------------------------------------------------------------\n size_t ZipDataStream::tell(void) const\n {\n\t\treturn zzip_tell(mZzipFile);\n }\n \/\/-----------------------------------------------------------------------\n bool ZipDataStream::eof(void) const\n {\n return (zzip_tell(mZzipFile) >= static_cast(mSize));\n }\n \/\/-----------------------------------------------------------------------\n void ZipDataStream::close(void)\n {\n zzip_file_close(mZzipFile);\n }\n \/\/-----------------------------------------------------------------------\n const String& ZipArchiveFactory::getType(void) const\n {\n static String name = \"Zip\";\n return name;\n }\n\n}\nTolerate someone calling ZDataStream::close before destruction\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n(Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\/\n\nCopyright (c) 2000-2006 Torus Knot Software Ltd\nAlso see acknowledgements in Readme.html\n\nThis program is free software; you can redistribute it and\/or modify it under\nthe terms of the GNU Lesser General Public License as published by the Free Software\nFoundation; either version 2 of the License, or (at your option) any later\nversion.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT\nANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\nFOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License along with\nthis program; if not, write to the Free Software Foundation, Inc., 59 Temple\nPlace - Suite 330, Boston, MA 02111-1307, USA, or go to\nhttp:\/\/www.gnu.org\/copyleft\/lesser.txt.\n\nYou may alternatively use this source under the terms of a specific version of\nthe OGRE Unrestricted License provided you have obtained such a license from\nTorus Knot Software Ltd.\n-----------------------------------------------------------------------------\n*\/\n#include \"OgreStableHeaders.h\"\n\n#include \"OgreZip.h\"\n\n#include \"OgreLogManager.h\"\n#include \"OgreException.h\"\n#include \"OgreStringVector.h\"\n#include \"OgreRoot.h\"\n\n#include \n\n\nnamespace Ogre {\n\n \/\/\/ Utility method to format out zzip errors\n String getZzipErrorDescription(zzip_error_t zzipError) \n {\n String errorMsg;\n switch (zzipError)\n {\n case ZZIP_NO_ERROR:\n break;\n case ZZIP_OUTOFMEM:\n errorMsg = \"Out of memory.\";\n break; \n case ZZIP_DIR_OPEN:\n case ZZIP_DIR_STAT: \n case ZZIP_DIR_SEEK:\n case ZZIP_DIR_READ:\n errorMsg = \"Unable to read zip file.\";\n break; \n case ZZIP_UNSUPP_COMPR:\n errorMsg = \"Unsupported compression format.\";\n break; \n case ZZIP_CORRUPTED:\n errorMsg = \"Corrupted archive.\";\n break; \n default:\n errorMsg = \"Unknown error.\";\n break; \n };\n\n return errorMsg;\n }\n \/\/-----------------------------------------------------------------------\n ZipArchive::ZipArchive(const String& name, const String& archType )\n : Archive(name, archType), mZzipDir(0)\n {\n }\n \/\/-----------------------------------------------------------------------\n ZipArchive::~ZipArchive()\n {\n unload();\n }\n \/\/-----------------------------------------------------------------------\n void ZipArchive::load()\n {\n if (!mZzipDir)\n {\n zzip_error_t zzipError;\n mZzipDir = zzip_dir_open(mName.c_str(), &zzipError);\n checkZzipError(zzipError, \"opening archive\");\n\n \/\/ Cache names\n ZZIP_DIRENT zzipEntry;\n while (zzip_dir_read(mZzipDir, &zzipEntry))\n {\n FileInfo info;\n\t\t\t\tinfo.archive = this;\n \/\/ Get basename \/ path\n StringUtil::splitFilename(zzipEntry.d_name, info.basename, info.path);\n info.filename = zzipEntry.d_name;\n \/\/ Get sizes\n info.compressedSize = static_cast(zzipEntry.d_csize);\n info.uncompressedSize = static_cast(zzipEntry.st_size);\n \/\/ folder entries\n if (info.basename.empty())\n {\n info.filename = info.filename.substr (0, info.filename.length () - 1);\n StringUtil::splitFilename(info.filename, info.basename, info.path);\n \/\/ Set compressed size to -1 for folders; anyway nobody will check\n \/\/ the compressed size of a folder, and if he does, its useless anyway\n info.compressedSize = size_t (-1);\n }\n\n mFileList.push_back(info);\n\n }\n\n }\n }\n \/\/-----------------------------------------------------------------------\n void ZipArchive::unload()\n {\n if (mZzipDir)\n {\n zzip_dir_close(mZzipDir);\n mZzipDir = 0;\n mFileList.clear();\n }\n \n }\n \/\/-----------------------------------------------------------------------\n\tDataStreamPtr ZipArchive::open(const String& filename) const\n {\n\n \/\/ Format not used here (always binary)\n ZZIP_FILE* zzipFile = \n zzip_file_open(mZzipDir, filename.c_str(), ZZIP_ONLYZIP | ZZIP_CASELESS);\n if (!zzipFile)\n\t\t{\n int zerr = zzip_error(mZzipDir);\n String zzDesc = getZzipErrorDescription((zzip_error_t)zerr);\n LogManager::getSingleton().logMessage(\n mName + \" - Unable to open file \" + filename + \", error was '\" + zzDesc + \"'\");\n \n\t\t\t\/\/ return null pointer\n\t\t\treturn DataStreamPtr();\n\t\t}\n\n\t\t\/\/ Get uncompressed size too\n\t\tZZIP_STAT zstat;\n\t\tzzip_dir_stat(mZzipDir, filename.c_str(), &zstat, ZZIP_CASEINSENSITIVE);\n\n \/\/ Construct & return stream\n return DataStreamPtr(OGRE_NEW ZipDataStream(filename, zzipFile, static_cast(zstat.st_size)));\n\n }\n \/\/-----------------------------------------------------------------------\n StringVectorPtr ZipArchive::list(bool recursive, bool dirs)\n {\n StringVectorPtr ret = StringVectorPtr(OGRE_NEW_T(StringVector, MEMCATEGORY_GENERAL)(), SPFM_DELETE_T);\n\n FileInfoList::iterator i, iend;\n iend = mFileList.end();\n for (i = mFileList.begin(); i != iend; ++i)\n if ((dirs == (i->compressedSize == size_t (-1))) &&\n (recursive || i->path.empty()))\n ret->push_back(i->filename);\n\n return ret;\n }\n \/\/-----------------------------------------------------------------------\n FileInfoListPtr ZipArchive::listFileInfo(bool recursive, bool dirs)\n {\n FileInfoList* fil = OGRE_NEW_T(FileInfoList, MEMCATEGORY_GENERAL)();\n FileInfoList::const_iterator i, iend;\n iend = mFileList.end();\n for (i = mFileList.begin(); i != iend; ++i)\n if ((dirs == (i->compressedSize == size_t (-1))) &&\n (recursive || i->path.empty()))\n fil->push_back(*i);\n\n return FileInfoListPtr(fil, SPFM_DELETE_T);\n }\n \/\/-----------------------------------------------------------------------\n StringVectorPtr ZipArchive::find(const String& pattern, bool recursive, bool dirs)\n {\n StringVectorPtr ret = StringVectorPtr(OGRE_NEW_T(StringVector, MEMCATEGORY_GENERAL)(), SPFM_DELETE_T);\n \/\/ If pattern contains a directory name, do a full match\n bool full_match = (pattern.find ('\/') != String::npos) ||\n (pattern.find ('\\\\') != String::npos);\n\n FileInfoList::iterator i, iend;\n iend = mFileList.end();\n for (i = mFileList.begin(); i != iend; ++i)\n if ((dirs == (i->compressedSize == size_t (-1))) &&\n (recursive || full_match || i->path.empty()))\n \/\/ Check basename matches pattern (zip is case insensitive)\n if (StringUtil::match(full_match ? i->filename : i->basename, pattern, false))\n ret->push_back(i->filename);\n\n return ret;\n }\n \/\/-----------------------------------------------------------------------\n\tFileInfoListPtr ZipArchive::findFileInfo(const String& pattern, \n bool recursive, bool dirs)\n {\n FileInfoListPtr ret = FileInfoListPtr(OGRE_NEW_T(FileInfoList, MEMCATEGORY_GENERAL)(), SPFM_DELETE_T);\n \/\/ If pattern contains a directory name, do a full match\n bool full_match = (pattern.find ('\/') != String::npos) ||\n (pattern.find ('\\\\') != String::npos);\n\n FileInfoList::iterator i, iend;\n iend = mFileList.end();\n for (i = mFileList.begin(); i != iend; ++i)\n if ((dirs == (i->compressedSize == size_t (-1))) &&\n (recursive || full_match || i->path.empty()))\n \/\/ Check name matches pattern (zip is case insensitive)\n if (StringUtil::match(full_match ? i->filename : i->basename, pattern, false))\n ret->push_back(*i);\n\n return ret;\n }\n \/\/-----------------------------------------------------------------------\n\tbool ZipArchive::exists(const String& filename)\n\t{\n\t\tZZIP_STAT zstat;\n\t\tint res = zzip_dir_stat(mZzipDir, filename.c_str(), &zstat, ZZIP_CASEINSENSITIVE);\n\n\t\treturn (res == ZZIP_NO_ERROR);\n\n\t}\n\t\/\/-----------------------------------------------------------------------\n void ZipArchive::checkZzipError(int zzipError, const String& operation) const\n {\n if (zzipError != ZZIP_NO_ERROR)\n {\n String errorMsg = getZzipErrorDescription(static_cast(zzipError));\n\n OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, \n mName + \" - error whilst \" + operation + \": \" + errorMsg,\n \"ZipArchive::checkZzipError\");\n }\n }\n \/\/-----------------------------------------------------------------------\n \/\/-----------------------------------------------------------------------\n \/\/-----------------------------------------------------------------------\n ZipDataStream::ZipDataStream(ZZIP_FILE* zzipFile, size_t uncompressedSize)\n : mZzipFile(zzipFile)\n {\n\t\tmSize = uncompressedSize;\n }\n \/\/-----------------------------------------------------------------------\n ZipDataStream::ZipDataStream(const String& name, ZZIP_FILE* zzipFile, size_t uncompressedSize)\n :DataStream(name), mZzipFile(zzipFile)\n {\n\t\tmSize = uncompressedSize;\n }\n \/\/-----------------------------------------------------------------------\n\tZipDataStream::~ZipDataStream()\n\t{\n\t\tclose();\n\t}\n \/\/-----------------------------------------------------------------------\n size_t ZipDataStream::read(void* buf, size_t count)\n {\n zzip_ssize_t r = zzip_file_read(mZzipFile, (char*)buf, count);\n if (r<0) {\n ZZIP_DIR *dir = zzip_dirhandle(mZzipFile);\n String msg = zzip_strerror_of(dir);\n OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR,\n mName+\" - error from zziplib: \"+msg,\n \"ZipDataStream::read\");\n }\n return (size_t) r;\n }\n \/\/-----------------------------------------------------------------------\n void ZipDataStream::skip(long count)\n {\n zzip_seek(mZzipFile, static_cast(count), SEEK_CUR);\n }\n \/\/-----------------------------------------------------------------------\n void ZipDataStream::seek( size_t pos )\n {\n\t\tzzip_seek(mZzipFile, static_cast(pos), SEEK_SET);\n }\n \/\/-----------------------------------------------------------------------\n size_t ZipDataStream::tell(void) const\n {\n\t\treturn zzip_tell(mZzipFile);\n }\n \/\/-----------------------------------------------------------------------\n bool ZipDataStream::eof(void) const\n {\n return (zzip_tell(mZzipFile) >= static_cast(mSize));\n }\n \/\/-----------------------------------------------------------------------\n void ZipDataStream::close(void)\n {\n\t\t\/\/ allow repeat calls\n\t\tif (mZzipFile)\n\t\t{\n\t\t\tzzip_file_close(mZzipFile);\n\t\t\tmZzipFile = 0;\n\t\t}\n }\n \/\/-----------------------------------------------------------------------\n const String& ZipArchiveFactory::getType(void) const\n {\n static String name = \"Zip\";\n return name;\n }\n\n}\n<|endoftext|>"} {"text":"\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n(Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\/\n\nCopyright (c) 2000-2006 Torus Knot Software Ltd\nAlso see acknowledgements in Readme.html\n\nThis program is free software; you can redistribute it and\/or modify it under\nthe terms of the GNU Lesser General Public License as published by the Free Software\nFoundation; either version 2 of the License, or (at your option) any later\nversion.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT\nANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\nFOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License along with\nthis program; if not, write to the Free Software Foundation, Inc., 59 Temple\nPlace - Suite 330, Boston, MA 02111-1307, USA, or go to\nhttp:\/\/www.gnu.org\/copyleft\/lesser.txt.\n\nYou may alternatively use this source under the terms of a specific version of\nthe OGRE Unrestricted License provided you have obtained such a license from\nTorus Knot Software Ltd.\n-----------------------------------------------------------------------------\n*\/\n#include \"OgreStableHeaders.h\"\n\n#include \"OgreZip.h\"\n\n#include \"OgreLogManager.h\"\n#include \"OgreException.h\"\n#include \"OgreStringVector.h\"\n#include \"OgreRoot.h\"\n\n#include \n\n\nnamespace Ogre {\n\n \/\/\/ Utility method to format out zzip errors\n String getZzipErrorDescription(zzip_error_t zzipError) \n {\n String errorMsg;\n switch (zzipError)\n {\n case ZZIP_NO_ERROR:\n break;\n case ZZIP_OUTOFMEM:\n errorMsg = \"Out of memory.\";\n break; \n case ZZIP_DIR_OPEN:\n case ZZIP_DIR_STAT: \n case ZZIP_DIR_SEEK:\n case ZZIP_DIR_READ:\n errorMsg = \"Unable to read zip file.\";\n break; \n case ZZIP_UNSUPP_COMPR:\n errorMsg = \"Unsupported compression format.\";\n break; \n case ZZIP_CORRUPTED:\n errorMsg = \"Corrupted archive.\";\n break; \n default:\n errorMsg = \"Unknown error.\";\n break; \n };\n\n return errorMsg;\n }\n \/\/-----------------------------------------------------------------------\n ZipArchive::ZipArchive(const String& name, const String& archType )\n : Archive(name, archType), mZzipDir(0)\n {\n }\n \/\/-----------------------------------------------------------------------\n ZipArchive::~ZipArchive()\n {\n unload();\n }\n \/\/-----------------------------------------------------------------------\n void ZipArchive::load()\n {\n if (!mZzipDir)\n {\n zzip_error_t zzipError;\n mZzipDir = zzip_dir_open(mName.c_str(), &zzipError);\n checkZzipError(zzipError, \"opening archive\");\n\n \/\/ Cache names\n ZZIP_DIRENT zzipEntry;\n while (zzip_dir_read(mZzipDir, &zzipEntry))\n {\n FileInfo info;\n\t\t\t\tinfo.archive = this;\n \/\/ Get basename \/ path\n StringUtil::splitFilename(zzipEntry.d_name, info.basename, info.path);\n info.filename = zzipEntry.d_name;\n \/\/ Get sizes\n info.compressedSize = static_cast(zzipEntry.d_csize);\n info.uncompressedSize = static_cast(zzipEntry.st_size);\n \/\/ folder entries\n if (info.basename.empty())\n {\n info.filename = info.filename.substr (0, info.filename.length () - 1);\n StringUtil::splitFilename(info.filename, info.basename, info.path);\n \/\/ Set compressed size to -1 for folders; anyway nobody will check\n \/\/ the compressed size of a folder, and if he does, its useless anyway\n info.compressedSize = size_t (-1);\n }\n\n mFileList.push_back(info);\n\n }\n\n }\n }\n \/\/-----------------------------------------------------------------------\n void ZipArchive::unload()\n {\n if (mZzipDir)\n {\n zzip_dir_close(mZzipDir);\n mZzipDir = 0;\n mFileList.clear();\n }\n \n }\n \/\/-----------------------------------------------------------------------\n\tDataStreamPtr ZipArchive::open(const String& filename) const\n {\n\n \/\/ Format not used here (always binary)\n ZZIP_FILE* zzipFile = \n zzip_file_open(mZzipDir, filename.c_str(), ZZIP_ONLYZIP | ZZIP_CASELESS);\n if (!zzipFile)\n\t\t{\n int zerr = zzip_error(mZzipDir);\n String zzDesc = getZzipErrorDescription((zzip_error_t)zerr);\n LogManager::getSingleton().logMessage(\n mName + \" - Unable to open file \" + filename + \", error was '\" + zzDesc + \"'\");\n \n\t\t\t\/\/ return null pointer\n\t\t\treturn DataStreamPtr();\n\t\t}\n\n\t\t\/\/ Get uncompressed size too\n\t\tZZIP_STAT zstat;\n\t\tzzip_dir_stat(mZzipDir, filename.c_str(), &zstat, ZZIP_CASEINSENSITIVE);\n\n \/\/ Construct & return stream\n return DataStreamPtr(OGRE_NEW ZipDataStream(filename, zzipFile, static_cast(zstat.st_size)));\n\n }\n \/\/-----------------------------------------------------------------------\n StringVectorPtr ZipArchive::list(bool recursive, bool dirs)\n {\n StringVectorPtr ret = StringVectorPtr(OGRE_NEW_T(StringVector, MEMCATEGORY_GENERAL)(), SPFM_DELETE_T);\n\n FileInfoList::iterator i, iend;\n iend = mFileList.end();\n for (i = mFileList.begin(); i != iend; ++i)\n if ((dirs == (i->compressedSize == size_t (-1))) &&\n (recursive || i->path.empty()))\n ret->push_back(i->filename);\n\n return ret;\n }\n \/\/-----------------------------------------------------------------------\n FileInfoListPtr ZipArchive::listFileInfo(bool recursive, bool dirs)\n {\n FileInfoList* fil = OGRE_NEW_T(FileInfoList, MEMCATEGORY_GENERAL)();\n FileInfoList::const_iterator i, iend;\n iend = mFileList.end();\n for (i = mFileList.begin(); i != iend; ++i)\n if ((dirs == (i->compressedSize == size_t (-1))) &&\n (recursive || i->path.empty()))\n fil->push_back(*i);\n\n return FileInfoListPtr(fil, SPFM_DELETE_T);\n }\n \/\/-----------------------------------------------------------------------\n StringVectorPtr ZipArchive::find(const String& pattern, bool recursive, bool dirs)\n {\n StringVectorPtr ret = StringVectorPtr(OGRE_NEW_T(StringVector, MEMCATEGORY_GENERAL)(), SPFM_DELETE_T);\n \/\/ If pattern contains a directory name, do a full match\n bool full_match = (pattern.find ('\/') != String::npos) ||\n (pattern.find ('\\\\') != String::npos);\n\n FileInfoList::iterator i, iend;\n iend = mFileList.end();\n for (i = mFileList.begin(); i != iend; ++i)\n if ((dirs == (i->compressedSize == size_t (-1))) &&\n (recursive || full_match || i->path.empty()))\n \/\/ Check basename matches pattern (zip is case insensitive)\n if (StringUtil::match(full_match ? i->filename : i->basename, pattern, false))\n ret->push_back(i->filename);\n\n return ret;\n }\n \/\/-----------------------------------------------------------------------\n\tFileInfoListPtr ZipArchive::findFileInfo(const String& pattern, \n bool recursive, bool dirs)\n {\n FileInfoListPtr ret = FileInfoListPtr(OGRE_NEW_T(FileInfoList, MEMCATEGORY_GENERAL)(), SPFM_DELETE_T);\n \/\/ If pattern contains a directory name, do a full match\n bool full_match = (pattern.find ('\/') != String::npos) ||\n (pattern.find ('\\\\') != String::npos);\n\n FileInfoList::iterator i, iend;\n iend = mFileList.end();\n for (i = mFileList.begin(); i != iend; ++i)\n if ((dirs == (i->compressedSize == size_t (-1))) &&\n (recursive || full_match || i->path.empty()))\n \/\/ Check name matches pattern (zip is case insensitive)\n if (StringUtil::match(full_match ? i->filename : i->basename, pattern, false))\n ret->push_back(*i);\n\n return ret;\n }\n \/\/-----------------------------------------------------------------------\n\tbool ZipArchive::exists(const String& filename)\n\t{\n\t\tZZIP_STAT zstat;\n\t\tint res = zzip_dir_stat(mZzipDir, filename.c_str(), &zstat, ZZIP_CASEINSENSITIVE);\n\n\t\treturn (res == ZZIP_NO_ERROR);\n\n\t}\n\t\/\/-----------------------------------------------------------------------\n void ZipArchive::checkZzipError(int zzipError, const String& operation) const\n {\n if (zzipError != ZZIP_NO_ERROR)\n {\n String errorMsg = getZzipErrorDescription(static_cast(zzipError));\n\n OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, \n mName + \" - error whilst \" + operation + \": \" + errorMsg,\n \"ZipArchive::checkZzipError\");\n }\n }\n \/\/-----------------------------------------------------------------------\n \/\/-----------------------------------------------------------------------\n \/\/-----------------------------------------------------------------------\n ZipDataStream::ZipDataStream(ZZIP_FILE* zzipFile, size_t uncompressedSize)\n : mZzipFile(zzipFile)\n {\n\t\tmSize = uncompressedSize;\n }\n \/\/-----------------------------------------------------------------------\n ZipDataStream::ZipDataStream(const String& name, ZZIP_FILE* zzipFile, size_t uncompressedSize)\n :DataStream(name), mZzipFile(zzipFile)\n {\n\t\tmSize = uncompressedSize;\n }\n \/\/-----------------------------------------------------------------------\n\tZipDataStream::~ZipDataStream()\n\t{\n\t\tclose();\n\t}\n \/\/-----------------------------------------------------------------------\n size_t ZipDataStream::read(void* buf, size_t count)\n {\n zzip_ssize_t r = zzip_file_read(mZzipFile, (char*)buf, count);\n if (r<0) {\n ZZIP_DIR *dir = zzip_dirhandle(mZzipFile);\n String msg = zzip_strerror_of(dir);\n OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR,\n mName+\" - error from zziplib: \"+msg,\n \"ZipDataStream::read\");\n }\n return (size_t) r;\n }\n \/\/-----------------------------------------------------------------------\n void ZipDataStream::skip(long count)\n {\n zzip_seek(mZzipFile, static_cast(count), SEEK_CUR);\n }\n \/\/-----------------------------------------------------------------------\n void ZipDataStream::seek( size_t pos )\n {\n\t\tzzip_seek(mZzipFile, static_cast(pos), SEEK_SET);\n }\n \/\/-----------------------------------------------------------------------\n size_t ZipDataStream::tell(void) const\n {\n\t\treturn zzip_tell(mZzipFile);\n }\n \/\/-----------------------------------------------------------------------\n bool ZipDataStream::eof(void) const\n {\n return (zzip_tell(mZzipFile) >= static_cast(mSize));\n }\n \/\/-----------------------------------------------------------------------\n void ZipDataStream::close(void)\n {\n zzip_file_close(mZzipFile);\n }\n \/\/-----------------------------------------------------------------------\n const String& ZipArchiveFactory::getType(void) const\n {\n static String name = \"Zip\";\n return name;\n }\n\n}\nTolerate someone calling ZDataStream::close before destruction\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n(Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\/\n\nCopyright (c) 2000-2006 Torus Knot Software Ltd\nAlso see acknowledgements in Readme.html\n\nThis program is free software; you can redistribute it and\/or modify it under\nthe terms of the GNU Lesser General Public License as published by the Free Software\nFoundation; either version 2 of the License, or (at your option) any later\nversion.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT\nANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\nFOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License along with\nthis program; if not, write to the Free Software Foundation, Inc., 59 Temple\nPlace - Suite 330, Boston, MA 02111-1307, USA, or go to\nhttp:\/\/www.gnu.org\/copyleft\/lesser.txt.\n\nYou may alternatively use this source under the terms of a specific version of\nthe OGRE Unrestricted License provided you have obtained such a license from\nTorus Knot Software Ltd.\n-----------------------------------------------------------------------------\n*\/\n#include \"OgreStableHeaders.h\"\n\n#include \"OgreZip.h\"\n\n#include \"OgreLogManager.h\"\n#include \"OgreException.h\"\n#include \"OgreStringVector.h\"\n#include \"OgreRoot.h\"\n\n#include \n\n\nnamespace Ogre {\n\n \/\/\/ Utility method to format out zzip errors\n String getZzipErrorDescription(zzip_error_t zzipError) \n {\n String errorMsg;\n switch (zzipError)\n {\n case ZZIP_NO_ERROR:\n break;\n case ZZIP_OUTOFMEM:\n errorMsg = \"Out of memory.\";\n break; \n case ZZIP_DIR_OPEN:\n case ZZIP_DIR_STAT: \n case ZZIP_DIR_SEEK:\n case ZZIP_DIR_READ:\n errorMsg = \"Unable to read zip file.\";\n break; \n case ZZIP_UNSUPP_COMPR:\n errorMsg = \"Unsupported compression format.\";\n break; \n case ZZIP_CORRUPTED:\n errorMsg = \"Corrupted archive.\";\n break; \n default:\n errorMsg = \"Unknown error.\";\n break; \n };\n\n return errorMsg;\n }\n \/\/-----------------------------------------------------------------------\n ZipArchive::ZipArchive(const String& name, const String& archType )\n : Archive(name, archType), mZzipDir(0)\n {\n }\n \/\/-----------------------------------------------------------------------\n ZipArchive::~ZipArchive()\n {\n unload();\n }\n \/\/-----------------------------------------------------------------------\n void ZipArchive::load()\n {\n if (!mZzipDir)\n {\n zzip_error_t zzipError;\n mZzipDir = zzip_dir_open(mName.c_str(), &zzipError);\n checkZzipError(zzipError, \"opening archive\");\n\n \/\/ Cache names\n ZZIP_DIRENT zzipEntry;\n while (zzip_dir_read(mZzipDir, &zzipEntry))\n {\n FileInfo info;\n\t\t\t\tinfo.archive = this;\n \/\/ Get basename \/ path\n StringUtil::splitFilename(zzipEntry.d_name, info.basename, info.path);\n info.filename = zzipEntry.d_name;\n \/\/ Get sizes\n info.compressedSize = static_cast(zzipEntry.d_csize);\n info.uncompressedSize = static_cast(zzipEntry.st_size);\n \/\/ folder entries\n if (info.basename.empty())\n {\n info.filename = info.filename.substr (0, info.filename.length () - 1);\n StringUtil::splitFilename(info.filename, info.basename, info.path);\n \/\/ Set compressed size to -1 for folders; anyway nobody will check\n \/\/ the compressed size of a folder, and if he does, its useless anyway\n info.compressedSize = size_t (-1);\n }\n\n mFileList.push_back(info);\n\n }\n\n }\n }\n \/\/-----------------------------------------------------------------------\n void ZipArchive::unload()\n {\n if (mZzipDir)\n {\n zzip_dir_close(mZzipDir);\n mZzipDir = 0;\n mFileList.clear();\n }\n \n }\n \/\/-----------------------------------------------------------------------\n\tDataStreamPtr ZipArchive::open(const String& filename) const\n {\n\n \/\/ Format not used here (always binary)\n ZZIP_FILE* zzipFile = \n zzip_file_open(mZzipDir, filename.c_str(), ZZIP_ONLYZIP | ZZIP_CASELESS);\n if (!zzipFile)\n\t\t{\n int zerr = zzip_error(mZzipDir);\n String zzDesc = getZzipErrorDescription((zzip_error_t)zerr);\n LogManager::getSingleton().logMessage(\n mName + \" - Unable to open file \" + filename + \", error was '\" + zzDesc + \"'\");\n \n\t\t\t\/\/ return null pointer\n\t\t\treturn DataStreamPtr();\n\t\t}\n\n\t\t\/\/ Get uncompressed size too\n\t\tZZIP_STAT zstat;\n\t\tzzip_dir_stat(mZzipDir, filename.c_str(), &zstat, ZZIP_CASEINSENSITIVE);\n\n \/\/ Construct & return stream\n return DataStreamPtr(OGRE_NEW ZipDataStream(filename, zzipFile, static_cast(zstat.st_size)));\n\n }\n \/\/-----------------------------------------------------------------------\n StringVectorPtr ZipArchive::list(bool recursive, bool dirs)\n {\n StringVectorPtr ret = StringVectorPtr(OGRE_NEW_T(StringVector, MEMCATEGORY_GENERAL)(), SPFM_DELETE_T);\n\n FileInfoList::iterator i, iend;\n iend = mFileList.end();\n for (i = mFileList.begin(); i != iend; ++i)\n if ((dirs == (i->compressedSize == size_t (-1))) &&\n (recursive || i->path.empty()))\n ret->push_back(i->filename);\n\n return ret;\n }\n \/\/-----------------------------------------------------------------------\n FileInfoListPtr ZipArchive::listFileInfo(bool recursive, bool dirs)\n {\n FileInfoList* fil = OGRE_NEW_T(FileInfoList, MEMCATEGORY_GENERAL)();\n FileInfoList::const_iterator i, iend;\n iend = mFileList.end();\n for (i = mFileList.begin(); i != iend; ++i)\n if ((dirs == (i->compressedSize == size_t (-1))) &&\n (recursive || i->path.empty()))\n fil->push_back(*i);\n\n return FileInfoListPtr(fil, SPFM_DELETE_T);\n }\n \/\/-----------------------------------------------------------------------\n StringVectorPtr ZipArchive::find(const String& pattern, bool recursive, bool dirs)\n {\n StringVectorPtr ret = StringVectorPtr(OGRE_NEW_T(StringVector, MEMCATEGORY_GENERAL)(), SPFM_DELETE_T);\n \/\/ If pattern contains a directory name, do a full match\n bool full_match = (pattern.find ('\/') != String::npos) ||\n (pattern.find ('\\\\') != String::npos);\n\n FileInfoList::iterator i, iend;\n iend = mFileList.end();\n for (i = mFileList.begin(); i != iend; ++i)\n if ((dirs == (i->compressedSize == size_t (-1))) &&\n (recursive || full_match || i->path.empty()))\n \/\/ Check basename matches pattern (zip is case insensitive)\n if (StringUtil::match(full_match ? i->filename : i->basename, pattern, false))\n ret->push_back(i->filename);\n\n return ret;\n }\n \/\/-----------------------------------------------------------------------\n\tFileInfoListPtr ZipArchive::findFileInfo(const String& pattern, \n bool recursive, bool dirs)\n {\n FileInfoListPtr ret = FileInfoListPtr(OGRE_NEW_T(FileInfoList, MEMCATEGORY_GENERAL)(), SPFM_DELETE_T);\n \/\/ If pattern contains a directory name, do a full match\n bool full_match = (pattern.find ('\/') != String::npos) ||\n (pattern.find ('\\\\') != String::npos);\n\n FileInfoList::iterator i, iend;\n iend = mFileList.end();\n for (i = mFileList.begin(); i != iend; ++i)\n if ((dirs == (i->compressedSize == size_t (-1))) &&\n (recursive || full_match || i->path.empty()))\n \/\/ Check name matches pattern (zip is case insensitive)\n if (StringUtil::match(full_match ? i->filename : i->basename, pattern, false))\n ret->push_back(*i);\n\n return ret;\n }\n \/\/-----------------------------------------------------------------------\n\tbool ZipArchive::exists(const String& filename)\n\t{\n\t\tZZIP_STAT zstat;\n\t\tint res = zzip_dir_stat(mZzipDir, filename.c_str(), &zstat, ZZIP_CASEINSENSITIVE);\n\n\t\treturn (res == ZZIP_NO_ERROR);\n\n\t}\n\t\/\/-----------------------------------------------------------------------\n void ZipArchive::checkZzipError(int zzipError, const String& operation) const\n {\n if (zzipError != ZZIP_NO_ERROR)\n {\n String errorMsg = getZzipErrorDescription(static_cast(zzipError));\n\n OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, \n mName + \" - error whilst \" + operation + \": \" + errorMsg,\n \"ZipArchive::checkZzipError\");\n }\n }\n \/\/-----------------------------------------------------------------------\n \/\/-----------------------------------------------------------------------\n \/\/-----------------------------------------------------------------------\n ZipDataStream::ZipDataStream(ZZIP_FILE* zzipFile, size_t uncompressedSize)\n : mZzipFile(zzipFile)\n {\n\t\tmSize = uncompressedSize;\n }\n \/\/-----------------------------------------------------------------------\n ZipDataStream::ZipDataStream(const String& name, ZZIP_FILE* zzipFile, size_t uncompressedSize)\n :DataStream(name), mZzipFile(zzipFile)\n {\n\t\tmSize = uncompressedSize;\n }\n \/\/-----------------------------------------------------------------------\n\tZipDataStream::~ZipDataStream()\n\t{\n\t\tclose();\n\t}\n \/\/-----------------------------------------------------------------------\n size_t ZipDataStream::read(void* buf, size_t count)\n {\n zzip_ssize_t r = zzip_file_read(mZzipFile, (char*)buf, count);\n if (r<0) {\n ZZIP_DIR *dir = zzip_dirhandle(mZzipFile);\n String msg = zzip_strerror_of(dir);\n OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR,\n mName+\" - error from zziplib: \"+msg,\n \"ZipDataStream::read\");\n }\n return (size_t) r;\n }\n \/\/-----------------------------------------------------------------------\n void ZipDataStream::skip(long count)\n {\n zzip_seek(mZzipFile, static_cast(count), SEEK_CUR);\n }\n \/\/-----------------------------------------------------------------------\n void ZipDataStream::seek( size_t pos )\n {\n\t\tzzip_seek(mZzipFile, static_cast(pos), SEEK_SET);\n }\n \/\/-----------------------------------------------------------------------\n size_t ZipDataStream::tell(void) const\n {\n\t\treturn zzip_tell(mZzipFile);\n }\n \/\/-----------------------------------------------------------------------\n bool ZipDataStream::eof(void) const\n {\n return (zzip_tell(mZzipFile) >= static_cast(mSize));\n }\n \/\/-----------------------------------------------------------------------\n void ZipDataStream::close(void)\n {\n\t\t\/\/ allow repeat calls\n\t\tif (mZzipFile)\n\t\t{\n\t\t\tzzip_file_close(mZzipFile);\n\t\t\tmZzipFile = 0;\n\t\t}\n }\n \/\/-----------------------------------------------------------------------\n const String& ZipArchiveFactory::getType(void) const\n {\n static String name = \"Zip\";\n return name;\n }\n\n}\n<|endoftext|>"} {"text":"\/*\n This file is part of Csound.\n\n Copyright (C) 2014 Rory Walsh\n\n The Csound Library is free software; you can redistribute it\n and\/or modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n Csound is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with Csound; if not, write to the Free Software\n Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n 02110-1301 USA\n *\/\n\n#include \"OpcodeBase.hpp\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace csound;\n\n\/* this function will load all samples of supported types into function\n tables number 'index' and upwards.\n It return the number of samples loaded *\/\nint loadSamplesToTables(CSOUND *csound, int index, char *directory,\n int skiptime, int format, int channel);\n\n\/\/-----------------------------------------------------------------\n\/\/ i-rate class\n\/\/-----------------------------------------------------------------\nclass iftsamplebank : public OpcodeBase {\npublic:\n \/\/ Outputs.\n MYFLT *numberOfFiles;\n \/\/ Inputs.\n STRINGDAT *sDirectory;\n MYFLT *index;\n \/\/ MYFLT* trigger;\n MYFLT *skiptime;\n MYFLT *format;\n MYFLT *channel;\n\n iftsamplebank() {\n channel = 0;\n index = 0;\n skiptime = 0;\n format = 0;\n index = 0;\n numberOfFiles = 0;\n sDirectory = NULL;\n }\n\n \/\/ init-pass\n int init(CSOUND *csound) {\n\n *numberOfFiles = loadSamplesToTables(\n csound, *index, (char *)sDirectory->data, *skiptime, *format, *channel);\n return OK;\n }\n\n int noteoff(CSOUND *) { return OK; }\n};\n\n\/\/-----------------------------------------------------------------\n\/\/ k-rate class\n\/\/-----------------------------------------------------------------\nclass kftsamplebank : public OpcodeBase {\npublic:\n \/\/ Outputs.\n MYFLT *numberOfFiles;\n \/\/ Inputs.\n STRINGDAT *sDirectory;\n MYFLT *index;\n MYFLT *trigger;\n MYFLT *skiptime;\n MYFLT *format;\n MYFLT *channel;\n int internalCounter;\n kftsamplebank() : internalCounter(0) {\n channel = 0;\n index = 0;\n skiptime = 0;\n format = 0;\n index = 0;\n trigger = 0;\n }\n\n \/\/ init-pass\n int init(CSOUND *csound) {\n IGN(csound);\n *numberOfFiles =\n loadSamplesToTables(csound, *index, (char *)sDirectory->data,\n *skiptime, *format, *channel);\n *trigger = 0;\n return OK;\n }\n\n int noteoff(CSOUND *) { return OK; }\n\n int kontrol(CSOUND *csound) {\n \/\/ if directry changes update tables..\n if (*trigger == 1) {\n *numberOfFiles =\n loadSamplesToTables(csound, *index, (char *)sDirectory->data,\n *skiptime, *format, *channel);\n *trigger = 0;\n }\n return OK;\n }\n};\n\n\/\/-----------------------------------------------------------------\n\/\/ load samples into function tables\n\/\/-----------------------------------------------------------------\nint loadSamplesToTables(CSOUND *csound, int index, char *directory,\n int skiptime, int format, int channel) {\n\n if (directory) {\n DIR *dir = opendir(directory);\n std::vector fileNames;\n std::vector fileExtensions;\n int noOfFiles = 0;\n fileExtensions.push_back(\".wav\");\n fileExtensions.push_back(\".aiff\");\n fileExtensions.push_back(\".ogg\");\n fileExtensions.push_back(\".flac\");\n\n \/\/ check for valid path first\n if (dir) {\n struct dirent *ent;\n while ((ent = readdir(dir)) != NULL) {\n std::ostringstream fullFileName;\n \/\/ only use supported file types\n for (int i = 0; (size_t)i < fileExtensions.size(); i++)\n {\n std::string fname = ent->d_name;\n std::string extension;\n if(fname.find_last_of(\".\") != std::string::npos)\n extension = fname.substr(fname.find_last_of(\".\"));\n\n if(extension == fileExtensions[i])\n {\n if (strlen(directory) > 0) {\n#if defined(WIN32)\n fullFileName << directory << \"\\\\\" << ent->d_name;\n#else\n fullFileName << directory << \"\/\" << ent->d_name;\n#endif\n }\n else\n fullFileName << ent->d_name;\n\n noOfFiles++;\n\n fileNames.push_back(fullFileName.str());\n }\n }\n }\n\n \/\/ Sort names\n std::sort(fileNames.begin(), fileNames.end());\n\n \/\/ push statements to score, starting with table number 'index'\n for (int y = 0; (size_t)y < fileNames.size(); y++) {\n std::ostringstream statement;\n statement << \"f\" << index + y << \" 0 0 1 \\\"\" << fileNames[y] << \"\\\" \"\n << skiptime << \" \" << format << \" \" << channel << \"\\n\";\n \/\/ csound->MessageS(csound, CSOUNDMSG_ORCH, statement.str().c_str());\n csound->InputMessage(csound, statement.str().c_str());\n }\n\n closedir(dir);\n } else {\n csound->Message(csound,\n Str(\"Cannot load file. Error opening directory: %s\\n\"),\n directory);\n }\n\n \/\/ return number of files\n return noOfFiles;\n } else\n return 0;\n}\n\ntypedef struct {\n OPDS h;\n ARRAYDAT *outArr;\n STRINGDAT *directoryName;\n MYFLT *extension;\n} DIR_STRUCT;\n\n\/* this function will looks for files of a set type, in a particular directory\n *\/\nstd::vector searchDir(CSOUND *csound, char *directory,\n char *extension);\n\n#include \"arrays.h\"\n#if 0\n\/* from Opcodes\/arrays.c *\/\nstatic inline void tabensure(CSOUND *csound, ARRAYDAT *p, int size) {\n if (p->data==NULL || p->dimensions == 0 ||\n (p->dimensions==1 && p->sizes[0] < size)) {\n size_t ss;\n if (p->data == NULL) {\n CS_VARIABLE* var = p->arrayType->createVariable(csound, NULL);\n p->arrayMemberSize = var->memBlockSize;\n }\n ss = p->arrayMemberSize*size;\n if (p->data==NULL) {\n p->data = (MYFLT*)csound->Calloc(csound, ss);\n p->allocated = ss;\n }\n else if (ss > p->allocated) {\n p->data = (MYFLT*) csound->ReAlloc(csound, p->data, ss);\n p->allocated = ss;\n }\n if (p->dimensions==0) {\n p->dimensions = 1;\n p->sizes = (int32_t*)csound->Malloc(csound, sizeof(int32_t));\n }\n }\n p->sizes[0] = size;\n}\n#endif\n\nstatic int directory(CSOUND *csound, DIR_STRUCT *p) {\n int inArgCount = p->INOCOUNT;\n char *extension, *file;\n std::vector fileNames;\n\n if (inArgCount == 0)\n return csound->InitError(\n csound, \"%s\", Str(\"Error: you must pass a directory as a string.\"));\n\n if (inArgCount == 1) {\n fileNames = searchDir(csound, p->directoryName->data, (char *)\"\");\n }\n\n else if (inArgCount == 2) {\n CS_TYPE *argType = csound->GetTypeForArg(p->extension);\n if (strcmp(\"S\", argType->varTypeName) == 0) {\n extension = csound->Strdup(csound, ((STRINGDAT *)p->extension)->data);\n fileNames = searchDir(csound, p->directoryName->data, extension);\n } else\n return csound->InitError(csound,\n \"%s\", Str(\"Error: second parameter to directory\"\n \" must be a string\"));\n }\n\n int numberOfFiles = fileNames.size();\n tabinit(csound, p->outArr, numberOfFiles);\n STRINGDAT *strings = (STRINGDAT *)p->outArr->data;\n\n for (int i = 0; i < numberOfFiles; i++) {\n file = &fileNames[i][0u];\n strings[i].size = strlen(file) + 1;\n strings[i].data = csound->Strdup(csound, file);\n }\n\n fileNames.clear();\n\n return OK;\n}\n\n\/\/-----------------------------------------------------------------\n\/\/ load samples into function tables\n\/\/-----------------------------------------------------------------\nstd::vector searchDir(CSOUND *csound, char *directory,\n char *extension) {\n std::vector fileNames;\n if (directory) {\n DIR *dir = opendir(directory);\n std::string fileExtension(extension);\n int noOfFiles = 0;\n\n \/\/ check for valid path first\n if (dir) {\n struct dirent *ent;\n while ((ent = readdir(dir)) != NULL) {\n std::ostringstream fullFileName;\n\n std::string fname = ent->d_name;\n size_t lastPos = fname.find_last_of(\".\");\n if (fname.length() > 0 && (fileExtension.empty() ||\n (lastPos != std::string::npos &&\n fname.substr(lastPos) == fileExtension))) {\n if (strlen(directory) > 0) {\n#if defined(WIN32)\n fullFileName << directory << \"\\\\\" << ent->d_name;\n#else\n fullFileName << directory << \"\/\" << ent->d_name;\n#endif\n } else\n fullFileName << ent->d_name;\n\n noOfFiles++;\n fileNames.push_back(fullFileName.str());\n }\n }\n\n \/\/ Sort names\n std::sort(fileNames.begin(), fileNames.end());\n } else {\n csound->Message(csound, Str(\"Cannot find directory. \"\n \"Error opening directory: %s\\n\"),\n directory);\n }\n closedir(dir);\n }\n\n return fileNames;\n}\n\nextern \"C\" {\n\nPUBLIC int csoundModuleInit_ftsamplebank(CSOUND *csound) {\n\n int status = csound->AppendOpcode(\n csound, (char *)\"ftsamplebank.k\", sizeof(kftsamplebank), 0, 3,\n (char *)\"k\", (char *)\"Skkkkk\",\n (int (*)(CSOUND *, void *))kftsamplebank::init_,\n (int (*)(CSOUND *, void *))kftsamplebank::kontrol_,\n (int (*)(CSOUND *, void *))0);\n\n status |= csound->AppendOpcode(\n csound, (char *)\"ftsamplebank.i\", sizeof(iftsamplebank), 0, 1,\n (char *)\"i\", (char *)\"Siiii\",\n (int (*)(CSOUND *, void *))iftsamplebank::init_,\n (int (*)(CSOUND *, void *))0, (int (*)(CSOUND *, void *))0);\n\n \/* status |= csound->AppendOpcode(csound,\n (char*)\"ftsamplebank\",\n 0xffff,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0); *\/\n\n status |= csound->AppendOpcode(\n csound, (char *)\"directory\", sizeof(DIR_STRUCT), 0, 1, (char *)\"S[]\",\n (char *)\"SN\", (int (*)(CSOUND *, void *))directory,\n (int (*)(CSOUND *, void *))0, (int (*)(CSOUND *, void *))0);\n return status;\n}\n\n#ifndef INIT_STATIC_MODULES\nPUBLIC int csoundModuleCreate(CSOUND *csound) {\n IGN(csound);\n return 0;\n}\n\nPUBLIC int csoundModuleInit(CSOUND *csound) {\n return csoundModuleInit_ftsamplebank(csound);\n}\n\nPUBLIC int csoundModuleDestroy(CSOUND *csound) {\n IGN(csound);\n return 0;\n}\n#endif\n}\nUpdate ftsamplebank.cpp\/*\n This file is part of Csound.\n\n Copyright (C) 2014 Rory Walsh\n\n The Csound Library is free software; you can redistribute it\n and\/or modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n Csound is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with Csound; if not, write to the Free Software\n Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n 02110-1301 USA\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"OpcodeBase.hpp\"\n#include \n#include \n\nusing namespace std;\nusing namespace csound;\n\n\/* this function will load all samples of supported types into function\n tables number 'index' and upwards.\n It return the number of samples loaded *\/\nint loadSamplesToTables(CSOUND *csound, int index, char *directory,\n int skiptime, int format, int channel);\n\n\/\/-----------------------------------------------------------------\n\/\/ i-rate class\n\/\/-----------------------------------------------------------------\nclass iftsamplebank : public OpcodeBase {\npublic:\n \/\/ Outputs.\n MYFLT *numberOfFiles;\n \/\/ Inputs.\n STRINGDAT *sDirectory;\n MYFLT *index;\n \/\/ MYFLT* trigger;\n MYFLT *skiptime;\n MYFLT *format;\n MYFLT *channel;\n\n iftsamplebank() {\n channel = 0;\n index = 0;\n skiptime = 0;\n format = 0;\n index = 0;\n numberOfFiles = 0;\n sDirectory = NULL;\n }\n\n \/\/ init-pass\n int init(CSOUND *csound) {\n\n *numberOfFiles = loadSamplesToTables(\n csound, *index, (char *)sDirectory->data, *skiptime, *format, *channel);\n return OK;\n }\n\n int noteoff(CSOUND *) { return OK; }\n};\n\n\/\/-----------------------------------------------------------------\n\/\/ k-rate class\n\/\/-----------------------------------------------------------------\nclass kftsamplebank : public OpcodeBase {\npublic:\n \/\/ Outputs.\n MYFLT *numberOfFiles;\n \/\/ Inputs.\n STRINGDAT *sDirectory;\n MYFLT *index;\n MYFLT *trigger;\n MYFLT *skiptime;\n MYFLT *format;\n MYFLT *channel;\n int internalCounter;\n kftsamplebank() : internalCounter(0) {\n channel = 0;\n index = 0;\n skiptime = 0;\n format = 0;\n index = 0;\n trigger = 0;\n }\n\n \/\/ init-pass\n int init(CSOUND *csound) {\n IGN(csound);\n *numberOfFiles =\n loadSamplesToTables(csound, *index, (char *)sDirectory->data,\n *skiptime, *format, *channel);\n *trigger = 0;\n return OK;\n }\n\n int noteoff(CSOUND *) { return OK; }\n\n int kontrol(CSOUND *csound) {\n \/\/ if directry changes update tables..\n if (*trigger == 1) {\n *numberOfFiles =\n loadSamplesToTables(csound, *index, (char *)sDirectory->data,\n *skiptime, *format, *channel);\n *trigger = 0;\n }\n return OK;\n }\n};\n\n\/\/-----------------------------------------------------------------\n\/\/ load samples into function tables\n\/\/-----------------------------------------------------------------\nint loadSamplesToTables(CSOUND *csound, int index, char *directory,\n int skiptime, int format, int channel) {\n\n if (directory) {\n DIR *dir = opendir(directory);\n std::vector fileNames;\n std::vector fileExtensions;\n int noOfFiles = 0;\n fileExtensions.push_back(\".wav\");\n fileExtensions.push_back(\".aiff\");\n fileExtensions.push_back(\".ogg\");\n fileExtensions.push_back(\".flac\");\n\n \/\/ check for valid path first\n if (dir) {\n struct dirent *ent;\n while ((ent = readdir(dir)) != NULL) {\n std::ostringstream fullFileName;\n \/\/ only use supported file types\n for (int i = 0; (size_t)i < fileExtensions.size(); i++)\n {\n std::string fname = ent->d_name;\n std::string extension;\n if(fname.find_last_of(\".\") != std::string::npos)\n extension = fname.substr(fname.find_last_of(\".\"));\n\n if(extension == fileExtensions[i])\n {\n if (strlen(directory) > 0) {\n#if defined(WIN32)\n fullFileName << directory << \"\\\\\" << ent->d_name;\n#else\n fullFileName << directory << \"\/\" << ent->d_name;\n#endif\n }\n else\n fullFileName << ent->d_name;\n\n noOfFiles++;\n\n fileNames.push_back(fullFileName.str());\n }\n }\n }\n\n \/\/ Sort names\n std::sort(fileNames.begin(), fileNames.end());\n\n \/\/ push statements to score, starting with table number 'index'\n for (int y = 0; (size_t)y < fileNames.size(); y++) {\n std::ostringstream statement;\n statement << \"f\" << index + y << \" 0 0 1 \\\"\" << fileNames[y] << \"\\\" \"\n << skiptime << \" \" << format << \" \" << channel << \"\\n\";\n \/\/ csound->MessageS(csound, CSOUNDMSG_ORCH, statement.str().c_str());\n csound->InputMessage(csound, statement.str().c_str());\n }\n\n closedir(dir);\n } else {\n csound->Message(csound,\n Str(\"Cannot load file. Error opening directory: %s\\n\"),\n directory);\n }\n\n \/\/ return number of files\n return noOfFiles;\n } else\n return 0;\n}\n\ntypedef struct {\n OPDS h;\n ARRAYDAT *outArr;\n STRINGDAT *directoryName;\n MYFLT *extension;\n} DIR_STRUCT;\n\n\/* this function will looks for files of a set type, in a particular directory\n *\/\nstd::vector searchDir(CSOUND *csound, char *directory,\n char *extension);\n\n#include \"arrays.h\"\n#if 0\n\/* from Opcodes\/arrays.c *\/\nstatic inline void tabensure(CSOUND *csound, ARRAYDAT *p, int size) {\n if (p->data==NULL || p->dimensions == 0 ||\n (p->dimensions==1 && p->sizes[0] < size)) {\n size_t ss;\n if (p->data == NULL) {\n CS_VARIABLE* var = p->arrayType->createVariable(csound, NULL);\n p->arrayMemberSize = var->memBlockSize;\n }\n ss = p->arrayMemberSize*size;\n if (p->data==NULL) {\n p->data = (MYFLT*)csound->Calloc(csound, ss);\n p->allocated = ss;\n }\n else if (ss > p->allocated) {\n p->data = (MYFLT*) csound->ReAlloc(csound, p->data, ss);\n p->allocated = ss;\n }\n if (p->dimensions==0) {\n p->dimensions = 1;\n p->sizes = (int32_t*)csound->Malloc(csound, sizeof(int32_t));\n }\n }\n p->sizes[0] = size;\n}\n#endif\n\nstatic int directory(CSOUND *csound, DIR_STRUCT *p) {\n int inArgCount = p->INOCOUNT;\n char *extension, *file;\n std::vector fileNames;\n\n if (inArgCount == 0)\n return csound->InitError(\n csound, \"%s\", Str(\"Error: you must pass a directory as a string.\"));\n\n if (inArgCount == 1) {\n fileNames = searchDir(csound, p->directoryName->data, (char *)\"\");\n }\n\n else if (inArgCount == 2) {\n CS_TYPE *argType = csound->GetTypeForArg(p->extension);\n if (strcmp(\"S\", argType->varTypeName) == 0) {\n extension = csound->Strdup(csound, ((STRINGDAT *)p->extension)->data);\n fileNames = searchDir(csound, p->directoryName->data, extension);\n } else\n return csound->InitError(csound,\n \"%s\", Str(\"Error: second parameter to directory\"\n \" must be a string\"));\n }\n\n int numberOfFiles = fileNames.size();\n tabinit(csound, p->outArr, numberOfFiles);\n STRINGDAT *strings = (STRINGDAT *)p->outArr->data;\n\n for (int i = 0; i < numberOfFiles; i++) {\n file = &fileNames[i][0u];\n strings[i].size = strlen(file) + 1;\n strings[i].data = csound->Strdup(csound, file);\n }\n\n fileNames.clear();\n\n return OK;\n}\n\n\/\/-----------------------------------------------------------------\n\/\/ load samples into function tables\n\/\/-----------------------------------------------------------------\nstd::vector searchDir(CSOUND *csound, char *directory,\n char *extension) {\n std::vector fileNames;\n if (directory) {\n DIR *dir = opendir(directory);\n std::string fileExtension(extension);\n int noOfFiles = 0;\n\n \/\/ check for valid path first\n if (dir) {\n struct dirent *ent;\n while ((ent = readdir(dir)) != NULL) {\n std::ostringstream fullFileName;\n\n std::string fname = ent->d_name;\n size_t lastPos = fname.find_last_of(\".\");\n if (fname.length() > 0 && (fileExtension.empty() ||\n (lastPos != std::string::npos &&\n fname.substr(lastPos) == fileExtension))) {\n if (strlen(directory) > 0) {\n#if defined(WIN32)\n fullFileName << directory << \"\\\\\" << ent->d_name;\n#else\n fullFileName << directory << \"\/\" << ent->d_name;\n#endif\n } else\n fullFileName << ent->d_name;\n\n noOfFiles++;\n fileNames.push_back(fullFileName.str());\n }\n }\n\n \/\/ Sort names\n std::sort(fileNames.begin(), fileNames.end());\n } else {\n csound->Message(csound, Str(\"Cannot find directory. \"\n \"Error opening directory: %s\\n\"),\n directory);\n }\n closedir(dir);\n }\n\n return fileNames;\n}\n\nextern \"C\" {\n\nPUBLIC int csoundModuleInit_ftsamplebank(CSOUND *csound) {\n\n int status = csound->AppendOpcode(\n csound, (char *)\"ftsamplebank.k\", sizeof(kftsamplebank), 0, 3,\n (char *)\"k\", (char *)\"Skkkkk\",\n (int (*)(CSOUND *, void *))kftsamplebank::init_,\n (int (*)(CSOUND *, void *))kftsamplebank::kontrol_,\n (int (*)(CSOUND *, void *))0);\n\n status |= csound->AppendOpcode(\n csound, (char *)\"ftsamplebank.i\", sizeof(iftsamplebank), 0, 1,\n (char *)\"i\", (char *)\"Siiii\",\n (int (*)(CSOUND *, void *))iftsamplebank::init_,\n (int (*)(CSOUND *, void *))0, (int (*)(CSOUND *, void *))0);\n\n \/* status |= csound->AppendOpcode(csound,\n (char*)\"ftsamplebank\",\n 0xffff,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0); *\/\n\n status |= csound->AppendOpcode(\n csound, (char *)\"directory\", sizeof(DIR_STRUCT), 0, 1, (char *)\"S[]\",\n (char *)\"SN\", (int (*)(CSOUND *, void *))directory,\n (int (*)(CSOUND *, void *))0, (int (*)(CSOUND *, void *))0);\n return status;\n}\n\n#ifndef INIT_STATIC_MODULES\nPUBLIC int csoundModuleCreate(CSOUND *csound) {\n IGN(csound);\n return 0;\n}\n\nPUBLIC int csoundModuleInit(CSOUND *csound) {\n return csoundModuleInit_ftsamplebank(csound);\n}\n\nPUBLIC int csoundModuleDestroy(CSOUND *csound) {\n IGN(csound);\n return 0;\n}\n#endif\n}\n<|endoftext|>"} {"text":"\/\/ Copyright Hugh Perkins 2016\n\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"shims.h\"\n\n#include \n\n\/\/ using namespace cocl;\n\/\/ using namespace std;\n\nnamespace cocl {\n\nShims::Shims() {\n _shimClByName[\"__shfl_down_3\"] = R\"(\ninline float __shfl_down_3(local int *scratch, float v0, int v1, int v2) {\n \/\/ local float mem[1024];\n local float *mem = (local float *)scratch;\n int tid = get_local_id(0);\n int warpid = tid % 32;\n int warpstart = tid - warpid;\n mem[tid] = v0;\n \/\/barrier(CLK_LOCAL_MEM_FENCE);\n int warpsrc = warpid + v1;\n warpsrc = warpsrc >= 32 ? warpid : warpsrc;\n return mem[warpstart + warpsrc];\n}\n)\";\n\n _shimClByName[\"__shfl_down_2\"] = R\"(\ninline float __shfl_down_2(local int *scratch, float v0, int v1) {\n return __shfl_down_3(scratch, v0, v1, 32);\n}\n)\";\n _dependenciesByName[\"__shfl_down_2\"].insert(\"__shfl_down_3\");\n\n \/\/ note to self: just realized, umulhi is actually available in opencl 1.2 :-)\n \/\/ so, we should migrate this to use that, probably\n _shimClByName[\"__umulhi\"] = R\"(\ninline unsigned int __umulhi(unsigned int v0, unsigned int v1) {\n unsigned long res = (unsigned long)v0 * v1;\n unsigned int res2 = res >> 32;\n return res2;\n}\n)\";\n\n\/\/ this code is from http:\/\/suhorukov.blogspot.co.uk\/2011\/12\/opencl-11-atomic-operations-on-floating.html\n _shimClByName[\"__atomic_add_float\"] = R\"(\ninline float __atomic_add_float(volatile __global float *source, const float operand) {\n union {\n unsigned int intVal;\n float floatVal;\n } newVal;\n union {\n unsigned int intVal;\n float floatVal;\n } prevVal;\n do {\n prevVal.floatVal = *source;\n newVal.floatVal = prevVal.floatVal + operand;\n } while (atomic_cmpxchg((volatile __global unsigned int *)source, prevVal.intVal, newVal.intVal) != prevVal.intVal);\n return prevVal.floatVal;\n}\n)\";\n\n _shimClByName[\"__atomic_inc_uint\"] = R\"(\ninline unsigned int __atomic_inc_uint(volatile __global int *data, const unsigned int old) {\n unsigned int prevVal;\n unsigned int newVal;\n while(true) {\n prevVal = *data;\n newVal = prevVal >= old ? 0 : prevVal + 1;\n unsigned int res = atomic_cmpxchg((volatile __global unsigned int *)data, prevVal, newVal);\n if(res == prevVal) {\n break;\n }\n }\n return prevVal;\n}\n)\";\n}\n\nvoid Shims::use(std::string name) {\n if(_shimClByName.find(name) == _shimClByName.end()) {\n std::cout << \"shim \" << name << \" does not exist. This is a bug in Coriander\" << std::endl;\n throw std::runtime_error(\"shim \" + name + \" does not exist. This is a bug in Coriander\");\n }\n shimsToBeUsed.insert(name);\n if(_dependenciesByName.find(name) != _dependenciesByName.end()) {\n const std::set &deps = _dependenciesByName[name];\n for(auto it=deps.begin(); it != deps.end(); it++) {\n shimsToBeUsed.insert(*it);\n }\n }\n}\n\nvoid Shims::writeCl(std::ostream &os) {\n std::set written;\n int attempts = 0;\n while(written.size() < shimsToBeUsed.size() && attempts < 10) {\n for(auto it=shimsToBeUsed.begin(); it != shimsToBeUsed.end(); it++) {\n std::string shimName = *it;\n std::cout << \"write check \" << shimName << std::endl;\n if(written.find(shimName) != written.end()) {\n continue;\n }\n bool writtenDependencies = true;\n \/\/ check written dependencies\n const std::set &deps = _dependenciesByName[shimName];\n for(auto childit=deps.begin(); childit != deps.end(); childit++) {\n std::string childName = *childit;\n if(written.find(childName) == written.end()) {\n std::cout << \" missing dep \" << childName << std::endl;\n writtenDependencies = false;\n break;\n }\n }\n if(writtenDependencies) {\n os << _shimClByName[shimName];\n written.insert(shimName);\n }\n }\n attempts++;\n }\n if(written.size() < shimsToBeUsed.size()) {\n for(auto it=written.begin(); it != written.end(); it++) {\n std::cout << \"wrote \" << *it << \" ok\" << std::endl;\n }\n std::cout << std::endl;\n std::cout << \"ERROR: Failed to write shims. This is a Coriander bug. Please log at https:\/\/github.com\/hughperkins\/coriander\/issues\" << std::endl;\n std::cout << std::endl;\n throw std::runtime_error(\"Failed to write shims\");\n }\n}\n\nvoid Shims::copyFrom(const Shims &source) {\n for(auto it=source.shimsToBeUsed.begin(); it != source.shimsToBeUsed.end(); it++) {\n \/\/ shimsToBeUsed.insert(*it);\n }\n shimsToBeUsed.insert(source.shimsToBeUsed.begin(), source.shimsToBeUsed.end());\n}\n\nbool Shims::isUsed(std::string name) {\n return shimsToBeUsed.find(name) != shimsToBeUsed.end();\n}\n\n\n\/\/ std::string Shims::getClByName(std::string name) {\n\/\/ return _shimClByName[name];\n\/\/ }\n\n\/\/ std::set Shims::getDependenciesByName(std::string name) {\n\/\/ return _dependenciesByName[name];\n\/\/ }\n\n} \/\/ namespace cocl\nreduce spam a bit\/\/ Copyright Hugh Perkins 2016\n\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"shims.h\"\n\n#include \n\n\/\/ using namespace cocl;\n\/\/ using namespace std;\n\nnamespace cocl {\n\nShims::Shims() {\n _shimClByName[\"__shfl_down_3\"] = R\"(\ninline float __shfl_down_3(local int *scratch, float v0, int v1, int v2) {\n \/\/ local float mem[1024];\n local float *mem = (local float *)scratch;\n int tid = get_local_id(0);\n int warpid = tid % 32;\n int warpstart = tid - warpid;\n mem[tid] = v0;\n \/\/barrier(CLK_LOCAL_MEM_FENCE);\n int warpsrc = warpid + v1;\n warpsrc = warpsrc >= 32 ? warpid : warpsrc;\n return mem[warpstart + warpsrc];\n}\n)\";\n\n _shimClByName[\"__shfl_down_2\"] = R\"(\ninline float __shfl_down_2(local int *scratch, float v0, int v1) {\n return __shfl_down_3(scratch, v0, v1, 32);\n}\n)\";\n _dependenciesByName[\"__shfl_down_2\"].insert(\"__shfl_down_3\");\n\n \/\/ note to self: just realized, umulhi is actually available in opencl 1.2 :-)\n \/\/ so, we should migrate this to use that, probably\n _shimClByName[\"__umulhi\"] = R\"(\ninline unsigned int __umulhi(unsigned int v0, unsigned int v1) {\n unsigned long res = (unsigned long)v0 * v1;\n unsigned int res2 = res >> 32;\n return res2;\n}\n)\";\n\n\/\/ this code is from http:\/\/suhorukov.blogspot.co.uk\/2011\/12\/opencl-11-atomic-operations-on-floating.html\n _shimClByName[\"__atomic_add_float\"] = R\"(\ninline float __atomic_add_float(volatile __global float *source, const float operand) {\n union {\n unsigned int intVal;\n float floatVal;\n } newVal;\n union {\n unsigned int intVal;\n float floatVal;\n } prevVal;\n do {\n prevVal.floatVal = *source;\n newVal.floatVal = prevVal.floatVal + operand;\n } while (atomic_cmpxchg((volatile __global unsigned int *)source, prevVal.intVal, newVal.intVal) != prevVal.intVal);\n return prevVal.floatVal;\n}\n)\";\n\n _shimClByName[\"__atomic_inc_uint\"] = R\"(\ninline unsigned int __atomic_inc_uint(volatile __global int *data, const unsigned int old) {\n unsigned int prevVal;\n unsigned int newVal;\n while(true) {\n prevVal = *data;\n newVal = prevVal >= old ? 0 : prevVal + 1;\n unsigned int res = atomic_cmpxchg((volatile __global unsigned int *)data, prevVal, newVal);\n if(res == prevVal) {\n break;\n }\n }\n return prevVal;\n}\n)\";\n}\n\nvoid Shims::use(std::string name) {\n if(_shimClByName.find(name) == _shimClByName.end()) {\n std::cout << \"shim \" << name << \" does not exist. This is a bug in Coriander\" << std::endl;\n throw std::runtime_error(\"shim \" + name + \" does not exist. This is a bug in Coriander\");\n }\n shimsToBeUsed.insert(name);\n if(_dependenciesByName.find(name) != _dependenciesByName.end()) {\n const std::set &deps = _dependenciesByName[name];\n for(auto it=deps.begin(); it != deps.end(); it++) {\n shimsToBeUsed.insert(*it);\n }\n }\n}\n\nvoid Shims::writeCl(std::ostream &os) {\n std::set written;\n int attempts = 0;\n while(written.size() < shimsToBeUsed.size() && attempts < 10) {\n for(auto it=shimsToBeUsed.begin(); it != shimsToBeUsed.end(); it++) {\n std::string shimName = *it;\n if(written.find(shimName) != written.end()) {\n continue;\n }\n bool writtenDependencies = true;\n \/\/ check written dependencies\n const std::set &deps = _dependenciesByName[shimName];\n for(auto childit=deps.begin(); childit != deps.end(); childit++) {\n std::string childName = *childit;\n if(written.find(childName) == written.end()) {\n writtenDependencies = false;\n break;\n }\n }\n if(writtenDependencies) {\n os << _shimClByName[shimName];\n written.insert(shimName);\n }\n }\n attempts++;\n }\n if(written.size() < shimsToBeUsed.size()) {\n for(auto it=written.begin(); it != written.end(); it++) {\n std::cout << \"wrote \" << *it << \" ok\" << std::endl;\n }\n std::cout << std::endl;\n std::cout << \"ERROR: Failed to write shims. This is a Coriander bug. Please log at https:\/\/github.com\/hughperkins\/coriander\/issues\" << std::endl;\n std::cout << std::endl;\n throw std::runtime_error(\"Failed to write shims\");\n }\n}\n\nvoid Shims::copyFrom(const Shims &source) {\n for(auto it=source.shimsToBeUsed.begin(); it != source.shimsToBeUsed.end(); it++) {\n \/\/ shimsToBeUsed.insert(*it);\n }\n shimsToBeUsed.insert(source.shimsToBeUsed.begin(), source.shimsToBeUsed.end());\n}\n\nbool Shims::isUsed(std::string name) {\n return shimsToBeUsed.find(name) != shimsToBeUsed.end();\n}\n\n\n\/\/ std::string Shims::getClByName(std::string name) {\n\/\/ return _shimClByName[name];\n\/\/ }\n\n\/\/ std::set Shims::getDependenciesByName(std::string name) {\n\/\/ return _dependenciesByName[name];\n\/\/ }\n\n} \/\/ namespace cocl\n<|endoftext|>"} {"text":"#include \"easylogging++.h\"\n#include \"json.hpp\"\n#include \"snake.h\"\n\nusing nlohmann::json;\n\n\/\/ Good runs: http:\/\/game.snake.cygni.se\/#\/viewgame\/88a759cf-e406-4941-9eba-28d51ed9c600\n\/\/ http:\/\/game.snake.cygni.se\/#\/viewgame\/af42c3a4-fbf9-4a14-b892-3fdf6da063a4\n\/\/ http:\/\/game.snake.cygni.se\/#\/viewgame\/ed59e861-8147-4845-8f6c-3b586b2b91a4\n\n\/\/ Postionen ges av int position => endast ett värde på mappen\n\n\/\/ ---------------------- NEXT MOOVE -------------------------------\n\nstd::string Snake::get_next_move(json map) {\n int mapHight = map[\"height\"] ;\n int mapWidth = map[\"width\"] ;\n\n \/\/int response = 1;\n std::string responsArray [] = {\"UP\", \"DOWN\", \"RIGHT\", \"LEFT\"};\n\n std::array responsValue;\n\n \/\/ Reset responsValue\n responsValue[0] = 0; \/\/ UP\n responsValue[1] = 0; \/\/ DOWN\n responsValue[2] = 0; \/\/ RIGHT\n responsValue[3] = 0; \/\/ LEFT\n\n\n \/\/ Hitta vår snake första gången vi spelar \n if(mySnakeSlot == -1){\n mySnakeSlot = 0;\n while(map[\"snakeInfos\"][mySnakeSlot][\"name\"] != name){\n mySnakeSlot++;\n } \n }\n\n int snake_x, snake_y;\n std::tie(snake_x,snake_y) = pos2xy(map[\"snakeInfos\"][mySnakeSlot][\"positions\"][0], map[\"width\"]);\n \/\/ LOG(INFO) << \"Snake pos: \" << x << \", \" << y ; \n \/\/ \n\n double danger[] = {0.0, 0.0, 0.0, 0.0};\n double food[] = {0.0, 0.0, 0.0, 0.0};\n int view_distance = 2;\n\n for (int i = 0; i < map[\"obstaclePositions\"].size(); ++i) \/\/ OBSTACLE\n {\n int i_x, i_y;\n std::tie(i_x,i_y) = pos2xy(map[\"obstaclePositions\"][i], map[\"width\"]);\n int dist_x = i_x - snake_x;\n int dist_y = i_y - snake_y;\n\n if (dist_y > -view_distance && dist_y < 0 && abs(dist_x) < view_distance) \/\/ danger up\n {\n danger[0] += (view_distance + dist_y)*(view_distance + dist_y);\n }\n else if (dist_y > 0 && dist_y < view_distance && abs(dist_x) < view_distance) \/\/ danger down\n {\n danger[1] += (view_distance - dist_y)*(view_distance - dist_y);\n }\n \n if (dist_x > -view_distance && dist_x < 0 && abs(dist_y) < view_distance)\n {\n danger[3] += (view_distance + dist_x)*(view_distance + dist_x);\n }\n else if (dist_x > 0 && dist_x < view_distance && abs(dist_y) < view_distance)\n {\n danger[2] += (view_distance - dist_y)*(view_distance - dist_y);\n }\n\n }\n\n for (int i = 0; i < map[\"foodPositions\"].size(); ++i) \/\/ FOOD \n {\n int i_x, i_y;\n std::tie(i_x,i_y) = pos2xy(map[\"foodPositions\"][i], map[\"width\"]);\n int dist_x = i_x - snake_x;\n int dist_y = i_y - snake_y;\n\n if (dist_y > -view_distance && dist_y < 0 && abs(dist_x) < view_distance) \n {\n food[0] += (view_distance + dist_y)*(view_distance + dist_y);\n }\n else if (dist_y > 0 && dist_y < view_distance && abs(dist_x) < view_distance) \n {\n food[1] += (view_distance - dist_y)*(view_distance - dist_y);\n }\n \n if (dist_x > -view_distance && dist_x < 0 && abs(dist_y) < view_distance)\n {\n food[3] += (view_distance + dist_x)*(view_distance + dist_x);\n }\n else if (dist_x > 0 && dist_x < view_distance && abs(dist_y) < view_distance)\n {\n food[2] += (view_distance - dist_y)*(view_distance - dist_y);\n }\n }\n\n for (int j = 0; j < map[\"snakeInfos\"].size(); ++j) \/\/ SNAKES (including yourself)\n {\n for (int i = 0; i < map[\"snakeInfos\"][j][\"positions\"].size(); ++i)\n {\n int i_x, i_y;\n std::tie(i_x,i_y) = pos2xy(map[\"snakeInfos\"][j][\"positions\"][i], map[\"width\"]);\n int dist_x = i_x - snake_x;\n int dist_y = i_y - snake_y;\n\n if (dist_y > -view_distance && dist_y < 0 && abs(dist_x) < view_distance) \/\/ danger up\n {\n danger[0] += (view_distance + dist_y)*(view_distance + dist_y)*(view_distance + dist_y);\n }\n else if (dist_y > 0 && dist_y < view_distance && abs(dist_x) < view_distance) \/\/ danger down\n {\n danger[1] += (view_distance - dist_y)*(view_distance - dist_y)*(view_distance - dist_y);\n }\n \n if (dist_x > -view_distance && dist_x < 0 && abs(dist_y) < view_distance)\n {\n danger[3] += (view_distance + dist_x)*(view_distance + dist_x)*(view_distance + dist_x);\n }\n else if (dist_x > 0 && dist_x < view_distance && abs(dist_y) < view_distance)\n {\n danger[2] += (view_distance - dist_y)*(view_distance - dist_y)*(view_distance - dist_y);\n }\n }\n }\n\n\n \/\/ WALLS \n if (snake_y < 5)\n {\n danger[0] += 10*(5 - snake_y)*(5 - snake_y);\n }\n if (mapHight - snake_y < 5)\n {\n danger[1] += 10*(5 - mapHight + snake_y)*(5 - mapHight + snake_y);\n }\n if (snake_x < 5)\n {\n danger[3] += 10*(5 - snake_x)*(5 - snake_x);\n }\n if (mapWidth - snake_x < 5)\n {\n danger[2] += 10*(5 - mapWidth + snake_x)*(5 - mapWidth + snake_x);\n }\n\n\n \/\/ if last move was up you cant go down next move if lastMove = 0\n \/*\n 0 - up\n 1 - down\n 2- right\n 3- left\n *\/\n\n \/\/ Avoid your last move \n if(lastMove == 0){\n avoidedMove = 1;\n }\n else if(lastMove == 1){\n avoidedMove = 0;\n }\n else if(lastMove == 2){\n avoidedMove = 3;\n }\n else{\n avoidedMove = 2;\n }\n danger[avoidedMove] += 1000;\n \/\/ Is not dangerous and food close, is not dagerous or food close \n int best_choice = 0;\n double choice_value = 1000;\n for (int i = 0; i < 4; ++i)\n {\n \/\/LOG(INFO) << \"dir: \" << i << \" d: \" << danger[i] << \" f: \" << food[i];\n if (danger[i] - food[i] < choice_value) \/\/ is good choice and better then the chosen one\n {\n best_choice = i;\n choice_value = danger[i] - food[i];\n }\n }\n \n lastMove = best_choice;\n\n \/\/LOG(INFO) << \"Snake is making move \" << responsArray[best_choice] << \" at worldtick: \" << map[\"worldTick\"];\n return responsArray[best_choice];\n\n};\n\/\/ ---------------------- OUR FUNCTIONS -------------------------------\nvoid Snake::initializeCurves(){\n curveFood[0]= 10; \n curveFood[1]= 5; \n curveFood[2]= 2.5; \n curveFood[3]= 1.25; \n curveFood[4]= 0; \n\n curveWall[0]= -30; \n curveWall[1]= -20; \n curveWall[2]= -10; \n curveWall[3]= -5; \n curveWall[4]= 0; \n\n curvePlayers[0]= -10; \n curvePlayers[1]= -5; \n curvePlayers[2]= -2.5; \n curvePlayers[3]= -1.25; \n curvePlayers[4]= 0; \n\n curveTail[0]= 0; \n curveTail[1]= 0; \n curveTail[2]= 0; \n curveTail[3]= 0; \n curveTail[4]= 0; \n\n curveObstacle[0]= -30; \n curveObstacle[1]= -20; \n curveObstacle[2]= -10; \n curveObstacle[3]= -5; \n curveObstacle[4]= 0; \n\n}\n\n\/\/ From int pos to x,y coords\nstd::tuple Snake::pos2xy(const int position, const int map_width) {\n float pos = position;\n float width = map_width;\n \n int y = floor(pos \/ width);\n int x = fabs(pos - y * width);\n\n return std::make_tuple(x, y);\n}\n\nint Snake::xy2pos(const int x, const int y, const int map_width) {\n int res = x + y * map_width;\n return res;\n}\n\n\n \/\/ ---------------------- THERE FUNCTIONS -------------------------------\nvoid Snake::on_game_ended() {\n LOG(INFO) << \"Game has ended\";\n};\n\nvoid Snake::on_tournament_ended() {\n LOG(INFO) << \"Tournament has ended\";\n};\n\nvoid Snake::on_snake_dead(std::string death_reason) {\n LOG(INFO) << \"Our snake has died, reason was: \" << death_reason;\n};\n\nvoid Snake::on_game_starting() {\n mySnakeSlot = -1;\n LOG(INFO) << \"Game is starting\";\n \/\/ Leta upp din snake ? \n initializeCurves();\n lastMove = 0; \n LOG(INFO) << \"initializeCurves finnished\";\n\n};\n\nvoid Snake::on_player_registered() {\n LOG(INFO) << \"Player was successfully registered\";\n};\n\nvoid Snake::on_invalid_playername() {\n LOG(INFO) << \"The player name is invalid, try another?\";\n};\n\nvoid Snake::on_game_result(nlohmann::json playerRanks) {\n LOG(INFO) << \"Game result:\";\n nlohmann::json playerRank;\n el::Logger* defaultLogger = el::Loggers::getLogger(\"default\");\n for (json::iterator it = playerRanks.begin(); it != playerRanks.end(); ++it) {\n playerRank = (nlohmann::json) *it;\n defaultLogger->info(\"%v.\\t%v pts\\t%v (%v)\", playerRank[\"rank\"], playerRank[\"points\"],\n playerRank[\"playerName\"], playerRank[\"alive\"] ? \"alive\" : \"dead\");\n }\n};\n;\n\nnew good run#include \"easylogging++.h\"\n#include \"json.hpp\"\n#include \"snake.h\"\n\nusing nlohmann::json;\n\n\/\/ Good runs: http:\/\/game.snake.cygni.se\/#\/viewgame\/88a759cf-e406-4941-9eba-28d51ed9c600\n\/\/ http:\/\/game.snake.cygni.se\/#\/viewgame\/af42c3a4-fbf9-4a14-b892-3fdf6da063a4\n\/\/ http:\/\/game.snake.cygni.se\/#\/viewgame\/ed59e861-8147-4845-8f6c-3b586b2b91a4\n\/\/ http:\/\/game.snake.cygni.se\/#\/viewgame\/9645084f-3969-4c84-88ca-35be7cbd8216 (distant 4)\n\/\/ http:\/\/game.snake.cygni.se\/#\/viewgame\/820f1c8b-77f3-4734-93ad-d5d9f5e424b2 (my good run)\n\n\/\/ Postionen ges av int position => endast ett värde på mappen\n\n\/\/ ---------------------- NEXT MOOVE -------------------------------\n\nstd::string Snake::get_next_move(json map) {\n int mapHight = map[\"height\"] ;\n int mapWidth = map[\"width\"] ;\n\n \/\/int response = 1;\n std::string responsArray [] = {\"UP\", \"DOWN\", \"RIGHT\", \"LEFT\"};\n\n std::array responsValue;\n\n \/\/ Reset responsValue\n responsValue[0] = 0; \/\/ UP\n responsValue[1] = 0; \/\/ DOWN\n responsValue[2] = 0; \/\/ RIGHT\n responsValue[3] = 0; \/\/ LEFT\n\n\n \/\/ Hitta vår snake första gången vi spelar \n if(mySnakeSlot == -1){\n mySnakeSlot = 0;\n while(map[\"snakeInfos\"][mySnakeSlot][\"name\"] != name){\n mySnakeSlot++;\n } \n }\n\n int snake_x, snake_y;\n std::tie(snake_x,snake_y) = pos2xy(map[\"snakeInfos\"][mySnakeSlot][\"positions\"][0], map[\"width\"]);\n \/\/ LOG(INFO) << \"Snake pos: \" << x << \", \" << y ; \n \/\/ \n\n double danger[] = {0.0, 0.0, 0.0, 0.0};\n double food[] = {0.0, 0.0, 0.0, 0.0};\n int view_distance = 2;\n\n for (int i = 0; i < map[\"obstaclePositions\"].size(); ++i) \/\/ OBSTACLE\n {\n int i_x, i_y;\n std::tie(i_x,i_y) = pos2xy(map[\"obstaclePositions\"][i], map[\"width\"]);\n int dist_x = i_x - snake_x;\n int dist_y = i_y - snake_y;\n\n if (dist_y > -view_distance && dist_y < 0 && abs(dist_x) < view_distance) \/\/ danger up\n {\n danger[0] += (view_distance + dist_y)*(view_distance + dist_y);\n }\n else if (dist_y > 0 && dist_y < view_distance && abs(dist_x) < view_distance) \/\/ danger down\n {\n danger[1] += (view_distance - dist_y)*(view_distance - dist_y);\n }\n \n if (dist_x > -view_distance && dist_x < 0 && abs(dist_y) < view_distance)\n {\n danger[3] += (view_distance + dist_x)*(view_distance + dist_x);\n }\n else if (dist_x > 0 && dist_x < view_distance && abs(dist_y) < view_distance)\n {\n danger[2] += (view_distance - dist_y)*(view_distance - dist_y);\n }\n\n }\n\n for (int i = 0; i < map[\"foodPositions\"].size(); ++i) \/\/ FOOD \n {\n int i_x, i_y;\n std::tie(i_x,i_y) = pos2xy(map[\"foodPositions\"][i], map[\"width\"]);\n int dist_x = i_x - snake_x;\n int dist_y = i_y - snake_y;\n\n if (dist_y > -view_distance && dist_y < 0 && abs(dist_x) < view_distance) \n {\n food[0] += (view_distance + dist_y)*(view_distance + dist_y);\n }\n else if (dist_y > 0 && dist_y < view_distance && abs(dist_x) < view_distance) \n {\n food[1] += (view_distance - dist_y)*(view_distance - dist_y);\n }\n \n if (dist_x > -view_distance && dist_x < 0 && abs(dist_y) < view_distance)\n {\n food[3] += (view_distance + dist_x)*(view_distance + dist_x);\n }\n else if (dist_x > 0 && dist_x < view_distance && abs(dist_y) < view_distance)\n {\n food[2] += (view_distance - dist_y)*(view_distance - dist_y);\n }\n }\n\n for (int j = 0; j < map[\"snakeInfos\"].size(); ++j) \/\/ SNAKES (including yourself)\n {\n for (int i = 0; i < map[\"snakeInfos\"][j][\"positions\"].size(); ++i)\n {\n int i_x, i_y;\n std::tie(i_x,i_y) = pos2xy(map[\"snakeInfos\"][j][\"positions\"][i], map[\"width\"]);\n int dist_x = i_x - snake_x;\n int dist_y = i_y - snake_y;\n\n if (dist_y > -view_distance && dist_y < 0 && abs(dist_x) < view_distance) \/\/ danger up\n {\n danger[0] += (view_distance + dist_y)*(view_distance + dist_y)*(view_distance + dist_y);\n }\n else if (dist_y > 0 && dist_y < view_distance && abs(dist_x) < view_distance) \/\/ danger down\n {\n danger[1] += (view_distance - dist_y)*(view_distance - dist_y)*(view_distance - dist_y);\n }\n \n if (dist_x > -view_distance && dist_x < 0 && abs(dist_y) < view_distance)\n {\n danger[3] += (view_distance + dist_x)*(view_distance + dist_x)*(view_distance + dist_x);\n }\n else if (dist_x > 0 && dist_x < view_distance && abs(dist_y) < view_distance)\n {\n danger[2] += (view_distance - dist_y)*(view_distance - dist_y)*(view_distance - dist_y);\n }\n }\n }\n\n\n \/\/ WALLS \n if (snake_y < view_distance)\n {\n danger[0] += 3*(view_distance - snake_y)*(view_distance - snake_y);\n }\n if (mapHight - snake_y < view_distance)\n {\n danger[1] += 3*(view_distance - mapHight + snake_y)*(view_distance - mapHight + snake_y);\n }\n if (snake_x < view_distance)\n {\n danger[3] += 3*(view_distance - snake_x)*(view_distance - snake_x);\n }\n if (mapWidth - snake_x < view_distance)\n {\n danger[2] += 3*(view_distance - mapWidth + snake_x)*(view_distance - mapWidth + snake_x);\n }\n\n\n \/\/ if last move was up you cant go down next move if lastMove = 0\n \/*\n 0 - up\n 1 - down\n 2- right\n 3- left\n *\/\n\n \/\/ Avoid your last move \n if(lastMove == 0){\n avoidedMove = 1;\n }\n else if(lastMove == 1){\n avoidedMove = 0;\n }\n else if(lastMove == 2){\n avoidedMove = 3;\n }\n else{\n avoidedMove = 2;\n }\n danger[avoidedMove] += 1000;\n \/\/ Is not dangerous and food close, is not dagerous or food close \n int best_choice = 0;\n double choice_value = 1000;\n for (int i = 0; i < 4; ++i)\n {\n LOG(INFO) << \"dir: \" << i << \" d: \" << danger[i] << \" f: \" << food[i];\n if (danger[i] - food[i] < choice_value) \/\/ is good choice and better then the chosen one\n {\n best_choice = i;\n choice_value = danger[i] - food[i];\n }\n }\n \n lastMove = best_choice;\n\n LOG(INFO) << \"Snake is making move \" << responsArray[best_choice] << \" at worldtick: \" << map[\"worldTick\"];\n return responsArray[best_choice];\n\n};\n\/\/ ---------------------- OUR FUNCTIONS -------------------------------\nvoid Snake::initializeCurves(){\n curveFood[0]= 10; \n curveFood[1]= 5; \n curveFood[2]= 2.5; \n curveFood[3]= 1.25; \n curveFood[4]= 0; \n\n curveWall[0]= -30; \n curveWall[1]= -20; \n curveWall[2]= -10; \n curveWall[3]= -5; \n curveWall[4]= 0; \n\n curvePlayers[0]= -10; \n curvePlayers[1]= -5; \n curvePlayers[2]= -2.5; \n curvePlayers[3]= -1.25; \n curvePlayers[4]= 0; \n\n curveTail[0]= 0; \n curveTail[1]= 0; \n curveTail[2]= 0; \n curveTail[3]= 0; \n curveTail[4]= 0; \n\n curveObstacle[0]= -30; \n curveObstacle[1]= -20; \n curveObstacle[2]= -10; \n curveObstacle[3]= -5; \n curveObstacle[4]= 0; \n\n}\n\n\/\/ From int pos to x,y coords\nstd::tuple Snake::pos2xy(const int position, const int map_width) {\n float pos = position;\n float width = map_width;\n \n int y = floor(pos \/ width);\n int x = fabs(pos - y * width);\n\n return std::make_tuple(x, y);\n}\n\nint Snake::xy2pos(const int x, const int y, const int map_width) {\n int res = x + y * map_width;\n return res;\n}\n\n\n \/\/ ---------------------- THERE FUNCTIONS -------------------------------\nvoid Snake::on_game_ended() {\n LOG(INFO) << \"Game has ended\";\n};\n\nvoid Snake::on_tournament_ended() {\n LOG(INFO) << \"Tournament has ended\";\n};\n\nvoid Snake::on_snake_dead(std::string death_reason) {\n LOG(INFO) << \"Our snake has died, reason was: \" << death_reason;\n};\n\nvoid Snake::on_game_starting() {\n mySnakeSlot = -1;\n LOG(INFO) << \"Game is starting\";\n \/\/ Leta upp din snake ? \n initializeCurves();\n lastMove = 0; \n LOG(INFO) << \"initializeCurves finnished\";\n\n};\n\nvoid Snake::on_player_registered() {\n LOG(INFO) << \"Player was successfully registered\";\n};\n\nvoid Snake::on_invalid_playername() {\n LOG(INFO) << \"The player name is invalid, try another?\";\n};\n\nvoid Snake::on_game_result(nlohmann::json playerRanks) {\n LOG(INFO) << \"Game result:\";\n nlohmann::json playerRank;\n el::Logger* defaultLogger = el::Loggers::getLogger(\"default\");\n for (json::iterator it = playerRanks.begin(); it != playerRanks.end(); ++it) {\n playerRank = (nlohmann::json) *it;\n defaultLogger->info(\"%v.\\t%v pts\\t%v (%v)\", playerRank[\"rank\"], playerRank[\"points\"],\n playerRank[\"playerName\"], playerRank[\"alive\"] ? \"alive\" : \"dead\");\n }\n};\n;\n\n<|endoftext|>"} {"text":"#ifndef string_hh_INCLUDED\n#define string_hh_INCLUDED\n\n#include \n#include \n#include \n#include \n\n#include \"memoryview.hh\"\n#include \"units.hh\"\n#include \"utf8.hh\"\n\nnamespace Kakoune\n{\n\ntypedef boost::regex Regex;\n\nclass String\n{\npublic:\n String() {}\n String(const char* content) : m_content(content) {}\n String(std::string content) : m_content(std::move(content)) {}\n String(const String& string) = default;\n String(String&& string) = default;\n explicit String(char content, CharCount count = 1) : m_content((size_t)(int)count, content) {}\n template\n String(Iterator begin, Iterator end) : m_content(begin, end) {}\n\n char operator[](ByteCount pos) const { return m_content[(int)pos]; }\n ByteCount length() const { return m_content.length(); }\n CharCount char_length() const { return utf8::distance(begin(), end()); }\n ByteCount byte_count_to(CharCount count) const { return utf8::advance(begin(), end(), (int)count) - begin(); }\n CharCount char_count_to(ByteCount count) const { return utf8::distance(begin(), begin() + (int)count); }\n bool empty() const { return m_content.empty(); }\n\n bool operator== (const String& other) const { return m_content == other.m_content; }\n bool operator!= (const String& other) const { return m_content != other.m_content; }\n bool operator< (const String& other) const { return m_content < other.m_content; }\n\n String& operator= (const String& other) { m_content = other.m_content; return *this; }\n String& operator= (String&& other) { m_content = std::move(other.m_content); return *this; }\n\n String operator+ (const String& other) const { return String(m_content + other.m_content); }\n String& operator+= (const String& other) { m_content += other.m_content; return *this; }\n\n String operator+ (char c) const { return String(m_content + c); }\n String& operator+= (char c) { m_content += c; return *this; }\n\n memoryview data() const { return memoryview(m_content.data(), m_content.size()); }\n const char* c_str() const { return m_content.c_str(); }\n\n String substr(ByteCount pos, ByteCount length = -1) const { return String(m_content.substr((int)pos, (int)length)); }\n String substr(CharCount pos, CharCount length = INT_MAX) const\n {\n auto b = utf8::advance(begin(), end(), (int)pos);\n auto e = utf8::advance(b, end(), (int)length);\n return String(b,e);\n }\n String replace(const String& expression, const String& replacement) const;\n\n using iterator = std::string::const_iterator;\n\n iterator begin() const { return m_content.begin(); }\n iterator end() const { return m_content.end(); }\n\n char front() const { return m_content.front(); }\n char back() const { return m_content.back(); }\n char& front() { return m_content.front(); }\n char& back() { return m_content.back(); }\n\n size_t hash() const { return std::hash()(m_content); }\n\n inline friend std::ostream& operator<<(std::ostream& os, const String& str)\n {\n return os << str.m_content;\n }\n\n enum { npos = -1 };\n\nprivate:\n std::string m_content;\n};\n\ninline String operator+(const char* lhs, const String& rhs)\n{\n return String(lhs) + rhs;\n}\n\ninline String operator+(char lhs, const String& rhs)\n{\n return String(lhs) + rhs;\n}\n\nString int_to_str(int value);\nint str_to_int(const String& str);\nstd::vector split(const String& str, char separator);\n\ninline String operator\"\" _str(const char* str, size_t)\n{\n return String(str);\n}\n\ninline String codepoint_to_str(Codepoint cp)\n{\n std::string str;\n auto it = back_inserter(str);\n utf8::dump(it, cp);\n return String(str);\n}\n\n}\n\nnamespace std\n{\n template<>\n struct hash\n {\n size_t operator()(const Kakoune::String& str) const\n {\n return str.hash();\n }\n };\n}\n\n#endif \/\/ string_hh_INCLUDED\n\nAdd a String(Codepoint, CharCount) constructor#ifndef string_hh_INCLUDED\n#define string_hh_INCLUDED\n\n#include \n#include \n#include \n#include \n\n#include \"memoryview.hh\"\n#include \"units.hh\"\n#include \"utf8.hh\"\n\nnamespace Kakoune\n{\n\ntypedef boost::regex Regex;\n\nclass String\n{\npublic:\n String() {}\n String(const char* content) : m_content(content) {}\n String(std::string content) : m_content(std::move(content)) {}\n String(const String& string) = default;\n String(String&& string) = default;\n explicit String(char content, CharCount count = 1) : m_content((size_t)(int)count, content) {}\n explicit String(Codepoint cp, CharCount count = 1)\n {\n std::string str;\n auto it = back_inserter(str);\n utf8::dump(it, cp);\n for (CharCount i = 0; i < count; ++i)\n m_content += str;\n }\n template\n String(Iterator begin, Iterator end) : m_content(begin, end) {}\n\n char operator[](ByteCount pos) const { return m_content[(int)pos]; }\n ByteCount length() const { return m_content.length(); }\n CharCount char_length() const { return utf8::distance(begin(), end()); }\n ByteCount byte_count_to(CharCount count) const { return utf8::advance(begin(), end(), (int)count) - begin(); }\n CharCount char_count_to(ByteCount count) const { return utf8::distance(begin(), begin() + (int)count); }\n bool empty() const { return m_content.empty(); }\n\n bool operator== (const String& other) const { return m_content == other.m_content; }\n bool operator!= (const String& other) const { return m_content != other.m_content; }\n bool operator< (const String& other) const { return m_content < other.m_content; }\n\n String& operator= (const String& other) { m_content = other.m_content; return *this; }\n String& operator= (String&& other) { m_content = std::move(other.m_content); return *this; }\n\n String operator+ (const String& other) const { return String(m_content + other.m_content); }\n String& operator+= (const String& other) { m_content += other.m_content; return *this; }\n\n String operator+ (char c) const { return String(m_content + c); }\n String& operator+= (char c) { m_content += c; return *this; }\n\n memoryview data() const { return memoryview(m_content.data(), m_content.size()); }\n const char* c_str() const { return m_content.c_str(); }\n\n String substr(ByteCount pos, ByteCount length = -1) const { return String(m_content.substr((int)pos, (int)length)); }\n String substr(CharCount pos, CharCount length = INT_MAX) const\n {\n auto b = utf8::advance(begin(), end(), (int)pos);\n auto e = utf8::advance(b, end(), (int)length);\n return String(b,e);\n }\n String replace(const String& expression, const String& replacement) const;\n\n using iterator = std::string::const_iterator;\n\n iterator begin() const { return m_content.begin(); }\n iterator end() const { return m_content.end(); }\n\n char front() const { return m_content.front(); }\n char back() const { return m_content.back(); }\n char& front() { return m_content.front(); }\n char& back() { return m_content.back(); }\n\n size_t hash() const { return std::hash()(m_content); }\n\n inline friend std::ostream& operator<<(std::ostream& os, const String& str)\n {\n return os << str.m_content;\n }\n\n enum { npos = -1 };\n\nprivate:\n std::string m_content;\n};\n\ninline String operator+(const char* lhs, const String& rhs)\n{\n return String(lhs) + rhs;\n}\n\ninline String operator+(char lhs, const String& rhs)\n{\n return String(lhs) + rhs;\n}\n\nString int_to_str(int value);\nint str_to_int(const String& str);\nstd::vector split(const String& str, char separator);\n\ninline String operator\"\" _str(const char* str, size_t)\n{\n return String(str);\n}\n\ninline String codepoint_to_str(Codepoint cp)\n{\n std::string str;\n auto it = back_inserter(str);\n utf8::dump(it, cp);\n return String(str);\n}\n\n}\n\nnamespace std\n{\n template<>\n struct hash\n {\n size_t operator()(const Kakoune::String& str) const\n {\n return str.hash();\n }\n };\n}\n\n#endif \/\/ string_hh_INCLUDED\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\n#include \"debug.h\"\n\n#define LED_PIN 2\n#define SW_PIN 0\n\nconst char *ssid = \"OnePlus2\";\nconst char *password = \"global@123\";\nconst char *mqtt_server = \"192.168.43.162\";\nconst char *control_topic = \"esp8266\/control\/led\";\nconst char *status_topic = \"esp8266\/status\/led\";\nconst char *override_topic = \"esp8266\/override\/led\";\n\nWiFiClient espClient;\nPubSubClient client(espClient);\n\nlong lastMsg = 0;\nchar msg[50];\nvolatile bool ledstate = true; \/\/Active low relay switch\nvolatile bool interrupted = false;\n\nvoid setup_wifi(void);\nvoid callback(char *topic, byte *payload, unsigned int length);\nvoid reconnect(void);\n\nvoid setup(void);\nvoid loop(void);\n\nvoid setup_wifi() {\n delay(10);\n Serial_println();\n Serial_print(\"Connecting to \");\n Serial_println(ssid);\n\n WiFi.mode(WIFI_STA);\n WiFi.begin(ssid, password);\n delay(10);\n\n while (WiFi.waitForConnectResult() != WL_CONNECTED) {\n Serial_println(\"Connection failed! rebooting...\");\n delay(5000);\n ESP.restart();\n }\n\n Serial_println(\"WiFi connected\");\n Serial_println(\"IP address: \");\n Serial_println(WiFi.localIP());\n}\n\nvoid callback(char *topic, byte *payload, unsigned int length) {\n Serial_print(\"Message arrived [\");\n Serial_print(topic);\n Serial_print(\"] \");\n for (int i = 0; i < length; i++) {\n Serial_print((char)payload[i]);\n }\n Serial_println();\n\n if(strcmp(control_topic,topic)==0){\n if ((char)payload[0] == '1') {\n ledstate = false;\n digitalWrite(LED_PIN, LOW);\n } else {\n ledstate = true;\n digitalWrite(LED_PIN, HIGH);\n }\n }\n}\n\nvoid reconnect() {\n while (!client.connected()) {\n Serial_print(\"Attempting MQTT connection...\");\n if (client.connect(\"ESP8266Client\")) {\n Serial_println(\"connected\");\n client.publish(status_topic, \"system ready\");\n client.subscribe(control_topic);\n } else {\n Serial_print(\"failed, rc=\");\n Serial_print(client.state());\n Serial_println(\" try again in 5 seconds\");\n delay(5000);\n }\n }\n}\n\n\/\/Interrupt function\nvoid handle_toggle_switch_interrupt(){\n ledstate = !ledstate;\n interrupted = true;\n}\n\nvoid handle_switching(){\n if(interrupted){\n digitalWrite(LED_PIN, ledstate);\n snprintf (msg, 75, \"%ld\", ledstate ? 0 : 1);\n Serial_print(\"Publish override message: ledstate \");\n Serial_println(msg);\n client.publish(override_topic, msg);\n interrupted = false;\n }\n}\n\nvoid setup() {\n Serial.begin(115200);\n setup_wifi();\n pinMode(LED_PIN, OUTPUT);\n pinMode(SW_PIN, INPUT_PULLUP);\n attachInterrupt(digitalPinToInterrupt(SW_PIN), handle_toggle_switch_interrupt, FALLING);\n client.setServer(mqtt_server, 1883);\n client.setCallback(callback);\n}\n\nvoid loop() {\n handle_switching();\n\n if (!client.connected()) {\n reconnect();\n }\n\n client.loop();\n\n long now = millis();\n\n if (now - lastMsg > 5000) {\n lastMsg = now;\n snprintf (msg, 75, \"%ld\", ledstate ? 0 : 1);\n Serial_print(\"Publish status message: ledstate \");\n Serial_println(msg);\n client.publish(status_topic, msg);\n }\n delay(90);\n}\noverrirde, on no mqtt connection#include \n#include \n#include \n#include \n\n#include \"debug.h\"\n\n#define LED_PIN 2\n#define SW_PIN 0\n\nconst char *ssid = \"OnePlus2\";\nconst char *password = \"global@123\";\nconst char *mqtt_server = \"192.168.43.162\";\nconst char *control_topic = \"esp8266\/control\/led\";\nconst char *status_topic = \"esp8266\/status\/led\";\nconst char *override_topic = \"esp8266\/override\/led\";\n\nWiFiClient espClient;\nPubSubClient client(espClient);\n\nlong lastMsg = 0;\nchar msg[50];\nvolatile bool ledstate = true; \/\/Active low relay switch\nvolatile bool interrupted = false;\n\nvoid setup_wifi(void);\nvoid callback(char *topic, byte *payload, unsigned int length);\nvoid reconnect(void);\nvoid handle_switching(void);\nvoid handle_toggle_switch_interrupt(void);\n\nvoid setup(void);\nvoid loop(void);\n\nvoid setup_wifi() {\n delay(10);\n Serial_println();\n Serial_print(\"Connecting to \");\n Serial_println(ssid);\n\n WiFi.mode(WIFI_STA);\n WiFi.begin(ssid, password);\n delay(10);\n\n while (WiFi.waitForConnectResult() != WL_CONNECTED) {\n Serial_println(\"Connection failed! rebooting...\");\n delay(5000);\n ESP.restart();\n }\n\n Serial_println(\"WiFi connected\");\n Serial_println(\"IP address: \");\n Serial_println(WiFi.localIP());\n}\n\nvoid callback(char *topic, byte *payload, unsigned int length) {\n Serial_print(\"Message arrived [\");\n Serial_print(topic);\n Serial_print(\"] \");\n for (int i = 0; i < length; i++) {\n Serial_print((char)payload[i]);\n }\n Serial_println();\n\n if(strcmp(control_topic,topic)==0){\n if ((char)payload[0] == '1') {\n ledstate = false;\n digitalWrite(LED_PIN, LOW);\n } else {\n ledstate = true;\n digitalWrite(LED_PIN, HIGH);\n }\n }\n}\n\nvoid reconnect() {\n while (!client.connected()) {\n Serial_print(\"Attempting MQTT connection...\");\n if (client.connect(\"ESP8266Client\")) {\n Serial_println(\"connected\");\n client.publish(status_topic, \"system ready\");\n client.subscribe(control_topic);\n } else {\n handle_switching();\n Serial_print(\"failed, rc=\");\n Serial_print(client.state());\n Serial_println(\" try again in 5 seconds\");\n for(int msec=0; msec < 5000; msec+= 500){\n delay(500);\n handle_switching();\n }\n }\n }\n}\n\n\/\/Interrupt function\nvoid handle_toggle_switch_interrupt(void){\n ledstate = !ledstate;\n interrupted = true;\n}\n\nvoid handle_switching(void){\n if(interrupted){\n digitalWrite(LED_PIN, ledstate);\n if(client.connected()){\n snprintf (msg, 75, \"%ld\", ledstate ? 0 : 1);\n Serial_print(\"Publish override message: ledstate \");\n Serial_println(msg);\n client.publish(override_topic, msg);\n interrupted = false;\n }\n }\n}\n\nvoid setup() {\n Serial.begin(115200);\n setup_wifi();\n pinMode(LED_PIN, OUTPUT);\n pinMode(SW_PIN, INPUT_PULLUP);\n attachInterrupt(digitalPinToInterrupt(SW_PIN), handle_toggle_switch_interrupt, FALLING);\n client.setServer(mqtt_server, 1883);\n client.setCallback(callback);\n}\n\nvoid loop() {\n handle_switching();\n\n if (!client.connected()) {\n reconnect();\n }\n\n client.loop();\n\n long now = millis();\n\n if (now - lastMsg > 5000) {\n lastMsg = now;\n snprintf (msg, 75, \"%ld\", ledstate ? 0 : 1);\n Serial_print(\"Publish status message: ledstate \");\n Serial_println(msg);\n client.publish(status_topic, msg);\n }\n delay(90);\n}\n<|endoftext|>"} {"text":"\/* timer.cpp -*- C++ -*-\n Rémi Attab (remi.attab@gmail.com), 27 Dec 2013\n FreeBSD-style copyright and disclaimer apply\n\n Timer implementation.\n*\/\n\n#include \"timer.h\"\n#include \"utils.h\"\n\n#include \n#include \n#include \n\nnamespace slick {\n\n\n\/******************************************************************************\/\n\/* TIMER *\/\n\/******************************************************************************\/\n\nTimer::\nTimer(double delay, double init)\n{\n int clockid = delay < 0.01 ? CLOCK_MONOTONIC : CLOCK_REALTIME;\n\n fd_ = timerfd_create(clockid, TFD_NONBLOCK);\n SLICK_CHECK_ERRNO(fd_ != -1, \"timer.create\");\n\n setDelay(delay, init);\n}\n\n\nTimer::\n~Timer()\n{\n if (fd_ >= 0) close(fd_);\n}\n\nvoid\nTimer::\npoll()\n{\n\n uint64_t expirations = 0;\n\n ssize_t bytes = read(fd_, &expirations, sizeof(expirations));\n\n if (bytes == -1) {\n if (errno == EAGAIN || EWOULDBLOCK) return;\n SLICK_CHECK_ERRNO(bytes != -1, \"timer.read\");\n }\n\n assert(bytes == sizeof(expirations));\n if (onTimer) onTimer(expirations);\n}\n\nvoid\nTimer::\nsetDelay(double delay, double init)\n{\n if (init == 0.0) init = delay;\n\n auto ts = [] (double value) {\n struct timespec ts;\n ts.tv_sec = uint64_t(value);\n ts.tv_nsec = value - ts.tv_sec;\n return ts;\n };\n\n struct itimerspec spec = { ts(delay), ts(init) };\n int res = timerfd_settime(fd_, 0, &spec, nullptr);\n SLICK_CHECK_ERRNO(res != -1, \"timer.settime\");\n}\n\n\n} \/\/ slick\nTimerFd now properly calculates sub-sec values.\/* timer.cpp -*- C++ -*-\n Rémi Attab (remi.attab@gmail.com), 27 Dec 2013\n FreeBSD-style copyright and disclaimer apply\n\n Timer implementation.\n*\/\n\n#include \"timer.h\"\n#include \"utils.h\"\n\n#include \n#include \n#include \n\nnamespace slick {\n\n\n\/******************************************************************************\/\n\/* TIMER *\/\n\/******************************************************************************\/\n\nTimer::\nTimer(double delay, double init)\n{\n int clockid = delay < 0.01 ? CLOCK_MONOTONIC : CLOCK_REALTIME;\n\n fd_ = timerfd_create(clockid, TFD_NONBLOCK);\n SLICK_CHECK_ERRNO(fd_ != -1, \"timer.create\");\n\n setDelay(delay, init);\n}\n\n\nTimer::\n~Timer()\n{\n if (fd_ >= 0) close(fd_);\n}\n\nvoid\nTimer::\npoll()\n{\n\n uint64_t expirations = 0;\n\n ssize_t bytes = read(fd_, &expirations, sizeof(expirations));\n\n if (bytes == -1) {\n if (errno == EAGAIN || EWOULDBLOCK) return;\n SLICK_CHECK_ERRNO(bytes != -1, \"timer.read\");\n }\n\n assert(bytes == sizeof(expirations));\n if (onTimer) onTimer(expirations);\n}\n\nvoid\nTimer::\nsetDelay(double delay, double init)\n{\n if (init == 0.0) init = delay;\n\n auto ts = [] (double value) {\n struct timespec ts;\n ts.tv_sec = uint64_t(value);\n ts.tv_nsec = (value - ts.tv_sec) * 1000000000;\n return ts;\n };\n\n\n struct itimerspec spec = { ts(delay), ts(init) };\n int res = timerfd_settime(fd_, 0, &spec, nullptr);\n SLICK_CHECK_ERRNO(res != -1, \"timer.settime\");\n}\n\n\n} \/\/ slick\n<|endoftext|>"} {"text":"\r\n#if !defined(MAX_TIMERS)\r\n#define MAX_TIMERS MAX_WORKER_THREADS\r\n#endif\r\n\r\ntypedef int (*taction)(void *arg);\r\n\r\nstruct timer {\r\n double time;\r\n double period;\r\n taction action;\r\n void * arg;\r\n};\r\n\r\nstruct timers {\r\n pthread_t threadid; \/* Timer thread ID *\/\n pthread_mutex_t mutex; \/* Protects timer lists *\/\n struct timer timers[MAX_TIMERS]; \/* List of timers *\/\n unsigned timer_count; \/* Current size of timer list *\/\n};\n\nstatic int timer_add(struct mg_context * ctx, double next_time, double period, int is_relative, taction action, void * arg)\n{\n unsigned u, v;\n int error = 0;\n struct timespec now;\n\n if (ctx->stop_flag) {\n return 0;\n }\n\n if (is_relative) {\n clock_gettime(CLOCK_MONOTONIC, &now);\n next_time += now.tv_sec;\n next_time += now.tv_nsec * 1.0E-9;\n }\n\n pthread_mutex_lock(&ctx->timers->mutex);\n if (ctx->timers->timer_count == MAX_TIMERS) {\n error = 1;\n } else {\n for (u=0; utimers->timer_count; u++) {\n if (ctx->timers->timers[u].time < next_time) {\n for (v=ctx->timers->timer_count; v>u; v--) {\n ctx->timers->timers[v] = ctx->timers->timers[v-1];\n }\n break;\n }\n }\n ctx->timers->timers[u].time = next_time;\n ctx->timers->timers[u].period = period;\n ctx->timers->timers[u].action = action;\n ctx->timers->timers[u].arg = arg;\n ctx->timers->timer_count++;\n }\n pthread_mutex_unlock(&ctx->timers->mutex);\n return error;\n}\n\nstatic void timer_thread_run(void *thread_func_param)\n{\n struct mg_context *ctx = (struct mg_context *) thread_func_param;\n struct timespec now;\n double d;\n unsigned u;\n int re_schedule;\n struct timer t;\n\n while (ctx->stop_flag == 0) {\n#if defined(HAVE_CLOCK_NANOSLEEP) \/* Linux with librt *\/\n while (clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &request, &request)==EINTR) {\/*nop*\/;}\n#else\n clock_gettime(CLOCK_MONOTONIC, &now);\n d = (double)now.tv_sec + (double)now.tv_nsec * 1.0E-9;\n for (;;) {\n pthread_mutex_lock(&ctx->timers->mutex);\n if (ctx->timers->timer_count > 0 && d >= ctx->timers->timers[0].time) {\n t = ctx->timers->timers[0];\n for (u=1; utimers->timer_count; u++) {\n ctx->timers->timers[u-1] = ctx->timers->timers[u];\n }\n ctx->timers->timer_count--;\n pthread_mutex_unlock(&ctx->timers->mutex);\n re_schedule = t.action(t.arg);\n if (re_schedule && (t.period>0)) {\n timer_add(ctx, t.time+t.period, t.period, 0, t.action, t.arg);\n }\n continue;\n } else {\n pthread_mutex_unlock(&ctx->timers->mutex);\n }\n mg_sleep(1);\n clock_gettime(CLOCK_MONOTONIC, &now);\n d = (double)now.tv_sec + (double)now.tv_nsec * 1.0E-9;\n }\n#endif\n }\n}\n\n#ifdef _WIN32\nstatic unsigned __stdcall timer_thread(void *thread_func_param)\n{\n timer_thread_run(thread_func_param);\n return 0;\n}\n#else\nstatic void *timer_thread(void *thread_func_param)\n{\n timer_thread_run(thread_func_param);\n return NULL;\n}\n#endif \/* _WIN32 *\/\n\nstatic int timers_init(struct mg_context * ctx)\n{\n ctx->timers = (struct timers*) mg_calloc(sizeof(struct timers), 1);\n (void) pthread_mutex_init(&ctx->timers->mutex, NULL);\n\n \/* Start timer thread *\/\n mg_start_thread_with_id(timer_thread, ctx, &ctx->timers->threadid);\n\n return 0;\n}\n\nstatic void timers_exit(struct mg_context * ctx)\n{\n (void) pthread_mutex_destroy(&ctx->timers->mutex);\n mg_free(ctx->timers);\n}\nTimer loop must exit when server closes\r\n#if !defined(MAX_TIMERS)\r\n#define MAX_TIMERS MAX_WORKER_THREADS\r\n#endif\r\n\r\ntypedef int (*taction)(void *arg);\r\n\r\nstruct timer {\r\n double time;\r\n double period;\r\n taction action;\r\n void * arg;\r\n};\r\n\r\nstruct timers {\r\n pthread_t threadid; \/* Timer thread ID *\/\n pthread_mutex_t mutex; \/* Protects timer lists *\/\n struct timer timers[MAX_TIMERS]; \/* List of timers *\/\n unsigned timer_count; \/* Current size of timer list *\/\n};\n\nstatic int timer_add(struct mg_context * ctx, double next_time, double period, int is_relative, taction action, void * arg)\n{\n unsigned u, v;\n int error = 0;\n struct timespec now;\n\n if (ctx->stop_flag) {\n return 0;\n }\n\n if (is_relative) {\n clock_gettime(CLOCK_MONOTONIC, &now);\n next_time += now.tv_sec;\n next_time += now.tv_nsec * 1.0E-9;\n }\n\n pthread_mutex_lock(&ctx->timers->mutex);\n if (ctx->timers->timer_count == MAX_TIMERS) {\n error = 1;\n } else {\n for (u=0; utimers->timer_count; u++) {\n if (ctx->timers->timers[u].time < next_time) {\n for (v=ctx->timers->timer_count; v>u; v--) {\n ctx->timers->timers[v] = ctx->timers->timers[v-1];\n }\n break;\n }\n }\n ctx->timers->timers[u].time = next_time;\n ctx->timers->timers[u].period = period;\n ctx->timers->timers[u].action = action;\n ctx->timers->timers[u].arg = arg;\n ctx->timers->timer_count++;\n }\n pthread_mutex_unlock(&ctx->timers->mutex);\n return error;\n}\n\nstatic void timer_thread_run(void *thread_func_param)\n{\n struct mg_context *ctx = (struct mg_context *) thread_func_param;\n struct timespec now;\n double d;\n unsigned u;\n int re_schedule;\n struct timer t;\n\n#if defined(HAVE_CLOCK_NANOSLEEP) \/* Linux with librt *\/\n \/* TODO *\/\n while (clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &request, &request)==EINTR) {\/*nop*\/;}\n#else\n clock_gettime(CLOCK_MONOTONIC, &now);\n d = (double)now.tv_sec + (double)now.tv_nsec * 1.0E-9;\n while (ctx->stop_flag == 0) {\n pthread_mutex_lock(&ctx->timers->mutex);\n if (ctx->timers->timer_count > 0 && d >= ctx->timers->timers[0].time) {\n t = ctx->timers->timers[0];\n for (u=1; utimers->timer_count; u++) {\n ctx->timers->timers[u-1] = ctx->timers->timers[u];\n }\n ctx->timers->timer_count--;\n pthread_mutex_unlock(&ctx->timers->mutex);\n re_schedule = t.action(t.arg);\n if (re_schedule && (t.period>0)) {\n timer_add(ctx, t.time+t.period, t.period, 0, t.action, t.arg);\n }\n continue;\n } else {\n pthread_mutex_unlock(&ctx->timers->mutex);\n }\n mg_sleep(1);\n clock_gettime(CLOCK_MONOTONIC, &now);\n d = (double)now.tv_sec + (double)now.tv_nsec * 1.0E-9;\n }\n#endif\n\n}\n\n#ifdef _WIN32\nstatic unsigned __stdcall timer_thread(void *thread_func_param)\n{\n timer_thread_run(thread_func_param);\n return 0;\n}\n#else\nstatic void *timer_thread(void *thread_func_param)\n{\n timer_thread_run(thread_func_param);\n return NULL;\n}\n#endif \/* _WIN32 *\/\n\nstatic int timers_init(struct mg_context * ctx)\n{\n ctx->timers = (struct timers*) mg_calloc(sizeof(struct timers), 1);\n (void) pthread_mutex_init(&ctx->timers->mutex, NULL);\n\n \/* Start timer thread *\/\n mg_start_thread_with_id(timer_thread, ctx, &ctx->timers->threadid);\n\n return 0;\n}\n\nstatic void timers_exit(struct mg_context * ctx)\n{\n (void) pthread_mutex_destroy(&ctx->timers->mutex);\n mg_free(ctx->timers);\n}\n<|endoftext|>"} {"text":"#ifndef ITER_TAKEWHILE_H_\n#define ITER_TAKEWHILE_H_\n\n#include \"iterbase.hpp\"\n\n#include \n#include \n#include \n\nnamespace iter {\n\n \/\/Forward declarations of TakeWhile and takewhile\n template \n class TakeWhile;\n\n template \n TakeWhile takewhile(FilterFunc, Container&&);\n\n template \n TakeWhile> takewhile(\n FilterFunc, std::initializer_list);\n\n template \n class TakeWhile {\n private:\n Container container;\n FilterFunc filter_func;\n\n friend TakeWhile takewhile(\n FilterFunc, Container&&);\n\n template \n friend TakeWhile> takewhile(\n FF, std::initializer_list);\n\n TakeWhile(FilterFunc in_filter_func, Container&& in_container)\n : container(std::forward(in_container)),\n filter_func(in_filter_func)\n { }\n\n\n public:\n\n class Iterator \n : public std::iterator>\n {\n private:\n iterator_type sub_iter;\n iterator_type sub_end;\n DerefHolder> item;\n FilterFunc *filter_func;\n\n void inc_sub_iter() {\n ++this->sub_iter;\n if (this->sub_iter != this->sub_end) {\n this->item.reset(*this->sub_iter);\n }\n }\n\n void check_current() {\n if (this->sub_iter != this->sub_end\n && !(*this->filter_func)(this->item.get())) {\n this->sub_iter = this->sub_end;\n }\n }\n\n public:\n Iterator(iterator_type&& iter,\n iterator_type&& end,\n FilterFunc& in_filter_func)\n : sub_iter{std::move(iter)},\n sub_end{std::move(end)},\n filter_func(&in_filter_func)\n { \n if (this->sub_iter != this->sub_end) {\n this->item.reset(*this->sub_iter);\n }\n this->check_current();\n } \n\n iterator_deref operator*() {\n return this->item.pull();\n }\n\n Iterator& operator++() { \n this->inc_sub_iter();\n this->check_current();\n return *this;\n }\n\n Iterator operator++(int) {\n auto ret = *this;\n ++*this;\n return ret;\n }\n\n bool operator!=(const Iterator& other) const {\n return this->sub_iter != other.sub_iter;\n }\n\n bool operator==(const Iterator& other) const {\n return !(*this != other);\n }\n \n };\n\n Iterator begin() {\n return {std::begin(this->container),\n std::end(this->container),\n this->filter_func};\n }\n\n Iterator end() {\n return {std::end(this->container),\n std::end(this->container),\n this->filter_func};\n }\n\n };\n\n template \n TakeWhile takewhile(\n FilterFunc filter_func, Container&& container) {\n return {filter_func, std::forward(container)};\n }\n\n template \n TakeWhile> takewhile(\n FilterFunc filter_func, std::initializer_list il)\n {\n return {filter_func, std::move(il)};\n }\n\n}\n\n#endif\ntakewhile uses get() instead of pull()#ifndef ITER_TAKEWHILE_H_\n#define ITER_TAKEWHILE_H_\n\n#include \"iterbase.hpp\"\n\n#include \n#include \n#include \n\nnamespace iter {\n\n \/\/Forward declarations of TakeWhile and takewhile\n template \n class TakeWhile;\n\n template \n TakeWhile takewhile(FilterFunc, Container&&);\n\n template \n TakeWhile> takewhile(\n FilterFunc, std::initializer_list);\n\n template \n class TakeWhile {\n private:\n Container container;\n FilterFunc filter_func;\n\n friend TakeWhile takewhile(\n FilterFunc, Container&&);\n\n template \n friend TakeWhile> takewhile(\n FF, std::initializer_list);\n\n TakeWhile(FilterFunc in_filter_func, Container&& in_container)\n : container(std::forward(in_container)),\n filter_func(in_filter_func)\n { }\n\n\n public:\n\n class Iterator \n : public std::iterator>\n {\n private:\n using Holder = DerefHolder>;\n iterator_type sub_iter;\n iterator_type sub_end;\n Holder item;\n FilterFunc *filter_func;\n\n void inc_sub_iter() {\n ++this->sub_iter;\n if (this->sub_iter != this->sub_end) {\n this->item.reset(*this->sub_iter);\n }\n }\n\n void check_current() {\n if (this->sub_iter != this->sub_end\n && !(*this->filter_func)(this->item.get())) {\n this->sub_iter = this->sub_end;\n }\n }\n\n public:\n Iterator(iterator_type&& iter,\n iterator_type&& end,\n FilterFunc& in_filter_func)\n : sub_iter{std::move(iter)},\n sub_end{std::move(end)},\n filter_func(&in_filter_func)\n { \n if (this->sub_iter != this->sub_end) {\n this->item.reset(*this->sub_iter);\n }\n this->check_current();\n } \n\n typename Holder::reference operator*() {\n return this->item.get();\n }\n\n Iterator& operator++() { \n this->inc_sub_iter();\n this->check_current();\n return *this;\n }\n\n Iterator operator++(int) {\n auto ret = *this;\n ++*this;\n return ret;\n }\n\n bool operator!=(const Iterator& other) const {\n return this->sub_iter != other.sub_iter;\n }\n\n bool operator==(const Iterator& other) const {\n return !(*this != other);\n }\n \n };\n\n Iterator begin() {\n return {std::begin(this->container),\n std::end(this->container),\n this->filter_func};\n }\n\n Iterator end() {\n return {std::end(this->container),\n std::end(this->container),\n this->filter_func};\n }\n\n };\n\n template \n TakeWhile takewhile(\n FilterFunc filter_func, Container&& container) {\n return {filter_func, std::forward(container)};\n }\n\n template \n TakeWhile> takewhile(\n FilterFunc filter_func, std::initializer_list il)\n {\n return {filter_func, std::move(il)};\n }\n\n}\n\n#endif\n<|endoftext|>"} {"text":"#include \"stdafx.h\"\r\n\r\nIBOID afCreateIndexBuffer(const AFIndex* indi, int numIndi)\r\n{\r\n\tIBOID ibo;\r\n\tglGenBuffers(1, &ibo.x);\r\n\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);\r\n\tglBufferData(GL_ELEMENT_ARRAY_BUFFER, numIndi * sizeof(AFIndex), &indi[0], GL_STATIC_DRAW);\r\n\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);\r\n\treturn ibo;\r\n}\r\n\r\nVBOID afCreateVertexBuffer(int size, const void* buf)\r\n{\r\n\tVBOID vbo;\r\n\tglGenBuffers(1, &vbo.x);\r\n\tglBindBuffer(GL_ARRAY_BUFFER, vbo);\r\n\tglBufferData(GL_ARRAY_BUFFER, size, buf, GL_STATIC_DRAW);\r\n\tglBindBuffer(GL_ARRAY_BUFFER, 0);\r\n\treturn vbo;\r\n}\r\n\r\nVBOID afCreateDynamicVertexBuffer(int size)\r\n{\r\n\tVBOID vbo;\r\n\tglGenBuffers(1, &vbo.x);\r\n\tglBindBuffer(GL_ARRAY_BUFFER, vbo);\r\n\tglBufferData(GL_ARRAY_BUFFER, size, NULL, GL_DYNAMIC_DRAW);\r\n\tglBindBuffer(GL_ARRAY_BUFFER, 0);\r\n\treturn vbo;\r\n}\r\n\r\nSSBOID afCreateSSBO(int size)\r\n{\r\n\tSSBOID name;\r\n\tglGenBuffers(1, &name.x);\r\n\tglBindBuffer(GL_SHADER_STORAGE_BUFFER, name);\r\n\tglBufferData(GL_SHADER_STORAGE_BUFFER, size, NULL, GL_DYNAMIC_DRAW);\r\n\tglBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);\r\n\treturn name;\r\n}\r\n\r\nUBOID afCreateUBO(int size)\r\n{\r\n\tUBOID name;\r\n\tglGenBuffers(1, &name.x);\r\n\tglBindBuffer(GL_UNIFORM_BUFFER, name);\r\n\tglBufferData(GL_UNIFORM_BUFFER, size, NULL, GL_DYNAMIC_DRAW);\r\n\tglBindBuffer(GL_UNIFORM_BUFFER, 0);\r\n\treturn name;\r\n}\r\n\r\nvoid afBindBuffer(GLuint program, const GLchar* name, SSBOID ssbo, GLuint storageBlockBinding)\r\n{\r\n\tglShaderStorageBlockBinding(program, glGetProgramResourceIndex(program, GL_SHADER_STORAGE_BLOCK, name), storageBlockBinding);\r\n\tglBindBufferBase(GL_SHADER_STORAGE_BUFFER, storageBlockBinding, ssbo);\r\n}\r\n\r\nvoid afBindBuffer(GLuint program, const GLchar* name, UBOID ubo, GLuint uniformBlockBinding)\r\n{\r\n\tglUniformBlockBinding(program, glGetUniformBlockIndex(program, name), uniformBlockBinding);\r\n\tglBindBufferBase(GL_UNIFORM_BUFFER, uniformBlockBinding, ubo);\r\n}\r\n\r\nGLuint afCreateDynamicTexture(int w, int h, AFDTFormat format)\r\n{\r\n\tGLuint texture;\r\n\tglGenTextures(1, &texture);\r\n\tglBindTexture(GL_TEXTURE_2D, texture);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);\r\n\tswitch (format) {\r\n\tcase AFDT_R8G8B8A8_UINT:\r\n\t\tglPixelStorei(GL_UNPACK_ALIGNMENT, 4);\r\n\t\tglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);\r\n\t\tbreak;\r\n\tcase AFDT_R5G6B5_UINT:\r\n\t\tglPixelStorei(GL_UNPACK_ALIGNMENT, 2);\r\n\t\tglTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 512, 512, 0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, nullptr);\r\n\t\tbreak;\r\n\t}\r\n\tglBindTexture(GL_TEXTURE_2D, 0);\r\n\treturn texture;\r\n}\r\n\r\nvoid afDrawIndexedTriangleList(IBOID ibo, int count, int start)\r\n{\r\n\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);\r\n\tglDrawElements(GL_TRIANGLES, count, AFIndexTypeToDevice, (void*)(start));\r\n\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);\r\n}\r\n\r\nvoid afSetVertexAttributes(GLuint program, const InputElement elements[], int numElements, int numBuffers, VBOID const *vertexBufferIds, const GLsizei* strides)\r\n{\r\n\tfor (int i = 0; i < numElements; i++) {\r\n\t\tconst InputElement& d = elements[i];\r\n\t\tglBindBuffer(GL_ARRAY_BUFFER, vertexBufferIds[d.inputSlot]);\r\n\t\tGLint h = glGetAttribLocation(program, d.name);\r\n\t\tif (h == -1) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tglEnableVertexAttribArray(h);\r\n\t\tswitch (d.format) {\r\n\t\tcase SF_R32_FLOAT:\r\n\t\tcase SF_R32G32_FLOAT:\r\n\t\tcase SF_R32G32B32_FLOAT:\r\n\t\tcase SF_R32G32B32A32_FLOAT:\r\n\t\t\tglVertexAttribPointer(h, d.format - SF_R32_FLOAT + 1, GL_FLOAT, GL_FALSE, strides[d.inputSlot], (void*)d.offset);\r\n\t\t\tbreak;\r\n\t\tcase SF_R8_UNORM:\r\n\t\tcase SF_R8G8_UNORM:\r\n\t\tcase SF_R8G8B8_UNORM:\r\n\t\tcase SF_R8G8B8A8_UNORM:\r\n\t\t\tglVertexAttribPointer(h, d.format - SF_R8_UNORM + 1, GL_UNSIGNED_BYTE, GL_TRUE, strides[d.inputSlot], (void*)d.offset);\r\n\t\t\tbreak;\r\n\t\tcase SF_R8_UINT:\r\n\t\tcase SF_R8G8_UINT:\r\n\t\tcase SF_R8G8B8_UINT:\r\n\t\tcase SF_R8G8B8A8_UINT:\r\n\t\t\t\/\/\t\t\tglVertexAttribPointer(h, d.format - SF_R8_UINT + 1, GL_UNSIGNED_BYTE, GL_FALSE, strides[d.inputSlot], (void*)d.offset);\r\n\t\t\tglVertexAttribIPointer(h, d.format - SF_R8_UINT + 1, GL_UNSIGNED_BYTE, strides[d.inputSlot], (void*)d.offset);\r\n\t\t\tbreak;\r\n\t\tcase SF_R16_UINT:\r\n\t\tcase SF_R16G16_UINT:\r\n\t\tcase SF_R16G16B16_UINT:\r\n\t\tcase SF_R16G16B16A16_UINT:\r\n\t\t\t\/\/\t\t\tglVertexAttribPointer(h, d.format - SF_R16_UINT + 1, GL_UNSIGNED_SHORT, GL_FALSE, strides[d.inputSlot], (void*)d.offset);\r\n\t\t\tglVertexAttribIPointer(h, d.format - SF_R16_UINT + 1, GL_UNSIGNED_SHORT, strides[d.inputSlot], (void*)d.offset);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tif (d.perInstance) {\r\n\t\t\tglVertexAttribDivisor(h, 1);\r\n\t\t}\r\n\t}\r\n\tglBindBuffer(GL_ARRAY_BUFFER, 0);\r\n}\r\n\r\nGLuint afCreateVAO(GLuint program, const InputElement elements[], int numElements, int numBuffers, VBOID const *vertexBufferIds, const GLsizei* strides, IBOID ibo)\r\n{\r\n\tGLuint vao;\r\n\tglGenVertexArrays(1, &vao);\r\n\tglBindVertexArray(vao);\r\n\tafSetVertexAttributes(program, elements, numElements, numBuffers, vertexBufferIds, strides);\r\n\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);\r\n\tglBindVertexArray(0);\r\n\treturn vao;\r\n}\r\nprevent bound buffer changing -- glBindBufferBase changes it!#include \"stdafx.h\"\r\n\r\nIBOID afCreateIndexBuffer(const AFIndex* indi, int numIndi)\r\n{\r\n\tIBOID ibo;\r\n\tglGenBuffers(1, &ibo.x);\r\n\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);\r\n\tglBufferData(GL_ELEMENT_ARRAY_BUFFER, numIndi * sizeof(AFIndex), &indi[0], GL_STATIC_DRAW);\r\n\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);\r\n\treturn ibo;\r\n}\r\n\r\nVBOID afCreateVertexBuffer(int size, const void* buf)\r\n{\r\n\tVBOID vbo;\r\n\tglGenBuffers(1, &vbo.x);\r\n\tglBindBuffer(GL_ARRAY_BUFFER, vbo);\r\n\tglBufferData(GL_ARRAY_BUFFER, size, buf, GL_STATIC_DRAW);\r\n\tglBindBuffer(GL_ARRAY_BUFFER, 0);\r\n\treturn vbo;\r\n}\r\n\r\nVBOID afCreateDynamicVertexBuffer(int size)\r\n{\r\n\tVBOID vbo;\r\n\tglGenBuffers(1, &vbo.x);\r\n\tglBindBuffer(GL_ARRAY_BUFFER, vbo);\r\n\tglBufferData(GL_ARRAY_BUFFER, size, NULL, GL_DYNAMIC_DRAW);\r\n\tglBindBuffer(GL_ARRAY_BUFFER, 0);\r\n\treturn vbo;\r\n}\r\n\r\nSSBOID afCreateSSBO(int size)\r\n{\r\n\tSSBOID name;\r\n\tglGenBuffers(1, &name.x);\r\n\tglBindBuffer(GL_SHADER_STORAGE_BUFFER, name);\r\n\tglBufferData(GL_SHADER_STORAGE_BUFFER, size, NULL, GL_DYNAMIC_DRAW);\r\n\tglBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);\r\n\treturn name;\r\n}\r\n\r\nUBOID afCreateUBO(int size)\r\n{\r\n\tUBOID name;\r\n\tglGenBuffers(1, &name.x);\r\n\tglBindBuffer(GL_UNIFORM_BUFFER, name);\r\n\tglBufferData(GL_UNIFORM_BUFFER, size, NULL, GL_DYNAMIC_DRAW);\r\n\tglBindBuffer(GL_UNIFORM_BUFFER, 0);\r\n\treturn name;\r\n}\r\n\r\nvoid afBindBuffer(GLuint program, const GLchar* name, SSBOID ssbo, GLuint storageBlockBinding)\r\n{\r\n\tglShaderStorageBlockBinding(program, glGetProgramResourceIndex(program, GL_SHADER_STORAGE_BLOCK, name), storageBlockBinding);\r\n\tGLint prev;\r\n\tglGetIntegerv(GL_SHADER_STORAGE_BUFFER_BINDING, &prev);\r\n\tglBindBufferBase(GL_SHADER_STORAGE_BUFFER, storageBlockBinding, ssbo);\r\n\tglBindBuffer(GL_SHADER_STORAGE_BUFFER, prev);\r\n}\r\n\r\nvoid afBindBuffer(GLuint program, const GLchar* name, UBOID ubo, GLuint uniformBlockBinding)\r\n{\r\n\tglUniformBlockBinding(program, glGetUniformBlockIndex(program, name), uniformBlockBinding);\r\n\tGLint prev;\r\n\tglGetIntegerv(GL_UNIFORM_BUFFER_BINDING, &prev);\r\n\tglBindBufferBase(GL_UNIFORM_BUFFER, uniformBlockBinding, ubo);\r\n\tglBindBuffer(GL_UNIFORM_BUFFER, prev);\r\n}\r\n\r\nGLuint afCreateDynamicTexture(int w, int h, AFDTFormat format)\r\n{\r\n\tGLuint texture;\r\n\tglGenTextures(1, &texture);\r\n\tglBindTexture(GL_TEXTURE_2D, texture);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);\r\n\tswitch (format) {\r\n\tcase AFDT_R8G8B8A8_UINT:\r\n\t\tglPixelStorei(GL_UNPACK_ALIGNMENT, 4);\r\n\t\tglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);\r\n\t\tbreak;\r\n\tcase AFDT_R5G6B5_UINT:\r\n\t\tglPixelStorei(GL_UNPACK_ALIGNMENT, 2);\r\n\t\tglTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 512, 512, 0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, nullptr);\r\n\t\tbreak;\r\n\t}\r\n\tglBindTexture(GL_TEXTURE_2D, 0);\r\n\treturn texture;\r\n}\r\n\r\nvoid afDrawIndexedTriangleList(IBOID ibo, int count, int start)\r\n{\r\n\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);\r\n\tglDrawElements(GL_TRIANGLES, count, AFIndexTypeToDevice, (void*)(start));\r\n\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);\r\n}\r\n\r\nvoid afSetVertexAttributes(GLuint program, const InputElement elements[], int numElements, int numBuffers, VBOID const *vertexBufferIds, const GLsizei* strides)\r\n{\r\n\tfor (int i = 0; i < numElements; i++) {\r\n\t\tconst InputElement& d = elements[i];\r\n\t\tglBindBuffer(GL_ARRAY_BUFFER, vertexBufferIds[d.inputSlot]);\r\n\t\tGLint h = glGetAttribLocation(program, d.name);\r\n\t\tif (h == -1) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tglEnableVertexAttribArray(h);\r\n\t\tswitch (d.format) {\r\n\t\tcase SF_R32_FLOAT:\r\n\t\tcase SF_R32G32_FLOAT:\r\n\t\tcase SF_R32G32B32_FLOAT:\r\n\t\tcase SF_R32G32B32A32_FLOAT:\r\n\t\t\tglVertexAttribPointer(h, d.format - SF_R32_FLOAT + 1, GL_FLOAT, GL_FALSE, strides[d.inputSlot], (void*)d.offset);\r\n\t\t\tbreak;\r\n\t\tcase SF_R8_UNORM:\r\n\t\tcase SF_R8G8_UNORM:\r\n\t\tcase SF_R8G8B8_UNORM:\r\n\t\tcase SF_R8G8B8A8_UNORM:\r\n\t\t\tglVertexAttribPointer(h, d.format - SF_R8_UNORM + 1, GL_UNSIGNED_BYTE, GL_TRUE, strides[d.inputSlot], (void*)d.offset);\r\n\t\t\tbreak;\r\n\t\tcase SF_R8_UINT:\r\n\t\tcase SF_R8G8_UINT:\r\n\t\tcase SF_R8G8B8_UINT:\r\n\t\tcase SF_R8G8B8A8_UINT:\r\n\t\t\t\/\/\t\t\tglVertexAttribPointer(h, d.format - SF_R8_UINT + 1, GL_UNSIGNED_BYTE, GL_FALSE, strides[d.inputSlot], (void*)d.offset);\r\n\t\t\tglVertexAttribIPointer(h, d.format - SF_R8_UINT + 1, GL_UNSIGNED_BYTE, strides[d.inputSlot], (void*)d.offset);\r\n\t\t\tbreak;\r\n\t\tcase SF_R16_UINT:\r\n\t\tcase SF_R16G16_UINT:\r\n\t\tcase SF_R16G16B16_UINT:\r\n\t\tcase SF_R16G16B16A16_UINT:\r\n\t\t\t\/\/\t\t\tglVertexAttribPointer(h, d.format - SF_R16_UINT + 1, GL_UNSIGNED_SHORT, GL_FALSE, strides[d.inputSlot], (void*)d.offset);\r\n\t\t\tglVertexAttribIPointer(h, d.format - SF_R16_UINT + 1, GL_UNSIGNED_SHORT, strides[d.inputSlot], (void*)d.offset);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tif (d.perInstance) {\r\n\t\t\tglVertexAttribDivisor(h, 1);\r\n\t\t}\r\n\t}\r\n\tglBindBuffer(GL_ARRAY_BUFFER, 0);\r\n}\r\n\r\nGLuint afCreateVAO(GLuint program, const InputElement elements[], int numElements, int numBuffers, VBOID const *vertexBufferIds, const GLsizei* strides, IBOID ibo)\r\n{\r\n\tGLuint vao;\r\n\tglGenVertexArrays(1, &vao);\r\n\tglBindVertexArray(vao);\r\n\tafSetVertexAttributes(program, elements, numElements, numBuffers, vertexBufferIds, strides);\r\n\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);\r\n\tglBindVertexArray(0);\r\n\treturn vao;\r\n}\r\n<|endoftext|>"} {"text":"\/******************************************************************************\\\n * ___ __ *\n * \/\\_ \\ __\/\\ \\ *\n * \\\/\/\\ \\ \/\\_\\ \\ \\____ ___ _____ _____ __ *\n * \\ \\ \\ \\\/\\ \\ \\ '__`\\ \/'___\\\/\\ '__`\\\/\\ '__`\\ \/'__`\\ *\n * \\_\\ \\_\\ \\ \\ \\ \\L\\ \\\/\\ \\__\/\\ \\ \\L\\ \\ \\ \\L\\ \\\/\\ \\L\\.\\_ *\n * \/\\____\\\\ \\_\\ \\_,__\/\\ \\____\\\\ \\ ,__\/\\ \\ ,__\/\\ \\__\/.\\_\\ *\n * \\\/____\/ \\\/_\/\\\/___\/ \\\/____\/ \\ \\ \\\/ \\ \\ \\\/ \\\/__\/\\\/_\/ *\n * \\ \\_\\ \\ \\_\\ *\n * \\\/_\/ \\\/_\/ *\n * *\n * Copyright (C) 2011-2013 *\n * Dominik Charousset *\n * *\n * This file is part of libcppa. *\n * libcppa is free software: you can redistribute it and\/or modify it under *\n * the terms of the GNU Lesser General Public License as published by the *\n * Free Software Foundation; either version 2.1 of the License, *\n * or (at your option) any later version. *\n * *\n * libcppa is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *\n * See the GNU Lesser General Public License for more details. *\n * *\n * You should have received a copy of the GNU Lesser General Public License *\n * along with libcppa. If not, see . *\n\\******************************************************************************\/\n\n\n#ifndef CPPA_OPTION_HPP\n#define CPPA_OPTION_HPP\n\n#include \n#include \n\n#include \"cppa\/none.hpp\"\n#include \"cppa\/config.hpp\"\n\nnamespace cppa {\n\n\/**\n * @brief Represents an optional value of @p T.\n *\/\ntemplate\nclass optional {\n\n public:\n\n \/**\n * @brief Typdef for @p T.\n *\/\n typedef T type;\n\n \/* *\n * @brief Default constructor.\n * @post valid() == false<\/tt>\n *\/\n \/\/optional() : m_valid(false) { }\n\n \/**\n * @post valid() == false<\/tt>\n *\/\n optional(const none_t&) : m_valid(false) { }\n\n \/**\n * @brief Creates an @p option from @p value.\n * @post valid() == true<\/tt>\n *\/\n optional(T value) : m_valid(false) { cr(std::move(value)); }\n\n optional(const optional& other) : m_valid(false) {\n if (other.m_valid) cr(other.m_value);\n }\n\n optional(optional&& other) : m_valid(false) {\n if (other.m_valid) cr(std::move(other.m_value));\n }\n\n ~optional() { destroy(); }\n\n optional& operator=(const optional& other) {\n if (m_valid) {\n if (other.m_valid) m_value = other.m_value;\n else destroy();\n }\n else if (other.m_valid) {\n cr(other.m_value);\n }\n return *this;\n }\n\n optional& operator=(optional&& other) {\n if (m_valid) {\n if (other.m_valid) m_value = std::move(other.m_value);\n else destroy();\n }\n else if (other.m_valid) {\n cr(std::move(other.m_value));\n }\n return *this;\n }\n\n \/**\n * @brief Returns @p true if this @p option has a valid value;\n * otherwise @p false.\n *\/\n inline bool valid() const { return m_valid; }\n\n \/**\n * @brief Returns !valid()<\/tt>.\n *\/\n inline bool empty() const { return !m_valid; }\n\n \/**\n * @copydoc valid()\n *\/\n inline explicit operator bool() const { return valid(); }\n\n \/**\n * @brief Returns !valid()<\/tt>.\n *\/\n inline bool operator!() const { return empty(); }\n\n \/**\n * @brief Returns the value.\n *\/\n inline T& operator*() {\n CPPA_REQUIRE(valid());\n return m_value;\n }\n\n \/**\n * @brief Returns the value.\n *\/\n inline const T& operator*() const {\n CPPA_REQUIRE(valid());\n return m_value;\n }\n\n \/**\n * @brief Returns the value.\n *\/\n inline T& get() {\n CPPA_REQUIRE(valid());\n return m_value;\n }\n\n \/**\n * @brief Returns the value.\n *\/\n inline const T& get() const {\n CPPA_REQUIRE(valid());\n return m_value;\n }\n\n \/**\n * @brief Returns the value. The value is set to @p default_value\n * if valid() == false<\/tt>.\n * @post valid() == true<\/tt>\n *\/\n inline const T& get_or_else(const T& default_value) const {\n if (valid()) return get();\n return default_value;\n }\n\n private:\n\n bool m_valid;\n union { T m_value; };\n\n void destroy() {\n if (m_valid) {\n m_value.~T();\n m_valid = false;\n }\n }\n\n template\n void cr(V&& value) {\n CPPA_REQUIRE(!valid());\n m_valid = true;\n new (&m_value) T (std::forward(value));\n }\n\n};\n\ntemplate\nclass optional {\n\n public:\n\n typedef T type;\n\n optional() : m_value(nullptr) { }\n\n optional(T& value) : m_value(&value) { }\n\n optional(const optional& other) = default;\n\n optional& operator=(const optional& other) = default;\n\n inline bool valid() const { return m_value != nullptr; }\n\n inline bool empty() const { return !valid(); }\n\n inline explicit operator bool() const { return valid(); }\n\n inline bool operator!() const { return empty(); }\n\n inline T& operator*() {\n CPPA_REQUIRE(valid());\n return *m_value;\n }\n\n inline const T& operator*() const {\n CPPA_REQUIRE(valid());\n return *m_value;\n }\n\n inline T& get() {\n CPPA_REQUIRE(valid());\n return *m_value;\n }\n\n inline const T& get() const {\n CPPA_REQUIRE(valid());\n return *m_value;\n }\n\n inline const T& get_or_else(const T& default_value) const {\n if (valid()) return get();\n return default_value;\n }\n\n private:\n\n T* m_value;\n\n};\n\n\/** @relates option *\/\ntemplate\nstruct is_optional { static constexpr bool value = false; };\n\ntemplate\nstruct is_optional> { static constexpr bool value = true; };\n\n\/** @relates option *\/\ntemplate\nbool operator==(const optional& lhs, const optional& rhs) {\n if ((lhs) && (rhs)) return *lhs == *rhs;\n return false;\n}\n\n\/** @relates option *\/\ntemplate\nbool operator==(const optional& lhs, const U& rhs) {\n if (lhs) return *lhs == rhs;\n return false;\n}\n\n\/** @relates option *\/\ntemplate\nbool operator==(const T& lhs, const optional& rhs) {\n return rhs == lhs;\n}\n\n\/** @relates option *\/\ntemplate\nbool operator!=(const optional& lhs, const optional& rhs) {\n return !(lhs == rhs);\n}\n\n\/** @relates option *\/\ntemplate\nbool operator!=(const optional& lhs, const U& rhs) {\n return !(lhs == rhs);\n}\n\n\/** @relates option *\/\ntemplate\nbool operator!=(const T& lhs, const optional& rhs) {\n return !(lhs == rhs);\n}\n\n} \/\/ namespace cppa\n\n#endif \/\/ CPPA_OPTION_HPP\nadded optional specialization\/******************************************************************************\\\n * ___ __ *\n * \/\\_ \\ __\/\\ \\ *\n * \\\/\/\\ \\ \/\\_\\ \\ \\____ ___ _____ _____ __ *\n * \\ \\ \\ \\\/\\ \\ \\ '__`\\ \/'___\\\/\\ '__`\\\/\\ '__`\\ \/'__`\\ *\n * \\_\\ \\_\\ \\ \\ \\ \\L\\ \\\/\\ \\__\/\\ \\ \\L\\ \\ \\ \\L\\ \\\/\\ \\L\\.\\_ *\n * \/\\____\\\\ \\_\\ \\_,__\/\\ \\____\\\\ \\ ,__\/\\ \\ ,__\/\\ \\__\/.\\_\\ *\n * \\\/____\/ \\\/_\/\\\/___\/ \\\/____\/ \\ \\ \\\/ \\ \\ \\\/ \\\/__\/\\\/_\/ *\n * \\ \\_\\ \\ \\_\\ *\n * \\\/_\/ \\\/_\/ *\n * *\n * Copyright (C) 2011-2013 *\n * Dominik Charousset *\n * *\n * This file is part of libcppa. *\n * libcppa is free software: you can redistribute it and\/or modify it under *\n * the terms of the GNU Lesser General Public License as published by the *\n * Free Software Foundation; either version 2.1 of the License, *\n * or (at your option) any later version. *\n * *\n * libcppa is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *\n * See the GNU Lesser General Public License for more details. *\n * *\n * You should have received a copy of the GNU Lesser General Public License *\n * along with libcppa. If not, see . *\n\\******************************************************************************\/\n\n\n#ifndef CPPA_OPTION_HPP\n#define CPPA_OPTION_HPP\n\n#include \n#include \n\n#include \"cppa\/none.hpp\"\n#include \"cppa\/config.hpp\"\n\nnamespace cppa {\n\n\/**\n * @brief Represents an optional value of @p T.\n *\/\ntemplate\nclass optional {\n\n public:\n\n \/**\n * @brief Typdef for @p T.\n *\/\n typedef T type;\n\n \/* *\n * @brief Default constructor.\n * @post valid() == false<\/tt>\n *\/\n \/\/optional() : m_valid(false) { }\n\n \/**\n * @post valid() == false<\/tt>\n *\/\n optional(const none_t&) : m_valid(false) { }\n\n \/**\n * @brief Creates an @p option from @p value.\n * @post valid() == true<\/tt>\n *\/\n optional(T value) : m_valid(false) { cr(std::move(value)); }\n\n optional(const optional& other) : m_valid(false) {\n if (other.m_valid) cr(other.m_value);\n }\n\n optional(optional&& other) : m_valid(false) {\n if (other.m_valid) cr(std::move(other.m_value));\n }\n\n ~optional() { destroy(); }\n\n optional& operator=(const optional& other) {\n if (m_valid) {\n if (other.m_valid) m_value = other.m_value;\n else destroy();\n }\n else if (other.m_valid) {\n cr(other.m_value);\n }\n return *this;\n }\n\n optional& operator=(optional&& other) {\n if (m_valid) {\n if (other.m_valid) m_value = std::move(other.m_value);\n else destroy();\n }\n else if (other.m_valid) {\n cr(std::move(other.m_value));\n }\n return *this;\n }\n\n \/**\n * @brief Returns @p true if this @p option has a valid value;\n * otherwise @p false.\n *\/\n inline bool valid() const { return m_valid; }\n\n \/**\n * @brief Returns !valid()<\/tt>.\n *\/\n inline bool empty() const { return !m_valid; }\n\n \/**\n * @copydoc valid()\n *\/\n inline explicit operator bool() const { return valid(); }\n\n \/**\n * @brief Returns !valid()<\/tt>.\n *\/\n inline bool operator!() const { return empty(); }\n\n \/**\n * @brief Returns the value.\n *\/\n inline T& operator*() {\n CPPA_REQUIRE(valid());\n return m_value;\n }\n\n \/**\n * @brief Returns the value.\n *\/\n inline const T& operator*() const {\n CPPA_REQUIRE(valid());\n return m_value;\n }\n\n \/**\n * @brief Returns the value.\n *\/\n inline T& get() {\n CPPA_REQUIRE(valid());\n return m_value;\n }\n\n \/**\n * @brief Returns the value.\n *\/\n inline const T& get() const {\n CPPA_REQUIRE(valid());\n return m_value;\n }\n\n \/**\n * @brief Returns the value. The value is set to @p default_value\n * if valid() == false<\/tt>.\n * @post valid() == true<\/tt>\n *\/\n inline const T& get_or_else(const T& default_value) const {\n if (valid()) return get();\n return default_value;\n }\n\n private:\n\n bool m_valid;\n union { T m_value; };\n\n void destroy() {\n if (m_valid) {\n m_value.~T();\n m_valid = false;\n }\n }\n\n template\n void cr(V&& value) {\n CPPA_REQUIRE(!valid());\n m_valid = true;\n new (&m_value) T (std::forward(value));\n }\n\n};\n\ntemplate\nclass optional {\n\n public:\n\n typedef T type;\n\n optional() : m_value(nullptr) { }\n\n optional(T& value) : m_value(&value) { }\n\n optional(const optional& other) = default;\n\n optional& operator=(const optional& other) = default;\n\n inline bool valid() const { return m_value != nullptr; }\n\n inline bool empty() const { return !valid(); }\n\n inline explicit operator bool() const { return valid(); }\n\n inline bool operator!() const { return empty(); }\n\n inline T& operator*() {\n CPPA_REQUIRE(valid());\n return *m_value;\n }\n\n inline const T& operator*() const {\n CPPA_REQUIRE(valid());\n return *m_value;\n }\n\n inline T& get() {\n CPPA_REQUIRE(valid());\n return *m_value;\n }\n\n inline const T& get() const {\n CPPA_REQUIRE(valid());\n return *m_value;\n }\n\n inline const T& get_or_else(const T& default_value) const {\n if (valid()) return get();\n return default_value;\n }\n\n private:\n\n T* m_value;\n\n};\n\ntemplate<>\nclass optional {\n\n optional() : m_valid(true) { }\n\n optional(const none_t&) : m_valid(false) { }\n\n inline bool valid() const { return m_valid; }\n\n inline bool empty() const { return !m_valid; }\n\n inline explicit operator bool() const { return valid(); }\n\n inline bool operator!() const { return empty(); }\n\n private:\n\n bool m_valid;\n\n};\n\n\/** @relates option *\/\ntemplate\nstruct is_optional { static constexpr bool value = false; };\n\ntemplate\nstruct is_optional> { static constexpr bool value = true; };\n\n\/** @relates option *\/\ntemplate\nbool operator==(const optional& lhs, const optional& rhs) {\n if ((lhs) && (rhs)) return *lhs == *rhs;\n return false;\n}\n\n\/** @relates option *\/\ntemplate\nbool operator==(const optional& lhs, const U& rhs) {\n if (lhs) return *lhs == rhs;\n return false;\n}\n\n\/** @relates option *\/\ntemplate\nbool operator==(const T& lhs, const optional& rhs) {\n return rhs == lhs;\n}\n\n\/** @relates option *\/\ntemplate\nbool operator!=(const optional& lhs, const optional& rhs) {\n return !(lhs == rhs);\n}\n\n\/** @relates option *\/\ntemplate\nbool operator!=(const optional& lhs, const U& rhs) {\n return !(lhs == rhs);\n}\n\n\/** @relates option *\/\ntemplate\nbool operator!=(const T& lhs, const optional& rhs) {\n return !(lhs == rhs);\n}\n\n} \/\/ namespace cppa\n\n#endif \/\/ CPPA_OPTION_HPP\n<|endoftext|>"} {"text":"\n\/\/ the syntax for messages is:\n\/\/ wd 'mb type buttons title message'\n\/\/\n\/\/ type specifies the icon and default behaviour:\n\/\/ info (default OK button)\n\/\/ warn (default OK button)\n\/\/ critical (default OK button)\n\/\/ query (requires two or three buttons)\n\/\/\n\/\/ if one button, there is no result,\n\/\/ otherwise the result is the button name (ok, cancel, ...)\n\/\/\n\/\/ buttons are from the set:\n\/\/ mb_ok\n\/\/ mb_cancel\n\/\/ mb_yes\n\/\/ mb_no\n\/\/ mb_save\n\/\/ mb_discard\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifndef ANDROID\n#include \n#include \nextern QPrinter *Printer;\n#endif\n\n#include \"wd.h\"\n#include \"cmd.h\"\n#include \"..\/base\/dialog.h\"\n\nQString mbcolor();\nQString mbdir();\nQString mbfont();\nQString mbinfo(QString);\n#ifndef ANDROID\nQString mbprint(bool);\nQString mbprintx(bool);\n#endif\nQString mbmsg();\nQString mbopen();\nQString mbsave();\n\nQString fixsep(QString s);\n\nQString type;\nQStringList arg;\n\nQMessageBox::StandardButton getdefaultbutton();\nQMessageBox::StandardButton getonebutton();\nQMessageBox::StandardButtons getotherbuttons();\nQString getname(int);\n\n\/\/ ---------------------------------------------------------------------\nQString mb(string p)\n{\n arg=qsplit(p);\n if (arg.size()<1) return mbinfo(\"missing mb type\");\n\n type=arg.first();\n arg.removeFirst();\n if (type==\"color\")\n return mbcolor();\n if (type==\"dir\")\n return mbdir();\n if (type==\"font\")\n return mbfont();\n if (type==\"open\")\n return mbopen();\n#ifndef ANDROID\n if (type==\"print\") {\n QString s=dlb(s2q(p.substr(5)));\n return mbprint('*'==s.at(0));\n }\n if (type==\"printx\") {\n QString s=dlb(s2q(p.substr(6)));\n return mbprintx('*'==s.at(0));\n }\n#endif\n if (type==\"save\")\n return mbsave();\n if (type==\"info\"||type==\"query\"||type==\"warn\"||type==\"critical\")\n return mbmsg();\n return mbinfo(\"invalid mb type: \" + type);\n}\n\n\/\/ ---------------------------------------------------------------------\nQString mbmsg()\n{\n int r;\n QString t,m;\n\n QMessageBox::StandardButton button1=getdefaultbutton();\n QMessageBox::StandardButtons buttons=getotherbuttons();\n\n if (arg.size()==1) {\n t=\"Message Box\";\n m=arg.at(0);\n } else if (arg.size()==2) {\n t=arg.at(0);\n m=arg.at(1);\n } else {\n return mbinfo (\"Need title and message: \"+arg.join(\" \"));\n }\n\n if (button1==-1) {\n button1=QMessageBox::Ok;\n if (type==\"query\")\n buttons=QMessageBox::Cancel;\n }\n buttons|=button1;\n\n if (type==\"query\") {\n r=QMessageBox::question(QApplication::focusWidget(),t,m,buttons,button1);\n return getname(r);\n }\n if (type==\"critical\")\n QMessageBox::critical(QApplication::focusWidget(),t,m,buttons,button1);\n else if (type==\"info\")\n QMessageBox::information(QApplication::focusWidget(),t,m,buttons,button1);\n else if (type==\"warn\")\n QMessageBox::warning(QApplication::focusWidget(),t,m,buttons,button1);\n return \"\";\n}\n\n\/\/ ---------------------------------------------------------------------\nQString mbcolor()\n{\n QColor c;\n int r,g,b;\n\n if (arg.size()==3) {\n r=c_strtoi(q2s(arg.at(0)));\n g=c_strtoi(q2s(arg.at(1)));\n b=c_strtoi(q2s(arg.at(2)));\n c=QColor(r,g,b);\n } else\n c=Qt::white;\n c=QColorDialog::getColor(c,QApplication::focusWidget());\n if (!c.isValid()) return \"\";\n return s2q(i2s(c.red()) + \" \" + i2s(c.green()) + \" \" + i2s(c.blue()));\n}\n\n\/\/ ---------------------------------------------------------------------\nQString mbdir()\n{\n QString title,dir;\n if (arg.size()!=2)\n return mbinfo(\"dir needs title and directory\");\n title=arg.at(0);\n dir=arg.at(1);\n return QFileDialog::getExistingDirectory(\n QApplication::focusWidget(),title,dir);\n}\n\n\/\/ ---------------------------------------------------------------------\nQString mbfont()\n{\n bool ok;\n QFont font, def;\n QString s;\n def.setStrikeOut(false);\n def.setUnderline(false);\n if (arg.size())\n def.setFamily(arg.at(0));\n if (arg.size()>1)\n def.setPointSize(arg.at(1).toFloat());\n for (int i=2; iexec() == QDialog::Accepted) {\n switch (Printer->outputFormat()) {\n case QPrinter::PdfFormat :\n r=\"_pdf:\" + Printer->outputFileName();\n break;\n case QPrinter::PostScriptFormat :\n r=\"_ps:\" + Printer->outputFileName();\n break;\n default :\n r=Printer->printerName();\n break;\n }\n }\n delete dlg;\n }\n return r;\n}\n\n\/\/ ---------------------------------------------------------------------\n\/\/ print with no dialog\nQString mbprintx(bool iftext)\n{\n if (arg.size()==0)\n return mbinfo(\"No text given for printx\");\n\n QString s=arg.at(0);\n if (!iftext) {\n if (!cfexist(s)) {\n mbinfo(\"File not found: \" + s);\n return \"\";\n }\n s=cfread(s);\n }\n QTextDocument *d=new QTextDocument(s);\n if (Printer==0)\n Printer=new QPrinter(QPrinter::HighResolution);\n if (!Printer->isValid())\n return mbinfo(\"Invalid printer: \" + Printer->printerName());\n d->print(Printer);\n return \"\";\n}\n#endif\n\n\/\/ ---------------------------------------------------------------------\nQString mbsave()\n{\n QString title,dir,filter;\n if (arg.size()<2)\n return mbinfo(\"save needs title, directory, [filters]\");\n title=arg.at(0);\n dir=arg.at(1);\n if (arg.size()==3)\n filter=fixsep(arg.at(2));\n return QFileDialog::getSaveFileName(\n QApplication::focusWidget(),title,dir,filter);\n}\n\n\/\/ ---------------------------------------------------------------------\nQString getname(int b)\n{\n if (b==QMessageBox::Ok)\n return \"ok\";\n if (b==QMessageBox::Cancel)\n return \"cancel\";\n if (b==QMessageBox::Yes)\n return \"yes\";\n if (b==QMessageBox::No)\n return \"no\";\n if (b==QMessageBox::Save)\n return \"save\";\n if (b==QMessageBox::Discard)\n return \"discard\";\n return \"unknown button\";\n}\n\n\/\/ ---------------------------------------------------------------------\nQMessageBox::StandardButton getonebutton()\n{\n if (arg.isEmpty()) return QMessageBox::NoButton;\n QString s=arg.first();\n if (s==\"mb_ok\")\n return QMessageBox::Ok;\n if (s==\"mb_cancel\")\n return QMessageBox::Cancel;\n if (s==\"mb_yes\")\n return QMessageBox::Yes;\n if (s==\"mb_no\")\n return QMessageBox::No;\n if (s==\"mb_save\")\n return QMessageBox::Save;\n if (s==\"mb_discard\")\n return QMessageBox::Discard;\n return QMessageBox::NoButton;\n}\n\n\/\/ ---------------------------------------------------------------------\nQMessageBox::StandardButton getdefaultbutton()\n{\n QMessageBox::StandardButton r=getonebutton();\n if (r!=QMessageBox::NoButton)\n arg.removeFirst();\n return r;\n}\n\n\/\/ ---------------------------------------------------------------------\nQMessageBox::StandardButtons getotherbuttons()\n{\n QMessageBox::StandardButtons r=QMessageBox::NoButton;\n QMessageBox::StandardButton b;\n while (arg.size()) {\n b=getonebutton();\n if (b==QMessageBox::NoButton)\n return r;\n r|=b;\n arg.removeFirst();\n }\n return r;\n}\n\n\/\/ ---------------------------------------------------------------------\nQString mbinfo(QString s)\n{\n info(\"Message Box\",s);\n return \"\";\n}\n\n\/\/ ---------------------------------------------------------------------\nQString fixsep(QString s)\n{\n return s.replace(\"|\",\";;\");\n}\nattemp to fix mbprint in mac\n\/\/ the syntax for messages is:\n\/\/ wd 'mb type buttons title message'\n\/\/\n\/\/ type specifies the icon and default behaviour:\n\/\/ info (default OK button)\n\/\/ warn (default OK button)\n\/\/ critical (default OK button)\n\/\/ query (requires two or three buttons)\n\/\/\n\/\/ if one button, there is no result,\n\/\/ otherwise the result is the button name (ok, cancel, ...)\n\/\/\n\/\/ buttons are from the set:\n\/\/ mb_ok\n\/\/ mb_cancel\n\/\/ mb_yes\n\/\/ mb_no\n\/\/ mb_save\n\/\/ mb_discard\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifndef ANDROID\n#include \n#include \nextern QPrinter *Printer;\n#endif\n\n#include \"wd.h\"\n#include \"cmd.h\"\n#include \"..\/base\/dialog.h\"\n\nQString mbcolor();\nQString mbdir();\nQString mbfont();\nQString mbinfo(QString);\n#ifndef ANDROID\nQString mbprint(bool);\nQString mbprintx(bool);\n#endif\nQString mbmsg();\nQString mbopen();\nQString mbsave();\n\nQString fixsep(QString s);\n\nQString type;\nQStringList arg;\n\nQMessageBox::StandardButton getdefaultbutton();\nQMessageBox::StandardButton getonebutton();\nQMessageBox::StandardButtons getotherbuttons();\nQString getname(int);\n\n\/\/ ---------------------------------------------------------------------\nQString mb(string p)\n{\n arg=qsplit(p);\n if (arg.size()<1) return mbinfo(\"missing mb type\");\n\n type=arg.first();\n arg.removeFirst();\n if (type==\"color\")\n return mbcolor();\n if (type==\"dir\")\n return mbdir();\n if (type==\"font\")\n return mbfont();\n if (type==\"open\")\n return mbopen();\n#ifndef ANDROID\n if (type==\"print\") {\n QString s=dlb(s2q(p.substr(5)));\n return mbprint('*'==s.at(0));\n }\n if (type==\"printx\") {\n QString s=dlb(s2q(p.substr(6)));\n return mbprintx('*'==s.at(0));\n }\n#endif\n if (type==\"save\")\n return mbsave();\n if (type==\"info\"||type==\"query\"||type==\"warn\"||type==\"critical\")\n return mbmsg();\n return mbinfo(\"invalid mb type: \" + type);\n}\n\n\/\/ ---------------------------------------------------------------------\nQString mbmsg()\n{\n int r;\n QString t,m;\n\n QMessageBox::StandardButton button1=getdefaultbutton();\n QMessageBox::StandardButtons buttons=getotherbuttons();\n\n if (arg.size()==1) {\n t=\"Message Box\";\n m=arg.at(0);\n } else if (arg.size()==2) {\n t=arg.at(0);\n m=arg.at(1);\n } else {\n return mbinfo (\"Need title and message: \"+arg.join(\" \"));\n }\n\n if (button1==-1) {\n button1=QMessageBox::Ok;\n if (type==\"query\")\n buttons=QMessageBox::Cancel;\n }\n buttons|=button1;\n\n if (type==\"query\") {\n r=QMessageBox::question(QApplication::focusWidget(),t,m,buttons,button1);\n return getname(r);\n }\n if (type==\"critical\")\n QMessageBox::critical(QApplication::focusWidget(),t,m,buttons,button1);\n else if (type==\"info\")\n QMessageBox::information(QApplication::focusWidget(),t,m,buttons,button1);\n else if (type==\"warn\")\n QMessageBox::warning(QApplication::focusWidget(),t,m,buttons,button1);\n return \"\";\n}\n\n\/\/ ---------------------------------------------------------------------\nQString mbcolor()\n{\n QColor c;\n int r,g,b;\n\n if (arg.size()==3) {\n r=c_strtoi(q2s(arg.at(0)));\n g=c_strtoi(q2s(arg.at(1)));\n b=c_strtoi(q2s(arg.at(2)));\n c=QColor(r,g,b);\n } else\n c=Qt::white;\n c=QColorDialog::getColor(c,QApplication::focusWidget());\n if (!c.isValid()) return \"\";\n return s2q(i2s(c.red()) + \" \" + i2s(c.green()) + \" \" + i2s(c.blue()));\n}\n\n\/\/ ---------------------------------------------------------------------\nQString mbdir()\n{\n QString title,dir;\n if (arg.size()!=2)\n return mbinfo(\"dir needs title and directory\");\n title=arg.at(0);\n dir=arg.at(1);\n return QFileDialog::getExistingDirectory(\n QApplication::focusWidget(),title,dir);\n}\n\n\/\/ ---------------------------------------------------------------------\nQString mbfont()\n{\n bool ok;\n QFont font, def;\n QString s;\n def.setStrikeOut(false);\n def.setUnderline(false);\n if (arg.size())\n def.setFamily(arg.at(0));\n if (arg.size()>1)\n def.setPointSize(arg.at(1).toFloat());\n for (int i=2; iexec() == QDialog::Accepted) {\n switch (Printer->outputFormat()) {\n case QPrinter::PdfFormat :\n r=\"_pdf:\" + Printer->outputFileName();\n break;\n case QPrinter::PostScriptFormat :\n r=\"_ps:\" + Printer->outputFileName();\n break;\n default :\n r=Printer->printerName();\n break;\n }\n }\n delete dlg;\n }\n return r;\n}\n\n\/\/ ---------------------------------------------------------------------\n\/\/ print with no dialog\nQString mbprintx(bool iftext)\n{\n if (arg.size()==0)\n return mbinfo(\"No text given for printx\");\n\n QString s=arg.at(0);\n if (!iftext) {\n if (!cfexist(s)) {\n mbinfo(\"File not found: \" + s);\n return \"\";\n }\n s=cfread(s);\n }\n QTextDocument *d=new QTextDocument(s);\n if (Printer==0)\n Printer=new QPrinter(QPrinter::HighResolution);\n if (!Printer->isValid())\n return mbinfo(\"Invalid printer: \" + Printer->printerName());\n d->print(Printer);\n return \"\";\n}\n#endif\n\n\/\/ ---------------------------------------------------------------------\nQString mbsave()\n{\n QString title,dir,filter;\n if (arg.size()<2)\n return mbinfo(\"save needs title, directory, [filters]\");\n title=arg.at(0);\n dir=arg.at(1);\n if (arg.size()==3)\n filter=fixsep(arg.at(2));\n return QFileDialog::getSaveFileName(\n QApplication::focusWidget(),title,dir,filter);\n}\n\n\/\/ ---------------------------------------------------------------------\nQString getname(int b)\n{\n if (b==QMessageBox::Ok)\n return \"ok\";\n if (b==QMessageBox::Cancel)\n return \"cancel\";\n if (b==QMessageBox::Yes)\n return \"yes\";\n if (b==QMessageBox::No)\n return \"no\";\n if (b==QMessageBox::Save)\n return \"save\";\n if (b==QMessageBox::Discard)\n return \"discard\";\n return \"unknown button\";\n}\n\n\/\/ ---------------------------------------------------------------------\nQMessageBox::StandardButton getonebutton()\n{\n if (arg.isEmpty()) return QMessageBox::NoButton;\n QString s=arg.first();\n if (s==\"mb_ok\")\n return QMessageBox::Ok;\n if (s==\"mb_cancel\")\n return QMessageBox::Cancel;\n if (s==\"mb_yes\")\n return QMessageBox::Yes;\n if (s==\"mb_no\")\n return QMessageBox::No;\n if (s==\"mb_save\")\n return QMessageBox::Save;\n if (s==\"mb_discard\")\n return QMessageBox::Discard;\n return QMessageBox::NoButton;\n}\n\n\/\/ ---------------------------------------------------------------------\nQMessageBox::StandardButton getdefaultbutton()\n{\n QMessageBox::StandardButton r=getonebutton();\n if (r!=QMessageBox::NoButton)\n arg.removeFirst();\n return r;\n}\n\n\/\/ ---------------------------------------------------------------------\nQMessageBox::StandardButtons getotherbuttons()\n{\n QMessageBox::StandardButtons r=QMessageBox::NoButton;\n QMessageBox::StandardButton b;\n while (arg.size()) {\n b=getonebutton();\n if (b==QMessageBox::NoButton)\n return r;\n r|=b;\n arg.removeFirst();\n }\n return r;\n}\n\n\/\/ ---------------------------------------------------------------------\nQString mbinfo(QString s)\n{\n info(\"Message Box\",s);\n return \"\";\n}\n\n\/\/ ---------------------------------------------------------------------\nQString fixsep(QString s)\n{\n return s.replace(\"|\",\";;\");\n}\n<|endoftext|>"} {"text":"\/*\n\tThis file is part of cpp-ethereum.\n\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tcpp-ethereum is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with cpp-ethereum. If not, see .\n*\/\n\/** @file main.cpp\n * @author Gav Wood \n * @date 2014\n * Ethereum client.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\nusing namespace dev;\nusing namespace dev::solidity;\nusing namespace dev::eth;\n\nvoid help()\n{\n\tcout\n\t\t<< \"Usage lllc [OPTIONS] \" << endl\n << \"Options:\" << endl\n\t\t<< \" -b,--binary Parse, compile and assemble; output byte code in binary.\" << endl\n\t\t<< \" -x,--hex Parse, compile and assemble; output byte code in hex.\" << endl\n\t\t<< \" -a,--assembly Only parse and compile; show assembly.\" << endl\n\t\t<< \" -t,--parse-tree Only parse; show parse tree.\" << endl\n\t\t<< \" -o,--optimise Turn on\/off the optimiser; on by default.\" << endl\n\t\t<< \" -h,--help Show this help message and exit.\" << endl\n\t\t<< \" -V,--version Show the version and exit.\" << endl;\n exit(0);\n}\n\nvoid version()\n{\n\tcout << \"LLLC, the Lovely Little Language Compiler \" << endl;\n\tcout << \" By Gav Wood, (c) 2014.\" << endl;\n\texit(0);\n}\n\n\/*\nThe equivalent of setlocale(LC_ALL, \"C\") is called before any user code is run.\nIf the user has an invalid environment setting then it is possible for the call\nto set locale to fail, so there are only two possible actions, the first is to\nthrow a runtime exception and cause the program to quit (default behaviour),\nor the second is to modify the environment to something sensible (least\nsurprising behaviour).\n\nThe follow code produces the least surprising behaviour. It will use the user\nspecified default locale if it is valid, and if not then it will modify the\nenvironment the process is running in to use a sensible default. This also means\nthat users do not need to install language packs for their OS.\n*\/\nvoid setDefaultOrCLocale()\n{\n#if __unix__\n\tif (!std::setlocale(LC_ALL, \"\"))\n\t{\n\t\tsetenv(\"LC_ALL\", \"C\", 1);\n\t}\n#endif\n}\n\nenum Mode { Binary, Hex, Assembly, ParseTree, Disassemble };\n\nint main(int argc, char** argv)\n{\n\tsetDefaultOrCLocale();\n\tunsigned optimise = 1;\n\tstring infile;\n\tMode mode = Hex;\n\n\tfor (int i = 1; i < argc; ++i)\n\t{\n\t\tstring arg = argv[i];\n\t\tif (arg == \"-h\" || arg == \"--help\")\n\t\t\thelp();\n\t\telse if (arg == \"-b\" || arg == \"--binary\")\n\t\t\tmode = Binary;\n\t\telse if (arg == \"-x\" || arg == \"--hex\")\n\t\t\tmode = Hex;\n\t\telse if (arg == \"-a\" || arg == \"--assembly\")\n\t\t\tmode = Assembly;\n\t\telse if (arg == \"-t\" || arg == \"--parse-tree\")\n\t\t\tmode = ParseTree;\n\t\telse if ((arg == \"-o\" || arg == \"--optimise\") && argc > i + 1)\n\t\t\toptimise = atoi(argv[++i]);\n\t\telse if (arg == \"-d\" || arg == \"--disassemble\")\n\t\t\tmode = Disassemble;\n\t\telse if (arg == \"-V\" || arg == \"--version\")\n\t\t\tversion();\n\t\telse\n\t\t\tinfile = argv[i];\n\t}\n\n\tstring src;\n\tif (infile.empty())\n\t{\n\t\tstring s;\n\t\twhile (!cin.eof())\n\t\t{\n\t\t\tgetline(cin, s);\n\t\t\tsrc.append(s);\n\t\t}\n\t}\n\telse\n\t\tsrc = contentsString(infile);\n\n\tvector errors;\n\tif (src.empty())\n\t\terrors.push_back(\"Empty file.\");\n\telse if (mode == Disassemble)\n\t{\n\t\tcout << disassemble(fromHex(src)) << endl;\n\t}\n\telse if (mode == Binary || mode == Hex)\n\t{\n\t\tauto bs = compileLLL(src, optimise ? true : false, &errors);\n\t\tif (mode == Hex)\n\t\t\tcout << toHex(bs) << endl;\n\t\telse if (mode == Binary)\n\t\t\tcout.write((char const*)bs.data(), bs.size());\n\t}\n\telse if (mode == ParseTree)\n\t\tcout << parseLLL(src) << endl;\n\telse if (mode == Assembly)\n\t\tcout << compileLLLToAsm(src, optimise ? true : false, &errors) << endl;\n\tfor (auto const& i: errors)\n\t\tcerr << i << endl;\n\tif ( errors.size() )\n\t\treturn 1;\n\treturn 0;\n}\nLLL: turn off optimiser by default\/*\n\tThis file is part of cpp-ethereum.\n\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tcpp-ethereum is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with cpp-ethereum. If not, see .\n*\/\n\/** @file main.cpp\n * @author Gav Wood \n * @date 2014\n * Ethereum client.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\nusing namespace dev;\nusing namespace dev::solidity;\nusing namespace dev::eth;\n\nvoid help()\n{\n\tcout\n\t\t<< \"Usage lllc [OPTIONS] \" << endl\n << \"Options:\" << endl\n\t\t<< \" -b,--binary Parse, compile and assemble; output byte code in binary.\" << endl\n\t\t<< \" -x,--hex Parse, compile and assemble; output byte code in hex.\" << endl\n\t\t<< \" -a,--assembly Only parse and compile; show assembly.\" << endl\n\t\t<< \" -t,--parse-tree Only parse; show parse tree.\" << endl\n\t\t<< \" -o,--optimise Turn on\/off the optimiser; off by default.\" << endl\n\t\t<< \" -h,--help Show this help message and exit.\" << endl\n\t\t<< \" -V,--version Show the version and exit.\" << endl;\n exit(0);\n}\n\nvoid version()\n{\n\tcout << \"LLLC, the Lovely Little Language Compiler \" << endl;\n\tcout << \" By Gav Wood, (c) 2014.\" << endl;\n\texit(0);\n}\n\n\/*\nThe equivalent of setlocale(LC_ALL, \"C\") is called before any user code is run.\nIf the user has an invalid environment setting then it is possible for the call\nto set locale to fail, so there are only two possible actions, the first is to\nthrow a runtime exception and cause the program to quit (default behaviour),\nor the second is to modify the environment to something sensible (least\nsurprising behaviour).\n\nThe follow code produces the least surprising behaviour. It will use the user\nspecified default locale if it is valid, and if not then it will modify the\nenvironment the process is running in to use a sensible default. This also means\nthat users do not need to install language packs for their OS.\n*\/\nvoid setDefaultOrCLocale()\n{\n#if __unix__\n\tif (!std::setlocale(LC_ALL, \"\"))\n\t{\n\t\tsetenv(\"LC_ALL\", \"C\", 1);\n\t}\n#endif\n}\n\nenum Mode { Binary, Hex, Assembly, ParseTree, Disassemble };\n\nint main(int argc, char** argv)\n{\n\tsetDefaultOrCLocale();\n\tunsigned optimise = 0;\n\tstring infile;\n\tMode mode = Hex;\n\n\tfor (int i = 1; i < argc; ++i)\n\t{\n\t\tstring arg = argv[i];\n\t\tif (arg == \"-h\" || arg == \"--help\")\n\t\t\thelp();\n\t\telse if (arg == \"-b\" || arg == \"--binary\")\n\t\t\tmode = Binary;\n\t\telse if (arg == \"-x\" || arg == \"--hex\")\n\t\t\tmode = Hex;\n\t\telse if (arg == \"-a\" || arg == \"--assembly\")\n\t\t\tmode = Assembly;\n\t\telse if (arg == \"-t\" || arg == \"--parse-tree\")\n\t\t\tmode = ParseTree;\n\t\telse if ((arg == \"-o\" || arg == \"--optimise\") && argc > i + 1)\n\t\t\toptimise = atoi(argv[++i]);\n\t\telse if (arg == \"-d\" || arg == \"--disassemble\")\n\t\t\tmode = Disassemble;\n\t\telse if (arg == \"-V\" || arg == \"--version\")\n\t\t\tversion();\n\t\telse\n\t\t\tinfile = argv[i];\n\t}\n\n\tstring src;\n\tif (infile.empty())\n\t{\n\t\tstring s;\n\t\twhile (!cin.eof())\n\t\t{\n\t\t\tgetline(cin, s);\n\t\t\tsrc.append(s);\n\t\t}\n\t}\n\telse\n\t\tsrc = contentsString(infile);\n\n\tvector errors;\n\tif (src.empty())\n\t\terrors.push_back(\"Empty file.\");\n\telse if (mode == Disassemble)\n\t{\n\t\tcout << disassemble(fromHex(src)) << endl;\n\t}\n\telse if (mode == Binary || mode == Hex)\n\t{\n\t\tauto bs = compileLLL(src, optimise ? true : false, &errors);\n\t\tif (mode == Hex)\n\t\t\tcout << toHex(bs) << endl;\n\t\telse if (mode == Binary)\n\t\t\tcout.write((char const*)bs.data(), bs.size());\n\t}\n\telse if (mode == ParseTree)\n\t\tcout << parseLLL(src) << endl;\n\telse if (mode == Assembly)\n\t\tcout << compileLLLToAsm(src, optimise ? true : false, &errors) << endl;\n\tfor (auto const& i: errors)\n\t\tcerr << i << endl;\n\tif ( errors.size() )\n\t\treturn 1;\n\treturn 0;\n}\n<|endoftext|>"} {"text":"\/*\nCopyright (C) 2007 \n\nThis File is part of Core3.\n\nThis program is free software; you can redistribute\nit and\/or modify it under the terms of the GNU Lesser\nGeneral Public License as published by the Free Software\nFoundation; either version 2 of the License,\nor (at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\nSee the GNU Lesser General Public License for\nmore details.\n\nYou should have received a copy of the GNU Lesser General\nPublic License along with this program; if not, write to\nthe Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n\nLinking Engine3 statically or dynamically with other modules\nis making a combined work based on Engine3.\nThus, the terms and conditions of the GNU Lesser General Public License\ncover the whole combination.\n\nIn addition, as a special exception, the copyright holders of Engine3\ngive you permission to combine Engine3 program with free software\nprograms or libraries that are released under the GNU LGPL and with\ncode included in the standard release of Core3 under the GNU LGPL\nlicense (or modified versions of such code, with unchanged license).\nYou may copy and distribute such a system following the terms of the\nGNU LGPL for Engine3 and the licenses of the other code concerned,\nprovided that you include the source code of that other code when\nand as the GNU LGPL requires distribution of source code.\n\nNote that people who make modified versions of Engine3 are not obligated\nto grant this special exception for their modified versions;\nit is their choice whether to do so. The GNU Lesser General Public License\ngives permission to release a modified version without this exception;\nthis exception also makes it possible to release a modified version\nwhich carries forward this exception.\n*\/\n\n#include \"NpcSpawnPoint.h\"\n#include \"server\/zone\/managers\/mission\/spawnmaps\/events\/DespawnMissionNpcTask.h\"\n\nNpcSpawnPoint::NpcSpawnPoint() {\n\tspawnType = 0;\n\tdespawnMissionNpcTask = NULL;\n}\n\nNpcSpawnPoint::NpcSpawnPoint(CreatureObject* player, const String& spawnTypes) {\n\t\/\/Parse spawn types.\n\tString st = spawnTypes.toLowerCase();\n\tspawnType = 0;\n\tif (st.contains(\"neutral\")) {\n\t\tspawnType |= NEUTRALSPAWN;\n\t}\n\tif (st.contains(\"imperial\")) {\n\t\tspawnType |= IMPERIALSPAWN;\n\t}\n\tif (st.contains(\"rebel\")) {\n\t\tspawnType |= REBELSPAWN;\n\t}\n\tif (st.contains(\"bhtarget\")) {\n\t\tspawnType |= BHTARGETSPAWN;\n\t}\n\tif (st.contains(\"nospawn\")) {\n\t\t\/\/No spawn overrides all other spawn types.\n\t\tspawnType = NOSPAWN;\n\t}\n\tposition.setX(player->getPosition().getX());\n\tposition.setY(player->getPosition().getY());\n\tdirection.setHeadingDirection(player->getDirection()->getRadians());\n\tinUseByNumberOfMissions = 0;\n\tdespawnMissionNpcTask = NULL;\n}\n\nvoid NpcSpawnPoint::readObject(LuaObject* luaObject) {\n\tfloat x = luaObject->getFloatAt(1);\n\tfloat y = luaObject->getFloatAt(2);\n\tfloat radians = luaObject->getFloatAt(3);\n\tspawnType = luaObject->getIntAt(4);\n\tposition.setX(x);\n\tposition.setY(y);\n\tposition.setZ(0);\n\tdirection.setHeadingDirection(radians);\n\tinUseByNumberOfMissions = 0;\n\tdespawnMissionNpcTask = NULL;\n}\n\nbool NpcSpawnPoint::parseFromBinaryStream(ObjectInputStream* stream) {\n\tspawnType = stream->readInt();\n\tinUseByNumberOfMissions = stream->readInt();\n\tbool result = position.parseFromBinaryStream(stream);\n\tresult &= direction.parseFromBinaryStream(stream);\n\treturn result & npc.parseFromBinaryStream(stream);\n}\n\nbool NpcSpawnPoint::toBinaryStream(ObjectOutputStream* stream) {\n\tstream->writeInt(spawnType);\n\tstream->writeInt(inUseByNumberOfMissions);\n\tbool result = position.toBinaryStream(stream);\n\tresult &= direction.toBinaryStream(stream);\n\treturn result & npc.toBinaryStream(stream);\n}\n\nvoid NpcSpawnPoint::spawnNpc(TerrainManager* terrainManager, CreatureManager* creatureManager, ManagedReference mission) {\n\tinUseByNumberOfMissions++;\n\n\tif (inUseByNumberOfMissions == 1) {\n\t\tif (despawnMissionNpcTask != NULL && despawnMissionNpcTask->isScheduled()) {\n\t\t\tdespawnMissionNpcTask->cancel();\n\t\t} else {\n\t\t\tString deliverNpc = \"deliver_npc\";\n\t\t\t\/\/Get the terrain height at the spawn point.\n\t\t\tfloat z = terrainManager->getHeight(position.getX(), position.getY());\n\t\t\t\/\/Spawn the NPC.\n\t\t\tnpc = cast(creatureManager->spawnCreature(deliverNpc.hashCode(), 0, position.getX(), z, position.getY(), 0));\n\t\t\t\/\/Update the heading direction of the NPC.\n\t\t\tnpc->updateDirection(direction.getW(), direction.getX(), direction.getY(), direction.getZ());\n\t\t\t\/\/Set the name of the NPC.\n\t\t\tnpc->setCustomObjectName(mission->getCreatorName(), true);\n\t\t}\n\t}\n}\n\nvoid NpcSpawnPoint::despawnNpc() {\n\tinUseByNumberOfMissions--;\n\tif (inUseByNumberOfMissions == 0) {\n\t\tif (despawnMissionNpcTask == NULL) {\n\t\t\tdespawnMissionNpcTask = new DespawnMissionNpcTask(npc, this);\n\t\t}\n\n\t\tif (despawnMissionNpcTask->isScheduled()) {\n\t\t\treturn;\n\t\t} else {\n\t\t\t\/\/Despawn after 1 minute.\n\t\t\tdespawnMissionNpcTask->schedule(60 * 1000);\n\t\t}\n\t}\n}\n(unstable) [fixed] Mission NPC names duplication from the same mission.\/*\nCopyright (C) 2007 \n\nThis File is part of Core3.\n\nThis program is free software; you can redistribute\nit and\/or modify it under the terms of the GNU Lesser\nGeneral Public License as published by the Free Software\nFoundation; either version 2 of the License,\nor (at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\nSee the GNU Lesser General Public License for\nmore details.\n\nYou should have received a copy of the GNU Lesser General\nPublic License along with this program; if not, write to\nthe Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n\nLinking Engine3 statically or dynamically with other modules\nis making a combined work based on Engine3.\nThus, the terms and conditions of the GNU Lesser General Public License\ncover the whole combination.\n\nIn addition, as a special exception, the copyright holders of Engine3\ngive you permission to combine Engine3 program with free software\nprograms or libraries that are released under the GNU LGPL and with\ncode included in the standard release of Core3 under the GNU LGPL\nlicense (or modified versions of such code, with unchanged license).\nYou may copy and distribute such a system following the terms of the\nGNU LGPL for Engine3 and the licenses of the other code concerned,\nprovided that you include the source code of that other code when\nand as the GNU LGPL requires distribution of source code.\n\nNote that people who make modified versions of Engine3 are not obligated\nto grant this special exception for their modified versions;\nit is their choice whether to do so. The GNU Lesser General Public License\ngives permission to release a modified version without this exception;\nthis exception also makes it possible to release a modified version\nwhich carries forward this exception.\n*\/\n\n#include \"NpcSpawnPoint.h\"\n#include \"server\/zone\/managers\/mission\/spawnmaps\/events\/DespawnMissionNpcTask.h\"\n#include \"server\/zone\/managers\/name\/NameManager.h\"\n\nNpcSpawnPoint::NpcSpawnPoint() {\n\tspawnType = 0;\n\tdespawnMissionNpcTask = NULL;\n}\n\nNpcSpawnPoint::NpcSpawnPoint(CreatureObject* player, const String& spawnTypes) {\n\t\/\/Parse spawn types.\n\tString st = spawnTypes.toLowerCase();\n\tspawnType = 0;\n\tif (st.contains(\"neutral\")) {\n\t\tspawnType |= NEUTRALSPAWN;\n\t}\n\tif (st.contains(\"imperial\")) {\n\t\tspawnType |= IMPERIALSPAWN;\n\t}\n\tif (st.contains(\"rebel\")) {\n\t\tspawnType |= REBELSPAWN;\n\t}\n\tif (st.contains(\"bhtarget\")) {\n\t\tspawnType |= BHTARGETSPAWN;\n\t}\n\tif (st.contains(\"nospawn\")) {\n\t\t\/\/No spawn overrides all other spawn types.\n\t\tspawnType = NOSPAWN;\n\t}\n\tposition.setX(player->getPosition().getX());\n\tposition.setY(player->getPosition().getY());\n\tdirection.setHeadingDirection(player->getDirection()->getRadians());\n\tinUseByNumberOfMissions = 0;\n\tdespawnMissionNpcTask = NULL;\n}\n\nvoid NpcSpawnPoint::readObject(LuaObject* luaObject) {\n\tfloat x = luaObject->getFloatAt(1);\n\tfloat y = luaObject->getFloatAt(2);\n\tfloat radians = luaObject->getFloatAt(3);\n\tspawnType = luaObject->getIntAt(4);\n\tposition.setX(x);\n\tposition.setY(y);\n\tposition.setZ(0);\n\tdirection.setHeadingDirection(radians);\n\tinUseByNumberOfMissions = 0;\n\tdespawnMissionNpcTask = NULL;\n}\n\nbool NpcSpawnPoint::parseFromBinaryStream(ObjectInputStream* stream) {\n\tspawnType = stream->readInt();\n\tinUseByNumberOfMissions = stream->readInt();\n\tbool result = position.parseFromBinaryStream(stream);\n\tresult &= direction.parseFromBinaryStream(stream);\n\treturn result & npc.parseFromBinaryStream(stream);\n}\n\nbool NpcSpawnPoint::toBinaryStream(ObjectOutputStream* stream) {\n\tstream->writeInt(spawnType);\n\tstream->writeInt(inUseByNumberOfMissions);\n\tbool result = position.toBinaryStream(stream);\n\tresult &= direction.toBinaryStream(stream);\n\treturn result & npc.toBinaryStream(stream);\n}\n\nvoid NpcSpawnPoint::spawnNpc(TerrainManager* terrainManager, CreatureManager* creatureManager, ManagedReference mission) {\n\tinUseByNumberOfMissions++;\n\n\tif (inUseByNumberOfMissions == 1) {\n\t\tif (despawnMissionNpcTask != NULL && despawnMissionNpcTask->isScheduled()) {\n\t\t\tdespawnMissionNpcTask->cancel();\n\t\t} else {\n\t\t\t\/\/Spawn the NPC.\n\t\t\tString deliverNpc = \"deliver_npc\";\n\t\t\tfloat z = terrainManager->getHeight(position.getX(), position.getY());\n\t\t\tnpc = cast(creatureManager->spawnCreature(deliverNpc.hashCode(), 0, position.getX(), z, position.getY(), 0));\n\t\t\tnpc->updateDirection(direction.getW(), direction.getX(), direction.getY(), direction.getZ());\n\t\t\t\/\/Set the name of the NPC.\n\t\t\tNameManager* nm = npc->getZoneProcessServer()->getNameManager();\n\t\t\tnpc->setCustomObjectName(nm->makeCreatureName(), true);\n\t\t}\n\t}\n}\n\nvoid NpcSpawnPoint::despawnNpc() {\n\tinUseByNumberOfMissions--;\n\n\tif (inUseByNumberOfMissions == 0) {\n\t\tif (despawnMissionNpcTask == NULL) {\n\t\t\tdespawnMissionNpcTask = new DespawnMissionNpcTask(npc, this);\n\t\t}\n\n\t\tif (despawnMissionNpcTask->isScheduled()) {\n\t\t\treturn;\n\t\t} else {\n\t\t\t\/\/Despawn after 1 minute.\n\t\t\tdespawnMissionNpcTask->schedule(60 * 1000);\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)\n *\n * This file is part of Orfeo Toolbox\n *\n * https:\/\/www.orfeo-toolbox.org\/\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"otbWrapperApplication.h\"\n#include \"otbWrapperApplicationFactory.h\"\n\n#include \"otbSpatialReference.h\"\n\nnamespace otb\n{\nnamespace Wrapper\n{\n\nclass ObtainUTMZoneFromGeoPoint : public Application\n{\npublic:\n \/** Standard class typedefs. *\/\n typedef ObtainUTMZoneFromGeoPoint Self;\n typedef Application Superclass;\n typedef itk::SmartPointer Pointer;\n typedef itk::SmartPointer ConstPointer;\n\n \/** Standard macro *\/\n itkNewMacro(Self);\n\n itkTypeMacro(ObtainUTMZoneFromGeoPoint, otb::Application);\n\nprivate:\n ObtainUTMZoneFromGeoPoint()\n {\n }\n\n ~ObtainUTMZoneFromGeoPoint() override\n {\n }\n\n void DoInit() override\n {\n SetName(\"ObtainUTMZoneFromGeoPoint\");\n SetDescription(\"UTM zone determination from a geographic point.\");\n\n \/\/ Documentation\n SetDocName(\"Obtain UTM Zone From Geo Point\");\n SetDocLongDescription(\"This application returns the UTM zone of an input geographic point.\");\n SetDocLimitations(\"None\");\n SetDocAuthors(\"OTB-Team\");\n SetDocSeeAlso(\" \");\n\n\tAddDocTag(\"Miscellaneous\");\n AddDocTag(Tags::Coordinates);\n\n AddParameter(ParameterType_Float, \"lat\", \"Latitude\");\n SetParameterDescription(\"lat\", \"Latitude value of desired point.\");\n\n AddParameter(ParameterType_Float, \"lon\", \"Longitude\");\n SetParameterDescription(\"lon\", \"Longitude value of desired point.\");\n\n AddParameter(ParameterType_Int,\"utm\",\"UTMZone\");\n SetParameterDescription(\"utm\",\"UTM Zone\");\n MandatoryOff(\"utm\");\n SetParameterRole(\"utm\", Role_Output);\n\n SetExampleComment(\"Obtain a UTM Zone\", 0);\n SetDocExampleParameterValue(\"lat\",\"10.0\");\n SetDocExampleParameterValue(\"lon\",\"124.0\");\n\n SetOfficialDocLink();\n }\n\n void DoUpdateParameters() override\n {\n \/\/ Nothing to do\n }\n\n void DoExecute() override\n {\n unsigned int utmZone = 0;\n otb::SpatialReference::hemisphere hem;\n\n\n otb::SpatialReference::UTMFromGeoPoint(GetParameterFloat(\"lon\"),\n GetParameterFloat(\"lat\"),utmZone,hem);\n\n SetParameterInt(\"utm\",utmZone);\n }\n\n};\n\n}\n}\n\nOTB_APPLICATION_EXPORT(otb::Wrapper::ObtainUTMZoneFromGeoPoint)\nBUG: inverted lat\/lon\/*\n * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)\n *\n * This file is part of Orfeo Toolbox\n *\n * https:\/\/www.orfeo-toolbox.org\/\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"otbWrapperApplication.h\"\n#include \"otbWrapperApplicationFactory.h\"\n\n#include \"otbSpatialReference.h\"\n\nnamespace otb\n{\nnamespace Wrapper\n{\n\nclass ObtainUTMZoneFromGeoPoint : public Application\n{\npublic:\n \/** Standard class typedefs. *\/\n typedef ObtainUTMZoneFromGeoPoint Self;\n typedef Application Superclass;\n typedef itk::SmartPointer Pointer;\n typedef itk::SmartPointer ConstPointer;\n\n \/** Standard macro *\/\n itkNewMacro(Self);\n\n itkTypeMacro(ObtainUTMZoneFromGeoPoint, otb::Application);\n\nprivate:\n ObtainUTMZoneFromGeoPoint()\n {\n }\n\n ~ObtainUTMZoneFromGeoPoint() override\n {\n }\n\n void DoInit() override\n {\n SetName(\"ObtainUTMZoneFromGeoPoint\");\n SetDescription(\"UTM zone determination from a geographic point.\");\n\n \/\/ Documentation\n SetDocName(\"Obtain UTM Zone From Geo Point\");\n SetDocLongDescription(\"This application returns the UTM zone of an input geographic point.\");\n SetDocLimitations(\"None\");\n SetDocAuthors(\"OTB-Team\");\n SetDocSeeAlso(\" \");\n\n\tAddDocTag(\"Miscellaneous\");\n AddDocTag(Tags::Coordinates);\n\n AddParameter(ParameterType_Float, \"lat\", \"Latitude\");\n SetParameterDescription(\"lat\", \"Latitude value of desired point.\");\n\n AddParameter(ParameterType_Float, \"lon\", \"Longitude\");\n SetParameterDescription(\"lon\", \"Longitude value of desired point.\");\n\n AddParameter(ParameterType_Int,\"utm\",\"UTMZone\");\n SetParameterDescription(\"utm\",\"UTM Zone\");\n MandatoryOff(\"utm\");\n SetParameterRole(\"utm\", Role_Output);\n\n SetExampleComment(\"Obtain a UTM Zone\", 0);\n SetDocExampleParameterValue(\"lat\",\"10.0\");\n SetDocExampleParameterValue(\"lon\",\"124.0\");\n\n SetOfficialDocLink();\n }\n\n void DoUpdateParameters() override\n {\n \/\/ Nothing to do\n }\n\n void DoExecute() override\n {\n unsigned int utmZone = 0;\n otb::SpatialReference::hemisphere hem;\n\n\n otb::SpatialReference::UTMFromGeoPoint(GetParameterFloat(\"lat\"),\n GetParameterFloat(\"lon\"),utmZone,hem);\n\n SetParameterInt(\"utm\",utmZone);\n }\n\n};\n\n}\n}\n\nOTB_APPLICATION_EXPORT(otb::Wrapper::ObtainUTMZoneFromGeoPoint)\n<|endoftext|>"} {"text":"#include \"mitkConcentrationCurveGenerator.h\"\n#include \"mitkConvertToConcentrationTurboFlashFunctor.h\"\n#include \"mitkConvertT2ConcentrationFunctor.h\"\n#include \"mitkConvertToConcentrationViaT1Functor.h\"\n#include \"mitkImageTimeSelector.h\"\n#include \"mitkImageCast.h\"\n#include \"mitkITKImageImport.h\"\n#include \"mitkModelBase.h\"\n#include \"mitkExtractTimeGrid.h\"\n#include \"mitkArbitraryTimeGeometry.h\"\n#include \"itkNaryAddImageFilter.h\"\n#include \"mitkImageAccessByItk.h\"\n#include \"itkImageIOBase.h\"\n#include \"itkBinaryFunctorImageFilter.h\"\n#include \"itkTernaryFunctorImageFilter.h\"\n#include \n#include \"itkMeanProjectionImageFilter.h\"\n\nmitk::ConcentrationCurveGenerator::ConcentrationCurveGenerator() : m_isT2weightedImage(false), m_isTurboFlashSequence(false), \n m_AbsoluteSignalEnhancement(false), m_RelativeSignalEnhancement(0.0), m_UsingT1Map(false), m_Factor(0.0), m_RecoveryTime(0.0), m_RelaxationTime(0.0),\n m_Relaxivity(0.0), m_FlipAngle(0.0), m_T2Factor(0.0), m_T2EchoTime(0.0)\n{\n}\n\nmitk::ConcentrationCurveGenerator::~ConcentrationCurveGenerator()\n{\n\n}\n\nmitk::Image::Pointer mitk::ConcentrationCurveGenerator::GetConvertedImage()\n{\n if(this->m_DynamicImage.IsNull())\n {\n itkExceptionMacro( << \"Dynamic Image not set!\");\n }\n else {\n Convert();\n }\n return m_ConvertedImage;\n\n}\n\nvoid mitk::ConcentrationCurveGenerator::Convert()\n{\n\n mitk::Image::Pointer tempImage = mitk::Image::New();\n mitk::PixelType pixeltype = mitk::MakeScalarPixelType();\n\n tempImage->Initialize(pixeltype,*this->m_DynamicImage->GetTimeGeometry());\n\n mitk::TimeGeometry::Pointer timeGeometry = (this->m_DynamicImage->GetTimeGeometry())->Clone();\n tempImage->SetTimeGeometry(timeGeometry);\n\n PrepareBaselineImage();\n mitk::ImageTimeSelector::Pointer imageTimeSelector = mitk::ImageTimeSelector::New();\n imageTimeSelector->SetInput(this->m_DynamicImage);\n\n for(unsigned int i = 0; i< this->m_DynamicImage->GetTimeSteps(); ++i)\n {\n imageTimeSelector->SetTimeNr(i);\n imageTimeSelector->UpdateLargestPossibleRegion();\n\n mitk::Image::Pointer mitkInputImage = imageTimeSelector->GetOutput();\n mitk::Image::Pointer outputImage = mitk::Image::New();\n\n outputImage = ConvertSignalToConcentrationCurve(mitkInputImage,this->m_BaselineImage);\n\n mitk::ImageReadAccessor accessor(outputImage);\n tempImage->SetVolume(accessor.GetData(), i);\n }\n\n this->m_ConvertedImage = tempImage;\n\n}\n\nvoid mitk::ConcentrationCurveGenerator::PrepareBaselineImage()\n{\n\n mitk::ImageTimeSelector::Pointer imageTimeSelector = mitk::ImageTimeSelector::New();\n imageTimeSelector->SetInput(this->m_DynamicImage);\n imageTimeSelector->SetTimeNr(0);\n imageTimeSelector->UpdateLargestPossibleRegion();\n mitk::Image::Pointer baselineImage;\n baselineImage = imageTimeSelector->GetOutput();\n \n if (m_BaselineStartTimeStep == m_BaselineEndTimeStep)\n {\n this->m_BaselineImage = imageTimeSelector->GetOutput();\n }\n else\n {\n try\n {\n AccessFixedDimensionByItk(this->m_DynamicImage, mitk::ConcentrationCurveGenerator::CalculateAverageBaselineImage, 4);\n }\n catch (itk::ExceptionObject & err)\n {\n std::cerr << \"ExceptionObject in ConcentrationCurveGenerator::CalculateAverageBaselineImage caught!\" << std::endl;\n std::cerr << err << std::endl;\n }\n }\n}\n\ntemplate\nvoid mitk::ConcentrationCurveGenerator::CalculateAverageBaselineImage(const itk::Image *itkBaselineImage)\n{\n if (itkBaselineImage == NULL)\n {\n mitkThrow() << \"Error in ConcentrationCurveGenerator::CalculateAverageBaselineImage. Input image is NULL.\";\n }\n if (m_BaselineStartTimeStep > m_BaselineEndTimeStep)\n {\n mitkThrow() << \"Error in ConcentrationCurveGenerator::CalculateAverageBaselineImage. End time point is before start time point.\";\n }\n \n typedef itk::Image TPixel4DImageType;\n typedef itk::Image TPixel3DImageType;\n typedef itk::Image Double3DImageType;\n typedef itk::Image Double4DImageType;\n typedef itk::ExtractImageFilter ExtractImageFilterType;\n typedef itk::ExtractImageFilter Extract3DImageFilterType;\n typedef itk::MeanProjectionImageFilter MeanProjectionImageFilterType;\n\n typename MeanProjectionImageFilterType::Pointer MeanProjectionImageFilter = MeanProjectionImageFilterType::New();\n typename Extract3DImageFilterType::Pointer Extract3DImageFilter = Extract3DImageFilterType::New();\n typename TPixel4DImageType::RegionType region_input = itkBaselineImage->GetLargestPossibleRegion();\n\n if (m_BaselineEndTimeStep > region_input.GetSize()[3])\n {\n mitkThrow() << \"Error in ConcentrationCurveGenerator::CalculateAverageBaselineImage. End time point is larger than total number of time points.\";\n }\n\n ExtractImageFilterType::Pointer ExtractFilter = ExtractImageFilterType::New();\n typename TPixel4DImageType::Pointer baselineTimeFrameImage = TPixel4DImageType::New();\n typename TPixel4DImageType::RegionType extractionRegion;\n typename TPixel4DImageType::SizeType size_input_aux = region_input.GetSize();\n size_input_aux[3] = m_BaselineEndTimeStep - m_BaselineStartTimeStep+1;\n typename TPixel4DImageType::IndexType start_input_aux = region_input.GetIndex();\n start_input_aux[3] = m_BaselineStartTimeStep;\n extractionRegion.SetSize(size_input_aux);\n extractionRegion.SetIndex(start_input_aux);\n ExtractFilter->SetExtractionRegion(extractionRegion);\n ExtractFilter->SetInput(itkBaselineImage);\n ExtractFilter->SetDirectionCollapseToSubmatrix();\n try\n {\n ExtractFilter->Update();\n }\n catch (itk::ExceptionObject & err)\n {\n std::cerr << \"ExceptionObject caught!\" << std::endl;\n std::cerr << err << std::endl;\n }\n baselineTimeFrameImage = ExtractFilter->GetOutput();\n MeanProjectionImageFilter->SetProjectionDimension(3);\n MeanProjectionImageFilter->SetInput(baselineTimeFrameImage);\n try\n {\n MeanProjectionImageFilter->Update();\n }\n catch (itk::ExceptionObject & err)\n {\n std::cerr << \"ExceptionObject caught!\" << std::endl;\n std::cerr << err << std::endl;\n }\n Extract3DImageFilter->SetInput(MeanProjectionImageFilter->GetOutput());\n size_input_aux[3] = 0;\n start_input_aux[3] = 0;\n extractionRegion.SetSize(size_input_aux);\n extractionRegion.SetIndex(start_input_aux);\n Extract3DImageFilter->SetExtractionRegion(extractionRegion);\n Extract3DImageFilter->SetDirectionCollapseToSubmatrix();\n try\n {\n Extract3DImageFilter->Update();\n }\n catch (itk::ExceptionObject & err)\n {\n std::cerr << \"ExceptionObject caught!\" << std::endl;\n std::cerr << err << std::endl;\n }\n\n Image::Pointer mitkBaselineImage = Image::New();\n CastToMitkImage(Extract3DImageFilter->GetOutput(), mitkBaselineImage);\n this->m_BaselineImage = mitkBaselineImage;\n}\n\n\nmitk::Image::Pointer mitk::ConcentrationCurveGenerator::ConvertSignalToConcentrationCurve(const mitk::Image* inputImage,const mitk::Image* baselineImage)\n{\n mitk::PixelType m_PixelType = inputImage->GetPixelType();\n AccessTwoImagesFixedDimensionByItk(inputImage, baselineImage, mitk::ConcentrationCurveGenerator::convertToConcentration, 3);\n return m_ConvertSignalToConcentrationCurve_OutputImage;\n\n}\n\n\ntemplate\nmitk::Image::Pointer mitk::ConcentrationCurveGenerator::convertToConcentration(const itk::Image *itkInputImage, const itk::Image *itkBaselineImage)\n{\n typedef itk::Image InputImageType;\n typedef itk::Image BaselineImageType;\n typedef itk::Image DoubleImageType;\n\n typename DoubleImageType::Pointer itkDoubleInputImage = DoubleImageType::New();\n typename DoubleImageType::Pointer itkDoubleBaselineImage = DoubleImageType::New();\n\n typedef itk::CastImageFilter CastInputImageToDoubleImageFilterType;\n typename CastInputImageToDoubleImageFilterType::Pointer CastInputImageToDoubleImageFilter = CastInputImageToDoubleImageFilterType::New();\n CastInputImageToDoubleImageFilter->SetInput(itkInputImage);\n CastInputImageToDoubleImageFilter->Update();\n itkDoubleInputImage = CastInputImageToDoubleImageFilter->GetOutput();\n\n typedef itk::CastImageFilter CastBaselineImageToDoubleImageFilterType;\n typename CastBaselineImageToDoubleImageFilterType::Pointer CastBaselineImageToDoubleImageFilter = CastBaselineImageToDoubleImageFilterType::New();\n CastBaselineImageToDoubleImageFilter->SetInput(itkBaselineImage);\n CastBaselineImageToDoubleImageFilter->Update();\n itkDoubleBaselineImage = CastBaselineImageToDoubleImageFilter->GetOutput();\n\n if (this->m_isT2weightedImage)\n {\n typedef mitk::ConvertT2ConcentrationFunctor ConversionFunctorT2Type;\n typedef itk::BinaryFunctorImageFilter FilterT2Type;\n\n ConversionFunctorT2Type ConversionT2Functor;\n ConversionT2Functor.initialize(this->m_T2Factor, this->m_T2EchoTime);\n\n typename FilterT2Type::Pointer ConversionT2Filter = FilterT2Type::New();\n\n ConversionT2Filter->SetFunctor(ConversionT2Functor);\n ConversionT2Filter->SetInput1(itkDoubleInputImage);\n ConversionT2Filter->SetInput2(itkDoubleBaselineImage);\n\n ConversionT2Filter->Update();\n\n m_ConvertSignalToConcentrationCurve_OutputImage = mitk::ImportItkImage(ConversionT2Filter->GetOutput())->Clone();\n }\n\n else\n {\n if(this->m_isTurboFlashSequence)\n {\n typedef mitk::ConvertToConcentrationTurboFlashFunctor ConversionFunctorTurboFlashType;\n typedef itk::BinaryFunctorImageFilter FilterTurboFlashType;\n\n ConversionFunctorTurboFlashType ConversionTurboFlashFunctor;\n ConversionTurboFlashFunctor.initialize(this->m_RelaxationTime, this->m_Relaxivity, this->m_RecoveryTime);\n\n typename FilterTurboFlashType::Pointer ConversionTurboFlashFilter = FilterTurboFlashType::New();\n\n ConversionTurboFlashFilter->SetFunctor(ConversionTurboFlashFunctor);\n ConversionTurboFlashFilter->SetInput1(itkDoubleInputImage);\n ConversionTurboFlashFilter->SetInput2(itkDoubleBaselineImage);\n\n ConversionTurboFlashFilter->Update();\n m_ConvertSignalToConcentrationCurve_OutputImage = mitk::ImportItkImage(ConversionTurboFlashFilter->GetOutput())->Clone();\n\n\n }\n else if(this->m_UsingT1Map)\n {\n typename DoubleImageType::Pointer itkT10Image = DoubleImageType::New();\n mitk::CastToItkImage(m_T10Image, itkT10Image);\n\n typedef mitk::ConvertToConcentrationViaT1CalcFunctor ConvertToConcentrationViaT1CalcFunctorType;\n typedef itk::TernaryFunctorImageFilter FilterT1MapType;\n\n ConvertToConcentrationViaT1CalcFunctorType ConversionT1MapFunctor;\n ConversionT1MapFunctor.initialize(this->m_Relaxivity, this->m_RecoveryTime, this->m_FlipAngle);\n\n typename FilterT1MapType::Pointer ConversionT1MapFilter = FilterT1MapType::New();\n\n ConversionT1MapFilter->SetFunctor(ConversionT1MapFunctor);\n ConversionT1MapFilter->SetInput1(itkDoubleInputImage);\n ConversionT1MapFilter->SetInput2(itkDoubleBaselineImage);\n ConversionT1MapFilter->SetInput3(itkT10Image);\n\n ConversionT1MapFilter->Update();\n m_ConvertSignalToConcentrationCurve_OutputImage = mitk::ImportItkImage(ConversionT1MapFilter->GetOutput())->Clone();\n\n\n }\n\n else if(this->m_AbsoluteSignalEnhancement)\n {\n typedef mitk::ConvertToConcentrationAbsoluteFunctor ConversionFunctorAbsoluteType;\n typedef itk::BinaryFunctorImageFilter FilterAbsoluteType;\n\n ConversionFunctorAbsoluteType ConversionAbsoluteFunctor;\n ConversionAbsoluteFunctor.initialize(this->m_Factor);\n\n typename FilterAbsoluteType::Pointer ConversionAbsoluteFilter = FilterAbsoluteType::New();\n\n ConversionAbsoluteFilter->SetFunctor(ConversionAbsoluteFunctor);\n ConversionAbsoluteFilter->SetInput1(itkDoubleInputImage);\n ConversionAbsoluteFilter->SetInput2(itkDoubleBaselineImage);\n\n ConversionAbsoluteFilter->Update();\n\n m_ConvertSignalToConcentrationCurve_OutputImage = mitk::ImportItkImage(ConversionAbsoluteFilter->GetOutput())->Clone();\n }\n\n else if(this->m_RelativeSignalEnhancement)\n {\n typedef mitk::ConvertToConcentrationRelativeFunctor ConversionFunctorRelativeType;\n typedef itk::BinaryFunctorImageFilter FilterRelativeType;\n\n ConversionFunctorRelativeType ConversionRelativeFunctor;\n ConversionRelativeFunctor.initialize(this->m_Factor);\n\n typename FilterRelativeType::Pointer ConversionRelativeFilter = FilterRelativeType::New();\n\n ConversionRelativeFilter->SetFunctor(ConversionRelativeFunctor);\n ConversionRelativeFilter->SetInput1(itkDoubleInputImage);\n ConversionRelativeFilter->SetInput2(itkDoubleBaselineImage);\n\n ConversionRelativeFilter->Update();\n\n m_ConvertSignalToConcentrationCurve_OutputImage = mitk::ImportItkImage(ConversionRelativeFilter->GetOutput())->Clone();\n }\n\n }\n return m_ConvertSignalToConcentrationCurve_OutputImage;\n\n}\n\n\nAdd brackets for better readability.#include \"mitkConcentrationCurveGenerator.h\"\n#include \"mitkConvertToConcentrationTurboFlashFunctor.h\"\n#include \"mitkConvertT2ConcentrationFunctor.h\"\n#include \"mitkConvertToConcentrationViaT1Functor.h\"\n#include \"mitkImageTimeSelector.h\"\n#include \"mitkImageCast.h\"\n#include \"mitkITKImageImport.h\"\n#include \"mitkModelBase.h\"\n#include \"mitkExtractTimeGrid.h\"\n#include \"mitkArbitraryTimeGeometry.h\"\n#include \"itkNaryAddImageFilter.h\"\n#include \"mitkImageAccessByItk.h\"\n#include \"itkImageIOBase.h\"\n#include \"itkBinaryFunctorImageFilter.h\"\n#include \"itkTernaryFunctorImageFilter.h\"\n#include \n#include \"itkMeanProjectionImageFilter.h\"\n\nmitk::ConcentrationCurveGenerator::ConcentrationCurveGenerator() : m_isT2weightedImage(false), m_isTurboFlashSequence(false), \n m_AbsoluteSignalEnhancement(false), m_RelativeSignalEnhancement(0.0), m_UsingT1Map(false), m_Factor(0.0), m_RecoveryTime(0.0), m_RelaxationTime(0.0),\n m_Relaxivity(0.0), m_FlipAngle(0.0), m_T2Factor(0.0), m_T2EchoTime(0.0)\n{\n}\n\nmitk::ConcentrationCurveGenerator::~ConcentrationCurveGenerator()\n{\n\n}\n\nmitk::Image::Pointer mitk::ConcentrationCurveGenerator::GetConvertedImage()\n{\n if(this->m_DynamicImage.IsNull())\n {\n itkExceptionMacro( << \"Dynamic Image not set!\");\n }\n else {\n Convert();\n }\n return m_ConvertedImage;\n\n}\n\nvoid mitk::ConcentrationCurveGenerator::Convert()\n{\n\n mitk::Image::Pointer tempImage = mitk::Image::New();\n mitk::PixelType pixeltype = mitk::MakeScalarPixelType();\n\n tempImage->Initialize(pixeltype,*this->m_DynamicImage->GetTimeGeometry());\n\n mitk::TimeGeometry::Pointer timeGeometry = (this->m_DynamicImage->GetTimeGeometry())->Clone();\n tempImage->SetTimeGeometry(timeGeometry);\n\n PrepareBaselineImage();\n mitk::ImageTimeSelector::Pointer imageTimeSelector = mitk::ImageTimeSelector::New();\n imageTimeSelector->SetInput(this->m_DynamicImage);\n\n for(unsigned int i = 0; i< this->m_DynamicImage->GetTimeSteps(); ++i)\n {\n imageTimeSelector->SetTimeNr(i);\n imageTimeSelector->UpdateLargestPossibleRegion();\n\n mitk::Image::Pointer mitkInputImage = imageTimeSelector->GetOutput();\n mitk::Image::Pointer outputImage = mitk::Image::New();\n\n outputImage = ConvertSignalToConcentrationCurve(mitkInputImage,this->m_BaselineImage);\n\n mitk::ImageReadAccessor accessor(outputImage);\n tempImage->SetVolume(accessor.GetData(), i);\n }\n\n this->m_ConvertedImage = tempImage;\n\n}\n\nvoid mitk::ConcentrationCurveGenerator::PrepareBaselineImage()\n{\n\n mitk::ImageTimeSelector::Pointer imageTimeSelector = mitk::ImageTimeSelector::New();\n imageTimeSelector->SetInput(this->m_DynamicImage);\n imageTimeSelector->SetTimeNr(0);\n imageTimeSelector->UpdateLargestPossibleRegion();\n mitk::Image::Pointer baselineImage;\n baselineImage = imageTimeSelector->GetOutput();\n \n if (m_BaselineStartTimeStep == m_BaselineEndTimeStep)\n {\n this->m_BaselineImage = imageTimeSelector->GetOutput();\n }\n else\n {\n try\n {\n AccessFixedDimensionByItk(this->m_DynamicImage, mitk::ConcentrationCurveGenerator::CalculateAverageBaselineImage, 4);\n }\n catch (itk::ExceptionObject & err)\n {\n std::cerr << \"ExceptionObject in ConcentrationCurveGenerator::CalculateAverageBaselineImage caught!\" << std::endl;\n std::cerr << err << std::endl;\n }\n }\n}\n\ntemplate\nvoid mitk::ConcentrationCurveGenerator::CalculateAverageBaselineImage(const itk::Image *itkBaselineImage)\n{\n if (itkBaselineImage == NULL)\n {\n mitkThrow() << \"Error in ConcentrationCurveGenerator::CalculateAverageBaselineImage. Input image is NULL.\";\n }\n if (m_BaselineStartTimeStep > m_BaselineEndTimeStep)\n {\n mitkThrow() << \"Error in ConcentrationCurveGenerator::CalculateAverageBaselineImage. End time point is before start time point.\";\n }\n \n typedef itk::Image TPixel4DImageType;\n typedef itk::Image TPixel3DImageType;\n typedef itk::Image Double3DImageType;\n typedef itk::Image Double4DImageType;\n typedef itk::ExtractImageFilter ExtractImageFilterType;\n typedef itk::ExtractImageFilter Extract3DImageFilterType;\n typedef itk::MeanProjectionImageFilter MeanProjectionImageFilterType;\n\n typename MeanProjectionImageFilterType::Pointer MeanProjectionImageFilter = MeanProjectionImageFilterType::New();\n typename Extract3DImageFilterType::Pointer Extract3DImageFilter = Extract3DImageFilterType::New();\n typename TPixel4DImageType::RegionType region_input = itkBaselineImage->GetLargestPossibleRegion();\n\n if (m_BaselineEndTimeStep > region_input.GetSize()[3])\n {\n mitkThrow() << \"Error in ConcentrationCurveGenerator::CalculateAverageBaselineImage. End time point is larger than total number of time points.\";\n }\n\n ExtractImageFilterType::Pointer ExtractFilter = ExtractImageFilterType::New();\n typename TPixel4DImageType::Pointer baselineTimeFrameImage = TPixel4DImageType::New();\n typename TPixel4DImageType::RegionType extractionRegion;\n typename TPixel4DImageType::SizeType size_input_aux = region_input.GetSize();\n size_input_aux[3] = (m_BaselineEndTimeStep - m_BaselineStartTimeStep+1);\n typename TPixel4DImageType::IndexType start_input_aux = region_input.GetIndex();\n start_input_aux[3] = m_BaselineStartTimeStep;\n extractionRegion.SetSize(size_input_aux);\n extractionRegion.SetIndex(start_input_aux);\n ExtractFilter->SetExtractionRegion(extractionRegion);\n ExtractFilter->SetInput(itkBaselineImage);\n ExtractFilter->SetDirectionCollapseToSubmatrix();\n try\n {\n ExtractFilter->Update();\n }\n catch (itk::ExceptionObject & err)\n {\n std::cerr << \"ExceptionObject caught!\" << std::endl;\n std::cerr << err << std::endl;\n }\n baselineTimeFrameImage = ExtractFilter->GetOutput();\n MeanProjectionImageFilter->SetProjectionDimension(3);\n MeanProjectionImageFilter->SetInput(baselineTimeFrameImage);\n try\n {\n MeanProjectionImageFilter->Update();\n }\n catch (itk::ExceptionObject & err)\n {\n std::cerr << \"ExceptionObject caught!\" << std::endl;\n std::cerr << err << std::endl;\n }\n Extract3DImageFilter->SetInput(MeanProjectionImageFilter->GetOutput());\n size_input_aux[3] = 0;\n start_input_aux[3] = 0;\n extractionRegion.SetSize(size_input_aux);\n extractionRegion.SetIndex(start_input_aux);\n Extract3DImageFilter->SetExtractionRegion(extractionRegion);\n Extract3DImageFilter->SetDirectionCollapseToSubmatrix();\n try\n {\n Extract3DImageFilter->Update();\n }\n catch (itk::ExceptionObject & err)\n {\n std::cerr << \"ExceptionObject caught!\" << std::endl;\n std::cerr << err << std::endl;\n }\n\n Image::Pointer mitkBaselineImage = Image::New();\n CastToMitkImage(Extract3DImageFilter->GetOutput(), mitkBaselineImage);\n this->m_BaselineImage = mitkBaselineImage;\n}\n\n\nmitk::Image::Pointer mitk::ConcentrationCurveGenerator::ConvertSignalToConcentrationCurve(const mitk::Image* inputImage,const mitk::Image* baselineImage)\n{\n mitk::PixelType m_PixelType = inputImage->GetPixelType();\n AccessTwoImagesFixedDimensionByItk(inputImage, baselineImage, mitk::ConcentrationCurveGenerator::convertToConcentration, 3);\n return m_ConvertSignalToConcentrationCurve_OutputImage;\n\n}\n\n\ntemplate\nmitk::Image::Pointer mitk::ConcentrationCurveGenerator::convertToConcentration(const itk::Image *itkInputImage, const itk::Image *itkBaselineImage)\n{\n typedef itk::Image InputImageType;\n typedef itk::Image BaselineImageType;\n typedef itk::Image DoubleImageType;\n\n typename DoubleImageType::Pointer itkDoubleInputImage = DoubleImageType::New();\n typename DoubleImageType::Pointer itkDoubleBaselineImage = DoubleImageType::New();\n\n typedef itk::CastImageFilter CastInputImageToDoubleImageFilterType;\n typename CastInputImageToDoubleImageFilterType::Pointer CastInputImageToDoubleImageFilter = CastInputImageToDoubleImageFilterType::New();\n CastInputImageToDoubleImageFilter->SetInput(itkInputImage);\n CastInputImageToDoubleImageFilter->Update();\n itkDoubleInputImage = CastInputImageToDoubleImageFilter->GetOutput();\n\n typedef itk::CastImageFilter CastBaselineImageToDoubleImageFilterType;\n typename CastBaselineImageToDoubleImageFilterType::Pointer CastBaselineImageToDoubleImageFilter = CastBaselineImageToDoubleImageFilterType::New();\n CastBaselineImageToDoubleImageFilter->SetInput(itkBaselineImage);\n CastBaselineImageToDoubleImageFilter->Update();\n itkDoubleBaselineImage = CastBaselineImageToDoubleImageFilter->GetOutput();\n\n if (this->m_isT2weightedImage)\n {\n typedef mitk::ConvertT2ConcentrationFunctor ConversionFunctorT2Type;\n typedef itk::BinaryFunctorImageFilter FilterT2Type;\n\n ConversionFunctorT2Type ConversionT2Functor;\n ConversionT2Functor.initialize(this->m_T2Factor, this->m_T2EchoTime);\n\n typename FilterT2Type::Pointer ConversionT2Filter = FilterT2Type::New();\n\n ConversionT2Filter->SetFunctor(ConversionT2Functor);\n ConversionT2Filter->SetInput1(itkDoubleInputImage);\n ConversionT2Filter->SetInput2(itkDoubleBaselineImage);\n\n ConversionT2Filter->Update();\n\n m_ConvertSignalToConcentrationCurve_OutputImage = mitk::ImportItkImage(ConversionT2Filter->GetOutput())->Clone();\n }\n\n else\n {\n if(this->m_isTurboFlashSequence)\n {\n typedef mitk::ConvertToConcentrationTurboFlashFunctor ConversionFunctorTurboFlashType;\n typedef itk::BinaryFunctorImageFilter FilterTurboFlashType;\n\n ConversionFunctorTurboFlashType ConversionTurboFlashFunctor;\n ConversionTurboFlashFunctor.initialize(this->m_RelaxationTime, this->m_Relaxivity, this->m_RecoveryTime);\n\n typename FilterTurboFlashType::Pointer ConversionTurboFlashFilter = FilterTurboFlashType::New();\n\n ConversionTurboFlashFilter->SetFunctor(ConversionTurboFlashFunctor);\n ConversionTurboFlashFilter->SetInput1(itkDoubleInputImage);\n ConversionTurboFlashFilter->SetInput2(itkDoubleBaselineImage);\n\n ConversionTurboFlashFilter->Update();\n m_ConvertSignalToConcentrationCurve_OutputImage = mitk::ImportItkImage(ConversionTurboFlashFilter->GetOutput())->Clone();\n\n\n }\n else if(this->m_UsingT1Map)\n {\n typename DoubleImageType::Pointer itkT10Image = DoubleImageType::New();\n mitk::CastToItkImage(m_T10Image, itkT10Image);\n\n typedef mitk::ConvertToConcentrationViaT1CalcFunctor ConvertToConcentrationViaT1CalcFunctorType;\n typedef itk::TernaryFunctorImageFilter FilterT1MapType;\n\n ConvertToConcentrationViaT1CalcFunctorType ConversionT1MapFunctor;\n ConversionT1MapFunctor.initialize(this->m_Relaxivity, this->m_RecoveryTime, this->m_FlipAngle);\n\n typename FilterT1MapType::Pointer ConversionT1MapFilter = FilterT1MapType::New();\n\n ConversionT1MapFilter->SetFunctor(ConversionT1MapFunctor);\n ConversionT1MapFilter->SetInput1(itkDoubleInputImage);\n ConversionT1MapFilter->SetInput2(itkDoubleBaselineImage);\n ConversionT1MapFilter->SetInput3(itkT10Image);\n\n ConversionT1MapFilter->Update();\n m_ConvertSignalToConcentrationCurve_OutputImage = mitk::ImportItkImage(ConversionT1MapFilter->GetOutput())->Clone();\n\n\n }\n\n else if(this->m_AbsoluteSignalEnhancement)\n {\n typedef mitk::ConvertToConcentrationAbsoluteFunctor ConversionFunctorAbsoluteType;\n typedef itk::BinaryFunctorImageFilter FilterAbsoluteType;\n\n ConversionFunctorAbsoluteType ConversionAbsoluteFunctor;\n ConversionAbsoluteFunctor.initialize(this->m_Factor);\n\n typename FilterAbsoluteType::Pointer ConversionAbsoluteFilter = FilterAbsoluteType::New();\n\n ConversionAbsoluteFilter->SetFunctor(ConversionAbsoluteFunctor);\n ConversionAbsoluteFilter->SetInput1(itkDoubleInputImage);\n ConversionAbsoluteFilter->SetInput2(itkDoubleBaselineImage);\n\n ConversionAbsoluteFilter->Update();\n\n m_ConvertSignalToConcentrationCurve_OutputImage = mitk::ImportItkImage(ConversionAbsoluteFilter->GetOutput())->Clone();\n }\n\n else if(this->m_RelativeSignalEnhancement)\n {\n typedef mitk::ConvertToConcentrationRelativeFunctor ConversionFunctorRelativeType;\n typedef itk::BinaryFunctorImageFilter FilterRelativeType;\n\n ConversionFunctorRelativeType ConversionRelativeFunctor;\n ConversionRelativeFunctor.initialize(this->m_Factor);\n\n typename FilterRelativeType::Pointer ConversionRelativeFilter = FilterRelativeType::New();\n\n ConversionRelativeFilter->SetFunctor(ConversionRelativeFunctor);\n ConversionRelativeFilter->SetInput1(itkDoubleInputImage);\n ConversionRelativeFilter->SetInput2(itkDoubleBaselineImage);\n\n ConversionRelativeFilter->Update();\n\n m_ConvertSignalToConcentrationCurve_OutputImage = mitk::ImportItkImage(ConversionRelativeFilter->GetOutput())->Clone();\n }\n\n }\n return m_ConvertSignalToConcentrationCurve_OutputImage;\n\n}\n\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/chromeos\/main_menu.h\"\n\n#include \n\n#include \"app\/gfx\/insets.h\"\n#include \"app\/resource_bundle.h\"\n#include \"base\/command_line.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/string_util.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/renderer_host\/render_view_host.h\"\n#include \"chrome\/browser\/renderer_host\/render_view_host_factory.h\"\n#include \"chrome\/browser\/renderer_host\/render_widget_host_view.h\"\n#include \"chrome\/browser\/renderer_host\/render_widget_host_view_gtk.h\"\n#include \"chrome\/browser\/renderer_host\/site_instance.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/browser\/tab_contents\/render_view_host_delegate_helper.h\"\n#include \"grit\/app_resources.h\"\n#include \"grit\/generated_resources.h\"\n#include \"third_party\/skia\/include\/core\/SkBitmap.h\"\n#include \"views\/background.h\"\n#include \"views\/painter.h\"\n#include \"views\/screen.h\"\n#include \"views\/widget\/root_view.h\"\n#include \"views\/widget\/widget_gtk.h\"\n\n\/\/ Initial size of the renderer. This is contained within a window whose size\n\/\/ is set to the size of the image IDR_MAIN_MENU_BUTTON_DROP_DOWN.\nstatic const int kRendererX = 0;\nstatic const int kRendererY = 25;\nstatic const int kRendererWidth = 250;\nstatic const int kRendererHeight = 400;\n\n\/\/ Insets defining the regions that are stretched and titled to create the\n\/\/ background of the popup. These constants are fed into\n\/\/ Painter::CreateImagePainter as the insets, see it for details.\nstatic const int kBackgroundImageTop = 27;\nstatic const int kBackgroundImageLeft = 85;\nstatic const int kBackgroundImageBottom = 10;\nstatic const int kBackgroundImageRight = 8;\n\n\/\/ Command line switch for specifying url of the page.\nstatic const wchar_t kURLSwitch[] = L\"main-menu-url\";\n\n\/\/ Command line switch for specifying the size of the main menu. The default is\n\/\/ full screen.\nstatic const wchar_t kMenuSizeSwitch[] = L\"main-menu-size\";\n\n\/\/ URL of the page to load. This is ignored if kURLSwitch is specified.\nstatic const char kMenuURL[] = \"http:\/\/goto.ext.google.com\/crux-menu\";\n\n\/\/ Returns the size of the popup. By default the popup is sized slightly\n\/\/ larger than full screen, but can be overriden by the command line switch\n\/\/ kMenuSizeSwitch.\nstatic gfx::Size GetPopupSize() {\n std::wstring cl_size =\n CommandLine::ForCurrentProcess()->GetSwitchValue(kMenuSizeSwitch);\n if (!cl_size.empty()) {\n std::vector chunks;\n SplitString(WideToUTF8(cl_size), 'x', &chunks);\n if (chunks.size() == 2)\n return gfx::Size(StringToInt(chunks[0]), StringToInt(chunks[1]));\n }\n\n gfx::Size size =\n views::Screen::GetMonitorAreaNearestPoint(gfx::Point(0, 0)).size();\n \/\/ When full screen we don't want to see the drop shadow. Adjust the width\n \/\/ so the drop shadow ends up off screen.\n size.Enlarge(kBackgroundImageRight, kBackgroundImageBottom);\n return size;\n}\n\n\/\/ Returns the size for the renderer widget host view given the specified\n\/\/ size of the popup.\nstatic gfx::Size CalculateRWHVSize(const gfx::Size& popup_size) {\n return gfx::Size(popup_size.width() - kRendererX - kBackgroundImageRight,\n popup_size.height() - kRendererY - kBackgroundImageBottom);\n}\n\n\/\/ Returns the URL of the menu.\nstatic GURL GetMenuURL() {\n std::wstring url_string =\n CommandLine::ForCurrentProcess()->GetSwitchValue(kURLSwitch);\n if (!url_string.empty())\n return GURL(WideToUTF8(url_string));\n return GURL(kMenuURL);\n}\n\n\/\/ static\nvoid MainMenu::Show(Browser* browser) {\n (new MainMenu(browser))->ShowImpl();\n}\n\nMainMenu::~MainMenu() {\n popup_->Close();\n menu_rvh_->Shutdown();\n}\n\nMainMenu::MainMenu(Browser* browser)\n : browser_(browser),\n popup_(NULL),\n site_instance_(NULL),\n menu_rvh_(NULL),\n rwhv_(NULL),\n ALLOW_THIS_IN_INITIALIZER_LIST(tab_contents_delegate_(this)) {\n}\n\nvoid MainMenu::ShowImpl() {\n SkBitmap* drop_down_image = ResourceBundle::GetSharedInstance().\n GetBitmapNamed(IDR_MAIN_MENU_BUTTON_DROP_DOWN);\n\n views::WidgetGtk* menu_popup =\n new views::WidgetGtk(views::WidgetGtk::TYPE_POPUP);\n popup_ = menu_popup;\n \/\/ The background image has transparency, so we make the window transparent.\n menu_popup->MakeTransparent();\n gfx::Size popup_size = GetPopupSize();\n menu_popup->Init(NULL, gfx::Rect(0, 0, popup_size.width(),\n popup_size.height()));\n\n views::Painter* painter = views::Painter::CreateImagePainter(\n *drop_down_image,\n gfx::Insets(kBackgroundImageTop, kBackgroundImageLeft,\n kBackgroundImageBottom, kBackgroundImageRight));\n menu_popup->GetRootView()->set_background(\n views::Background::CreateBackgroundPainter(true, painter));\n\n GURL menu_url(GetMenuURL());\n site_instance_ = SiteInstance::CreateSiteInstanceForURL(browser_->profile(),\n menu_url);\n menu_rvh_ = new RenderViewHost(site_instance_, this, MSG_ROUTING_NONE);\n\n rwhv_ = new RenderWidgetHostViewGtk(menu_rvh_);\n rwhv_->InitAsChild();\n menu_rvh_->CreateRenderView();\n menu_popup->AddChild(rwhv_->GetNativeView());\n gfx::Size rwhv_size = CalculateRWHVSize(popup_size);\n menu_popup->PositionChild(rwhv_->GetNativeView(), kRendererX, kRendererY,\n rwhv_size.width(), rwhv_size.height());\n rwhv_->SetSize(rwhv_size);\n menu_rvh_->NavigateToURL(menu_url);\n menu_popup->Show();\n\n GtkWidget* rwhv_widget = rwhv_->GetNativeView();\n gtk_widget_realize(rwhv_widget);\n g_signal_connect(rwhv_widget, \"button-press-event\",\n G_CALLBACK(CallButtonPressEvent), this);\n \/\/ Do a mouse grab on the renderer widget host view's widget so that we can\n \/\/ close the popup if the user clicks anywhere else. And do a keyboard\n \/\/ grab so that we get all key events.\n gdk_pointer_grab(rwhv_widget->window, FALSE,\n static_cast(\n GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK |\n GDK_POINTER_MOTION_MASK),\n NULL, NULL, GDK_CURRENT_TIME);\n gdk_keyboard_grab(rwhv_widget->window, FALSE, GDK_CURRENT_TIME);\n}\n\nvoid MainMenu::Delete(bool now) {\n gdk_keyboard_ungrab(GDK_CURRENT_TIME);\n gdk_pointer_ungrab(GDK_CURRENT_TIME);\n \/\/ Hide the popup immediately. We don't close it as it contains the\n \/\/ renderwidgethostview, which hasn't been shutdown yet.\n popup_->Hide();\n if (now)\n delete this;\n else\n MessageLoop::current()->DeleteSoon(FROM_HERE, this);\n}\n\n\/\/ static\ngboolean MainMenu::CallButtonPressEvent(GtkWidget* widget,\n GdkEventButton* event,\n MainMenu* menu) {\n return menu->OnButtonPressEvent(widget, event);\n}\n\ngboolean MainMenu::OnButtonPressEvent(GtkWidget* widget,\n GdkEventButton* event) {\n if (event->x < 0 || event->y < 0 ||\n event->x >= widget->allocation.width ||\n event->y >= widget->allocation.height) {\n \/\/ The user clicked outside the bounds of the menu, delete the main which\n \/\/ results in closing it.\n Delete(true);\n }\n return FALSE;\n}\n\nvoid MainMenu::RequestMove(const gfx::Rect& new_bounds) {\n \/\/ Invoking PositionChild results in a gtk signal that triggers attempting to\n \/\/ to resize the window. We need to set the size request so that it resizes\n \/\/ correctly when this happens.\n gtk_widget_set_size_request(popup_->GetNativeView(),\n new_bounds.width(), new_bounds.height());\n gfx::Size rwhv_size = CalculateRWHVSize(new_bounds.size());\n popup_->PositionChild(rwhv_->GetNativeView(), kRendererX, kRendererY,\n rwhv_size.width(), rwhv_size.height());\n popup_->SetBounds(new_bounds);\n rwhv_->SetSize(rwhv_size);\n}\n\nvoid MainMenu::CreateNewWindow(int route_id) {\n if (pending_contents_.get()) {\n NOTREACHED();\n return;\n }\n\n helper_.CreateNewWindow(route_id, browser_->profile(), site_instance_,\n DOMUIFactory::GetDOMUIType(GURL(GetMenuURL())),\n NULL);\n pending_contents_.reset(helper_.GetCreatedWindow(route_id));\n pending_contents_->set_delegate(&tab_contents_delegate_);\n}\n\nvoid MainMenu::ShowCreatedWindow(int route_id,\n WindowOpenDisposition disposition,\n const gfx::Rect& initial_pos,\n bool user_gesture,\n const GURL& creator_url) {\n if (disposition == NEW_POPUP) {\n pending_contents_->set_delegate(NULL);\n browser_->GetSelectedTabContents()->AddNewContents(\n pending_contents_.release(), disposition, initial_pos, user_gesture,\n creator_url);\n Delete(false);\n }\n}\n\nvoid MainMenu::TabContentsDelegateImpl::OpenURLFromTab(\n TabContents* source,\n const GURL& url,\n const GURL& referrer,\n WindowOpenDisposition disposition,\n PageTransition::Type transition) {\n menu_->browser_->OpenURL(url, referrer, NEW_FOREGROUND_TAB,\n PageTransition::LINK);\n menu_->Delete(true);\n}\nChanges the url of the main menu.\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/chromeos\/main_menu.h\"\n\n#include \n\n#include \"app\/gfx\/insets.h\"\n#include \"app\/resource_bundle.h\"\n#include \"base\/command_line.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/string_util.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/renderer_host\/render_view_host.h\"\n#include \"chrome\/browser\/renderer_host\/render_view_host_factory.h\"\n#include \"chrome\/browser\/renderer_host\/render_widget_host_view.h\"\n#include \"chrome\/browser\/renderer_host\/render_widget_host_view_gtk.h\"\n#include \"chrome\/browser\/renderer_host\/site_instance.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/browser\/tab_contents\/render_view_host_delegate_helper.h\"\n#include \"grit\/app_resources.h\"\n#include \"grit\/generated_resources.h\"\n#include \"third_party\/skia\/include\/core\/SkBitmap.h\"\n#include \"views\/background.h\"\n#include \"views\/painter.h\"\n#include \"views\/screen.h\"\n#include \"views\/widget\/root_view.h\"\n#include \"views\/widget\/widget_gtk.h\"\n\n\/\/ Initial size of the renderer. This is contained within a window whose size\n\/\/ is set to the size of the image IDR_MAIN_MENU_BUTTON_DROP_DOWN.\nstatic const int kRendererX = 0;\nstatic const int kRendererY = 25;\nstatic const int kRendererWidth = 250;\nstatic const int kRendererHeight = 400;\n\n\/\/ Insets defining the regions that are stretched and titled to create the\n\/\/ background of the popup. These constants are fed into\n\/\/ Painter::CreateImagePainter as the insets, see it for details.\nstatic const int kBackgroundImageTop = 27;\nstatic const int kBackgroundImageLeft = 85;\nstatic const int kBackgroundImageBottom = 10;\nstatic const int kBackgroundImageRight = 8;\n\n\/\/ Command line switch for specifying url of the page.\nstatic const wchar_t kURLSwitch[] = L\"main-menu-url\";\n\n\/\/ Command line switch for specifying the size of the main menu. The default is\n\/\/ full screen.\nstatic const wchar_t kMenuSizeSwitch[] = L\"main-menu-size\";\n\n\/\/ URL of the page to load. This is ignored if kURLSwitch is specified.\nstatic const char kMenuURL[] = \"http:\/\/goto.ext.google.com\/crux-home\";\n\n\/\/ Returns the size of the popup. By default the popup is sized slightly\n\/\/ larger than full screen, but can be overriden by the command line switch\n\/\/ kMenuSizeSwitch.\nstatic gfx::Size GetPopupSize() {\n std::wstring cl_size =\n CommandLine::ForCurrentProcess()->GetSwitchValue(kMenuSizeSwitch);\n if (!cl_size.empty()) {\n std::vector chunks;\n SplitString(WideToUTF8(cl_size), 'x', &chunks);\n if (chunks.size() == 2)\n return gfx::Size(StringToInt(chunks[0]), StringToInt(chunks[1]));\n }\n\n gfx::Size size =\n views::Screen::GetMonitorAreaNearestPoint(gfx::Point(0, 0)).size();\n \/\/ When full screen we don't want to see the drop shadow. Adjust the width\n \/\/ so the drop shadow ends up off screen.\n size.Enlarge(kBackgroundImageRight, kBackgroundImageBottom);\n return size;\n}\n\n\/\/ Returns the size for the renderer widget host view given the specified\n\/\/ size of the popup.\nstatic gfx::Size CalculateRWHVSize(const gfx::Size& popup_size) {\n return gfx::Size(popup_size.width() - kRendererX - kBackgroundImageRight,\n popup_size.height() - kRendererY - kBackgroundImageBottom);\n}\n\n\/\/ Returns the URL of the menu.\nstatic GURL GetMenuURL() {\n std::wstring url_string =\n CommandLine::ForCurrentProcess()->GetSwitchValue(kURLSwitch);\n if (!url_string.empty())\n return GURL(WideToUTF8(url_string));\n return GURL(kMenuURL);\n}\n\n\/\/ static\nvoid MainMenu::Show(Browser* browser) {\n (new MainMenu(browser))->ShowImpl();\n}\n\nMainMenu::~MainMenu() {\n popup_->Close();\n menu_rvh_->Shutdown();\n}\n\nMainMenu::MainMenu(Browser* browser)\n : browser_(browser),\n popup_(NULL),\n site_instance_(NULL),\n menu_rvh_(NULL),\n rwhv_(NULL),\n ALLOW_THIS_IN_INITIALIZER_LIST(tab_contents_delegate_(this)) {\n}\n\nvoid MainMenu::ShowImpl() {\n SkBitmap* drop_down_image = ResourceBundle::GetSharedInstance().\n GetBitmapNamed(IDR_MAIN_MENU_BUTTON_DROP_DOWN);\n\n views::WidgetGtk* menu_popup =\n new views::WidgetGtk(views::WidgetGtk::TYPE_POPUP);\n popup_ = menu_popup;\n \/\/ The background image has transparency, so we make the window transparent.\n menu_popup->MakeTransparent();\n gfx::Size popup_size = GetPopupSize();\n menu_popup->Init(NULL, gfx::Rect(0, 0, popup_size.width(),\n popup_size.height()));\n\n views::Painter* painter = views::Painter::CreateImagePainter(\n *drop_down_image,\n gfx::Insets(kBackgroundImageTop, kBackgroundImageLeft,\n kBackgroundImageBottom, kBackgroundImageRight));\n menu_popup->GetRootView()->set_background(\n views::Background::CreateBackgroundPainter(true, painter));\n\n GURL menu_url(GetMenuURL());\n site_instance_ = SiteInstance::CreateSiteInstanceForURL(browser_->profile(),\n menu_url);\n menu_rvh_ = new RenderViewHost(site_instance_, this, MSG_ROUTING_NONE);\n\n rwhv_ = new RenderWidgetHostViewGtk(menu_rvh_);\n rwhv_->InitAsChild();\n menu_rvh_->CreateRenderView();\n menu_popup->AddChild(rwhv_->GetNativeView());\n gfx::Size rwhv_size = CalculateRWHVSize(popup_size);\n menu_popup->PositionChild(rwhv_->GetNativeView(), kRendererX, kRendererY,\n rwhv_size.width(), rwhv_size.height());\n rwhv_->SetSize(rwhv_size);\n menu_rvh_->NavigateToURL(menu_url);\n menu_popup->Show();\n\n GtkWidget* rwhv_widget = rwhv_->GetNativeView();\n gtk_widget_realize(rwhv_widget);\n g_signal_connect(rwhv_widget, \"button-press-event\",\n G_CALLBACK(CallButtonPressEvent), this);\n \/\/ Do a mouse grab on the renderer widget host view's widget so that we can\n \/\/ close the popup if the user clicks anywhere else. And do a keyboard\n \/\/ grab so that we get all key events.\n gdk_pointer_grab(rwhv_widget->window, FALSE,\n static_cast(\n GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK |\n GDK_POINTER_MOTION_MASK),\n NULL, NULL, GDK_CURRENT_TIME);\n gdk_keyboard_grab(rwhv_widget->window, FALSE, GDK_CURRENT_TIME);\n}\n\nvoid MainMenu::Delete(bool now) {\n gdk_keyboard_ungrab(GDK_CURRENT_TIME);\n gdk_pointer_ungrab(GDK_CURRENT_TIME);\n \/\/ Hide the popup immediately. We don't close it as it contains the\n \/\/ renderwidgethostview, which hasn't been shutdown yet.\n popup_->Hide();\n if (now)\n delete this;\n else\n MessageLoop::current()->DeleteSoon(FROM_HERE, this);\n}\n\n\/\/ static\ngboolean MainMenu::CallButtonPressEvent(GtkWidget* widget,\n GdkEventButton* event,\n MainMenu* menu) {\n return menu->OnButtonPressEvent(widget, event);\n}\n\ngboolean MainMenu::OnButtonPressEvent(GtkWidget* widget,\n GdkEventButton* event) {\n if (event->x < 0 || event->y < 0 ||\n event->x >= widget->allocation.width ||\n event->y >= widget->allocation.height) {\n \/\/ The user clicked outside the bounds of the menu, delete the main which\n \/\/ results in closing it.\n Delete(true);\n }\n return FALSE;\n}\n\nvoid MainMenu::RequestMove(const gfx::Rect& new_bounds) {\n \/\/ Invoking PositionChild results in a gtk signal that triggers attempting to\n \/\/ to resize the window. We need to set the size request so that it resizes\n \/\/ correctly when this happens.\n gtk_widget_set_size_request(popup_->GetNativeView(),\n new_bounds.width(), new_bounds.height());\n gfx::Size rwhv_size = CalculateRWHVSize(new_bounds.size());\n popup_->PositionChild(rwhv_->GetNativeView(), kRendererX, kRendererY,\n rwhv_size.width(), rwhv_size.height());\n popup_->SetBounds(new_bounds);\n rwhv_->SetSize(rwhv_size);\n}\n\nvoid MainMenu::CreateNewWindow(int route_id) {\n if (pending_contents_.get()) {\n NOTREACHED();\n return;\n }\n\n helper_.CreateNewWindow(route_id, browser_->profile(), site_instance_,\n DOMUIFactory::GetDOMUIType(GURL(GetMenuURL())),\n NULL);\n pending_contents_.reset(helper_.GetCreatedWindow(route_id));\n pending_contents_->set_delegate(&tab_contents_delegate_);\n}\n\nvoid MainMenu::ShowCreatedWindow(int route_id,\n WindowOpenDisposition disposition,\n const gfx::Rect& initial_pos,\n bool user_gesture,\n const GURL& creator_url) {\n if (disposition == NEW_POPUP) {\n pending_contents_->set_delegate(NULL);\n browser_->GetSelectedTabContents()->AddNewContents(\n pending_contents_.release(), disposition, initial_pos, user_gesture,\n creator_url);\n Delete(false);\n }\n}\n\nvoid MainMenu::TabContentsDelegateImpl::OpenURLFromTab(\n TabContents* source,\n const GURL& url,\n const GURL& referrer,\n WindowOpenDisposition disposition,\n PageTransition::Type transition) {\n menu_->browser_->OpenURL(url, referrer, NEW_FOREGROUND_TAB,\n PageTransition::LINK);\n menu_->Delete(true);\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/file_select_helper.h\"\n\n#include \n\n#include \"base\/file_util.h\"\n#include \"base\/string_split.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"net\/base\/mime_util.h\"\n#include \"chrome\/browser\/platform_util.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/renderer_host\/render_view_host.h\"\n#include \"chrome\/browser\/renderer_host\/render_widget_host_view.h\"\n#include \"chrome\/browser\/shell_dialogs.h\"\n#include \"chrome\/common\/notification_details.h\"\n#include \"chrome\/common\/notification_source.h\"\n#include \"chrome\/common\/render_messages_params.h\"\n#include \"grit\/generated_resources.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n\nFileSelectHelper::FileSelectHelper(Profile* profile)\n : profile_(profile),\n render_view_host_(NULL),\n select_file_dialog_(),\n dialog_type_(SelectFileDialog::SELECT_OPEN_FILE) {\n}\n\nFileSelectHelper::~FileSelectHelper() {\n \/\/ There may be pending file dialogs, we need to tell them that we've gone\n \/\/ away so they don't try and call back to us.\n if (select_file_dialog_.get())\n select_file_dialog_->ListenerDestroyed();\n\n \/\/ Stop any pending directory enumeration and prevent a callback.\n if (directory_lister_.get()) {\n directory_lister_->set_delegate(NULL);\n directory_lister_->Cancel();\n }\n}\n\nvoid FileSelectHelper::FileSelected(const FilePath& path,\n int index, void* params) {\n if (!render_view_host_)\n return;\n\n profile_->set_last_selected_directory(path.DirName());\n\n if (dialog_type_ == SelectFileDialog::SELECT_FOLDER) {\n DirectorySelected(path);\n return;\n }\n\n std::vector files;\n files.push_back(path);\n render_view_host_->FilesSelectedInChooser(files);\n \/\/ We are done with this showing of the dialog.\n render_view_host_ = NULL;\n}\n\nvoid FileSelectHelper::MultiFilesSelected(const std::vector& files,\n void* params) {\n if (!files.empty())\n profile_->set_last_selected_directory(files[0].DirName());\n if (!render_view_host_)\n return;\n\n render_view_host_->FilesSelectedInChooser(files);\n \/\/ We are done with this showing of the dialog.\n render_view_host_ = NULL;\n}\n\nvoid FileSelectHelper::FileSelectionCanceled(void* params) {\n if (!render_view_host_)\n return;\n\n \/\/ If the user cancels choosing a file to upload we pass back an\n \/\/ empty vector.\n render_view_host_->FilesSelectedInChooser(std::vector());\n\n \/\/ We are done with this showing of the dialog.\n render_view_host_ = NULL;\n}\n\nvoid FileSelectHelper::DirectorySelected(const FilePath& path) {\n directory_lister_ = new net::DirectoryLister(path,\n true,\n net::DirectoryLister::NO_SORT,\n this);\n if (!directory_lister_->Start())\n FileSelectionCanceled(NULL);\n}\n\nvoid FileSelectHelper::OnListFile(\n const net::DirectoryLister::DirectoryListerData& data) {\n \/\/ Directory upload only cares about files. This util call just checks\n \/\/ the flags in the structure; there's no file I\/O going on.\n if (file_util::FileEnumerator::IsDirectory(data.info))\n return;\n\n directory_lister_results_.push_back(data.path);\n}\n\nvoid FileSelectHelper::OnListDone(int error) {\n if (!render_view_host_)\n return;\n\n if (error) {\n FileSelectionCanceled(NULL);\n return;\n }\n\n render_view_host_->FilesSelectedInChooser(directory_lister_results_);\n render_view_host_ = NULL;\n directory_lister_ = NULL;\n directory_lister_results_.clear();\n}\n\nSelectFileDialog::FileTypeInfo* FileSelectHelper::GetFileTypesFromAcceptType(\n const string16& accept_types) {\n if (accept_types.empty())\n return NULL;\n\n \/\/ Split the accept-type string on commas.\n std::vector mime_types;\n base::SplitStringUsingSubstr(accept_types, ASCIIToUTF16(\",\"), &mime_types);\n if (mime_types.empty())\n return NULL;\n\n \/\/ Create FileTypeInfo and pre-allocate for the first extension list.\n scoped_ptr file_type(\n new SelectFileDialog::FileTypeInfo());\n file_type->include_all_files = true;\n file_type->extensions.resize(1);\n std::vector* extensions = &file_type->extensions.back();\n\n \/\/ Find the correspondinge extensions.\n int valid_type_count = 0;\n int description_id = 0;\n for (size_t i = 0; i < mime_types.size(); ++i) {\n string16 mime_type = mime_types[i];\n std::string ascii_mime_type = StringToLowerASCII(UTF16ToASCII(mime_type));\n\n TrimWhitespace(ascii_mime_type, TRIM_ALL, &ascii_mime_type);\n if (ascii_mime_type.empty())\n continue;\n\n size_t old_extension_size = extensions->size();\n if (ascii_mime_type == \"image\/*\") {\n description_id = IDS_IMAGE_FILES;\n net::GetImageExtensions(extensions);\n } else if (ascii_mime_type == \"audio\/*\") {\n description_id = IDS_AUDIO_FILES;\n net::GetAudioExtensions(extensions);\n } else if (ascii_mime_type == \"video\/*\") {\n description_id = IDS_VIDEO_FILES;\n net::GetVideoExtensions(extensions);\n } else {\n net::GetExtensionsForMimeType(ascii_mime_type, extensions);\n }\n\n if (extensions->size() > old_extension_size)\n valid_type_count++;\n }\n\n \/\/ If no valid extension is added, bail out.\n if (valid_type_count == 0)\n return NULL;\n\n \/\/ Use a generic description \"Custom Files\" if either of the following is\n \/\/ true:\n \/\/ 1) There're multiple types specified, like \"audio\/*,video\/*\"\n \/\/ 2) There're multiple extensions for a MIME type without parameter, like\n \/\/ \"ehtml,shtml,htm,html\" for \"text\/html\". On Windows, the select file\n \/\/ dialog uses the first extension in the list to form the description,\n \/\/ like \"EHTML Files\". This is not what we want.\n if (valid_type_count > 1 ||\n (valid_type_count == 1 && description_id == 0 && extensions->size() > 1))\n description_id = IDS_CUSTOM_FILES;\n\n if (description_id) {\n file_type->extension_description_overrides.push_back(\n l10n_util::GetStringUTF16(description_id));\n }\n\n return file_type.release();\n}\n\nvoid FileSelectHelper::RunFileChooser(\n RenderViewHost* render_view_host,\n const ViewHostMsg_RunFileChooser_Params ¶ms) {\n DCHECK(!render_view_host_);\n render_view_host_ = render_view_host;\n notification_registrar_.RemoveAll();\n notification_registrar_.Add(this,\n NotificationType::RENDER_WIDGET_HOST_DESTROYED,\n Source(render_view_host));\n\n if (!select_file_dialog_.get())\n select_file_dialog_ = SelectFileDialog::Create(this);\n\n switch (params.mode) {\n case ViewHostMsg_RunFileChooser_Params::Open:\n dialog_type_ = SelectFileDialog::SELECT_OPEN_FILE;\n break;\n case ViewHostMsg_RunFileChooser_Params::OpenMultiple:\n dialog_type_ = SelectFileDialog::SELECT_OPEN_MULTI_FILE;\n break;\n case ViewHostMsg_RunFileChooser_Params::OpenFolder:\n dialog_type_ = SelectFileDialog::SELECT_FOLDER;\n break;\n case ViewHostMsg_RunFileChooser_Params::Save:\n dialog_type_ = SelectFileDialog::SELECT_SAVEAS_FILE;\n break;\n default:\n dialog_type_ = SelectFileDialog::SELECT_OPEN_FILE; \/\/ Prevent warning.\n NOTREACHED();\n }\n scoped_ptr file_types(\n GetFileTypesFromAcceptType(params.accept_types));\n FilePath default_file_name = params.default_file_name;\n if (default_file_name.empty())\n default_file_name = profile_->last_selected_directory();\n\n gfx::NativeWindow owning_window =\n platform_util::GetTopLevel(render_view_host_->view()->GetNativeView());\n select_file_dialog_->SelectFile(dialog_type_,\n params.title,\n default_file_name,\n file_types.get(),\n file_types.get() ? 1 : 0, \/\/ 1-based index.\n FILE_PATH_LITERAL(\"\"),\n owning_window,\n NULL);\n}\n\nvoid FileSelectHelper::Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n DCHECK(type == NotificationType::RENDER_WIDGET_HOST_DESTROYED);\n DCHECK(Details(details).ptr() == render_view_host_);\n render_view_host_ = NULL;\n}\nFor directory upload, show empty directories (all directories, in fact) by including the corresponding \".\" file in the result set.\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/file_select_helper.h\"\n\n#include \n\n#include \"base\/file_util.h\"\n#include \"base\/string_split.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"net\/base\/mime_util.h\"\n#include \"chrome\/browser\/platform_util.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/renderer_host\/render_view_host.h\"\n#include \"chrome\/browser\/renderer_host\/render_widget_host_view.h\"\n#include \"chrome\/browser\/shell_dialogs.h\"\n#include \"chrome\/common\/notification_details.h\"\n#include \"chrome\/common\/notification_source.h\"\n#include \"chrome\/common\/render_messages_params.h\"\n#include \"grit\/generated_resources.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n\nFileSelectHelper::FileSelectHelper(Profile* profile)\n : profile_(profile),\n render_view_host_(NULL),\n select_file_dialog_(),\n dialog_type_(SelectFileDialog::SELECT_OPEN_FILE) {\n}\n\nFileSelectHelper::~FileSelectHelper() {\n \/\/ There may be pending file dialogs, we need to tell them that we've gone\n \/\/ away so they don't try and call back to us.\n if (select_file_dialog_.get())\n select_file_dialog_->ListenerDestroyed();\n\n \/\/ Stop any pending directory enumeration and prevent a callback.\n if (directory_lister_.get()) {\n directory_lister_->set_delegate(NULL);\n directory_lister_->Cancel();\n }\n}\n\nvoid FileSelectHelper::FileSelected(const FilePath& path,\n int index, void* params) {\n if (!render_view_host_)\n return;\n\n profile_->set_last_selected_directory(path.DirName());\n\n if (dialog_type_ == SelectFileDialog::SELECT_FOLDER) {\n DirectorySelected(path);\n return;\n }\n\n std::vector files;\n files.push_back(path);\n render_view_host_->FilesSelectedInChooser(files);\n \/\/ We are done with this showing of the dialog.\n render_view_host_ = NULL;\n}\n\nvoid FileSelectHelper::MultiFilesSelected(const std::vector& files,\n void* params) {\n if (!files.empty())\n profile_->set_last_selected_directory(files[0].DirName());\n if (!render_view_host_)\n return;\n\n render_view_host_->FilesSelectedInChooser(files);\n \/\/ We are done with this showing of the dialog.\n render_view_host_ = NULL;\n}\n\nvoid FileSelectHelper::FileSelectionCanceled(void* params) {\n if (!render_view_host_)\n return;\n\n \/\/ If the user cancels choosing a file to upload we pass back an\n \/\/ empty vector.\n render_view_host_->FilesSelectedInChooser(std::vector());\n\n \/\/ We are done with this showing of the dialog.\n render_view_host_ = NULL;\n}\n\nvoid FileSelectHelper::DirectorySelected(const FilePath& path) {\n directory_lister_ = new net::DirectoryLister(path,\n true,\n net::DirectoryLister::NO_SORT,\n this);\n if (!directory_lister_->Start())\n FileSelectionCanceled(NULL);\n}\n\nvoid FileSelectHelper::OnListFile(\n const net::DirectoryLister::DirectoryListerData& data) {\n \/\/ Directory upload returns directories via a \".\" file, so that\n \/\/ empty directories are included. This util call just checks\n \/\/ the flags in the structure; there's no file I\/O going on.\n if (file_util::FileEnumerator::IsDirectory(data.info))\n directory_lister_results_.push_back(\n data.path.Append(FILE_PATH_LITERAL(\".\")));\n else\n directory_lister_results_.push_back(data.path);\n}\n\nvoid FileSelectHelper::OnListDone(int error) {\n if (!render_view_host_)\n return;\n\n if (error) {\n FileSelectionCanceled(NULL);\n return;\n }\n\n render_view_host_->FilesSelectedInChooser(directory_lister_results_);\n render_view_host_ = NULL;\n directory_lister_ = NULL;\n directory_lister_results_.clear();\n}\n\nSelectFileDialog::FileTypeInfo* FileSelectHelper::GetFileTypesFromAcceptType(\n const string16& accept_types) {\n if (accept_types.empty())\n return NULL;\n\n \/\/ Split the accept-type string on commas.\n std::vector mime_types;\n base::SplitStringUsingSubstr(accept_types, ASCIIToUTF16(\",\"), &mime_types);\n if (mime_types.empty())\n return NULL;\n\n \/\/ Create FileTypeInfo and pre-allocate for the first extension list.\n scoped_ptr file_type(\n new SelectFileDialog::FileTypeInfo());\n file_type->include_all_files = true;\n file_type->extensions.resize(1);\n std::vector* extensions = &file_type->extensions.back();\n\n \/\/ Find the correspondinge extensions.\n int valid_type_count = 0;\n int description_id = 0;\n for (size_t i = 0; i < mime_types.size(); ++i) {\n string16 mime_type = mime_types[i];\n std::string ascii_mime_type = StringToLowerASCII(UTF16ToASCII(mime_type));\n\n TrimWhitespace(ascii_mime_type, TRIM_ALL, &ascii_mime_type);\n if (ascii_mime_type.empty())\n continue;\n\n size_t old_extension_size = extensions->size();\n if (ascii_mime_type == \"image\/*\") {\n description_id = IDS_IMAGE_FILES;\n net::GetImageExtensions(extensions);\n } else if (ascii_mime_type == \"audio\/*\") {\n description_id = IDS_AUDIO_FILES;\n net::GetAudioExtensions(extensions);\n } else if (ascii_mime_type == \"video\/*\") {\n description_id = IDS_VIDEO_FILES;\n net::GetVideoExtensions(extensions);\n } else {\n net::GetExtensionsForMimeType(ascii_mime_type, extensions);\n }\n\n if (extensions->size() > old_extension_size)\n valid_type_count++;\n }\n\n \/\/ If no valid extension is added, bail out.\n if (valid_type_count == 0)\n return NULL;\n\n \/\/ Use a generic description \"Custom Files\" if either of the following is\n \/\/ true:\n \/\/ 1) There're multiple types specified, like \"audio\/*,video\/*\"\n \/\/ 2) There're multiple extensions for a MIME type without parameter, like\n \/\/ \"ehtml,shtml,htm,html\" for \"text\/html\". On Windows, the select file\n \/\/ dialog uses the first extension in the list to form the description,\n \/\/ like \"EHTML Files\". This is not what we want.\n if (valid_type_count > 1 ||\n (valid_type_count == 1 && description_id == 0 && extensions->size() > 1))\n description_id = IDS_CUSTOM_FILES;\n\n if (description_id) {\n file_type->extension_description_overrides.push_back(\n l10n_util::GetStringUTF16(description_id));\n }\n\n return file_type.release();\n}\n\nvoid FileSelectHelper::RunFileChooser(\n RenderViewHost* render_view_host,\n const ViewHostMsg_RunFileChooser_Params ¶ms) {\n DCHECK(!render_view_host_);\n render_view_host_ = render_view_host;\n notification_registrar_.RemoveAll();\n notification_registrar_.Add(this,\n NotificationType::RENDER_WIDGET_HOST_DESTROYED,\n Source(render_view_host));\n\n if (!select_file_dialog_.get())\n select_file_dialog_ = SelectFileDialog::Create(this);\n\n switch (params.mode) {\n case ViewHostMsg_RunFileChooser_Params::Open:\n dialog_type_ = SelectFileDialog::SELECT_OPEN_FILE;\n break;\n case ViewHostMsg_RunFileChooser_Params::OpenMultiple:\n dialog_type_ = SelectFileDialog::SELECT_OPEN_MULTI_FILE;\n break;\n case ViewHostMsg_RunFileChooser_Params::OpenFolder:\n dialog_type_ = SelectFileDialog::SELECT_FOLDER;\n break;\n case ViewHostMsg_RunFileChooser_Params::Save:\n dialog_type_ = SelectFileDialog::SELECT_SAVEAS_FILE;\n break;\n default:\n dialog_type_ = SelectFileDialog::SELECT_OPEN_FILE; \/\/ Prevent warning.\n NOTREACHED();\n }\n scoped_ptr file_types(\n GetFileTypesFromAcceptType(params.accept_types));\n FilePath default_file_name = params.default_file_name;\n if (default_file_name.empty())\n default_file_name = profile_->last_selected_directory();\n\n gfx::NativeWindow owning_window =\n platform_util::GetTopLevel(render_view_host_->view()->GetNativeView());\n select_file_dialog_->SelectFile(dialog_type_,\n params.title,\n default_file_name,\n file_types.get(),\n file_types.get() ? 1 : 0, \/\/ 1-based index.\n FILE_PATH_LITERAL(\"\"),\n owning_window,\n NULL);\n}\n\nvoid FileSelectHelper::Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n DCHECK(type == NotificationType::RENDER_WIDGET_HOST_DESTROYED);\n DCHECK(Details(details).ptr() == render_view_host_);\n render_view_host_ = NULL;\n}\n<|endoftext|>"} {"text":"#include \"ospray\/common\/OSPCommon.h\"\n#include \"ospray\/common\/Thread.h\"\n#include \"common\/sys\/sync\/barrier.h\"\n\nnamespace ospray {\n\n using namespace std;\n\n volatile size_t sum = 0;\n volatile int nextFreeID = 0;\n volatile bool done = 0;\n double timeToRun = 1.f;\n embree::MutexSys mutex;\n embree::BarrierSys barrier;\n\n struct MyThread : public Thread {\n MyThread(int numThreads)\n {\n }\n\n virtual void run()\n {\n mutex.lock();\n int myID = nextFreeID++;\n mutex.unlock();\n\n barrier.wait();\n double t0 = getSysTime();\n int lastPing = 0;\n while (1) {\n barrier.wait();\n if (done) {\n break;\n }\n mutex.lock();\n sum += 1;\n mutex.unlock();\n barrier.wait();\n\n double t1 = getSysTime();\n\n if (myID == 0) {\n int numSecs = int(t1-t0);\n if (numSecs > lastPing) {\n printf(\"after t=%5.fs: num ops =%8li, that's %f ops\/sec\\n\",\n t1-t0,sum,sum\/(t1-t0));\n lastPing = numSecs;\n }\n }\n if (myID == 0 && (t1 - t0) >= timeToRun)\n done = true;\n }\n\n if (myID == 0)\n cout << \"total number of OPs: \" << sum << endl;\n }\n \n };\n\n int numThreads = 10;\n int firstThreadID = 1;\n\n extern \"C\" int main(int ac, char **av)\n {\n for (int i=1;istart(firstThreadID+i);\n }\n\n while (1) {\n sleep(1);\n if (done) break;\n }\n\n\n for (int i=0;ijoin();\n return 0;\n }\n\n}\nprinting addr and thread id of main#include \"ospray\/common\/OSPCommon.h\"\n#include \"ospray\/common\/Thread.h\"\n#include \"common\/sys\/sync\/barrier.h\"\n#include \n\nnamespace ospray {\n\n using namespace std;\n\n volatile size_t sum = 0;\n volatile int nextFreeID = 0;\n volatile bool done = 0;\n double timeToRun = 1.f;\n embree::MutexSys mutex;\n embree::BarrierSys barrier;\n\n struct MyThread : public Thread {\n MyThread(int numThreads)\n {\n }\n\n virtual void run()\n {\n mutex.lock();\n int myID = nextFreeID++;\n mutex.unlock();\n\n barrier.wait();\n double t0 = getSysTime();\n int lastPing = 0;\n while (1) {\n barrier.wait();\n if (done) {\n break;\n }\n mutex.lock();\n sum += 1;\n mutex.unlock();\n barrier.wait();\n\n double t1 = getSysTime();\n\n if (myID == 0) {\n int numSecs = int(t1-t0);\n if (numSecs > lastPing) {\n printf(\"after t=%5.fs: num ops =%8li, that's %f ops\/sec\\n\",\n t1-t0,sum,sum\/(t1-t0));\n lastPing = numSecs;\n }\n }\n if (myID == 0 && (t1 - t0) >= timeToRun)\n done = true;\n }\n\n if (myID == 0)\n cout << \"total number of OPs: \" << sum << endl;\n }\n \n };\n\n int numThreads = 10;\n int firstThreadID = 1;\n\n extern \"C\" int main(int ac, char **av)\n {\n#ifdef __LINUX__\n printf(\"main thread runs on core %i\\n\",sched_getcpu());\n#endif\n printf(\"address of global variables is %li\\n\",(long)&sum);\n\n for (int i=1;istart(firstThreadID+i);\n }\n\n while (1) {\n sleep(1);\n if (done) break;\n }\n\n\n for (int i=0;ijoin();\n return 0;\n }\n\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/common\/common_param_traits.h\"\n\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"gfx\/rect.h\"\n#include \"googleurl\/src\/gurl.h\"\n#ifndef EXCLUDE_SKIA_DEPENDENCIES\n#include \"third_party\/skia\/include\/core\/SkBitmap.h\"\n#endif\n#include \"webkit\/glue\/dom_operations.h\"\n\nnamespace IPC {\n\n#ifndef EXCLUDE_SKIA_DEPENDENCIES\n\nnamespace {\n\nstruct SkBitmap_Data {\n \/\/ The configuration for the bitmap (bits per pixel, etc).\n SkBitmap::Config fConfig;\n\n \/\/ The width of the bitmap in pixels.\n uint32 fWidth;\n\n \/\/ The height of the bitmap in pixels.\n uint32 fHeight;\n\n void InitSkBitmapDataForTransfer(const SkBitmap& bitmap) {\n fConfig = bitmap.config();\n fWidth = bitmap.width();\n fHeight = bitmap.height();\n }\n\n \/\/ Returns whether |bitmap| successfully initialized.\n bool InitSkBitmapFromData(SkBitmap* bitmap, const char* pixels,\n size_t total_pixels) const {\n if (total_pixels) {\n bitmap->setConfig(fConfig, fWidth, fHeight, 0);\n if (!bitmap->allocPixels())\n return false;\n if (total_pixels != bitmap->getSize())\n return false;\n memcpy(bitmap->getPixels(), pixels, total_pixels);\n }\n return true;\n }\n};\n\n} \/\/ namespace\n\n\nvoid ParamTraits::Write(Message* m, const SkBitmap& p) {\n size_t fixed_size = sizeof(SkBitmap_Data);\n SkBitmap_Data bmp_data;\n bmp_data.InitSkBitmapDataForTransfer(p);\n m->WriteData(reinterpret_cast(&bmp_data),\n static_cast(fixed_size));\n size_t pixel_size = p.getSize();\n SkAutoLockPixels p_lock(p);\n m->WriteData(reinterpret_cast(p.getPixels()),\n static_cast(pixel_size));\n}\n\nbool ParamTraits::Read(const Message* m, void** iter, SkBitmap* r) {\n const char* fixed_data;\n int fixed_data_size = 0;\n if (!m->ReadData(iter, &fixed_data, &fixed_data_size) ||\n (fixed_data_size <= 0)) {\n NOTREACHED();\n return false;\n }\n if (fixed_data_size != sizeof(SkBitmap_Data))\n return false; \/\/ Message is malformed.\n\n const char* variable_data;\n int variable_data_size = 0;\n if (!m->ReadData(iter, &variable_data, &variable_data_size) ||\n (variable_data_size < 0)) {\n NOTREACHED();\n return false;\n }\n const SkBitmap_Data* bmp_data =\n reinterpret_cast(fixed_data);\n return bmp_data->InitSkBitmapFromData(r, variable_data, variable_data_size);\n}\n\nvoid ParamTraits::Log(const SkBitmap& p, std::wstring* l) {\n l->append(StringPrintf(L\"\"));\n}\n\n#endif \/\/ EXCLUDE_SKIA_DEPENDENCIES\n\nvoid ParamTraits::Write(Message* m, const GURL& p) {\n m->WriteString(p.possibly_invalid_spec());\n \/\/ TODO(brettw) bug 684583: Add encoding for query params.\n}\n\nbool ParamTraits::Read(const Message* m, void** iter, GURL* p) {\n std::string s;\n if (!m->ReadString(iter, &s) || s.length() > chrome::kMaxURLChars) {\n *p = GURL();\n return false;\n }\n *p = GURL(s);\n return true;\n}\n\nvoid ParamTraits::Log(const GURL& p, std::wstring* l) {\n l->append(UTF8ToWide(p.spec()));\n}\n\nvoid ParamTraits::Write(Message* m, const gfx::Point& p) {\n m->WriteInt(p.x());\n m->WriteInt(p.y());\n}\n\nbool ParamTraits::Read(const Message* m, void** iter,\n gfx::Point* r) {\n int x, y;\n if (!m->ReadInt(iter, &x) ||\n !m->ReadInt(iter, &y))\n return false;\n r->set_x(x);\n r->set_y(y);\n return true;\n}\n\nvoid ParamTraits::Log(const gfx::Point& p, std::wstring* l) {\n l->append(StringPrintf(L\"(%d, %d)\", p.x(), p.y()));\n}\n\n\nvoid ParamTraits::Write(Message* m, const gfx::Rect& p) {\n m->WriteInt(p.x());\n m->WriteInt(p.y());\n m->WriteInt(p.width());\n m->WriteInt(p.height());\n}\n\nbool ParamTraits::Read(const Message* m, void** iter, gfx::Rect* r) {\n int x, y, w, h;\n if (!m->ReadInt(iter, &x) ||\n !m->ReadInt(iter, &y) ||\n !m->ReadInt(iter, &w) ||\n !m->ReadInt(iter, &h))\n return false;\n r->set_x(x);\n r->set_y(y);\n r->set_width(w);\n r->set_height(h);\n return true;\n}\n\nvoid ParamTraits::Log(const gfx::Rect& p, std::wstring* l) {\n l->append(StringPrintf(L\"(%d, %d, %d, %d)\", p.x(), p.y(),\n p.width(), p.height()));\n}\n\n\nvoid ParamTraits::Write(Message* m, const gfx::Size& p) {\n m->WriteInt(p.width());\n m->WriteInt(p.height());\n}\n\nbool ParamTraits::Read(const Message* m, void** iter, gfx::Size* r) {\n int w, h;\n if (!m->ReadInt(iter, &w) ||\n !m->ReadInt(iter, &h))\n return false;\n r->set_width(w);\n r->set_height(h);\n return true;\n}\n\nvoid ParamTraits::Log(const gfx::Size& p, std::wstring* l) {\n l->append(StringPrintf(L\"(%d, %d)\", p.width(), p.height()));\n}\n\nvoid ParamTraits::Write(\n Message* m, const ContentSettings& settings) {\n for (size_t i = 0; i < arraysize(settings.settings); ++i)\n WriteParam(m, settings.settings[i]);\n}\n\nbool ParamTraits::Read(\n const Message* m, void** iter, ContentSettings* r) {\n for (size_t i = 0; i < arraysize(r->settings); ++i) {\n if (!ReadParam(m, iter, &r->settings[i]))\n return false;\n }\n return true;\n}\n\nvoid ParamTraits::Log(\n const ContentSettings& p, std::wstring* l) {\n l->append(StringPrintf(L\"\"));\n}\n\nvoid ParamTraits::Write(\n Message* m, const webkit_glue::WebApplicationInfo& p) {\n WriteParam(m, p.title);\n WriteParam(m, p.description);\n WriteParam(m, p.app_url);\n WriteParam(m, p.icons.size());\n for (size_t i = 0; i < p.icons.size(); ++i) {\n WriteParam(m, p.icons[i].url);\n WriteParam(m, p.icons[i].width);\n WriteParam(m, p.icons[i].height);\n }\n}\n\nbool ParamTraits::Read(\n const Message* m, void** iter, webkit_glue::WebApplicationInfo* r) {\n size_t icon_count;\n bool result =\n ReadParam(m, iter, &r->title) &&\n ReadParam(m, iter, &r->description) &&\n ReadParam(m, iter, &r->app_url) &&\n ReadParam(m, iter, &icon_count);\n if (!result)\n return false;\n for (size_t i = 0; i < icon_count; ++i) {\n param_type::IconInfo icon_info;\n result =\n ReadParam(m, iter, &icon_info.url) &&\n ReadParam(m, iter, &icon_info.width) &&\n ReadParam(m, iter, &icon_info.height);\n if (!result)\n return false;\n r->icons.push_back(icon_info);\n }\n return true;\n}\n\nvoid ParamTraits::Log(\n const webkit_glue::WebApplicationInfo& p, std::wstring* l) {\n l->append(L\"\");\n}\n\nvoid ParamTraits::Write(\n Message* m, const Geoposition::ErrorCode& p) {\n int error_code = p;\n WriteParam(m, error_code);\n}\n\nbool ParamTraits::Read(\n const Message* m, void** iter, Geoposition::ErrorCode* p) {\n int error_code_param = 0;\n bool ret = ReadParam(m, iter, &error_code_param);\n *p = static_cast(error_code_param);\n return ret;\n}\n\nvoid ParamTraits::Log(\n const Geoposition::ErrorCode& p, std::wstring* l) {\n int error_code = p;\n l->append(StringPrintf(L\"%d\", error_code));\n}\n\nvoid ParamTraits::Write(Message* m, const Geoposition& p) {\n WriteParam(m, p.latitude);\n WriteParam(m, p.longitude);\n WriteParam(m, p.accuracy);\n WriteParam(m, p.altitude);\n WriteParam(m, p.altitude_accuracy);\n WriteParam(m, p.speed);\n WriteParam(m, p.heading);\n WriteParam(m, p.timestamp);\n WriteParam(m, p.error_code);\n WriteParam(m, p.error_message);\n}\n\nbool ParamTraits::Read(\n const Message* m, void** iter, Geoposition* p) {\n bool ret = ReadParam(m, iter, &p->latitude);\n ret = ret && ReadParam(m, iter, &p->longitude);\n ret = ret && ReadParam(m, iter, &p->accuracy);\n ret = ret && ReadParam(m, iter, &p->altitude);\n ret = ret && ReadParam(m, iter, &p->altitude_accuracy);\n ret = ret && ReadParam(m, iter, &p->speed);\n ret = ret && ReadParam(m, iter, &p->heading);\n ret = ret && ReadParam(m, iter, &p->timestamp);\n ret = ret && ReadParam(m, iter, &p->error_code);\n ret = ret && ReadParam(m, iter, &p->error_message);\n return ret;\n}\n\nvoid ParamTraits::Log(const Geoposition& p, std::wstring* l) {\n l->append(\n StringPrintf(\n L\"\"\n L\"%.6f %.6f %.6f %.6f \"\n L\"%.6f %.6f %.6f \",\n p.latitude, p.longitude, p.accuracy, p.altitude,\n p.altitude_accuracy, p.speed, p.heading));\n LogParam(p.timestamp, l);\n l->append(L\" \");\n l->append(p.error_message);\n LogParam(p.error_code, l);\n}\n\n} \/\/ namespace IPC\nApply a sanity limit to objects with width & height.\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/common\/common_param_traits.h\"\n\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"gfx\/rect.h\"\n#include \"googleurl\/src\/gurl.h\"\n#ifndef EXCLUDE_SKIA_DEPENDENCIES\n#include \"third_party\/skia\/include\/core\/SkBitmap.h\"\n#endif\n#include \"webkit\/glue\/dom_operations.h\"\n\nnamespace IPC {\n\n#ifndef EXCLUDE_SKIA_DEPENDENCIES\n\nnamespace {\n\nstruct SkBitmap_Data {\n \/\/ The configuration for the bitmap (bits per pixel, etc).\n SkBitmap::Config fConfig;\n\n \/\/ The width of the bitmap in pixels.\n uint32 fWidth;\n\n \/\/ The height of the bitmap in pixels.\n uint32 fHeight;\n\n void InitSkBitmapDataForTransfer(const SkBitmap& bitmap) {\n fConfig = bitmap.config();\n fWidth = bitmap.width();\n fHeight = bitmap.height();\n }\n\n \/\/ Returns whether |bitmap| successfully initialized.\n bool InitSkBitmapFromData(SkBitmap* bitmap, const char* pixels,\n size_t total_pixels) const {\n if (total_pixels) {\n bitmap->setConfig(fConfig, fWidth, fHeight, 0);\n if (!bitmap->allocPixels())\n return false;\n if (total_pixels != bitmap->getSize())\n return false;\n memcpy(bitmap->getPixels(), pixels, total_pixels);\n }\n return true;\n }\n};\n\n} \/\/ namespace\n\n\nvoid ParamTraits::Write(Message* m, const SkBitmap& p) {\n size_t fixed_size = sizeof(SkBitmap_Data);\n SkBitmap_Data bmp_data;\n bmp_data.InitSkBitmapDataForTransfer(p);\n m->WriteData(reinterpret_cast(&bmp_data),\n static_cast(fixed_size));\n size_t pixel_size = p.getSize();\n SkAutoLockPixels p_lock(p);\n m->WriteData(reinterpret_cast(p.getPixels()),\n static_cast(pixel_size));\n}\n\nbool ParamTraits::Read(const Message* m, void** iter, SkBitmap* r) {\n const char* fixed_data;\n int fixed_data_size = 0;\n if (!m->ReadData(iter, &fixed_data, &fixed_data_size) ||\n (fixed_data_size <= 0)) {\n NOTREACHED();\n return false;\n }\n if (fixed_data_size != sizeof(SkBitmap_Data))\n return false; \/\/ Message is malformed.\n\n const char* variable_data;\n int variable_data_size = 0;\n if (!m->ReadData(iter, &variable_data, &variable_data_size) ||\n (variable_data_size < 0)) {\n NOTREACHED();\n return false;\n }\n const SkBitmap_Data* bmp_data =\n reinterpret_cast(fixed_data);\n return bmp_data->InitSkBitmapFromData(r, variable_data, variable_data_size);\n}\n\nvoid ParamTraits::Log(const SkBitmap& p, std::wstring* l) {\n l->append(StringPrintf(L\"\"));\n}\n\n#endif \/\/ EXCLUDE_SKIA_DEPENDENCIES\n\nvoid ParamTraits::Write(Message* m, const GURL& p) {\n m->WriteString(p.possibly_invalid_spec());\n \/\/ TODO(brettw) bug 684583: Add encoding for query params.\n}\n\nbool ParamTraits::Read(const Message* m, void** iter, GURL* p) {\n std::string s;\n if (!m->ReadString(iter, &s) || s.length() > chrome::kMaxURLChars) {\n *p = GURL();\n return false;\n }\n *p = GURL(s);\n return true;\n}\n\nvoid ParamTraits::Log(const GURL& p, std::wstring* l) {\n l->append(UTF8ToWide(p.spec()));\n}\n\nvoid ParamTraits::Write(Message* m, const gfx::Point& p) {\n m->WriteInt(p.x());\n m->WriteInt(p.y());\n}\n\nbool ParamTraits::Read(const Message* m, void** iter,\n gfx::Point* r) {\n int x, y;\n if (!m->ReadInt(iter, &x) ||\n !m->ReadInt(iter, &y))\n return false;\n r->set_x(x);\n r->set_y(y);\n return true;\n}\n\nvoid ParamTraits::Log(const gfx::Point& p, std::wstring* l) {\n l->append(StringPrintf(L\"(%d, %d)\", p.x(), p.y()));\n}\n\n\nvoid ParamTraits::Write(Message* m, const gfx::Rect& p) {\n m->WriteInt(p.x());\n m->WriteInt(p.y());\n m->WriteInt(p.width());\n m->WriteInt(p.height());\n}\n\nbool ParamTraits::Read(const Message* m, void** iter, gfx::Rect* r) {\n int x, y, w, h;\n if (!m->ReadInt(iter, &x) ||\n !m->ReadInt(iter, &y) ||\n !m->ReadInt(iter, &w) ||\n !m->ReadInt(iter, &h))\n return false;\n if (x < 0 || y < 0 || x >= (INT_MAX - w) || y >= (INT_MAX - h) ||\n w < 0 || h < 0 || h >= ((INT_MAX \/ 16) \/ (w ? w : 1)))\n return false;\n r->set_x(x);\n r->set_y(y);\n r->set_width(w);\n r->set_height(h);\n return true;\n}\n\nvoid ParamTraits::Log(const gfx::Rect& p, std::wstring* l) {\n l->append(StringPrintf(L\"(%d, %d, %d, %d)\", p.x(), p.y(),\n p.width(), p.height()));\n}\n\n\nvoid ParamTraits::Write(Message* m, const gfx::Size& p) {\n m->WriteInt(p.width());\n m->WriteInt(p.height());\n}\n\nbool ParamTraits::Read(const Message* m, void** iter, gfx::Size* r) {\n int w, h;\n if (!m->ReadInt(iter, &w) ||\n !m->ReadInt(iter, &h))\n return false;\n if (w < 0 || h < 0 || h >= ((INT_MAX \/ 16) \/ (w ? w : 1)))\n return false;\n r->set_width(w);\n r->set_height(h);\n return true;\n}\n\nvoid ParamTraits::Log(const gfx::Size& p, std::wstring* l) {\n l->append(StringPrintf(L\"(%d, %d)\", p.width(), p.height()));\n}\n\nvoid ParamTraits::Write(\n Message* m, const ContentSettings& settings) {\n for (size_t i = 0; i < arraysize(settings.settings); ++i)\n WriteParam(m, settings.settings[i]);\n}\n\nbool ParamTraits::Read(\n const Message* m, void** iter, ContentSettings* r) {\n for (size_t i = 0; i < arraysize(r->settings); ++i) {\n if (!ReadParam(m, iter, &r->settings[i]))\n return false;\n }\n return true;\n}\n\nvoid ParamTraits::Log(\n const ContentSettings& p, std::wstring* l) {\n l->append(StringPrintf(L\"\"));\n}\n\nvoid ParamTraits::Write(\n Message* m, const webkit_glue::WebApplicationInfo& p) {\n WriteParam(m, p.title);\n WriteParam(m, p.description);\n WriteParam(m, p.app_url);\n WriteParam(m, p.icons.size());\n for (size_t i = 0; i < p.icons.size(); ++i) {\n WriteParam(m, p.icons[i].url);\n WriteParam(m, p.icons[i].width);\n WriteParam(m, p.icons[i].height);\n }\n}\n\nbool ParamTraits::Read(\n const Message* m, void** iter, webkit_glue::WebApplicationInfo* r) {\n size_t icon_count;\n bool result =\n ReadParam(m, iter, &r->title) &&\n ReadParam(m, iter, &r->description) &&\n ReadParam(m, iter, &r->app_url) &&\n ReadParam(m, iter, &icon_count);\n if (!result)\n return false;\n for (size_t i = 0; i < icon_count; ++i) {\n param_type::IconInfo icon_info;\n result =\n ReadParam(m, iter, &icon_info.url) &&\n ReadParam(m, iter, &icon_info.width) &&\n ReadParam(m, iter, &icon_info.height);\n if (!result)\n return false;\n r->icons.push_back(icon_info);\n }\n return true;\n}\n\nvoid ParamTraits::Log(\n const webkit_glue::WebApplicationInfo& p, std::wstring* l) {\n l->append(L\"\");\n}\n\nvoid ParamTraits::Write(\n Message* m, const Geoposition::ErrorCode& p) {\n int error_code = p;\n WriteParam(m, error_code);\n}\n\nbool ParamTraits::Read(\n const Message* m, void** iter, Geoposition::ErrorCode* p) {\n int error_code_param = 0;\n bool ret = ReadParam(m, iter, &error_code_param);\n *p = static_cast(error_code_param);\n return ret;\n}\n\nvoid ParamTraits::Log(\n const Geoposition::ErrorCode& p, std::wstring* l) {\n int error_code = p;\n l->append(StringPrintf(L\"%d\", error_code));\n}\n\nvoid ParamTraits::Write(Message* m, const Geoposition& p) {\n WriteParam(m, p.latitude);\n WriteParam(m, p.longitude);\n WriteParam(m, p.accuracy);\n WriteParam(m, p.altitude);\n WriteParam(m, p.altitude_accuracy);\n WriteParam(m, p.speed);\n WriteParam(m, p.heading);\n WriteParam(m, p.timestamp);\n WriteParam(m, p.error_code);\n WriteParam(m, p.error_message);\n}\n\nbool ParamTraits::Read(\n const Message* m, void** iter, Geoposition* p) {\n bool ret = ReadParam(m, iter, &p->latitude);\n ret = ret && ReadParam(m, iter, &p->longitude);\n ret = ret && ReadParam(m, iter, &p->accuracy);\n ret = ret && ReadParam(m, iter, &p->altitude);\n ret = ret && ReadParam(m, iter, &p->altitude_accuracy);\n ret = ret && ReadParam(m, iter, &p->speed);\n ret = ret && ReadParam(m, iter, &p->heading);\n ret = ret && ReadParam(m, iter, &p->timestamp);\n ret = ret && ReadParam(m, iter, &p->error_code);\n ret = ret && ReadParam(m, iter, &p->error_message);\n return ret;\n}\n\nvoid ParamTraits::Log(const Geoposition& p, std::wstring* l) {\n l->append(\n StringPrintf(\n L\"\"\n L\"%.6f %.6f %.6f %.6f \"\n L\"%.6f %.6f %.6f \",\n p.latitude, p.longitude, p.accuracy, p.altitude,\n p.altitude_accuracy, p.speed, p.heading));\n LogParam(p.timestamp, l);\n l->append(L\" \");\n l->append(p.error_message);\n LogParam(p.error_code, l);\n}\n\n} \/\/ namespace IPC\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2020 The Orbit Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"Process.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \"ElfUtils\/ElfFile.h\"\n#include \"OrbitBase\/ExecutablePath.h\"\n#include \"OrbitBase\/Logging.h\"\n#include \"OrbitBase\/ReadFileToString.h\"\n#include \"OrbitBase\/Result.h\"\n#include \"ServiceUtils.h\"\n\nnamespace orbit_service {\n\nvoid Process::UpdateCpuUsage(utils::Jiffies process_cpu_time, utils::TotalCpuTime total_cpu_time) {\n const auto diff_process_cpu_time =\n static_cast(process_cpu_time.value - previous_process_cpu_time_.value);\n const auto diff_total_cpu_time =\n static_cast(total_cpu_time.jiffies.value - previous_total_cpu_time_.value);\n\n \/\/ When the counters wrap, `cpu_usage` might be smaller than 0.0 or larger than 1.0,\n \/\/ depending on the signedness of `Jiffies`. Reference implementations like top and htop usually\n \/\/ clamp in this case. So that's what we're also doing here. Since 100% is usually considered\n \/\/ the usage of a single logical core, we multiply by the number of cores (cpus) - just like\n \/\/ top and htop do as well.\n const auto cpu_usage =\n std::clamp(diff_process_cpu_time \/ diff_total_cpu_time, 0.0, 1.0) * total_cpu_time.cpus;\n\n \/\/ TODO(hebecker): Rename cpu_usage to cpu_usage_rate and normalize. Being in percent was\n \/\/ surprising\n set_cpu_usage(cpu_usage * 100.0);\n\n previous_process_cpu_time_ = process_cpu_time;\n previous_total_cpu_time_ = total_cpu_time.jiffies;\n}\n\nErrorMessageOr Process::FromPid(pid_t pid) {\n const auto path = std::filesystem::path{\"\/proc\"} \/ std::to_string(pid);\n\n if (!std::filesystem::is_directory(path)) {\n return ErrorMessage{absl::StrFormat(\"PID %d does not exist\", pid)};\n }\n\n const std::filesystem::path name_file_path = path \/ \"comm\";\n auto name_file_result = orbit_base::ReadFileToString(name_file_path);\n if (!name_file_result) {\n return ErrorMessage{absl::StrFormat(\"Failed to read %s: %s\", name_file_path.string(),\n name_file_result.error().message())};\n }\n\n std::string name = std::move(name_file_result.value());\n \/\/ Remove new line character.\n absl::StripTrailingAsciiWhitespace(&name);\n if (name.empty()) {\n return ErrorMessage{absl::StrFormat(\"Could not determine the process name of process %d\", pid)};\n }\n\n Process process{};\n process.set_pid(pid);\n process.set_name(name);\n\n const auto total_cpu_time = utils::GetCumulativeTotalCpuTime();\n const auto cpu_time = utils::GetCumulativeCpuTimeFromProcess(process.pid());\n if (cpu_time && total_cpu_time) {\n process.UpdateCpuUsage(cpu_time.value(), total_cpu_time.value());\n } else {\n LOG(\"Could not update the CPU usage of process %d\", process.pid());\n }\n\n \/\/ \"The command-line arguments appear [...] as a set of strings\n \/\/ separated by null bytes ('\\0')\".\n const std::filesystem::path cmdline_file_path = path \/ \"cmdline\";\n auto cmdline_file_result = orbit_base::ReadFileToString(cmdline_file_path);\n if (!cmdline_file_result) {\n return ErrorMessage{absl::StrFormat(\"Failed to read %s: %s\", cmdline_file_path.string(),\n cmdline_file_result.error().message())};\n }\n\n std::string cmdline = std::move(cmdline_file_result.value());\n std::replace(cmdline.begin(), cmdline.end(), '\\0', ' ');\n process.set_command_line(cmdline);\n\n auto file_path_result = orbit_base::GetExecutablePath(pid);\n if (file_path_result) {\n process.set_full_path(std::move(file_path_result.value()));\n\n const auto& elf_file = orbit_elf_utils::ElfFile::Create(file_path_result.value().string());\n if (elf_file) {\n process.set_is_64_bit(elf_file.value()->Is64Bit());\n } else {\n LOG(\"Warning: Unable to parse the executable \\\"%s\\\" as elf file. (pid: %d)\",\n file_path_result.value(), pid);\n }\n }\n\n return process;\n}\n\n} \/\/ namespace orbit_service\nFix use-after-move for process executable path\/\/ Copyright (c) 2020 The Orbit Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"Process.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \"ElfUtils\/ElfFile.h\"\n#include \"OrbitBase\/ExecutablePath.h\"\n#include \"OrbitBase\/Logging.h\"\n#include \"OrbitBase\/ReadFileToString.h\"\n#include \"OrbitBase\/Result.h\"\n#include \"ServiceUtils.h\"\n\nnamespace orbit_service {\n\nvoid Process::UpdateCpuUsage(utils::Jiffies process_cpu_time, utils::TotalCpuTime total_cpu_time) {\n const auto diff_process_cpu_time =\n static_cast(process_cpu_time.value - previous_process_cpu_time_.value);\n const auto diff_total_cpu_time =\n static_cast(total_cpu_time.jiffies.value - previous_total_cpu_time_.value);\n\n \/\/ When the counters wrap, `cpu_usage` might be smaller than 0.0 or larger than 1.0,\n \/\/ depending on the signedness of `Jiffies`. Reference implementations like top and htop usually\n \/\/ clamp in this case. So that's what we're also doing here. Since 100% is usually considered\n \/\/ the usage of a single logical core, we multiply by the number of cores (cpus) - just like\n \/\/ top and htop do as well.\n const auto cpu_usage =\n std::clamp(diff_process_cpu_time \/ diff_total_cpu_time, 0.0, 1.0) * total_cpu_time.cpus;\n\n \/\/ TODO(hebecker): Rename cpu_usage to cpu_usage_rate and normalize. Being in percent was\n \/\/ surprising\n set_cpu_usage(cpu_usage * 100.0);\n\n previous_process_cpu_time_ = process_cpu_time;\n previous_total_cpu_time_ = total_cpu_time.jiffies;\n}\n\nErrorMessageOr Process::FromPid(pid_t pid) {\n const auto path = std::filesystem::path{\"\/proc\"} \/ std::to_string(pid);\n\n if (!std::filesystem::is_directory(path)) {\n return ErrorMessage{absl::StrFormat(\"PID %d does not exist\", pid)};\n }\n\n const std::filesystem::path name_file_path = path \/ \"comm\";\n auto name_file_result = orbit_base::ReadFileToString(name_file_path);\n if (!name_file_result) {\n return ErrorMessage{absl::StrFormat(\"Failed to read %s: %s\", name_file_path.string(),\n name_file_result.error().message())};\n }\n\n std::string name = std::move(name_file_result.value());\n \/\/ Remove new line character.\n absl::StripTrailingAsciiWhitespace(&name);\n if (name.empty()) {\n return ErrorMessage{absl::StrFormat(\"Could not determine the process name of process %d\", pid)};\n }\n\n Process process{};\n process.set_pid(pid);\n process.set_name(name);\n\n const auto total_cpu_time = utils::GetCumulativeTotalCpuTime();\n const auto cpu_time = utils::GetCumulativeCpuTimeFromProcess(process.pid());\n if (cpu_time && total_cpu_time) {\n process.UpdateCpuUsage(cpu_time.value(), total_cpu_time.value());\n } else {\n LOG(\"Could not update the CPU usage of process %d\", process.pid());\n }\n\n \/\/ \"The command-line arguments appear [...] as a set of strings\n \/\/ separated by null bytes ('\\0')\".\n const std::filesystem::path cmdline_file_path = path \/ \"cmdline\";\n auto cmdline_file_result = orbit_base::ReadFileToString(cmdline_file_path);\n if (!cmdline_file_result) {\n return ErrorMessage{absl::StrFormat(\"Failed to read %s: %s\", cmdline_file_path.string(),\n cmdline_file_result.error().message())};\n }\n\n std::string cmdline = std::move(cmdline_file_result.value());\n std::replace(cmdline.begin(), cmdline.end(), '\\0', ' ');\n process.set_command_line(cmdline);\n\n auto file_path_result = orbit_base::GetExecutablePath(pid);\n if (file_path_result) {\n process.set_full_path(file_path_result.value());\n\n const auto& elf_file = orbit_elf_utils::ElfFile::Create(file_path_result.value());\n if (elf_file) {\n process.set_is_64_bit(elf_file.value()->Is64Bit());\n } else {\n LOG(\"Warning: Unable to parse the executable \\\"%s\\\" as elf file. (pid: %d)\",\n file_path_result.value(), pid);\n }\n }\n\n return process;\n}\n\n} \/\/ namespace orbit_service\n<|endoftext|>"} {"text":"\/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/*\n * Copyright 2015 Couchbase, Inc\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"config.h\"\n#include \n#include \n#include \n#include \n#include \n#include \"topkeys.h\"\n\nstatic topkey_item_t *topkey_item_init(const void *key, int nkey, rel_time_t ct) {\n topkey_item_t *it = (topkey_item_t *)calloc(sizeof(topkey_item_t) + nkey, 1);\n cb_assert(it);\n cb_assert(key);\n cb_assert(nkey > 0);\n it->ti_nkey = nkey;\n it->ti_ctime = ct;\n it->ti_atime = ct;\n \/* Copy the key into the part trailing the struct *\/\n memcpy(it + 1, key, nkey);\n return it;\n}\n\nTopKeys::TopKeys(int mkeys)\n : nkeys(0), max_keys(mkeys)\n{\n list.next = &list;\n list.prev = &list;\n}\n\nTopKeys::~TopKeys() {\n dlist_t *p = list.next;\n while (p != &list) {\n dlist_t *tmp = p->next;\n free(p);\n p = tmp;\n }\n}\n\nstatic void dlist_remove(dlist_t *list) {\n cb_assert(list->prev->next == list);\n cb_assert(list->next->prev == list);\n list->prev->next = list->next;\n list->next->prev = list->prev;\n}\n\nstatic void dlist_insert_after(dlist_t *list, dlist_t *newitem) {\n newitem->next = list->next;\n newitem->prev = list;\n list->next->prev = newitem;\n list->next = newitem;\n}\n\nstatic void dlist_iter(dlist_t *list,\n void (*iterfunc)(dlist_t *item, void *arg),\n void *arg)\n{\n dlist_t *p = list;\n while ((p = p->next) != list) {\n iterfunc(p, arg);\n }\n}\n\nvoid TopKeys::deleteTail() {\n topkey_item_t *it = (topkey_item_t*)(list.prev);\n std::string key(reinterpret_cast(it+1), it->ti_nkey);\n auto iterator = hash.find(key);\n cb_assert(iterator != hash.end());\n hash.erase(iterator);\n dlist_remove(&it->ti_list);\n --nkeys;\n free(it);\n}\n\n\ntopkey_item_t *TopKeys::getOrCreate(const void *key, size_t nkey, const rel_time_t ct) {\n try {\n std::string k(reinterpret_cast(key), nkey);\n auto iterator = hash.find(k);\n topkey_item_t *it = nullptr;\n\n if (iterator == hash.end()) {\n it = topkey_item_init(key, (int)nkey, ct);\n if (it != NULL) {\n if (++nkeys > max_keys) {\n deleteTail();\n }\n hash[k] = it;\n } else {\n return NULL;\n }\n } else {\n it = iterator->second;\n dlist_remove(&it->ti_list);\n }\n dlist_insert_after(&list, &it->ti_list);\n return it;\n } catch (const std::bad_alloc&) {\n return nullptr;\n }\n}\n\nvoid TopKeys::updateKey(const void *key, size_t nkey,\n rel_time_t operation_time) {\n cb_assert(key);\n cb_assert(nkey > 0);\n std::lock_guard lock(mutex);\n topkey_item_t *tmp = getOrCreate(key, nkey, operation_time);\n if (tmp != NULL) {\n tmp->ti_access_count++;\n }\n}\n\nstruct tk_context {\n tk_context(const void *c, ADD_STAT a, rel_time_t t, cJSON *arr)\n : cookie(c), add_stat(a), current_time(t), array(arr)\n {\n \/\/ empty\n }\n\n const void *cookie;\n ADD_STAT add_stat;\n rel_time_t current_time;\n cJSON *array;\n};\n\nstatic void tk_iterfunc(dlist_t *list, void *arg) {\n struct tk_context *c = (struct tk_context*)arg;\n topkey_item_t *it = (topkey_item_t*)list;\n char val_str[500];\n int vlen = snprintf(val_str, sizeof(val_str) - 1, \"get_hits=%d,\"\n \"get_misses=0,cmd_set=0,incr_hits=0,incr_misses=0,\"\n \"decr_hits=0,decr_misses=0,delete_hits=0,\"\n \"delete_misses=0,evictions=0,cas_hits=0,cas_badval=0,\"\n \"cas_misses=0,get_replica=0,evict=0,getl=0,unlock=0,\"\n \"get_meta=0,set_meta=0,del_meta=0,ctime=%\" PRIu32\n \",atime=%\" PRIu32, it->ti_access_count,\n c->current_time - it->ti_ctime,\n c->current_time - it->ti_atime);\n c->add_stat((char*)(it + 1), it->ti_nkey, val_str, vlen, c->cookie);\n}\n\n\/**\n * Passing in a list of keys, context, and cJSON array will populate that\n * array with an object for each key in the following format:\n * {\n * \"key\": \"somekey\",\n * \"access_count\": nnn,\n * \"ctime\": ccc,\n * \"atime\": aaa\n * }\n *\/\nstatic void tk_jsonfunc(dlist_t *list, void *arg) {\n struct tk_context *c = (struct tk_context*)arg;\n topkey_item_t *it = (topkey_item_t*)list;\n cb_assert(it != NULL);\n cJSON *key = cJSON_CreateObject();\n cJSON_AddItemToObject(key, \"key\", cJSON_CreateString((char *)(it + 1)));\n cJSON_AddItemToObject(key, \"access_count\",\n cJSON_CreateNumber(it->ti_access_count));\n cJSON_AddItemToObject(key, \"ctime\", cJSON_CreateNumber(c->current_time\n - it->ti_ctime));\n cJSON_AddItemToObject(key, \"atime\", cJSON_CreateNumber(c->current_time\n - it->ti_atime));\n cb_assert(c->array != NULL);\n cJSON_AddItemToArray(c->array, key);\n}\n\nENGINE_ERROR_CODE TopKeys::stats(const void *cookie,\n const rel_time_t current_time,\n ADD_STAT add_stat) {\n struct tk_context context(cookie, add_stat, current_time, nullptr);\n\n std::lock_guard lock(mutex);\n dlist_iter(&list, tk_iterfunc, &context);\n\n return ENGINE_SUCCESS;\n}\n\n\/**\n * Passing a set of topkeys, and relevant context data will\n * return a cJSON object containing an array of topkeys (with each key\n * appearing as in the example above for tk_jsonfunc):\n * {\n * \"topkeys\": [\n * { ... }, ..., { ... }\n * ]\n * }\n *\/\nENGINE_ERROR_CODE TopKeys::json_stats(cJSON *object,\n const rel_time_t current_time) {\n\n cJSON *topkeys = cJSON_CreateArray();\n struct tk_context context(nullptr, nullptr, current_time, topkeys);\n\n \/* Collate the topkeys JSON object *\/\n {\n std::lock_guard lock(mutex);\n dlist_iter(&list, tk_jsonfunc, &context);\n }\n\n cJSON_AddItemToObject(object, \"topkeys\", topkeys);\n return ENGINE_SUCCESS;\n}\nMB-15780: Fix use of non-NUL terminated string in JSON topkeys\/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/*\n * Copyright 2015 Couchbase, Inc\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"config.h\"\n#include \n#include \n#include \n#include \n#include \n#include \"topkeys.h\"\n\nstatic topkey_item_t *topkey_item_init(const void *key, int nkey, rel_time_t ct) {\n topkey_item_t *it = (topkey_item_t *)calloc(sizeof(topkey_item_t) + nkey, 1);\n cb_assert(it);\n cb_assert(key);\n cb_assert(nkey > 0);\n it->ti_nkey = nkey;\n it->ti_ctime = ct;\n it->ti_atime = ct;\n \/* Copy the key into the part trailing the struct *\/\n memcpy(it + 1, key, nkey);\n return it;\n}\n\nTopKeys::TopKeys(int mkeys)\n : nkeys(0), max_keys(mkeys)\n{\n list.next = &list;\n list.prev = &list;\n}\n\nTopKeys::~TopKeys() {\n dlist_t *p = list.next;\n while (p != &list) {\n dlist_t *tmp = p->next;\n free(p);\n p = tmp;\n }\n}\n\nstatic void dlist_remove(dlist_t *list) {\n cb_assert(list->prev->next == list);\n cb_assert(list->next->prev == list);\n list->prev->next = list->next;\n list->next->prev = list->prev;\n}\n\nstatic void dlist_insert_after(dlist_t *list, dlist_t *newitem) {\n newitem->next = list->next;\n newitem->prev = list;\n list->next->prev = newitem;\n list->next = newitem;\n}\n\nstatic void dlist_iter(dlist_t *list,\n void (*iterfunc)(dlist_t *item, void *arg),\n void *arg)\n{\n dlist_t *p = list;\n while ((p = p->next) != list) {\n iterfunc(p, arg);\n }\n}\n\nvoid TopKeys::deleteTail() {\n topkey_item_t *it = (topkey_item_t*)(list.prev);\n std::string key(reinterpret_cast(it+1), it->ti_nkey);\n auto iterator = hash.find(key);\n cb_assert(iterator != hash.end());\n hash.erase(iterator);\n dlist_remove(&it->ti_list);\n --nkeys;\n free(it);\n}\n\n\ntopkey_item_t *TopKeys::getOrCreate(const void *key, size_t nkey, const rel_time_t ct) {\n try {\n std::string k(reinterpret_cast(key), nkey);\n auto iterator = hash.find(k);\n topkey_item_t *it = nullptr;\n\n if (iterator == hash.end()) {\n it = topkey_item_init(key, (int)nkey, ct);\n if (it != NULL) {\n if (++nkeys > max_keys) {\n deleteTail();\n }\n hash[k] = it;\n } else {\n return NULL;\n }\n } else {\n it = iterator->second;\n dlist_remove(&it->ti_list);\n }\n dlist_insert_after(&list, &it->ti_list);\n return it;\n } catch (const std::bad_alloc&) {\n return nullptr;\n }\n}\n\nvoid TopKeys::updateKey(const void *key, size_t nkey,\n rel_time_t operation_time) {\n cb_assert(key);\n cb_assert(nkey > 0);\n std::lock_guard lock(mutex);\n topkey_item_t *tmp = getOrCreate(key, nkey, operation_time);\n if (tmp != NULL) {\n tmp->ti_access_count++;\n }\n}\n\nstruct tk_context {\n tk_context(const void *c, ADD_STAT a, rel_time_t t, cJSON *arr)\n : cookie(c), add_stat(a), current_time(t), array(arr)\n {\n \/\/ empty\n }\n\n const void *cookie;\n ADD_STAT add_stat;\n rel_time_t current_time;\n cJSON *array;\n};\n\nstatic void tk_iterfunc(dlist_t *list, void *arg) {\n struct tk_context *c = (struct tk_context*)arg;\n topkey_item_t *it = (topkey_item_t*)list;\n char val_str[500];\n int vlen = snprintf(val_str, sizeof(val_str) - 1, \"get_hits=%d,\"\n \"get_misses=0,cmd_set=0,incr_hits=0,incr_misses=0,\"\n \"decr_hits=0,decr_misses=0,delete_hits=0,\"\n \"delete_misses=0,evictions=0,cas_hits=0,cas_badval=0,\"\n \"cas_misses=0,get_replica=0,evict=0,getl=0,unlock=0,\"\n \"get_meta=0,set_meta=0,del_meta=0,ctime=%\" PRIu32\n \",atime=%\" PRIu32, it->ti_access_count,\n c->current_time - it->ti_ctime,\n c->current_time - it->ti_atime);\n c->add_stat((char*)(it + 1), it->ti_nkey, val_str, vlen, c->cookie);\n}\n\n\/**\n * Passing in a list of keys, context, and cJSON array will populate that\n * array with an object for each key in the following format:\n * {\n * \"key\": \"somekey\",\n * \"access_count\": nnn,\n * \"ctime\": ccc,\n * \"atime\": aaa\n * }\n *\/\nstatic void tk_jsonfunc(dlist_t *list, void *arg) {\n struct tk_context *c = (struct tk_context*)arg;\n topkey_item_t *it = (topkey_item_t*)list;\n cb_assert(it != NULL);\n cJSON *key = cJSON_CreateObject();\n std::string key_name((char *)(it + 1), it->ti_nkey);\n cJSON_AddItemToObject(key, \"key\", cJSON_CreateString(key_name.c_str()));\n cJSON_AddItemToObject(key, \"access_count\",\n cJSON_CreateNumber(it->ti_access_count));\n cJSON_AddItemToObject(key, \"ctime\", cJSON_CreateNumber(c->current_time\n - it->ti_ctime));\n cJSON_AddItemToObject(key, \"atime\", cJSON_CreateNumber(c->current_time\n - it->ti_atime));\n cb_assert(c->array != NULL);\n cJSON_AddItemToArray(c->array, key);\n}\n\nENGINE_ERROR_CODE TopKeys::stats(const void *cookie,\n const rel_time_t current_time,\n ADD_STAT add_stat) {\n struct tk_context context(cookie, add_stat, current_time, nullptr);\n\n std::lock_guard lock(mutex);\n dlist_iter(&list, tk_iterfunc, &context);\n\n return ENGINE_SUCCESS;\n}\n\n\/**\n * Passing a set of topkeys, and relevant context data will\n * return a cJSON object containing an array of topkeys (with each key\n * appearing as in the example above for tk_jsonfunc):\n * {\n * \"topkeys\": [\n * { ... }, ..., { ... }\n * ]\n * }\n *\/\nENGINE_ERROR_CODE TopKeys::json_stats(cJSON *object,\n const rel_time_t current_time) {\n\n cJSON *topkeys = cJSON_CreateArray();\n struct tk_context context(nullptr, nullptr, current_time, topkeys);\n\n \/* Collate the topkeys JSON object *\/\n {\n std::lock_guard lock(mutex);\n dlist_iter(&list, tk_jsonfunc, &context);\n }\n\n cJSON_AddItemToObject(object, \"topkeys\", topkeys);\n return ENGINE_SUCCESS;\n}\n<|endoftext|>"} {"text":"\/*********************************************************************\n *\n * Copyright 2011 Intel Corporation\n * All Rights Reserved.\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use, copy,\n * modify, merge, publish, distribute, sublicense, and\/or sell copies\n * of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *********************************************************************\/\n\n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \"os_string.hpp\"\n#include \"os_process.hpp\"\n\n#include \"cli.hpp\"\n#include \"cli_resources.hpp\"\n\n\n#if defined(__APPLE__)\n#define TRACE_VARIABLE \"DYLD_LIBRARY_PATH\"\n#define GL_TRACE_WRAPPER \"OpenGL\"\n#elif defined(_WIN32)\n#define GL_TRACE_WRAPPER \"opengl32.dll\"\n#else\n#define TRACE_VARIABLE \"LD_PRELOAD\"\n#define GL_TRACE_WRAPPER \"glxtrace.so\"\n#define EGL_TRACE_WRAPPER \"egltrace.so\"\n#endif\n\n\nstatic inline bool\ncopyWrapper(const os::String & wrapperPath,\n const char *programPath,\n bool verbose)\n{\n os::String wrapperFilename(wrapperPath);\n wrapperFilename.trimDirectory();\n\n os::String tmpWrapper(programPath);\n tmpWrapper.trimFilename();\n tmpWrapper.join(wrapperFilename);\n\n if (verbose) {\n std::cerr << wrapperPath << \" -> \" << tmpWrapper << \"\\n\";\n }\n\n if (tmpWrapper.exists()) {\n std::cerr << \"error: not overwriting \" << tmpWrapper << \"\\n\";\n return false;\n }\n\n if (!os::copyFile(wrapperPath, tmpWrapper, false)) {\n std::cerr << \"error: failed to copy \" << wrapperPath << \" into \" << tmpWrapper << \"\\n\";\n return false;\n }\n\n return true;\n}\n\n\nstatic int\ntraceProgram(trace::API api,\n char * const *argv,\n const char *output,\n bool verbose)\n{\n const char *wrapperFilename;\n std::vector args;\n int status = 1;\n\n \/*\n * TODO: simplify code\n *\/\n\n bool useInject = false;\n switch (api) {\n case trace::API_GL:\n wrapperFilename = GL_TRACE_WRAPPER;\n break;\n#ifdef EGL_TRACE_WRAPPER\n case trace::API_EGL:\n wrapperFilename = EGL_TRACE_WRAPPER;\n break;\n#endif\n#ifdef _WIN32\n case trace::API_D3D7:\n wrapperFilename = \"ddraw.dll\";\n break;\n case trace::API_D3D8:\n wrapperFilename = \"d3d8.dll\";\n break;\n case trace::API_D3D9:\n wrapperFilename = \"d3d9.dll\";\n break;\n case trace::API_DXGI:\n wrapperFilename = \"dxgitrace.dll\";\n useInject = true;\n break;\n#endif\n default:\n std::cerr << \"error: unsupported API\\n\";\n return 1;\n }\n\n os::String wrapperPath = findWrapper(wrapperFilename);\n if (!wrapperPath.length()) {\n std::cerr << \"error: failed to find \" << wrapperFilename << \"\\n\";\n goto exit;\n }\n\n#if defined(_WIN32)\n if (useInject) {\n args.push_back(\"inject\");\n args.push_back(wrapperPath);\n } else {\n \/* On Windows copy the wrapper to the program directory.\n *\/\n if (!copyWrapper(wrapperPath, argv[0], verbose)) {\n goto exit;\n }\n }\n#else \/* !_WIN32 *\/\n (void)useInject;\n#endif \/* !_WIN32 *\/\n\n#if defined(__APPLE__)\n \/* On Mac OS X, using DYLD_LIBRARY_PATH, we actually set the\n * directory, not the file. *\/\n wrapperPath.trimFilename();\n#endif\n\n#if defined(TRACE_VARIABLE)\n if (verbose) {\n std::cerr << TRACE_VARIABLE << \"=\" << wrapperPath.str() << \"\\n\";\n }\n \/* FIXME: Don't modify the current environment *\/\n os::setEnvironment(TRACE_VARIABLE, wrapperPath.str());\n#endif \/* TRACE_VARIABLE *\/\n\n if (output) {\n os::setEnvironment(\"TRACE_FILE\", output);\n }\n\n for (char * const * arg = argv; *arg; ++arg) {\n args.push_back(*arg);\n }\n args.push_back(NULL);\n\n if (verbose) {\n const char *sep = \"\";\n for (unsigned i = 0; i < args.size(); ++i) {\n std::cerr << sep << args[i];\n sep = \" \";\n }\n std::cerr << \"\\n\";\n }\n\n status = os::execute((char * const *)&args[0]);\n\nexit:\n#if defined(TRACE_VARIABLE)\n os::unsetEnvironment(TRACE_VARIABLE);\n#endif\n#if defined(_WIN32)\n if (!useInject) {\n os::String tmpWrapper(argv[0]);\n tmpWrapper.trimFilename();\n tmpWrapper.join(wrapperFilename);\n os::removeFile(tmpWrapper);\n }\n#endif\n\n if (output) {\n os::unsetEnvironment(\"TRACE_FILE\");\n }\n \n return status;\n\n}\n\n\nstatic const char *synopsis = \"Generate a new trace by executing the given program.\";\n\nstatic void\nusage(void)\n{\n std::cout << \"usage: apitrace trace [OPTIONS] PROGRAM [ARGS ...]\\n\"\n << synopsis << \"\\n\"\n \"\\n\"\n \" The given program will be executed with the given arguments.\\n\"\n \" During execution, all OpenGL calls will be captured to a trace\\n\"\n \" file. That trace file can then be used\\n\"\n \" with other apitrace utilities for replay or analysis.\\n\"\n \"\\n\"\n \" -v, --verbose verbose output\\n\"\n \" -a, --api=API specify API to trace (\"\n#ifdef _WIN32\n \"gl, d3d7, d3d8, d3d9, or dxgi (for d3d10 and higher) \"\n#else\n \"gl or egl\"\n#endif\n \");\\n\"\n \" default is `gl`\\n\"\n \" -o, --output=TRACE specify output trace file;\\n\"\n \" default is `PROGRAM.trace`\\n\";\n}\n\nconst static char *\nshortOptions = \"+hva:o:\";\n\nconst static struct option\nlongOptions[] = {\n {\"help\", no_argument, 0, 'h'},\n {\"verbose\", no_argument, 0, 'v'},\n {\"api\", required_argument, 0, 'a'},\n {\"output\", required_argument, 0, 'o'},\n {0, 0, 0, 0}\n};\n\nstatic int\ncommand(int argc, char *argv[])\n{\n bool verbose = false;\n trace::API api = trace::API_GL;\n const char *output = NULL;\n\n int opt;\n while ((opt = getopt_long(argc, argv, shortOptions, longOptions, NULL)) != -1) {\n switch (opt) {\n case 'h':\n usage();\n return 0;\n case 'v':\n verbose = true;\n break;\n case 'a':\n if (strcmp(optarg, \"gl\") == 0) {\n api = trace::API_GL;\n } else if (strcmp(optarg, \"egl\") == 0) {\n api = trace::API_EGL;\n } else if (strcmp(optarg, \"d3d7\") == 0) {\n api = trace::API_D3D7;\n } else if (strcmp(optarg, \"d3d8\") == 0) {\n api = trace::API_D3D8;\n } else if (strcmp(optarg, \"d3d9\") == 0) {\n api = trace::API_D3D9;\n } else if (strcmp(optarg, \"dxgi\") == 0 ||\n strcmp(optarg, \"d3d10\") == 0 ||\n strcmp(optarg, \"d3d10_1\") == 0 ||\n strcmp(optarg, \"d3d11\") == 0 ||\n strcmp(optarg, \"d3d11_1\") == 0) {\n api = trace::API_DXGI;\n } else {\n std::cerr << \"error: unknown API `\" << optarg << \"`\\n\";\n usage();\n return 1;\n }\n break;\n case 'o':\n output = optarg;\n break;\n default:\n std::cerr << \"error: unexpected option `\" << opt << \"`\\n\";\n usage();\n return 1;\n }\n }\n\n if (optind == argc) {\n std::cerr << \"error: no command specified\\n\";\n usage();\n return 1;\n }\n\n assert(argv[argc] == 0);\n return traceProgram(api, argv + optind, output, verbose);\n}\n\nconst Command trace_command = {\n \"trace\",\n synopsis,\n usage,\n command\n};\ncli: Inject DLL on windows by default.\/*********************************************************************\n *\n * Copyright 2011 Intel Corporation\n * All Rights Reserved.\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use, copy,\n * modify, merge, publish, distribute, sublicense, and\/or sell copies\n * of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *********************************************************************\/\n\n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \"os_string.hpp\"\n#include \"os_process.hpp\"\n\n#include \"cli.hpp\"\n#include \"cli_resources.hpp\"\n\n\n#if defined(__APPLE__)\n#define TRACE_VARIABLE \"DYLD_LIBRARY_PATH\"\n#define GL_TRACE_WRAPPER \"OpenGL\"\n#elif defined(_WIN32)\n#define GL_TRACE_WRAPPER \"opengl32.dll\"\n#else\n#define TRACE_VARIABLE \"LD_PRELOAD\"\n#define GL_TRACE_WRAPPER \"glxtrace.so\"\n#define EGL_TRACE_WRAPPER \"egltrace.so\"\n#endif\n\n\nstatic inline bool\ncopyWrapper(const os::String & wrapperPath,\n const char *programPath,\n bool verbose)\n{\n os::String wrapperFilename(wrapperPath);\n wrapperFilename.trimDirectory();\n\n os::String tmpWrapper(programPath);\n tmpWrapper.trimFilename();\n tmpWrapper.join(wrapperFilename);\n\n if (verbose) {\n std::cerr << wrapperPath << \" -> \" << tmpWrapper << \"\\n\";\n }\n\n if (tmpWrapper.exists()) {\n std::cerr << \"error: not overwriting \" << tmpWrapper << \"\\n\";\n return false;\n }\n\n if (!os::copyFile(wrapperPath, tmpWrapper, false)) {\n std::cerr << \"error: failed to copy \" << wrapperPath << \" into \" << tmpWrapper << \"\\n\";\n return false;\n }\n\n return true;\n}\n\n\nstatic int\ntraceProgram(trace::API api,\n char * const *argv,\n const char *output,\n bool verbose)\n{\n const char *wrapperFilename;\n std::vector args;\n int status = 1;\n\n \/*\n * TODO: simplify code\n *\/\n\n bool useInject = false;\n switch (api) {\n case trace::API_GL:\n wrapperFilename = GL_TRACE_WRAPPER;\n break;\n#ifdef EGL_TRACE_WRAPPER\n case trace::API_EGL:\n wrapperFilename = EGL_TRACE_WRAPPER;\n break;\n#endif\n#ifdef _WIN32\n case trace::API_D3D7:\n wrapperFilename = \"ddraw.dll\";\n break;\n case trace::API_D3D8:\n wrapperFilename = \"d3d8.dll\";\n break;\n case trace::API_D3D9:\n wrapperFilename = \"d3d9.dll\";\n break;\n case trace::API_DXGI:\n wrapperFilename = \"dxgitrace.dll\";\n useInject = true;\n break;\n#endif\n default:\n std::cerr << \"error: unsupported API\\n\";\n return 1;\n }\n\n os::String wrapperPath = findWrapper(wrapperFilename);\n if (!wrapperPath.length()) {\n std::cerr << \"error: failed to find \" << wrapperFilename << \"\\n\";\n goto exit;\n }\n\n#if defined(_WIN32)\n useInject = true;\n if (useInject) {\n args.push_back(\"inject\");\n args.push_back(wrapperPath);\n } else {\n \/* On Windows copy the wrapper to the program directory.\n *\/\n if (!copyWrapper(wrapperPath, argv[0], verbose)) {\n goto exit;\n }\n }\n#else \/* !_WIN32 *\/\n (void)useInject;\n#endif \/* !_WIN32 *\/\n\n#if defined(__APPLE__)\n \/* On Mac OS X, using DYLD_LIBRARY_PATH, we actually set the\n * directory, not the file. *\/\n wrapperPath.trimFilename();\n#endif\n\n#if defined(TRACE_VARIABLE)\n if (verbose) {\n std::cerr << TRACE_VARIABLE << \"=\" << wrapperPath.str() << \"\\n\";\n }\n \/* FIXME: Don't modify the current environment *\/\n os::setEnvironment(TRACE_VARIABLE, wrapperPath.str());\n#endif \/* TRACE_VARIABLE *\/\n\n if (output) {\n os::setEnvironment(\"TRACE_FILE\", output);\n }\n\n for (char * const * arg = argv; *arg; ++arg) {\n args.push_back(*arg);\n }\n args.push_back(NULL);\n\n if (verbose) {\n const char *sep = \"\";\n for (unsigned i = 0; i < args.size(); ++i) {\n std::cerr << sep << args[i];\n sep = \" \";\n }\n std::cerr << \"\\n\";\n }\n\n status = os::execute((char * const *)&args[0]);\n\nexit:\n#if defined(TRACE_VARIABLE)\n os::unsetEnvironment(TRACE_VARIABLE);\n#endif\n#if defined(_WIN32)\n if (!useInject) {\n os::String tmpWrapper(argv[0]);\n tmpWrapper.trimFilename();\n tmpWrapper.join(wrapperFilename);\n os::removeFile(tmpWrapper);\n }\n#endif\n\n if (output) {\n os::unsetEnvironment(\"TRACE_FILE\");\n }\n \n return status;\n\n}\n\n\nstatic const char *synopsis = \"Generate a new trace by executing the given program.\";\n\nstatic void\nusage(void)\n{\n std::cout << \"usage: apitrace trace [OPTIONS] PROGRAM [ARGS ...]\\n\"\n << synopsis << \"\\n\"\n \"\\n\"\n \" The given program will be executed with the given arguments.\\n\"\n \" During execution, all OpenGL calls will be captured to a trace\\n\"\n \" file. That trace file can then be used\\n\"\n \" with other apitrace utilities for replay or analysis.\\n\"\n \"\\n\"\n \" -v, --verbose verbose output\\n\"\n \" -a, --api=API specify API to trace (\"\n#ifdef _WIN32\n \"gl, d3d7, d3d8, d3d9, or dxgi (for d3d10 and higher) \"\n#else\n \"gl or egl\"\n#endif\n \");\\n\"\n \" default is `gl`\\n\"\n \" -o, --output=TRACE specify output trace file;\\n\"\n \" default is `PROGRAM.trace`\\n\";\n}\n\nconst static char *\nshortOptions = \"+hva:o:\";\n\nconst static struct option\nlongOptions[] = {\n {\"help\", no_argument, 0, 'h'},\n {\"verbose\", no_argument, 0, 'v'},\n {\"api\", required_argument, 0, 'a'},\n {\"output\", required_argument, 0, 'o'},\n {0, 0, 0, 0}\n};\n\nstatic int\ncommand(int argc, char *argv[])\n{\n bool verbose = false;\n trace::API api = trace::API_GL;\n const char *output = NULL;\n\n int opt;\n while ((opt = getopt_long(argc, argv, shortOptions, longOptions, NULL)) != -1) {\n switch (opt) {\n case 'h':\n usage();\n return 0;\n case 'v':\n verbose = true;\n break;\n case 'a':\n if (strcmp(optarg, \"gl\") == 0) {\n api = trace::API_GL;\n } else if (strcmp(optarg, \"egl\") == 0) {\n api = trace::API_EGL;\n } else if (strcmp(optarg, \"d3d7\") == 0) {\n api = trace::API_D3D7;\n } else if (strcmp(optarg, \"d3d8\") == 0) {\n api = trace::API_D3D8;\n } else if (strcmp(optarg, \"d3d9\") == 0) {\n api = trace::API_D3D9;\n } else if (strcmp(optarg, \"dxgi\") == 0 ||\n strcmp(optarg, \"d3d10\") == 0 ||\n strcmp(optarg, \"d3d10_1\") == 0 ||\n strcmp(optarg, \"d3d11\") == 0 ||\n strcmp(optarg, \"d3d11_1\") == 0) {\n api = trace::API_DXGI;\n } else {\n std::cerr << \"error: unknown API `\" << optarg << \"`\\n\";\n usage();\n return 1;\n }\n break;\n case 'o':\n output = optarg;\n break;\n default:\n std::cerr << \"error: unexpected option `\" << opt << \"`\\n\";\n usage();\n return 1;\n }\n }\n\n if (optind == argc) {\n std::cerr << \"error: no command specified\\n\";\n usage();\n return 1;\n }\n\n assert(argv[argc] == 0);\n return traceProgram(api, argv + optind, output, verbose);\n}\n\nconst Command trace_command = {\n \"trace\",\n synopsis,\n usage,\n command\n};\n<|endoftext|>"} {"text":"\/\/\/\n\/\/ CrabLlvm -- Abstract Interpretation-based Analyzer for LLVM bitcode\n\/\/\/\n\n#include \"llvm\/LinkAllPasses.h\"\n#include \"llvm\/IR\/LegacyPassManager.h\"\n#include \"llvm\/IR\/LLVMContext.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/IRReader\/IRReader.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/ManagedStatic.h\"\n#include \"llvm\/Support\/PrettyStackTrace.h\"\n#include \"llvm\/Support\/Signals.h\"\n#include \"llvm\/Support\/SourceMgr.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/ToolOutputFile.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/Bitcode\/BitcodeWriter.h\"\n#include \"llvm\/Bitcode\/BitcodeWriterPass.h\"\n#include \"llvm\/IR\/Verifier.h\"\n#include \"crab_llvm\/config.h\"\n\n#ifdef HAVE_LLVM_SEAHORN\n#include \"llvm_seahorn\/Transforms\/Scalar.h\"\n#endif \n\n#include \"crab_llvm\/Passes.hh\"\n#include \"crab_llvm\/CrabLlvm.hh\"\n#include \"crab_llvm\/Transforms\/InsertInvariants.hh\"\n#include \"crab\/common\/debug.hpp\"\n\nstatic llvm::cl::opt\nInputFilename(llvm::cl::Positional, llvm::cl::desc(\"\"),\n llvm::cl::Required, llvm::cl::value_desc(\"filename\"));\n\nstatic llvm::cl::opt\nOutputFilename(\"o\", llvm::cl::desc(\"Override output filename\"),\n llvm::cl::init(\"\"), llvm::cl::value_desc(\"filename\"));\n\nstatic llvm::cl::opt\nOutputAssembly(\"S\", llvm::cl::desc(\"Write output as LLVM assembly\"));\n\nstatic llvm::cl::opt\nAsmOutputFilename(\"oll\", llvm::cl::desc(\"Output analyzed bitcode\"),\n llvm::cl::init(\"\"), llvm::cl::value_desc(\"filename\"));\n\nstatic llvm::cl::opt\nDefaultDataLayout(\"default-data-layout\",\n llvm::cl::desc(\"data layout string to use if not specified by module\"),\n llvm::cl::init(\"\"), llvm::cl::value_desc(\"layout-string\"));\n\nstatic llvm::cl::opt\nNoCrab(\"no-crab\", \n llvm::cl::desc(\"Output preprocessed bitcode but disabling Crab analysis\"),\n llvm::cl::init(false),\n llvm::cl::Hidden);\n\nstatic llvm::cl::opt\nTurnUndefNondet(\"crab-turn-undef-nondet\", \n llvm::cl::desc(\"Turn undefined behaviour into non-determinism\"),\n llvm::cl::init(false),\n llvm::cl::Hidden);\n\nstatic llvm::cl::opt\nLowerUnsignedICmp(\"crab-lower-unsigned-icmp\",\n\t llvm::cl::desc(\"Lower ULT and ULE instructions\"),\n\t llvm::cl::init(false));\n\nstatic llvm::cl::opt\nLowerCstExpr(\"crab-lower-constant-expr\",\n\t llvm::cl::desc(\"Lower constant expressions to instructions\"),\n\t llvm::cl::init(true));\n\nstatic llvm::cl::opt\nLowerInvoke(\"crab-lower-invoke\",\n\t llvm::cl::desc(\"Lower invoke instructions\"),\n\t llvm::cl::init(true));\n\nstatic llvm::cl::opt\nLowerSwitch(\"crab-lower-switch\",\n\t llvm::cl::desc(\"Lower switch instructions\"),\n\t llvm::cl::init(true));\n\nstatic llvm::cl::opt\nLowerSelect(\"crab-lower-select\", \n llvm::cl::desc(\"Lower all select instructions\"),\n llvm::cl::init(false));\n\nstatic llvm::cl::opt\nPromoteAssume(\"crab-promote-assume\", \n\t llvm::cl::desc(\"Promote verifier.assume to llvm.assume intrinsics\"),\n\t llvm::cl::init(false));\n\n\/* logging and verbosity *\/\n\nstruct LogOpt {\n void operator=(const std::string &tag) const \n { crab::CrabEnableLog(tag); } \n};\n\nLogOpt loc;\n\nstatic llvm::cl::opt > \nLogClOption(\"log\",\n llvm::cl::desc(\"Enable specified log level\"),\n llvm::cl::location(loc),\n llvm::cl::value_desc(\"string\"),\n llvm::cl::ValueRequired, llvm::cl::ZeroOrMore);\n\nstruct VerboseOpt {\n void operator=(unsigned level) const \n { crab::CrabEnableVerbosity(level); } \n};\n\nVerboseOpt verbose;\n\nstatic llvm::cl::opt > \nCrabVerbose(\"crab-verbose\",\n\t llvm::cl::desc(\"Enable verbose messages\"),\n\t llvm::cl::location(verbose),\n\t llvm::cl::value_desc(\"uint\"));\n\n\nstruct WarningOpt {\n void operator=(bool val) const \n { crab::CrabEnableWarningMsg(val); } \n};\n\nWarningOpt warning;\n\nstatic llvm::cl::opt > \nCrabEnableWarning(\"crab-enable-warnings\",\n\t llvm::cl::desc(\"Enable warning messages\"),\n\t llvm::cl::location(warning),\n\t llvm::cl::value_desc(\"bool\"));\n\nstruct SanityChecksOpt {\n void operator=(bool val) const \n { crab::CrabEnableSanityChecks(val); } \n};\n\nSanityChecksOpt sanity;\n\nstatic llvm::cl::opt > \nCrabSanityChecks(\"crab-sanity-checks\",\n\t llvm::cl::desc(\"Enable sanity checks\"),\n\t llvm::cl::location(sanity),\n\t llvm::cl::value_desc(\"bool\"));\n\nusing namespace crab_llvm;\n\n\/\/ removes extension from filename if there is one\nstd::string getFileName(const std::string &str) {\n std::string filename = str;\n size_t lastdot = str.find_last_of(\".\");\n if (lastdot != std::string::npos)\n filename = str.substr(0, lastdot);\n return filename;\n}\n\nint main(int argc, char **argv) {\n llvm::llvm_shutdown_obj shutdown; \/\/ calls llvm_shutdown() on exit\n llvm::cl::ParseCommandLineOptions(argc, argv,\n \"CrabLlvm-- Abstract Interpretation-based Analyzer of LLVM bitcode\\n\");\n\n llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);\n llvm::PrettyStackTraceProgram PSTP(argc, argv);\n llvm::EnableDebugBuffering = true;\n\n std::error_code error_code;\n llvm::SMDiagnostic err;\n static llvm::LLVMContext context;\n std::unique_ptr module;\n std::unique_ptr output;\n std::unique_ptr asmOutput;\n \n module = llvm::parseIRFile(InputFilename, err, context);\n if (!module) {\n if (llvm::errs().has_colors()) llvm::errs().changeColor(llvm::raw_ostream::RED);\n llvm::errs() << \"error: \"\n << \"Bitcode was not properly read; \" << err.getMessage() << \"\\n\";\n if (llvm::errs().has_colors()) llvm::errs().resetColor();\n return 3;\n }\n\n if (!AsmOutputFilename.empty())\n asmOutput = \n llvm::make_unique(AsmOutputFilename.c_str(), error_code, \n llvm::sys::fs::F_Text);\n if (error_code) {\n if (llvm::errs().has_colors()) \n llvm::errs().changeColor(llvm::raw_ostream::RED);\n llvm::errs() << \"error: Could not open \" << AsmOutputFilename << \": \" \n << error_code.message() << \"\\n\";\n if (llvm::errs().has_colors()) llvm::errs().resetColor();\n return 3;\n }\n\n if (!OutputFilename.empty())\n output = llvm::make_unique\n (OutputFilename.c_str(), error_code, llvm::sys::fs::F_None);\n \n if (error_code) {\n if (llvm::errs().has_colors()) llvm::errs().changeColor(llvm::raw_ostream::RED);\n llvm::errs() << \"error: Could not open \" << OutputFilename << \": \" \n << error_code.message() << \"\\n\";\n if (llvm::errs().has_colors()) llvm::errs().resetColor();\n return 3;\n }\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ initialise and run passes \/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n llvm::legacy::PassManager pass_manager;\n llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();\n llvm::initializeAnalysis(Registry);\n\n \/\/\/ call graph and other IPA passes\n \/\/ llvm::initializeIPA (Registry);\n \/\/ XXX: porting to 3.8\n llvm::initializeCallGraphWrapperPassPass(Registry);\n \/\/ XXX: commented while porting to 5.0 \n \/\/llvm::initializeCallGraphPrinterPass(Registry);\n llvm::initializeCallGraphViewerPass(Registry);\n \/\/ XXX: not sure if needed anymore\n llvm::initializeGlobalsAAWrapperPassPass(Registry);\n \n \/\/ add an appropriate DataLayout instance for the module\n const llvm::DataLayout *dl = &module->getDataLayout();\n if (!dl && !DefaultDataLayout.empty())\n {\n module->setDataLayout(DefaultDataLayout);\n dl = &module->getDataLayout();\n }\n\n assert(dl && \"Could not find Data Layout for the module\");\n \n \/**\n * Here only passes that are strictly necessary to avoid crashes or\n * useless results. Passes that are only for improving precision\n * should be run in crabllvm-pp.\n **\/\n \n \/\/ kill unused internal global \n pass_manager.add(llvm::createGlobalDCEPass()); \n pass_manager.add(crab_llvm::createRemoveUnreachableBlocksPass());\n\n \/\/ -- promote alloca's to registers\n pass_manager.add(llvm::createPromoteMemoryToRegisterPass());\n #ifdef HAVE_LLVM_SEAHORN\n if (TurnUndefNondet) {\n \/\/ -- Turn undef into nondet\n pass_manager.add(llvm_seahorn::createNondetInitPass());\n }\n #endif\n if (LowerInvoke) {\n \/\/ -- lower invoke's\n pass_manager.add(llvm::createLowerInvokePass());\n \/\/ cleanup after lowering invoke's\n pass_manager.add(llvm::createCFGSimplificationPass());\n }\n \/\/ -- ensure one single exit point per function\n pass_manager.add(llvm::createUnifyFunctionExitNodesPass());\n \/\/ -- remove unreachable blocks \n pass_manager.add(crab_llvm::createRemoveUnreachableBlocksPass());\n if (LowerSwitch) {\n \/\/ -- remove switch constructions\n pass_manager.add(llvm::createLowerSwitchPass());\n \/\/ cleanup after lowering switches\n pass_manager.add(llvm::createCFGSimplificationPass());\n }\n \/\/ -- lower constant expressions to instructions\n if (LowerCstExpr) {\n pass_manager.add(crab_llvm::createLowerCstExprPass());\n \/\/ cleanup after lowering constant expressions\n pass_manager.add(llvm::createDeadCodeEliminationPass());\n }\n #ifdef HAVE_LLVM_SEAHORN\n if (TurnUndefNondet) {\n pass_manager.add(llvm_seahorn::createDeadNondetElimPass());\n }\n #endif \n\n \/\/ -- lower ULT and ULE instructions \n if(LowerUnsignedICmp) {\n pass_manager.add(crab_llvm::createLowerUnsignedICmpPass()); \n \/\/ cleanup unnecessary and unreachable blocks \n pass_manager.add(llvm::createCFGSimplificationPass());\n pass_manager.add(crab_llvm::createRemoveUnreachableBlocksPass());\n }\n \n \/\/ -- must be the last ones before running crab.\n if (LowerSelect) {\n pass_manager.add(crab_llvm::createLowerSelectPass());\n }\n\n if (!NoCrab) {\n \/\/\/ -- run the crab analyzer\n pass_manager.add(new crab_llvm::CrabLlvmPass());\n }\n\n if(!AsmOutputFilename.empty()) \n pass_manager.add(createPrintModulePass(asmOutput->os()));\n \n if (!NoCrab) {\n \/\/ -- perform dead code elimination and insert invariants as\n \/\/ -- assume instructions\n pass_manager.add(new crab_llvm::InsertInvariants());\n \/\/ -- simplify invariants added in the bytecode.\n #ifdef HAVE_LLVM_SEAHORN\n pass_manager.add(llvm_seahorn::createInstructionCombiningPass());\n #else\n pass_manager.add(llvm::createInstructionCombiningPass());\n #endif\n if (PromoteAssume) {\n \/\/ -- promote verifier.assume to llvm.assume intrinsics\n pass_manager.add(crab_llvm::createPromoteAssumePass());\n } \n }\n \n if (!OutputFilename.empty()) {\n if (OutputAssembly)\n pass_manager.add(createPrintModulePass(output->os()));\n else \n pass_manager.add(createBitcodeWriterPass(output->os()));\n }\n \n pass_manager.run(*module.get());\n\n if (!AsmOutputFilename.empty()) asmOutput->keep();\n if (!OutputFilename.empty()) output->keep();\n\n return 0;\n}\nUnify exit nodes after lower select and unsigned icmp insts\/\/\/\n\/\/ CrabLlvm -- Abstract Interpretation-based Analyzer for LLVM bitcode\n\/\/\/\n\n#include \"llvm\/LinkAllPasses.h\"\n#include \"llvm\/IR\/LegacyPassManager.h\"\n#include \"llvm\/IR\/LLVMContext.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/IRReader\/IRReader.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/ManagedStatic.h\"\n#include \"llvm\/Support\/PrettyStackTrace.h\"\n#include \"llvm\/Support\/Signals.h\"\n#include \"llvm\/Support\/SourceMgr.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/ToolOutputFile.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/Bitcode\/BitcodeWriter.h\"\n#include \"llvm\/Bitcode\/BitcodeWriterPass.h\"\n#include \"llvm\/IR\/Verifier.h\"\n#include \"crab_llvm\/config.h\"\n\n#ifdef HAVE_LLVM_SEAHORN\n#include \"llvm_seahorn\/Transforms\/Scalar.h\"\n#endif \n\n#include \"crab_llvm\/Passes.hh\"\n#include \"crab_llvm\/CrabLlvm.hh\"\n#include \"crab_llvm\/Transforms\/InsertInvariants.hh\"\n#include \"crab\/common\/debug.hpp\"\n\nstatic llvm::cl::opt\nInputFilename(llvm::cl::Positional, llvm::cl::desc(\"\"),\n llvm::cl::Required, llvm::cl::value_desc(\"filename\"));\n\nstatic llvm::cl::opt\nOutputFilename(\"o\", llvm::cl::desc(\"Override output filename\"),\n llvm::cl::init(\"\"), llvm::cl::value_desc(\"filename\"));\n\nstatic llvm::cl::opt\nOutputAssembly(\"S\", llvm::cl::desc(\"Write output as LLVM assembly\"));\n\nstatic llvm::cl::opt\nAsmOutputFilename(\"oll\", llvm::cl::desc(\"Output analyzed bitcode\"),\n llvm::cl::init(\"\"), llvm::cl::value_desc(\"filename\"));\n\nstatic llvm::cl::opt\nDefaultDataLayout(\"default-data-layout\",\n llvm::cl::desc(\"data layout string to use if not specified by module\"),\n llvm::cl::init(\"\"), llvm::cl::value_desc(\"layout-string\"));\n\nstatic llvm::cl::opt\nNoCrab(\"no-crab\", \n llvm::cl::desc(\"Output preprocessed bitcode but disabling Crab analysis\"),\n llvm::cl::init(false),\n llvm::cl::Hidden);\n\nstatic llvm::cl::opt\nTurnUndefNondet(\"crab-turn-undef-nondet\", \n llvm::cl::desc(\"Turn undefined behaviour into non-determinism\"),\n llvm::cl::init(false),\n llvm::cl::Hidden);\n\nstatic llvm::cl::opt\nLowerUnsignedICmp(\"crab-lower-unsigned-icmp\",\n\t llvm::cl::desc(\"Lower ULT and ULE instructions\"),\n\t llvm::cl::init(false));\n\nstatic llvm::cl::opt\nLowerCstExpr(\"crab-lower-constant-expr\",\n\t llvm::cl::desc(\"Lower constant expressions to instructions\"),\n\t llvm::cl::init(true));\n\nstatic llvm::cl::opt\nLowerInvoke(\"crab-lower-invoke\",\n\t llvm::cl::desc(\"Lower invoke instructions\"),\n\t llvm::cl::init(true));\n\nstatic llvm::cl::opt\nLowerSwitch(\"crab-lower-switch\",\n\t llvm::cl::desc(\"Lower switch instructions\"),\n\t llvm::cl::init(true));\n\nstatic llvm::cl::opt\nLowerSelect(\"crab-lower-select\", \n llvm::cl::desc(\"Lower all select instructions\"),\n llvm::cl::init(false));\n\nstatic llvm::cl::opt\nPromoteAssume(\"crab-promote-assume\", \n\t llvm::cl::desc(\"Promote verifier.assume to llvm.assume intrinsics\"),\n\t llvm::cl::init(false));\n\n\/* logging and verbosity *\/\n\nstruct LogOpt {\n void operator=(const std::string &tag) const \n { crab::CrabEnableLog(tag); } \n};\n\nLogOpt loc;\n\nstatic llvm::cl::opt > \nLogClOption(\"log\",\n llvm::cl::desc(\"Enable specified log level\"),\n llvm::cl::location(loc),\n llvm::cl::value_desc(\"string\"),\n llvm::cl::ValueRequired, llvm::cl::ZeroOrMore);\n\nstruct VerboseOpt {\n void operator=(unsigned level) const \n { crab::CrabEnableVerbosity(level); } \n};\n\nVerboseOpt verbose;\n\nstatic llvm::cl::opt > \nCrabVerbose(\"crab-verbose\",\n\t llvm::cl::desc(\"Enable verbose messages\"),\n\t llvm::cl::location(verbose),\n\t llvm::cl::value_desc(\"uint\"));\n\n\nstruct WarningOpt {\n void operator=(bool val) const \n { crab::CrabEnableWarningMsg(val); } \n};\n\nWarningOpt warning;\n\nstatic llvm::cl::opt > \nCrabEnableWarning(\"crab-enable-warnings\",\n\t llvm::cl::desc(\"Enable warning messages\"),\n\t llvm::cl::location(warning),\n\t llvm::cl::value_desc(\"bool\"));\n\nstruct SanityChecksOpt {\n void operator=(bool val) const \n { crab::CrabEnableSanityChecks(val); } \n};\n\nSanityChecksOpt sanity;\n\nstatic llvm::cl::opt > \nCrabSanityChecks(\"crab-sanity-checks\",\n\t llvm::cl::desc(\"Enable sanity checks\"),\n\t llvm::cl::location(sanity),\n\t llvm::cl::value_desc(\"bool\"));\n\nusing namespace crab_llvm;\n\n\/\/ removes extension from filename if there is one\nstd::string getFileName(const std::string &str) {\n std::string filename = str;\n size_t lastdot = str.find_last_of(\".\");\n if (lastdot != std::string::npos)\n filename = str.substr(0, lastdot);\n return filename;\n}\n\nint main(int argc, char **argv) {\n llvm::llvm_shutdown_obj shutdown; \/\/ calls llvm_shutdown() on exit\n llvm::cl::ParseCommandLineOptions(argc, argv,\n \"CrabLlvm-- Abstract Interpretation-based Analyzer of LLVM bitcode\\n\");\n\n llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);\n llvm::PrettyStackTraceProgram PSTP(argc, argv);\n llvm::EnableDebugBuffering = true;\n\n std::error_code error_code;\n llvm::SMDiagnostic err;\n static llvm::LLVMContext context;\n std::unique_ptr module;\n std::unique_ptr output;\n std::unique_ptr asmOutput;\n \n module = llvm::parseIRFile(InputFilename, err, context);\n if (!module) {\n if (llvm::errs().has_colors()) llvm::errs().changeColor(llvm::raw_ostream::RED);\n llvm::errs() << \"error: \"\n << \"Bitcode was not properly read; \" << err.getMessage() << \"\\n\";\n if (llvm::errs().has_colors()) llvm::errs().resetColor();\n return 3;\n }\n\n if (!AsmOutputFilename.empty())\n asmOutput = \n llvm::make_unique(AsmOutputFilename.c_str(), error_code, \n llvm::sys::fs::F_Text);\n if (error_code) {\n if (llvm::errs().has_colors()) \n llvm::errs().changeColor(llvm::raw_ostream::RED);\n llvm::errs() << \"error: Could not open \" << AsmOutputFilename << \": \" \n << error_code.message() << \"\\n\";\n if (llvm::errs().has_colors()) llvm::errs().resetColor();\n return 3;\n }\n\n if (!OutputFilename.empty())\n output = llvm::make_unique\n (OutputFilename.c_str(), error_code, llvm::sys::fs::F_None);\n \n if (error_code) {\n if (llvm::errs().has_colors()) llvm::errs().changeColor(llvm::raw_ostream::RED);\n llvm::errs() << \"error: Could not open \" << OutputFilename << \": \" \n << error_code.message() << \"\\n\";\n if (llvm::errs().has_colors()) llvm::errs().resetColor();\n return 3;\n }\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ initialise and run passes \/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n llvm::legacy::PassManager pass_manager;\n llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();\n llvm::initializeAnalysis(Registry);\n\n \/\/\/ call graph and other IPA passes\n \/\/ llvm::initializeIPA (Registry);\n \/\/ XXX: porting to 3.8\n llvm::initializeCallGraphWrapperPassPass(Registry);\n \/\/ XXX: commented while porting to 5.0 \n \/\/llvm::initializeCallGraphPrinterPass(Registry);\n llvm::initializeCallGraphViewerPass(Registry);\n \/\/ XXX: not sure if needed anymore\n llvm::initializeGlobalsAAWrapperPassPass(Registry);\n \n \/\/ add an appropriate DataLayout instance for the module\n const llvm::DataLayout *dl = &module->getDataLayout();\n if (!dl && !DefaultDataLayout.empty())\n {\n module->setDataLayout(DefaultDataLayout);\n dl = &module->getDataLayout();\n }\n\n assert(dl && \"Could not find Data Layout for the module\");\n \n \/**\n * Here only passes that are strictly necessary to avoid crashes or\n * useless results. Passes that are only for improving precision\n * should be run in crabllvm-pp.\n **\/\n \n \/\/ kill unused internal global \n pass_manager.add(llvm::createGlobalDCEPass()); \n pass_manager.add(crab_llvm::createRemoveUnreachableBlocksPass());\n\n \/\/ -- promote alloca's to registers\n pass_manager.add(llvm::createPromoteMemoryToRegisterPass());\n #ifdef HAVE_LLVM_SEAHORN\n if (TurnUndefNondet) {\n \/\/ -- Turn undef into nondet\n pass_manager.add(llvm_seahorn::createNondetInitPass());\n }\n #endif\n if (LowerInvoke) {\n \/\/ -- lower invoke's\n pass_manager.add(llvm::createLowerInvokePass());\n \/\/ cleanup after lowering invoke's\n pass_manager.add(llvm::createCFGSimplificationPass());\n }\n \/\/ -- ensure one single exit point per function\n pass_manager.add(llvm::createUnifyFunctionExitNodesPass());\n \/\/ -- remove unreachable blocks \n pass_manager.add(crab_llvm::createRemoveUnreachableBlocksPass());\n if (LowerSwitch) {\n \/\/ -- remove switch constructions\n pass_manager.add(llvm::createLowerSwitchPass());\n \/\/ cleanup after lowering switches\n pass_manager.add(llvm::createCFGSimplificationPass());\n }\n \/\/ -- lower constant expressions to instructions\n if (LowerCstExpr) {\n pass_manager.add(crab_llvm::createLowerCstExprPass());\n \/\/ cleanup after lowering constant expressions\n pass_manager.add(llvm::createDeadCodeEliminationPass());\n }\n #ifdef HAVE_LLVM_SEAHORN\n if (TurnUndefNondet) {\n pass_manager.add(llvm_seahorn::createDeadNondetElimPass());\n }\n #endif \n\n \/\/ -- lower ULT and ULE instructions \n if(LowerUnsignedICmp) {\n pass_manager.add(crab_llvm::createLowerUnsignedICmpPass()); \n \/\/ cleanup unnecessary and unreachable blocks \n pass_manager.add(llvm::createCFGSimplificationPass());\n pass_manager.add(crab_llvm::createRemoveUnreachableBlocksPass());\n }\n \n \/\/ -- must be the last ones before running crab.\n if (LowerSelect) {\n pass_manager.add(crab_llvm::createLowerSelectPass());\n }\n\n \/\/ -- ensure one single exit point per function\n \/\/ LowerUnsignedIcmpPass and LowerSelect can add multiple returns.\n pass_manager.add(llvm::createUnifyFunctionExitNodesPass());\n \n if (!NoCrab) {\n \/\/\/ -- run the crab analyzer\n pass_manager.add(new crab_llvm::CrabLlvmPass());\n }\n\n if(!AsmOutputFilename.empty()) \n pass_manager.add(createPrintModulePass(asmOutput->os()));\n \n if (!NoCrab) {\n \/\/ -- perform dead code elimination and insert invariants as\n \/\/ -- assume instructions\n pass_manager.add(new crab_llvm::InsertInvariants());\n \/\/ -- simplify invariants added in the bytecode.\n #ifdef HAVE_LLVM_SEAHORN\n pass_manager.add(llvm_seahorn::createInstructionCombiningPass());\n #else\n pass_manager.add(llvm::createInstructionCombiningPass());\n #endif\n if (PromoteAssume) {\n \/\/ -- promote verifier.assume to llvm.assume intrinsics\n pass_manager.add(crab_llvm::createPromoteAssumePass());\n } \n }\n \n if (!OutputFilename.empty()) {\n if (OutputAssembly)\n pass_manager.add(createPrintModulePass(output->os()));\n else \n pass_manager.add(createBitcodeWriterPass(output->os()));\n }\n \n pass_manager.run(*module.get());\n\n if (!AsmOutputFilename.empty()) asmOutput->keep();\n if (!OutputFilename.empty()) output->keep();\n\n return 0;\n}\n<|endoftext|>"} {"text":"Bugfix: create OpenGL 3.0 context.<|endoftext|>"} {"text":"\/\/===- opt.cpp - The LLVM Modular Optimizer -------------------------------===\/\/\n\/\/ \n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Optimizations may be specified an arbitrary number of times on the command\n\/\/ line, they are run in the order specified.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Module.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/Bytecode\/Reader.h\"\n#include \"llvm\/Bytecode\/WriteBytecodePass.h\"\n#include \"llvm\/Assembly\/PrintModulePass.h\"\n#include \"llvm\/Analysis\/Verifier.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Target\/TargetMachineImpls.h\"\n#include \"llvm\/Support\/PassNameParser.h\"\n#include \"llvm\/System\/Signals.h\"\n#include \"Support\/SystemUtils.h\"\n#include \n#include \n#include \n\nusing namespace llvm;\n\n\/\/ The OptimizationList is automatically populated with registered Passes by the\n\/\/ PassNameParser.\n\/\/\nstatic cl::list >\nOptimizationList(cl::desc(\"Optimizations available:\"));\n\n\n\/\/ Other command line options...\n\/\/\nstatic cl::opt\nInputFilename(cl::Positional, cl::desc(\"\"), cl::init(\"-\"));\n\nstatic cl::opt\nOutputFilename(\"o\", cl::desc(\"Override output filename\"),\n cl::value_desc(\"filename\"), cl::init(\"-\"));\n\nstatic cl::opt\nForce(\"f\", cl::desc(\"Overwrite output files\"));\n\nstatic cl::opt\nPrintEachXForm(\"p\", cl::desc(\"Print module after each transformation\"));\n\nstatic cl::opt\nNoOutput(\"disable-output\",\n cl::desc(\"Do not write result bytecode file\"), cl::Hidden);\n\nstatic cl::opt\nNoVerify(\"disable-verify\", cl::desc(\"Do not verify result module\"), cl::Hidden);\n\nstatic cl::opt\nQuiet(\"q\", cl::desc(\"Don't print 'program modified' message\"));\n\nstatic cl::alias\nQuietA(\"quiet\", cl::desc(\"Alias for -q\"), cl::aliasopt(Quiet));\n\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ main for opt\n\/\/\nint main(int argc, char **argv) {\n cl::ParseCommandLineOptions(argc, argv,\n\t\t\t \" llvm .bc -> .bc modular optimizer\\n\");\n PrintStackTraceOnErrorSignal();\n\n \/\/ Allocate a full target machine description only if necessary...\n \/\/ FIXME: The choice of target should be controllable on the command line.\n std::auto_ptr target;\n\n TargetMachine* TM = NULL;\n std::string ErrorMessage;\n\n \/\/ Load the input module...\n std::auto_ptr M(ParseBytecodeFile(InputFilename, &ErrorMessage));\n if (M.get() == 0) {\n std::cerr << argv[0] << \": \";\n if (ErrorMessage.size())\n std::cerr << ErrorMessage << \"\\n\";\n else\n std::cerr << \"bytecode didn't read correctly.\\n\";\n return 1;\n }\n\n \/\/ Figure out what stream we are supposed to write to...\n std::ostream *Out = &std::cout; \/\/ Default to printing to stdout...\n if (OutputFilename != \"-\") {\n if (!Force && std::ifstream(OutputFilename.c_str())) {\n \/\/ If force is not specified, make sure not to overwrite a file!\n std::cerr << argv[0] << \": error opening '\" << OutputFilename\n << \"': file exists!\\n\"\n << \"Use -f command line argument to force output\\n\";\n return 1;\n }\n Out = new std::ofstream(OutputFilename.c_str());\n\n if (!Out->good()) {\n std::cerr << argv[0] << \": error opening \" << OutputFilename << \"!\\n\";\n return 1;\n }\n\n \/\/ Make sure that the Output file gets unlinked from the disk if we get a\n \/\/ SIGINT\n RemoveFileOnSignal(OutputFilename);\n }\n\n \/\/ If the output is set to be emitted to standard out, and standard out is a\n \/\/ console, print out a warning message and refuse to do it. We don't impress\n \/\/ anyone by spewing tons of binary goo to a terminal.\n if (Out == &std::cout && isStandardOutAConsole() && !Force && !NoOutput \n && !Quiet) {\n std::cerr << \"WARNING: It looks like you're attempting to print out a \"\n << \"bytecode file. I'm\\ngoing to pretend you didn't ask me to do\"\n << \" this (for your own good). If you\\nREALLY want to taste LLVM\"\n << \" bytecode first hand, you can force output with the\\n'-f'\"\n << \" option.\\n\\n\";\n NoOutput = true;\n }\n\n \/\/ Create a PassManager to hold and optimize the collection of passes we are\n \/\/ about to build...\n \/\/\n PassManager Passes;\n\n \/\/ Add an appropriate TargetData instance for this module...\n Passes.add(new TargetData(\"opt\", M.get()));\n\n \/\/ Create a new optimization pass for each one specified on the command line\n for (unsigned i = 0; i < OptimizationList.size(); ++i) {\n const PassInfo *Opt = OptimizationList[i];\n \n if (Opt->getNormalCtor())\n Passes.add(Opt->getNormalCtor()());\n else if (Opt->getTargetCtor()) {\n#if 0\n if (target.get() == NULL)\n target.reset(allocateSparcTargetMachine()); \/\/ FIXME: target option\n#endif\n assert(target.get() && \"Could not allocate target machine!\");\n Passes.add(Opt->getTargetCtor()(*target.get()));\n } else\n std::cerr << argv[0] << \": cannot create pass: \" << Opt->getPassName()\n << \"\\n\";\n\n if (PrintEachXForm)\n Passes.add(new PrintModulePass(&std::cerr));\n }\n\n \/\/ Check that the module is well formed on completion of optimization\n if (!NoVerify)\n Passes.add(createVerifierPass());\n\n \/\/ Write bytecode out to disk or cout as the last step...\n if (!NoOutput)\n Passes.add(new WriteBytecodePass(Out, Out != &std::cout));\n\n \/\/ Now that we have all of the passes ready, run them.\n if (Passes.run(*M.get()) )\n return 0;\n\n return 0;\n}\nNeuter the -q option. Stop printing the \"program modified\" message, ever\/\/===- opt.cpp - The LLVM Modular Optimizer -------------------------------===\/\/\n\/\/ \n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Optimizations may be specified an arbitrary number of times on the command\n\/\/ line, they are run in the order specified.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Module.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/Bytecode\/Reader.h\"\n#include \"llvm\/Bytecode\/WriteBytecodePass.h\"\n#include \"llvm\/Assembly\/PrintModulePass.h\"\n#include \"llvm\/Analysis\/Verifier.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Target\/TargetMachineImpls.h\"\n#include \"llvm\/Support\/PassNameParser.h\"\n#include \"llvm\/System\/Signals.h\"\n#include \"Support\/SystemUtils.h\"\n#include \n#include \n#include \n\nusing namespace llvm;\n\n\/\/ The OptimizationList is automatically populated with registered Passes by the\n\/\/ PassNameParser.\n\/\/\nstatic cl::list >\nOptimizationList(cl::desc(\"Optimizations available:\"));\n\n\n\/\/ Other command line options...\n\/\/\nstatic cl::opt\nInputFilename(cl::Positional, cl::desc(\"\"), cl::init(\"-\"));\n\nstatic cl::opt\nOutputFilename(\"o\", cl::desc(\"Override output filename\"),\n cl::value_desc(\"filename\"), cl::init(\"-\"));\n\nstatic cl::opt\nForce(\"f\", cl::desc(\"Overwrite output files\"));\n\nstatic cl::opt\nPrintEachXForm(\"p\", cl::desc(\"Print module after each transformation\"));\n\nstatic cl::opt\nNoOutput(\"disable-output\",\n cl::desc(\"Do not write result bytecode file\"), cl::Hidden);\n\nstatic cl::opt\nNoVerify(\"disable-verify\", cl::desc(\"Do not verify result module\"), cl::Hidden);\n\nstatic cl::opt\nQuiet(\"q\", cl::desc(\"Obsolete option\"), cl::Hidden);\n\nstatic cl::alias\nQuietA(\"quiet\", cl::desc(\"Alias for -q\"), cl::aliasopt(Quiet));\n\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ main for opt\n\/\/\nint main(int argc, char **argv) {\n cl::ParseCommandLineOptions(argc, argv,\n\t\t\t \" llvm .bc -> .bc modular optimizer\\n\");\n PrintStackTraceOnErrorSignal();\n\n \/\/ Allocate a full target machine description only if necessary...\n \/\/ FIXME: The choice of target should be controllable on the command line.\n std::auto_ptr target;\n\n TargetMachine* TM = NULL;\n std::string ErrorMessage;\n\n \/\/ Load the input module...\n std::auto_ptr M(ParseBytecodeFile(InputFilename, &ErrorMessage));\n if (M.get() == 0) {\n std::cerr << argv[0] << \": \";\n if (ErrorMessage.size())\n std::cerr << ErrorMessage << \"\\n\";\n else\n std::cerr << \"bytecode didn't read correctly.\\n\";\n return 1;\n }\n\n \/\/ Figure out what stream we are supposed to write to...\n std::ostream *Out = &std::cout; \/\/ Default to printing to stdout...\n if (OutputFilename != \"-\") {\n if (!Force && std::ifstream(OutputFilename.c_str())) {\n \/\/ If force is not specified, make sure not to overwrite a file!\n std::cerr << argv[0] << \": error opening '\" << OutputFilename\n << \"': file exists!\\n\"\n << \"Use -f command line argument to force output\\n\";\n return 1;\n }\n Out = new std::ofstream(OutputFilename.c_str());\n\n if (!Out->good()) {\n std::cerr << argv[0] << \": error opening \" << OutputFilename << \"!\\n\";\n return 1;\n }\n\n \/\/ Make sure that the Output file gets unlinked from the disk if we get a\n \/\/ SIGINT\n RemoveFileOnSignal(OutputFilename);\n }\n\n \/\/ If the output is set to be emitted to standard out, and standard out is a\n \/\/ console, print out a warning message and refuse to do it. We don't impress\n \/\/ anyone by spewing tons of binary goo to a terminal.\n if (Out == &std::cout && isStandardOutAConsole() && !Force && !NoOutput \n && !Quiet) {\n std::cerr << \"WARNING: It looks like you're attempting to print out a \"\n << \"bytecode file. I'm\\ngoing to pretend you didn't ask me to do\"\n << \" this (for your own good). If you\\nREALLY want to taste LLVM\"\n << \" bytecode first hand, you can force output with the\\n'-f'\"\n << \" option.\\n\\n\";\n NoOutput = true;\n }\n\n \/\/ Create a PassManager to hold and optimize the collection of passes we are\n \/\/ about to build...\n \/\/\n PassManager Passes;\n\n \/\/ Add an appropriate TargetData instance for this module...\n Passes.add(new TargetData(\"opt\", M.get()));\n\n \/\/ Create a new optimization pass for each one specified on the command line\n for (unsigned i = 0; i < OptimizationList.size(); ++i) {\n const PassInfo *Opt = OptimizationList[i];\n \n if (Opt->getNormalCtor())\n Passes.add(Opt->getNormalCtor()());\n else if (Opt->getTargetCtor()) {\n#if 0\n if (target.get() == NULL)\n target.reset(allocateSparcTargetMachine()); \/\/ FIXME: target option\n#endif\n assert(target.get() && \"Could not allocate target machine!\");\n Passes.add(Opt->getTargetCtor()(*target.get()));\n } else\n std::cerr << argv[0] << \": cannot create pass: \" << Opt->getPassName()\n << \"\\n\";\n\n if (PrintEachXForm)\n Passes.add(new PrintModulePass(&std::cerr));\n }\n\n \/\/ Check that the module is well formed on completion of optimization\n if (!NoVerify)\n Passes.add(createVerifierPass());\n\n \/\/ Write bytecode out to disk or cout as the last step...\n if (!NoOutput)\n Passes.add(new WriteBytecodePass(Out, Out != &std::cout));\n\n \/\/ Now that we have all of the passes ready, run them.\n Passes.run(*M.get());\n\n return 0;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \"libs\/catch\/catch.hpp\"\n#include \"libs\/exceptionpp\/exception.h\"\n\n#include \"src\/simpleconcurrentcache.h\"\n#include \"src\/simpleserialcache.h\"\n#include \"src\/simpleline.h\"\n\nTEST_CASE(\"cachepp|concurrentcache\") {\n\tstd::shared_ptr> c (new cachepp::SimpleConcurrentCache(2));\n}\n\nTEST_CASE(\"cachepp|serialcache\") {\n\tstd::shared_ptr> c (new cachepp::SimpleSerialCache(2));\n\n\tstd::vector> v;\n\tfor(size_t i = 0; i < 10; ++i) {\n\t\tv.push_back(std::shared_ptr (new cachepp::SimpleLine(rand(), false)));\n\t}\n\n\tfor(size_t i = 0; i < 10; ++i) {\n\t\tREQUIRE(v.at(i)->get_is_loaded() == false);\n\t}\n\n\t\/\/ test cache line juggling\n\tfor(size_t i = 0; i < 10; ++i) {\n\t\tc->acquire(v.at(i));\n\t\tREQUIRE(v.at(i)->get_is_loaded() == true);\n\t}\n\n\tsize_t loaded_lines = 0;\n\tfor(size_t i = 0; i < 10; ++i) {\n\t\tloaded_lines += v.at(i)->get_is_loaded();\n\t}\n\n\tREQUIRE(loaded_lines == 2);\n\n\tc->clear();\n\n\tloaded_lines = 0;\n\tfor(size_t i = 0; i < 10; ++i) {\n\t\tloaded_lines += v.at(i)->get_is_loaded();\n\t}\n\n\tREQUIRE(loaded_lines == 0);\n\n\t\/\/ test selection policy\n\tc->acquire(v.at(0));\n\tc->acquire(v.at(1));\n\n\tREQUIRE_THROWS_AS(c->access(v.at(2)), exceptionpp::RuntimeError);\n\n\tc->access(v.at(0));\n\tc->acquire(v.at(2));\n\n\tREQUIRE(v.at(0)->get_is_loaded() == true);\n\tREQUIRE(v.at(1)->get_is_loaded() == false);\n\tREQUIRE(v.at(2)->get_is_loaded() == true);\n\n\tc->acquire(v.at(3));\n\n\tREQUIRE(v.at(0)->get_is_loaded() == false);\n\tREQUIRE(v.at(2)->get_is_loaded() == true);\n\tREQUIRE(v.at(3)->get_is_loaded() == true);\n}\nadded concurrent cache tests#include \n#include \n#include \n\n#include \"libs\/catch\/catch.hpp\"\n#include \"libs\/exceptionpp\/exception.h\"\n\n#include \"src\/simpleconcurrentcache.h\"\n#include \"src\/simpleserialcache.h\"\n#include \"src\/simpleline.h\"\n\nTEST_CASE(\"cachepp|concurrentcache\") {\n\tstd::shared_ptr> c (new cachepp::SimpleConcurrentCache(2));\n\n\tstd::vector> v;\n\tfor(size_t i = 0; i < 10; ++i) {\n\t\tv.push_back(std::shared_ptr (new cachepp::SimpleLine(rand(), false)));\n\t}\n\n\tfor(size_t i = 0; i < 10; ++i) {\n\t\tREQUIRE(v.at(i)->get_is_loaded() == false);\n\t}\n\n\t\/\/ test cache line juggling\n\tfor(size_t i = 0; i < 10; ++i) {\n\t\tc->acquire(v.at(i));\n\t\tREQUIRE(v.at(i)->get_is_loaded() == true);\n\t}\n\n\tsize_t loaded_lines = 0;\n\tfor(size_t i = 0; i < 10; ++i) {\n\t\tloaded_lines += v.at(i)->get_is_loaded();\n\t}\n\n\tREQUIRE(loaded_lines == 2);\n\n\tc->clear();\n\n\tloaded_lines = 0;\n\tfor(size_t i = 0; i < 10; ++i) {\n\t\tloaded_lines += v.at(i)->get_is_loaded();\n\t}\n\n\tREQUIRE(loaded_lines == 0);\n\n\t\/\/ test selection policy\n\tc->acquire(v.at(0));\n\tc->acquire(v.at(1));\n\n\tREQUIRE_THROWS_AS(c->access(v.at(2)), exceptionpp::RuntimeError);\n\n\tc->access(v.at(0));\n\tc->acquire(v.at(2));\n\n\tREQUIRE(v.at(0)->get_is_loaded() == true);\n\tREQUIRE(v.at(1)->get_is_loaded() == false);\n\tREQUIRE(v.at(2)->get_is_loaded() == true);\n\n\tc->acquire(v.at(3));\n\n\tREQUIRE(v.at(0)->get_is_loaded() == false);\n\tREQUIRE(v.at(2)->get_is_loaded() == true);\n\tREQUIRE(v.at(3)->get_is_loaded() == true);\n}\n\nTEST_CASE(\"cachepp|serialcache\") {\n\tstd::shared_ptr> c (new cachepp::SimpleSerialCache(2));\n\n\tstd::vector> v;\n\tfor(size_t i = 0; i < 10; ++i) {\n\t\tv.push_back(std::shared_ptr (new cachepp::SimpleLine(rand(), false)));\n\t}\n\n\tfor(size_t i = 0; i < 10; ++i) {\n\t\tREQUIRE(v.at(i)->get_is_loaded() == false);\n\t}\n\n\t\/\/ test cache line juggling\n\tfor(size_t i = 0; i < 10; ++i) {\n\t\tc->acquire(v.at(i));\n\t\tREQUIRE(v.at(i)->get_is_loaded() == true);\n\t}\n\n\tsize_t loaded_lines = 0;\n\tfor(size_t i = 0; i < 10; ++i) {\n\t\tloaded_lines += v.at(i)->get_is_loaded();\n\t}\n\n\tREQUIRE(loaded_lines == 2);\n\n\tc->clear();\n\n\tloaded_lines = 0;\n\tfor(size_t i = 0; i < 10; ++i) {\n\t\tloaded_lines += v.at(i)->get_is_loaded();\n\t}\n\n\tREQUIRE(loaded_lines == 0);\n\n\t\/\/ test selection policy\n\tc->acquire(v.at(0));\n\tc->acquire(v.at(1));\n\n\tREQUIRE_THROWS_AS(c->access(v.at(2)), exceptionpp::RuntimeError);\n\n\tc->access(v.at(0));\n\tc->acquire(v.at(2));\n\n\tREQUIRE(v.at(0)->get_is_loaded() == true);\n\tREQUIRE(v.at(1)->get_is_loaded() == false);\n\tREQUIRE(v.at(2)->get_is_loaded() == true);\n\n\tc->acquire(v.at(3));\n\n\tREQUIRE(v.at(0)->get_is_loaded() == false);\n\tREQUIRE(v.at(2)->get_is_loaded() == true);\n\tREQUIRE(v.at(3)->get_is_loaded() == true);\n}\n<|endoftext|>"} {"text":"\/*\n Copyright 2008 Brain Research Institute, Melbourne, Australia\n\n Written by J-Donald Tournier, 27\/06\/08.\n\n This file is part of MRtrix.\n\n MRtrix is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n MRtrix is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with MRtrix. If not, see .\n\n*\/\n\n#include \"command.h\"\n#include \"progressbar.h\"\n#include \"image\/buffer.h\"\n#include \"image\/voxel.h\"\n#include \"image\/axis.h\"\n#include \"image\/threaded_copy.h\"\n#include \"image\/adapter\/extract.h\"\n#include \"image\/adapter\/permute_axes.h\"\n#include \"image\/stride.h\"\n#include \"dwi\/gradient.h\"\n\n\nusing namespace MR;\nusing namespace App;\n\nvoid usage ()\n{\n DESCRIPTION\n + \"perform conversion between different file types and optionally \"\n \"extract a subset of the input image.\"\n\n + \"If used correctly, this program can be a very useful workhorse. \"\n \"In addition to converting images between different formats, it can \"\n \"be used to extract specific studies from a data set, extract a \"\n \"specific region of interest, or flip the images.\";\n\n ARGUMENTS\n + Argument (\"input\", \"the input image.\").type_image_in ()\n + Argument (\"output\", \"the output image.\").type_image_out ();\n\n OPTIONS\n + Option (\"coord\",\n \"extract data from the input image only at the coordinates specified.\")\n .allow_multiple()\n + Argument (\"axis\").type_integer (0, 0, std::numeric_limits::max())\n + Argument (\"coord\").type_sequence_int()\n\n + Option (\"vox\",\n \"change the voxel dimensions of the output image. The new sizes should \"\n \"be provided as a comma-separated list of values. Only those values \"\n \"specified will be changed. For example: 1,,3.5 will change the voxel \"\n \"size along the x & z axes, and leave the y-axis voxel size unchanged.\")\n + Argument (\"sizes\").type_sequence_float()\n\n + Option (\"axes\",\n \"specify the axes from the input image that will be used to form the output \"\n \"image. This allows the permutation, ommission, or addition of axes into the \"\n \"output image. The axes should be supplied as a comma-separated list of axes. \"\n \"Any ommitted axes must have dimension 1. Axes can be inserted by supplying \"\n \"-1 at the corresponding position in the list.\")\n + Argument (\"axes\").type_sequence_int()\n\n + Image::Stride::StrideOption\n\n + DataType::options()\n\n + DWI::GradImportOptions (false)\n + DWI::GradExportOptions();\n}\n\n\n\n\ntemplate \ninline std::vector set_header (Image::Header& header, const InfoType& input)\n{\n \/\/ need to preserve dataype, already parsed from command-line:\n auto datatype = header.datatype();\n header.info() = input.info();\n header.datatype() = datatype;\n\n if (get_options (\"grad\").size() || get_options (\"fslgrad\").size())\n header.DW_scheme() = DWI::get_DW_scheme (header);\n\n Options opt = get_options (\"axes\");\n std::vector axes;\n if (opt.size()) {\n axes = opt[0][0];\n header.set_ndim (axes.size());\n for (size_t i = 0; i < axes.size(); ++i) {\n if (axes[i] >= static_cast (input.ndim()))\n throw Exception (\"axis supplied to option -axes is out of bounds\");\n header.dim(i) = axes[i] < 0 ? 1 : input.dim (axes[i]);\n }\n } else {\n header.set_ndim (input.ndim());\n axes.assign (input.ndim(), 0);\n for (size_t i = 0; i < axes.size(); ++i) {\n axes[i] = i;\n header.dim (i) = input.dim (i);\n }\n }\n\n opt = get_options (\"vox\");\n if (opt.size()) {\n std::vector vox = opt[0][0];\n if (vox.size() > header.ndim())\n throw Exception (\"too many axes supplied to -vox option\");\n for (size_t n = 0; n < vox.size(); ++n) {\n if (std::isfinite (vox[n]))\n header.vox(n) = vox[n];\n }\n }\n\n Image::Stride::set_from_command_line (header);\n\n return axes;\n}\n\n\n\n\ntemplate \ninline void copy_permute (Image::Header& header_in, Image::Header& header_out, const std::vector< std::vector >& pos, const std::string& output_filename)\n{\n typedef Image::Buffer buffer_type;\n typedef typename buffer_type::voxel_type voxel_type;\n typedef Image::Adapter::Extract extract_type;\n\n buffer_type buffer_in (header_in);\n voxel_type in = buffer_in.voxel();\n\n\n if (pos.empty()) {\n\n const std::vector axes = set_header (header_out, in);\n buffer_type buffer_out (output_filename, header_out);\n voxel_type out = buffer_out.voxel();\n DWI::export_grad_commandline (buffer_out);\n\n Image::Adapter::PermuteAxes perm (in, axes);\n Image::threaded_copy_with_progress (perm, out, 2);\n\n } else {\n\n extract_type extract (in, pos);\n const std::vector axes = set_header (header_out, extract);\n buffer_type buffer_out (output_filename, header_out);\n voxel_type out = buffer_out.voxel();\n DWI::export_grad_commandline (buffer_out);\n\n Image::Adapter::PermuteAxes perm (extract, axes);\n Image::threaded_copy_with_progress (perm, out, 2);\n\n }\n\n}\n\n\n\n\n\n\n\n\n\n\nvoid run ()\n{\n Image::Header header_in (argument[0]);\n\n Image::Header header_out (header_in);\n header_out.datatype() = DataType::from_command_line (header_out.datatype());\n header_out.set_intensity_scaling (header_in);\n\n if (header_in.datatype().is_complex() && !header_out.datatype().is_complex())\n WARN (\"requested datatype is real but input datatype is complex - imaginary component will be ignored\");\n\n Options opt = get_options (\"coord\");\n std::vector< std::vector > pos;\n if (opt.size()) {\n pos.assign (header_in.ndim(), std::vector());\n for (size_t n = 0; n < opt.size(); n++) {\n int axis = opt[n][0];\n if (axis >= (int)header_in.ndim())\n throw Exception (\"axis \" + str(axis) + \" provided with -coord option is out of range of input image\");\n if (pos[axis].size())\n throw Exception (\"\\\"coord\\\" option specified twice for axis \" + str (axis));\n pos[axis] = parse_ints (opt[n][1], header_in.dim(axis)-1);\n if (axis == 3 && header_in.DW_scheme().is_set()) {\n Math::Matrix& grad (header_in.DW_scheme());\n if ((int)grad.rows() != header_in.dim(3)) {\n WARN (\"Diffusion encoding of input file does not match number of image volumes; omitting gradient information from output image\");\n header_out.DW_scheme().clear();\n }\n else {\n Math::Matrix extract_grad (pos[3].size(), 4);\n for (size_t dir = 0; dir != pos[3].size(); ++dir)\n extract_grad.row(dir) = grad.row((pos[3])[dir]);\n header_out.DW_scheme() = extract_grad;\n }\n }\n }\n\n for (size_t n = 0; n < header_in.ndim(); ++n) {\n if (pos[n].empty()) {\n pos[n].resize (header_in.dim (n));\n for (size_t i = 0; i < pos[n].size(); i++)\n pos[n][i] = i;\n }\n }\n }\n\n switch (header_out.datatype()() & DataType::Type) {\n case DataType::Undefined: throw Exception (\"Undefined output image data type\"); break;\n case DataType::Bit:\n case DataType::UInt8:\n case DataType::UInt16:\n case DataType::UInt32:\n if (header_out.datatype().is_signed())\n copy_permute (header_in, header_out, pos, argument[1]);\n else\n copy_permute (header_in, header_out, pos, argument[1]);\n break;\n case DataType::UInt64:\n if (header_out.datatype().is_signed())\n copy_permute (header_in, header_out, pos, argument[1]);\n else\n copy_permute (header_in, header_out, pos, argument[1]);\n break;\n case DataType::Float32:\n case DataType::Float64:\n if (header_out.datatype().is_complex())\n copy_permute (header_in, header_out, pos, argument[1]);\n else\n copy_permute (header_in, header_out, pos, argument[1]);\n break;\n }\n\n}\n\nmrconvert: add -scaling option to control intensity scaling parameters\/*\n Copyright 2008 Brain Research Institute, Melbourne, Australia\n\n Written by J-Donald Tournier, 27\/06\/08.\n\n This file is part of MRtrix.\n\n MRtrix is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n MRtrix is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with MRtrix. If not, see .\n\n*\/\n\n#include \"command.h\"\n#include \"progressbar.h\"\n#include \"image\/buffer.h\"\n#include \"image\/voxel.h\"\n#include \"image\/axis.h\"\n#include \"image\/threaded_copy.h\"\n#include \"image\/adapter\/extract.h\"\n#include \"image\/adapter\/permute_axes.h\"\n#include \"image\/stride.h\"\n#include \"dwi\/gradient.h\"\n\n\nusing namespace MR;\nusing namespace App;\n\nvoid usage ()\n{\n DESCRIPTION\n + \"perform conversion between different file types and optionally \"\n \"extract a subset of the input image.\"\n\n + \"If used correctly, this program can be a very useful workhorse. \"\n \"In addition to converting images between different formats, it can \"\n \"be used to extract specific studies from a data set, extract a \"\n \"specific region of interest, or flip the images.\";\n\n ARGUMENTS\n + Argument (\"input\", \"the input image.\").type_image_in ()\n + Argument (\"output\", \"the output image.\").type_image_out ();\n\n OPTIONS\n + Option (\"coord\",\n \"extract data from the input image only at the coordinates specified.\")\n .allow_multiple()\n + Argument (\"axis\").type_integer (0, 0, std::numeric_limits::max())\n + Argument (\"coord\").type_sequence_int()\n\n + Option (\"vox\",\n \"change the voxel dimensions of the output image. The new sizes should \"\n \"be provided as a comma-separated list of values. Only those values \"\n \"specified will be changed. For example: 1,,3.5 will change the voxel \"\n \"size along the x & z axes, and leave the y-axis voxel size unchanged.\")\n + Argument (\"sizes\").type_sequence_float()\n\n + Option (\"axes\",\n \"specify the axes from the input image that will be used to form the output \"\n \"image. This allows the permutation, ommission, or addition of axes into the \"\n \"output image. The axes should be supplied as a comma-separated list of axes. \"\n \"Any ommitted axes must have dimension 1. Axes can be inserted by supplying \"\n \"-1 at the corresponding position in the list.\")\n + Argument (\"axes\").type_sequence_int()\n\n + Option (\"scaling\",\n \"specify the data scaling parameters used to rescale the intensity values. \"\n \"These take the form of a comma-separated 2-vector of floating-point values, \"\n \"corresponding to offset & scale, with final intensity values being given by \"\n \"offset + scale * stored_value. By default, the values in the original header \"\n \"are preserved.\")\n + Argument (\"values\").type_sequence_float()\n\n + Image::Stride::StrideOption\n\n + DataType::options()\n\n + DWI::GradImportOptions (false)\n + DWI::GradExportOptions();\n}\n\n\n\n\ntemplate \ninline std::vector set_header (Image::Header& header, const InfoType& input)\n{\n \/\/ need to preserve dataype, already parsed from command-line:\n auto datatype = header.datatype();\n header.info() = input.info();\n header.datatype() = datatype;\n\n Options opt = get_options (\"scaling\");\n if (opt.size()) {\n std::vector scaling = opt[0][0];\n if (scaling.size() != 2) \n throw Exception (\"-scaling option expects comma-separated 2-vector of floating-point values\");\n header.intensity_offset() = scaling[0];\n header.intensity_scale() = scaling[1];\n }\n\n if (get_options (\"grad\").size() || get_options (\"fslgrad\").size())\n header.DW_scheme() = DWI::get_DW_scheme (header);\n\n opt = get_options (\"axes\");\n std::vector axes;\n if (opt.size()) {\n axes = opt[0][0];\n header.set_ndim (axes.size());\n for (size_t i = 0; i < axes.size(); ++i) {\n if (axes[i] >= static_cast (input.ndim()))\n throw Exception (\"axis supplied to option -axes is out of bounds\");\n header.dim(i) = axes[i] < 0 ? 1 : input.dim (axes[i]);\n }\n } else {\n header.set_ndim (input.ndim());\n axes.assign (input.ndim(), 0);\n for (size_t i = 0; i < axes.size(); ++i) {\n axes[i] = i;\n header.dim (i) = input.dim (i);\n }\n }\n\n opt = get_options (\"vox\");\n if (opt.size()) {\n std::vector vox = opt[0][0];\n if (vox.size() > header.ndim())\n throw Exception (\"too many axes supplied to -vox option\");\n for (size_t n = 0; n < vox.size(); ++n) {\n if (std::isfinite (vox[n]))\n header.vox(n) = vox[n];\n }\n }\n\n Image::Stride::set_from_command_line (header);\n\n return axes;\n}\n\n\n\n\ntemplate \ninline void copy_permute (Image::Header& header_in, Image::Header& header_out, const std::vector< std::vector >& pos, const std::string& output_filename)\n{\n typedef Image::Buffer buffer_type;\n typedef typename buffer_type::voxel_type voxel_type;\n typedef Image::Adapter::Extract extract_type;\n\n buffer_type buffer_in (header_in);\n voxel_type in = buffer_in.voxel();\n\n\n if (pos.empty()) {\n\n const std::vector axes = set_header (header_out, in);\n buffer_type buffer_out (output_filename, header_out);\n voxel_type out = buffer_out.voxel();\n DWI::export_grad_commandline (buffer_out);\n\n Image::Adapter::PermuteAxes perm (in, axes);\n Image::threaded_copy_with_progress (perm, out, 2);\n\n } else {\n\n extract_type extract (in, pos);\n const std::vector axes = set_header (header_out, extract);\n buffer_type buffer_out (output_filename, header_out);\n voxel_type out = buffer_out.voxel();\n DWI::export_grad_commandline (buffer_out);\n\n Image::Adapter::PermuteAxes perm (extract, axes);\n Image::threaded_copy_with_progress (perm, out, 2);\n\n }\n\n}\n\n\n\n\n\n\n\n\n\n\nvoid run ()\n{\n Image::Header header_in (argument[0]);\n\n Image::Header header_out (header_in);\n header_out.datatype() = DataType::from_command_line (header_out.datatype());\n header_out.set_intensity_scaling (header_in);\n\n if (header_in.datatype().is_complex() && !header_out.datatype().is_complex())\n WARN (\"requested datatype is real but input datatype is complex - imaginary component will be ignored\");\n\n Options opt = get_options (\"coord\");\n std::vector< std::vector > pos;\n if (opt.size()) {\n pos.assign (header_in.ndim(), std::vector());\n for (size_t n = 0; n < opt.size(); n++) {\n int axis = opt[n][0];\n if (axis >= (int)header_in.ndim())\n throw Exception (\"axis \" + str(axis) + \" provided with -coord option is out of range of input image\");\n if (pos[axis].size())\n throw Exception (\"\\\"coord\\\" option specified twice for axis \" + str (axis));\n pos[axis] = parse_ints (opt[n][1], header_in.dim(axis)-1);\n if (axis == 3 && header_in.DW_scheme().is_set()) {\n Math::Matrix& grad (header_in.DW_scheme());\n if ((int)grad.rows() != header_in.dim(3)) {\n WARN (\"Diffusion encoding of input file does not match number of image volumes; omitting gradient information from output image\");\n header_out.DW_scheme().clear();\n }\n else {\n Math::Matrix extract_grad (pos[3].size(), 4);\n for (size_t dir = 0; dir != pos[3].size(); ++dir)\n extract_grad.row(dir) = grad.row((pos[3])[dir]);\n header_out.DW_scheme() = extract_grad;\n }\n }\n }\n\n for (size_t n = 0; n < header_in.ndim(); ++n) {\n if (pos[n].empty()) {\n pos[n].resize (header_in.dim (n));\n for (size_t i = 0; i < pos[n].size(); i++)\n pos[n][i] = i;\n }\n }\n }\n\n switch (header_out.datatype()() & DataType::Type) {\n case DataType::Undefined: throw Exception (\"Undefined output image data type\"); break;\n case DataType::Bit:\n case DataType::UInt8:\n case DataType::UInt16:\n case DataType::UInt32:\n if (header_out.datatype().is_signed())\n copy_permute (header_in, header_out, pos, argument[1]);\n else\n copy_permute (header_in, header_out, pos, argument[1]);\n break;\n case DataType::UInt64:\n if (header_out.datatype().is_signed())\n copy_permute (header_in, header_out, pos, argument[1]);\n else\n copy_permute (header_in, header_out, pos, argument[1]);\n break;\n case DataType::Float32:\n case DataType::Float64:\n if (header_out.datatype().is_complex())\n copy_permute (header_in, header_out, pos, argument[1]);\n else\n copy_permute (header_in, header_out, pos, argument[1]);\n break;\n }\n\n}\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n\/\/ #include \"mloConvHost.hpp\"\n\nvoid failed(const char * msg, const char* file, int line)\n{\n printf(\"FAILED: %s: %s:%i\\n\", msg, file, line);\n std::abort();\n}\n\n#define CHECK(...) if (!(__VA_ARGS__)) failed(#__VA_ARGS__, __FILE__, __LINE__)\n\nstruct handle_fixture\n{\n mlopenHandle_t handle;\n cl_command_queue q;\n\n handle_fixture()\n {\n mlopenCreate(&handle);\n mlopenGetStream(handle, &q);\n }\n\n ~handle_fixture()\n {\n mlopenDestroy(handle);\n }\n};\n\nstruct input_tensor_fixture : virtual handle_fixture\n{\n mlopenTensorDescriptor_t inputTensor;\n\n input_tensor_fixture()\n {\n mlopenCreateTensorDescriptor(handle, &inputTensor);\n mlopenInit4dTensorDescriptor(handle,\n inputTensor,\n mlopenFloat,\n 100,\n 32,\n 8,\n 8);\n \n }\n\n ~input_tensor_fixture()\n {\n mlopenDestroyTensorDescriptor(inputTensor);\n }\n\n void run()\n {\n int n, c, h, w;\n int nStride, cStride, hStride, wStride;\n mlopenDataType_t dt;\n\n mlopenGet4dTensorDescriptor(handle,\n inputTensor,\n &dt,\n &n,\n &c,\n &h,\n &w,\n &nStride,\n &cStride,\n &hStride,\n &wStride);\n\n CHECK(dt == 1);\n CHECK(n == 100);\n CHECK(c == 32);\n CHECK(h == 8);\n CHECK(w == 8);\n CHECK(nStride == 1);\n CHECK(cStride == 1);\n CHECK(hStride == 1);\n CHECK(wStride == 1);\n }\n};\n\nstruct conv_filter_fixture : virtual handle_fixture\n{\n mlopenTensorDescriptor_t convFilter;\n mlopenConvolutionDescriptor_t convDesc;\n\n static const mlopenConvolutionMode_t mode = mlopenConvolution;\n\n conv_filter_fixture()\n {\n mlopenCreateTensorDescriptor(handle, &convFilter);\n \/\/ weights\n mlopenInit4dTensorDescriptor(handle,\n convFilter,\n mlopenFloat,\n 64, \/\/ outputs\n 32, \/\/ inputs\n 5, \/\/ kernel size\n 5);\n \n mlopenCreateConvolutionDescriptor(handle, &convDesc);\n \/\/ convolution with padding 2\n mlopenInitConvolutionDescriptor(convDesc,\n mode,\n 2,\n 2,\n 1,\n 1,\n 1,\n 1);\n \n }\n ~conv_filter_fixture()\n {\n mlopenDestroyTensorDescriptor(convFilter);\n mlopenDestroyConvolutionDescriptor(convDesc);\n }\n\n void run()\n {\n \/\/ TODO: Update API to not require mode by pointer\n mlopenConvolutionMode_t lmode = mode;\n int pad_w, pad_h, u, v, upx, upy;\n mlopenGetConvolutionDescriptor(convDesc,\n &lmode,\n &pad_h, &pad_w, &u, &v,\n &upx, &upy);\n\n CHECK(mode == 0);\n CHECK(pad_h == 2);\n CHECK(pad_w == 2);\n CHECK(u == 1);\n CHECK(v == 1);\n CHECK(upx == 1);\n CHECK(upy == 1);\n }\n};\n\nstruct output_tensor_fixture : conv_filter_fixture, input_tensor_fixture\n{\n mlopenTensorDescriptor_t outputTensor;\n output_tensor_fixture()\n {\n int x, y, z, a;\n mlopenGetConvolutionForwardOutputDim(convDesc, inputTensor, convFilter, &x, &y, &z, &a);\n\n mlopenCreateTensorDescriptor(handle, &outputTensor);\n\n mlopenInit4dTensorDescriptor(handle,\n outputTensor,\n mlopenFloat,\n x,\n y,\n z,\n a);\n }\n ~output_tensor_fixture()\n {\n mlopenDestroyTensorDescriptor(outputTensor);\n }\n\n void run()\n {\n int x, y, z, a;\n mlopenGetConvolutionForwardOutputDim(convDesc, inputTensor, convFilter, &x, &y, &z, &a);\n\n CHECK(x == 100);\n CHECK(y == 64);\n CHECK(z == 8);\n CHECK(a == 8);\n }\n};\n\nstruct conv_forward : output_tensor_fixture\n{\n void run()\n {\n int alpha = 1, beta = 1;\n mlopenTransformTensor(handle,\n &alpha,\n inputTensor,\n NULL,\n &beta,\n convFilter,\n NULL);\n\n int value = 10;\n mlopenSetTensor(handle, inputTensor, NULL, &value);\n\n mlopenScaleTensor(handle, inputTensor, NULL, &alpha);\n\n \/\/ Setup OpenCL buffers\n\n cl_int status;\n const int sz = 1024;\n std::vector a1(sz, 1.0);\n std::vector b1(sz, 6.0);\n std::vector c1(sz, 0.0);\n\n cl_context ctx;\n clGetCommandQueueInfo(q, CL_QUEUE_CONTEXT, sizeof(cl_context), &ctx, NULL);\n\n cl_mem adev = clCreateBuffer(ctx, CL_MEM_READ_ONLY, 4*sz,NULL, &status);\n CHECK(status == CL_SUCCESS);\n\n cl_mem bdev = clCreateBuffer(ctx, CL_MEM_READ_ONLY, 4*sz,NULL, NULL);\n cl_mem cdev = clCreateBuffer(ctx, CL_MEM_READ_WRITE, 4*sz,NULL, NULL);\n\n status = clEnqueueWriteBuffer(q, adev, CL_TRUE, 0, 4*sz, a1.data(), 0, NULL, NULL);\n status |= clEnqueueWriteBuffer(q, bdev, CL_TRUE, 0, 4*sz, b1.data(), 0, NULL, NULL);\n status |= clEnqueueWriteBuffer(q, cdev, CL_TRUE, 0, 4*sz, c1.data(), 0, NULL, NULL);\n CHECK(status == CL_SUCCESS);\n\n int ret_algo_count;\n mlopenConvAlgoPerf_t perf;\n\n mlopenFindConvolutionForwardAlgorithm(handle,\n inputTensor,\n adev,\n convFilter,\n bdev,\n convDesc,\n outputTensor,\n cdev,\n 1,\n &ret_algo_count,\n &perf,\n mlopenConvolutionFastest,\n NULL,\n 10);\n\n mlopenConvolutionForward(handle,\n &alpha,\n inputTensor,\n NULL,\n convFilter,\n NULL,\n convDesc,\n mlopenConvolutionFwdAlgoDirect,\n &beta,\n outputTensor,\n NULL);\n }\n};\n\n\n\nint main() {\n input_tensor_fixture{}.run();\n conv_filter_fixture{}.run();\n output_tensor_fixture{}.run();\n conv_forward{}.run();\n}\n\n\nFix tests with update paramters#include \n#include \n#include \n#include \n#include \n\/\/ #include \"mloConvHost.hpp\"\n\nvoid failed(const char * msg, const char* file, int line)\n{\n printf(\"FAILED: %s: %s:%i\\n\", msg, file, line);\n std::abort();\n}\n\n#define CHECK(...) if (!(__VA_ARGS__)) failed(#__VA_ARGS__, __FILE__, __LINE__)\n\nstruct handle_fixture\n{\n mlopenHandle_t handle;\n cl_command_queue q;\n\n handle_fixture()\n {\n mlopenCreate(&handle);\n mlopenGetStream(handle, &q);\n }\n\n ~handle_fixture()\n {\n mlopenDestroy(handle);\n }\n};\n\nstruct input_tensor_fixture : virtual handle_fixture\n{\n mlopenTensorDescriptor_t inputTensor;\n\n input_tensor_fixture()\n {\n mlopenCreateTensorDescriptor(handle, &inputTensor);\n mlopenInit4dTensorDescriptor(handle,\n inputTensor,\n mlopenFloat,\n 100,\n 32,\n 8,\n 8);\n \n }\n\n ~input_tensor_fixture()\n {\n mlopenDestroyTensorDescriptor(inputTensor);\n }\n\n void run()\n {\n int n, c, h, w;\n int nStride, cStride, hStride, wStride;\n mlopenDataType_t dt;\n\n mlopenGet4dTensorDescriptor(handle,\n inputTensor,\n &dt,\n &n,\n &c,\n &h,\n &w,\n &nStride,\n &cStride,\n &hStride,\n &wStride);\n\n CHECK(dt == 1);\n CHECK(n == 100);\n CHECK(c == 32);\n CHECK(h == 8);\n CHECK(w == 8);\n CHECK(nStride == 1);\n CHECK(cStride == 1);\n CHECK(hStride == 1);\n CHECK(wStride == 1);\n }\n};\n\nstruct conv_filter_fixture : virtual handle_fixture\n{\n mlopenTensorDescriptor_t convFilter;\n mlopenConvolutionDescriptor_t convDesc;\n\n static const mlopenConvolutionMode_t mode = mlopenConvolution;\n\n conv_filter_fixture()\n {\n mlopenCreateTensorDescriptor(handle, &convFilter);\n \/\/ weights\n mlopenInit4dTensorDescriptor(handle,\n convFilter,\n mlopenFloat,\n 64, \/\/ outputs\n 32, \/\/ inputs\n 5, \/\/ kernel size\n 5);\n \n mlopenCreateConvolutionDescriptor(handle, &convDesc);\n \/\/ convolution with padding 2\n mlopenInitConvolutionDescriptor(convDesc,\n mode,\n 2,\n 2,\n 1,\n 1,\n 1,\n 1);\n \n }\n ~conv_filter_fixture()\n {\n mlopenDestroyTensorDescriptor(convFilter);\n mlopenDestroyConvolutionDescriptor(convDesc);\n }\n\n void run()\n {\n \/\/ TODO: Update API to not require mode by pointer\n mlopenConvolutionMode_t lmode = mode;\n int pad_w, pad_h, u, v, upx, upy;\n mlopenGetConvolutionDescriptor(convDesc,\n &lmode,\n &pad_h, &pad_w, &u, &v,\n &upx, &upy);\n\n CHECK(mode == 0);\n CHECK(pad_h == 2);\n CHECK(pad_w == 2);\n CHECK(u == 1);\n CHECK(v == 1);\n CHECK(upx == 1);\n CHECK(upy == 1);\n }\n};\n\nstruct output_tensor_fixture : conv_filter_fixture, input_tensor_fixture\n{\n mlopenTensorDescriptor_t outputTensor;\n output_tensor_fixture()\n {\n int x, y, z, a;\n mlopenGetConvolutionForwardOutputDim(convDesc, inputTensor, convFilter, &x, &y, &z, &a);\n\n mlopenCreateTensorDescriptor(handle, &outputTensor);\n\n mlopenInit4dTensorDescriptor(handle,\n outputTensor,\n mlopenFloat,\n x,\n y,\n z,\n a);\n }\n ~output_tensor_fixture()\n {\n mlopenDestroyTensorDescriptor(outputTensor);\n }\n\n void run()\n {\n int x, y, z, a;\n mlopenGetConvolutionForwardOutputDim(convDesc, inputTensor, convFilter, &x, &y, &z, &a);\n\n CHECK(x == 100);\n CHECK(y == 64);\n CHECK(z == 8);\n CHECK(a == 8);\n }\n};\n\nstruct conv_forward : output_tensor_fixture\n{\n void run()\n {\n int alpha = 1, beta = 1;\n mlopenTransformTensor(handle,\n &alpha,\n inputTensor,\n NULL,\n &beta,\n convFilter,\n NULL);\n\n int value = 10;\n mlopenSetTensor(handle, inputTensor, NULL, &value);\n\n mlopenScaleTensor(handle, inputTensor, NULL, &alpha);\n\n \/\/ Setup OpenCL buffers\n\n cl_int status;\n const int sz = 1024;\n std::vector a1(sz, 1.0);\n std::vector b1(sz, 6.0);\n std::vector c1(sz, 0.0);\n\n cl_context ctx;\n clGetCommandQueueInfo(q, CL_QUEUE_CONTEXT, sizeof(cl_context), &ctx, NULL);\n\n cl_mem adev = clCreateBuffer(ctx, CL_MEM_READ_ONLY, 4*sz,NULL, &status);\n CHECK(status == CL_SUCCESS);\n\n cl_mem bdev = clCreateBuffer(ctx, CL_MEM_READ_ONLY, 4*sz,NULL, NULL);\n cl_mem cdev = clCreateBuffer(ctx, CL_MEM_READ_WRITE, 4*sz,NULL, NULL);\n\n status = clEnqueueWriteBuffer(q, adev, CL_TRUE, 0, 4*sz, a1.data(), 0, NULL, NULL);\n status |= clEnqueueWriteBuffer(q, bdev, CL_TRUE, 0, 4*sz, b1.data(), 0, NULL, NULL);\n status |= clEnqueueWriteBuffer(q, cdev, CL_TRUE, 0, 4*sz, c1.data(), 0, NULL, NULL);\n CHECK(status == CL_SUCCESS);\n\n int ret_algo_count;\n mlopenConvAlgoPerf_t perf;\n\n mlopenFindConvolutionForwardAlgorithm(handle,\n inputTensor,\n adev,\n convFilter,\n bdev,\n convDesc,\n outputTensor,\n cdev,\n 1,\n &ret_algo_count,\n &perf,\n mlopenConvolutionFastest,\n NULL,\n 10);\n\n mlopenConvolutionForward(handle,\n &alpha,\n inputTensor,\n NULL,\n convFilter,\n NULL,\n convDesc,\n mlopenConvolutionFwdAlgoDirect,\n &beta,\n outputTensor,\n NULL,\n NULL,\n 0);\n }\n};\n\n\n\nint main() {\n input_tensor_fixture{}.run();\n conv_filter_fixture{}.run();\n output_tensor_fixture{}.run();\n conv_forward{}.run();\n}\n\n\n<|endoftext|>"} {"text":"\/\/ Copyright 2019 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"test.h\"\n\n#include \n#include \n\nnamespace {\n\nbool wildcard_match(const char* p, const char* str) {\n while (*p && *str && (*p == *str || *p == '?') && *p != '*') {\n str++;\n p++;\n }\n\n if (!*p) {\n return *str == 0;\n } else if (*p == '*') {\n p++;\n do {\n if (wildcard_match(p, str)) {\n return true;\n }\n } while(*str++);\n }\n return !*p;\n}\n\nstd::vector>>& tests() {\n static std::vector>> v;\n return v;\n}\n\n} \/\/ namespace\n\nnamespace nda {\n\ntest::test(const std::string& name, std::function fn) {\n add_test(name, fn);\n}\n\nvoid add_test(const std::string& name, std::function fn) {\n tests().push_back(std::make_pair(name, fn));\n}\n\n} \/\/ namespace nda\n\nusing namespace nda;\n\nint main(int argc, const char** argv) {\n \/\/ By default, the filter matches all tests.\n const char* filter = \"*\";\n if (argc > 1) {\n filter = argv[1];\n std::cout << \"Running tests matching '\" << filter << \"'...\" << std::endl;\n }\n\n size_t passed = 0;\n size_t total = 0;\n for (auto& i : tests()) {\n if (!wildcard_match(filter, i.first.c_str())) continue;\n\n std::cout << i.first;\n#ifndef NDARRAY_NO_EXCEPTIONS\n try {\n#endif\n i.second();\n std::cout << \" passed\" << std::endl;\n passed++;\n#ifndef NDARRAY_NO_EXCEPTIONS\n } catch(const std::exception& e) {\n std::cout << \" failed: \" << e.what() << std::endl;\n }\n#endif\n total++;\n }\n std::cout << passed << \" of \" << total << \" tests passed, \" << tests().size() - total << \" skipped\" << std::endl;\n return passed < total ? -1 : 0;\n}\nFix formatting.\/\/ Copyright 2019 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"test.h\"\n\n#include \n#include \n\nnamespace {\n\nbool wildcard_match(const char* p, const char* str) {\n while (*p && *str && (*p == *str || *p == '?') && *p != '*') {\n str++;\n p++;\n }\n\n if (!*p) {\n return *str == 0;\n } else if (*p == '*') {\n p++;\n do {\n if (wildcard_match(p, str)) {\n return true;\n }\n } while(*str++);\n }\n return !*p;\n}\n\nstd::vector>>& tests() {\n static std::vector>> v;\n return v;\n}\n\n} \/\/ namespace\n\nnamespace nda {\n\ntest::test(const std::string& name, std::function fn) {\n add_test(name, fn);\n}\n\nvoid add_test(const std::string& name, std::function fn) {\n tests().push_back(std::make_pair(name, fn));\n}\n\n} \/\/ namespace nda\n\nusing namespace nda;\n\nint main(int argc, const char** argv) {\n \/\/ By default, the filter matches all tests.\n const char* filter = \"*\";\n if (argc > 1) {\n filter = argv[1];\n std::cout << \"Running tests matching '\" << filter << \"'...\" << std::endl;\n }\n\n size_t passed = 0;\n size_t total = 0;\n for (auto& i : tests()) {\n if (!wildcard_match(filter, i.first.c_str())) continue;\n\n std::cout << i.first << \" \";\n#ifndef NDARRAY_NO_EXCEPTIONS\n try {\n#endif\n i.second();\n std::cout << \"passed\" << std::endl;\n passed++;\n#ifndef NDARRAY_NO_EXCEPTIONS\n } catch(const std::exception& e) {\n std::cout << \"failed: \" << e.what() << std::endl;\n }\n#endif\n total++;\n }\n std::cout << passed << \" of \" << total << \" tests passed, \" << tests().size() - total << \" skipped\" << std::endl;\n return passed < total ? -1 : 0;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\n#include \"dependencies\/Catch\/catch_with_main.hpp\"\n\n#include \"..\/reflect.h\"\n\n\nstruct Perfect {\n int m = 0;\n\n Perfect(const Perfect&) = delete;\n Perfect(Perfect&&) = delete;\n};\n\nstruct NonCopyable {\n int m;\n\n NonCopyable(const NonCopyable&) = delete;\n NonCopyable(NonCopyable&&) = default;\n\n NonCopyable& operator=(NonCopyable&&) = default;\n NonCopyable& operator=(const NonCopyable&) = delete;\n};\n\nstatic int tally = 0;\n\nstruct Foo {\n int i = 0;\n bool b = false;\n char c = '\\0';\n NonCopyable ncmem{ 0 };\n\n void Bar() {\n std::cout << \"Bar called\" << std::endl;\n b = true;\n }\n\n int Baz() {\n std::cout << \"Baz called\" << std::endl;\n return i;\n }\n\n int Baz2(int x) {\n std::cout << \"Baz2 called\" << std::endl;\n return x;\n }\n\n void Perf(Perfect&& n) {\n std::cout << \"Perf called\" << std::endl;\n }\n\n void NC(NonCopyable nc) {\n std::cout << \"NC called\" << std::endl;\n }\n\n void Tally(int x) {\n tally += 1 + x % static_cast(std::sqrt(tally + 10));\n }\n};\n\nREFLECT_ENABLE(Foo, i, b, c, ncmem, Bar, Baz, Baz2, Perf, NC, Tally)\n\nstruct Static {\n static int abc;\n};\n\nint Static::abc = 1;\n\nREFLECT_ENABLE(Static, abc);\n\nstruct Const {\n const static int _static = 10;\n const int _const = 12;\n};\n\nconst int Const::_static;\n\nREFLECT_ENABLE(Const, _static, _const);\n\nstruct Arrays {\n int* iptr = new int(42);\n int iarr10[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n\n ~Arrays() {\n delete iptr;\n }\n};\n\nREFLECT_ENABLE(Arrays, iptr, iarr10);\n\nSCENARIO(\"members can be written to\", \"[reflection]\") {\nGIVEN(\"a reflected object\") {\n Foo f{};\n auto reflectfoo = reflect::reflect(f);\n\n REQUIRE(f.i == 0);\n REQUIRE(f.b == false);\n REQUIRE(f.c == 0);\n REQUIRE(f.ncmem.m == 0);\n\nWHEN(\"an int is assigned to an int member\") {\n constexpr int ten = 10;\n CHECK_NOTHROW(reflectfoo[\"i\"] = ten);\n\nTHEN(\"the value is changed\") {\n CHECK(ten == f.i);\n}\n}\n\nWHEN(\"a char is assigned to an int member\") {\n constexpr char c = 'c';\n CHECK_NOTHROW(reflectfoo[\"i\"] = c);\n\nTHEN(\"the value is changed\") {\n CHECK(c == f.i);\n}\n}\n\nWHEN(\"a size_t is assigned to an int member\") {\n constexpr std::size_t eleven = 11;\n CHECK_NOTHROW(reflectfoo[\"i\"] = eleven);\n\nTHEN(\"the value is changed\") {\n CHECK(eleven == f.i);\n}\n}\n\nWHEN(\"a char is assigned to a char member\") {\n constexpr char c = 'c';\n CHECK_NOTHROW(reflectfoo[\"c\"] = c);\n\nTHEN(\"the value is changed\") {\n CHECK(c == f.c);\n}\n}\n\nWHEN(\"a string is assigned to a char member\") {\nTHEN(\"an exception is thrown\") {\n static const std::string s = \"hello world\";\n CHECK_THROWS_AS(reflectfoo[\"c\"] = s, const reflect::invalid_assignment_type&);\n}\n}\n\nWHEN(\"a string is assigned to a function member\") {\nTHEN(\"an exception is thrown\") {\n static const std::string s = \"hello world\";\n CHECK_THROWS_AS(reflectfoo[\"Bar\"] = s, const reflect::invalid_assignment_type&);\n}\n}\n\n}\n}\n\n\/*\nint main() {\n\n Foo f{};\n auto reflectfoo = reflect::reflect(f);\n {\n reflectfoo[\"i\"] = 'c';\n\n reflectfoo[\"i\"] = 10;\n assert(f.i == 10);\n std::cout << f.i << std::endl;\n\n int a = reflectfoo[\"i\"];\n assert(a == 10);\n\n int& aref = reflectfoo[\"i\"];\n assert(aref == 10);\n\n char c = reflectfoo[\"i\"];\n\n reflectfoo[\"Bar\"]();\n reflectfoo[\"Bar\"].invoke();\n assert(f.b);\n\n try {\n reflectfoo[\"i\"]();\n assert(false);\n }\n catch (const reflect::invalid_function_call& e) {\n std::cout << \"caught: \" << e.what() << std::endl;\n }\n\n reflectfoo[\"i\"] = std::size_t{ 0 };\n assert(f.i == 0);\n\n try {\n reflectfoo[\"i\"] = std::string();\n assert(false);\n }\n catch (const reflect::invalid_assignment_type& e) {\n std::cout << \"caught: \" << e.what() << std::endl;\n }\n\n int i = reflectfoo[\"Baz\"]();\n assert(i == f.i);\n\n reflectfoo[\"Baz\"]();\n\n int x = reflectfoo[\"Baz2\"](42);\n assert(x == 42);\n double d = reflectfoo[\"Baz2\"](42.0);\n\n try {\n int x = reflectfoo[\"Bar\"]();\n assert(false);\n }\n catch (const reflect::invalid_function_call& e) {\n std::cout << \"caught: \" << e.what() << std::endl;\n }\n\n std::size_t sizei = reflectfoo[\"i\"];\n assert(f.i == sizei);\n\n try {\n std::string s = reflectfoo[\"i\"];\n assert(false);\n }\n catch (const reflect::invalid_requested_member_type& e) {\n std::cout << \"caught: \" << e.what() << std::endl;\n }\n\n reflectfoo[\"Perf\"](Perfect{ 10 });\n\n NonCopyable& ncref = reflectfoo[\"ncmem\"];\n assert(ncref.m == 43);\n\n NonCopyable nc2{ 10 };\n reflectfoo[\"ncmem\"] = std::move(nc2);\n assert(ncref.m == 10);\n\n NonCopyable nc{ 10 };\n reflectfoo[\"NC\"](std::move(nc));\n }\n\n auto reflectstaticfoo = reflect::reflect();\n {\n try {\n int i = reflectstaticfoo[\"i\"];\n assert(false);\n }\n catch (const reflect::member_access_error& e) {\n std::cout << \"caught: \" << e.what() << std::endl;\n }\n }\n\n auto reflectstatic = reflect::reflect();\n {\n int abc = reflectstatic[\"abc\"];\n assert(abc == Static::abc);\n\n reflectstatic[\"abc\"] = 2;\n assert(Static::abc == 2);\n }\n\n Const _const;\n auto reflectconst = reflect::reflect(_const);\n {\n int c = reflectconst[\"_const\"];\n assert(c == _const._const);\n\n try {\n reflectconst[\"_const\"] = 10;\n assert(false);\n }\n catch (const reflect::invalid_assignment_to_const& e) {\n std::cout << \"caught: \" << e.what() << std::endl;\n }\n\n int s = reflectconst[\"_static\"];\n assert(s == Const::_static);\n\n try {\n reflectconst[\"_static\"] = 10;\n assert(false);\n }\n catch (const reflect::invalid_assignment_to_const& e) {\n std::cout << \"caught: \" << e.what() << std::endl;\n }\n }\n\n Arrays arrays;\n auto reflectarrays = reflect::reflect(arrays);\n {\n int* p = reflectarrays[\"iptr\"];\n assert(p == arrays.iptr);\n\n int* arrptr = reflectarrays[\"iarr10\"];\n assert(arrptr == arrays.iarr10);\n\n int (&arrref)[10] = reflectarrays[\"iarr10\"];\n assert(arrref == arrays.iarr10);\n\n try {\n int (&badarref)[2] = reflectarrays[\"iarr10\"];\n assert(false);\n }\n catch (const reflect::invalid_requested_member_type& e) {\n std::cout << \"caught: \" << e.what() << std::endl;\n }\n }\n\n constexpr int iters = 100000000;\n std::chrono::time_point start, end;\n start = std::chrono::high_resolution_clock::now();\n\n for (int i = 0; i < iters; ++i) {\n f.Tally(42);\n }\n\n end = std::chrono::high_resolution_clock::now();\n\n std::chrono::duration delta = end - start;\n long double delta_per_iter = delta.count() \/ (long double)iters;\n std::cout.precision(15);\n\n std::cout << \"direct: \\t\" << delta_per_iter << \" ns\/iter\" << std::endl;\n\n start = std::chrono::high_resolution_clock::now();\n\n for (int i = 0; i < iters; ++i) {\n reflectfoo[\"Tally\"](42);\n }\n\n end = std::chrono::high_resolution_clock::now();\n\n delta = end - start;\n delta_per_iter = delta.count() \/ (long double)iters;\n std::cout.precision(15);\n\n std::cout << \"reflected: \\t\" << delta_per_iter << \" ns\/iter\" << std::endl;\n\n std::cout << tally << std::endl;\n\n std::cin.ignore();\n}\n\/\/*\/\nsome more tests#include \n#include \n#include \n#include \n\n#include \"dependencies\/Catch\/catch_with_main.hpp\"\n\n#include \"..\/reflect.h\"\n\n\nstruct Perfect {\n int m = 0;\n\n Perfect(const Perfect&) = delete;\n Perfect(Perfect&&) = delete;\n};\n\nstruct NonCopyable {\n int m;\n\n NonCopyable(const NonCopyable&) = delete;\n NonCopyable(NonCopyable&&) = default;\n\n NonCopyable& operator=(NonCopyable&&) = default;\n NonCopyable& operator=(const NonCopyable&) = delete;\n};\n\nstatic int tally = 0;\n\nstruct Foo {\n int i = 0;\n bool b = false;\n char c = '\\0';\n NonCopyable ncmem{ 0 };\n\n void Bar() {\n std::cout << \"Bar called\" << std::endl;\n b = true;\n }\n\n int Baz() {\n std::cout << \"Baz called\" << std::endl;\n return i;\n }\n\n int Baz2(int x) {\n std::cout << \"Baz2 called\" << std::endl;\n return x;\n }\n\n void Perf(Perfect&& n) {\n std::cout << \"Perf called\" << std::endl;\n }\n\n void NC(NonCopyable nc) {\n std::cout << \"NC called\" << std::endl;\n }\n\n void Tally(int x) {\n tally += 1 + x % static_cast(std::sqrt(tally + 10));\n }\n};\n\nREFLECT_ENABLE(Foo, i, b, c, ncmem, Bar, Baz, Baz2, Perf, NC, Tally)\n\nstruct Static {\n static int abc;\n};\n\nint Static::abc = 0;\n\nREFLECT_ENABLE(Static, abc);\n\nstruct Const {\n const static int _static = 10;\n const int _const = 12;\n};\n\nconst int Const::_static;\n\nREFLECT_ENABLE(Const, _static, _const);\n\nstruct Arrays {\n int* iptr = new int(42);\n int iarr10[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n\n ~Arrays() {\n delete iptr;\n }\n};\n\nREFLECT_ENABLE(Arrays, iptr, iarr10);\n\nSCENARIO(\"members can be written to\", \"[reflection]\") {\nGIVEN(\"a reflected object\") {\n Foo f{};\n auto reflected = reflect::reflect(f);\n\n REQUIRE(f.i == 0);\n REQUIRE(f.b == false);\n REQUIRE(f.c == 0);\n REQUIRE(f.ncmem.m == 0);\n\nWHEN(\"an int literal is assigned to an int member\") {\n CHECK_NOTHROW(reflected[\"i\"] = 10);\n\nTHEN(\"the value is changed\") {\n CHECK(10 == f.i);\n}\n}\n\nWHEN(\"an int is assigned to an int member\") {\n constexpr int ten = 10;\n CHECK_NOTHROW(reflected[\"i\"] = ten);\n\nTHEN(\"the value is changed\") {\n CHECK(ten == f.i);\n}\n}\n\nWHEN(\"a char is assigned to an int member\") {\n constexpr char c = 'c';\n CHECK_NOTHROW(reflected[\"i\"] = c);\n\nTHEN(\"the value is changed\") {\n CHECK(c == f.i);\n}\n}\n\nWHEN(\"a size_t is assigned to an int member\") {\n constexpr std::size_t eleven = 11;\n CHECK_NOTHROW(reflected[\"i\"] = eleven);\n\nTHEN(\"the value is changed\") {\n CHECK(eleven == f.i);\n}\n}\n\nWHEN(\"a char is assigned to a char member\") {\n constexpr char c = 'c';\n CHECK_NOTHROW(reflected[\"c\"] = c);\n\nTHEN(\"the value is changed\") {\n CHECK(c == f.c);\n}\n}\n\nWHEN(\"a string is assigned to a char member\") {\nTHEN(\"an exception is thrown\") {\n static const std::string s = \"hello world\";\n CHECK_THROWS_AS(reflected[\"c\"] = s, const reflect::invalid_assignment_type&);\n}\n}\n\nWHEN(\"a string is assigned to a function member\") {\nTHEN(\"an exception is thrown\") {\n static const std::string s = \"hello world\";\n CHECK_THROWS_AS(reflected[\"Bar\"] = s, const reflect::invalid_assignment_type&);\n}\n}\n}\n\nGIVEN(\"a reflected static instance with non-static members\") {\n auto reflected = reflect::reflect();\n\nWHEN(\"a non-static member is accessed\") {\nTHEN(\"an exception is thrown\") {\n CHECK_THROWS_AS(reflected[\"i\"] = 0, const reflect::member_access_error&);\n}\n}\n}\n\nGIVEN(\"a reflected static instance with static members\") {\n auto reflected = reflect::reflect();\n REQUIRE(Static::abc == 0);\n\nWHEN(\"a static member is accessed\") {\n CHECK_NOTHROW(reflected[\"abc\"] = 10);\n\nTHEN(\"the value is changed\") {\n CHECK(10 == Static::abc);\n}\n}\n}\n}\n\n\/*\nint main() {\n\n Foo f{};\n auto reflectfoo = reflect::reflect(f);\n {\n reflectfoo[\"i\"] = 'c';\n\n reflectfoo[\"i\"] = 10;\n assert(f.i == 10);\n std::cout << f.i << std::endl;\n\n int a = reflectfoo[\"i\"];\n assert(a == 10);\n\n int& aref = reflectfoo[\"i\"];\n assert(aref == 10);\n\n char c = reflectfoo[\"i\"];\n\n reflectfoo[\"Bar\"]();\n reflectfoo[\"Bar\"].invoke();\n assert(f.b);\n\n try {\n reflectfoo[\"i\"]();\n assert(false);\n }\n catch (const reflect::invalid_function_call& e) {\n std::cout << \"caught: \" << e.what() << std::endl;\n }\n\n reflectfoo[\"i\"] = std::size_t{ 0 };\n assert(f.i == 0);\n\n try {\n reflectfoo[\"i\"] = std::string();\n assert(false);\n }\n catch (const reflect::invalid_assignment_type& e) {\n std::cout << \"caught: \" << e.what() << std::endl;\n }\n\n int i = reflectfoo[\"Baz\"]();\n assert(i == f.i);\n\n reflectfoo[\"Baz\"]();\n\n int x = reflectfoo[\"Baz2\"](42);\n assert(x == 42);\n double d = reflectfoo[\"Baz2\"](42.0);\n\n try {\n int x = reflectfoo[\"Bar\"]();\n assert(false);\n }\n catch (const reflect::invalid_function_call& e) {\n std::cout << \"caught: \" << e.what() << std::endl;\n }\n\n std::size_t sizei = reflectfoo[\"i\"];\n assert(f.i == sizei);\n\n try {\n std::string s = reflectfoo[\"i\"];\n assert(false);\n }\n catch (const reflect::invalid_requested_member_type& e) {\n std::cout << \"caught: \" << e.what() << std::endl;\n }\n\n reflectfoo[\"Perf\"](Perfect{ 10 });\n\n NonCopyable& ncref = reflectfoo[\"ncmem\"];\n assert(ncref.m == 43);\n\n NonCopyable nc2{ 10 };\n reflectfoo[\"ncmem\"] = std::move(nc2);\n assert(ncref.m == 10);\n\n NonCopyable nc{ 10 };\n reflectfoo[\"NC\"](std::move(nc));\n }\n\n auto reflectstaticfoo = reflect::reflect();\n {\n try {\n int i = reflectstaticfoo[\"i\"];\n assert(false);\n }\n catch (const reflect::member_access_error& e) {\n std::cout << \"caught: \" << e.what() << std::endl;\n }\n }\n\n auto reflectstatic = reflect::reflect();\n {\n int abc = reflectstatic[\"abc\"];\n assert(abc == Static::abc);\n\n reflectstatic[\"abc\"] = 2;\n assert(Static::abc == 2);\n }\n\n Const _const;\n auto reflectconst = reflect::reflect(_const);\n {\n int c = reflectconst[\"_const\"];\n assert(c == _const._const);\n\n try {\n reflectconst[\"_const\"] = 10;\n assert(false);\n }\n catch (const reflect::invalid_assignment_to_const& e) {\n std::cout << \"caught: \" << e.what() << std::endl;\n }\n\n int s = reflectconst[\"_static\"];\n assert(s == Const::_static);\n\n try {\n reflectconst[\"_static\"] = 10;\n assert(false);\n }\n catch (const reflect::invalid_assignment_to_const& e) {\n std::cout << \"caught: \" << e.what() << std::endl;\n }\n }\n\n Arrays arrays;\n auto reflectarrays = reflect::reflect(arrays);\n {\n int* p = reflectarrays[\"iptr\"];\n assert(p == arrays.iptr);\n\n int* arrptr = reflectarrays[\"iarr10\"];\n assert(arrptr == arrays.iarr10);\n\n int (&arrref)[10] = reflectarrays[\"iarr10\"];\n assert(arrref == arrays.iarr10);\n\n try {\n int (&badarref)[2] = reflectarrays[\"iarr10\"];\n assert(false);\n }\n catch (const reflect::invalid_requested_member_type& e) {\n std::cout << \"caught: \" << e.what() << std::endl;\n }\n }\n\n constexpr int iters = 100000000;\n std::chrono::time_point start, end;\n start = std::chrono::high_resolution_clock::now();\n\n for (int i = 0; i < iters; ++i) {\n f.Tally(42);\n }\n\n end = std::chrono::high_resolution_clock::now();\n\n std::chrono::duration delta = end - start;\n long double delta_per_iter = delta.count() \/ (long double)iters;\n std::cout.precision(15);\n\n std::cout << \"direct: \\t\" << delta_per_iter << \" ns\/iter\" << std::endl;\n\n start = std::chrono::high_resolution_clock::now();\n\n for (int i = 0; i < iters; ++i) {\n reflectfoo[\"Tally\"](42);\n }\n\n end = std::chrono::high_resolution_clock::now();\n\n delta = end - start;\n delta_per_iter = delta.count() \/ (long double)iters;\n std::cout.precision(15);\n\n std::cout << \"reflected: \\t\" << delta_per_iter << \" ns\/iter\" << std::endl;\n\n std::cout << tally << std::endl;\n\n std::cin.ignore();\n}\n\/\/*\/\n<|endoftext|>"} {"text":"\/\/\n\/\/ This file is part of the Marble Virtual Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2011 Daniel Marth \n\/\/ Copyright 2012 Bernhard Beschow \n\/\/\n\n#include \"QtPositioningPositionProviderPlugin.h\"\n\n#include \n#include \n#include \n\n#if QT_VERSION < 0x050000\n\nQTM_USE_NAMESPACE\n\n#endif\n\nnamespace Marble {\n\nclass QtPositioningPositionProviderPluginPrivate\n{\npublic:\n QtPositioningPositionProviderPluginPrivate();\n\n QGeoPositionInfoSource *const m_source;\n PositionProviderStatus m_status;\n};\n\nQtPositioningPositionProviderPluginPrivate::QtPositioningPositionProviderPluginPrivate() :\n m_source( QGeoPositionInfoSource::createDefaultSource( 0 ) ),\n m_status( PositionProviderStatusAcquiring )\n{\n}\n\nQString QtPositioningPositionProviderPlugin::name() const\n{\n return tr( \"Qt Psoitioning Position Provider Plugin\" );\n}\n\nQString QtPositioningPositionProviderPlugin::nameId() const\n{\n return \"QtPositioning\";\n}\n\nQString QtPositioningPositionProviderPlugin::guiString() const\n{\n return tr( \"Qt Positioning Location\" );\n}\n\nQString QtPositioningPositionProviderPlugin::version() const\n{\n return \"1.0\";\n}\n\nQString QtPositioningPositionProviderPlugin::description() const\n{\n return tr( \"Reports the GPS position of a QtPositioning compatible device.\" );\n}\n\nQString QtPositioningPositionProviderPlugin::copyrightYears() const\n{\n return \"2011\";\n}\n\nQList QtPositioningPositionProviderPlugin::pluginAuthors() const\n{\n return QList()\n << PluginAuthor( \"Daniel Marth\", \"danielmarth@gmx.at\" );\n}\n\nQIcon QtPositioningPositionProviderPlugin::icon() const\n{\n return QIcon();\n}\n\nPositionProviderPlugin* QtPositioningPositionProviderPlugin::newInstance() const\n{\n return new QtPositioningPositionProviderPlugin;\n}\n\nPositionProviderStatus QtPositioningPositionProviderPlugin::status() const\n{\n return d->m_status;\n}\n\nGeoDataCoordinates QtPositioningPositionProviderPlugin::position() const\n{\n if ( d->m_source == 0 ) {\n return GeoDataCoordinates();\n }\n\n const QGeoCoordinate p = d->m_source->lastKnownPosition().coordinate();\n if( !p.isValid() ) {\n return GeoDataCoordinates();\n }\n\n return GeoDataCoordinates( p.longitude(), p.latitude(),\n p.altitude(), GeoDataCoordinates::Degree );\n}\n\nGeoDataAccuracy QtPositioningPositionProviderPlugin::accuracy() const\n{\n if ( d->m_source == 0 ) {\n return GeoDataAccuracy();\n }\n\n const QGeoPositionInfo info = d->m_source->lastKnownPosition();\n\n if( !info.hasAttribute( QGeoPositionInfo::HorizontalAccuracy ) ||\n !info.hasAttribute( QGeoPositionInfo::VerticalAccuracy ) ) {\n return GeoDataAccuracy();\n }\n\n const qreal horizontal = info.attribute( QGeoPositionInfo::HorizontalAccuracy );\n const qreal vertical = info.attribute( QGeoPositionInfo::VerticalAccuracy );\n\n return GeoDataAccuracy( GeoDataAccuracy::Detailed, horizontal, vertical );\n}\n\nQtPositioningPositionProviderPlugin::QtPositioningPositionProviderPlugin() :\n d( new QtPositioningPositionProviderPluginPrivate )\n{\n}\n\nQtPositioningPositionProviderPlugin::~QtPositioningPositionProviderPlugin()\n{\n delete d;\n}\n\nvoid QtPositioningPositionProviderPlugin::initialize()\n{\n if( d->m_source ) {\n connect( d->m_source, SIGNAL(positionUpdated(QGeoPositionInfo)), this, SLOT(update()) );\n d->m_source->setUpdateInterval( 1000 );\n d->m_source->startUpdates();\n }\n}\n\nbool QtPositioningPositionProviderPlugin::isInitialized() const\n{\n return d->m_source != 0;\n}\n\nqreal QtPositioningPositionProviderPlugin::speed() const\n{\n if ( d->m_source == 0 ) {\n return 0.0;\n }\n\n if( !d->m_source->lastKnownPosition().hasAttribute( QGeoPositionInfo::GroundSpeed ) ) {\n return 0.0;\n }\n\n return d->m_source->lastKnownPosition().attribute( QGeoPositionInfo::GroundSpeed );\n}\n\nqreal QtPositioningPositionProviderPlugin::direction() const\n{\n if ( d->m_source == 0 ) {\n return 0.0;\n }\n\n if( !d->m_source->lastKnownPosition().hasAttribute( QGeoPositionInfo::Direction ) ) {\n return 0.0;\n }\n\n return d->m_source->lastKnownPosition().attribute( QGeoPositionInfo::Direction );\n}\n\nQDateTime QtPositioningPositionProviderPlugin::timestamp() const\n{\n if ( d->m_source == 0 ) {\n return QDateTime();\n }\n\n return d->m_source->lastKnownPosition().timestamp();\n}\n\nvoid QtPositioningPositionProviderPlugin::update()\n{\n PositionProviderStatus newStatus = PositionProviderStatusAcquiring;\n if ( d->m_source ) {\n if ( d->m_source->lastKnownPosition().isValid() ) {\n newStatus = PositionProviderStatusAvailable;\n }\n else {\n newStatus = PositionProviderStatusError;\n }\n }\n\n if ( newStatus != d->m_status ) {\n d->m_status = newStatus;\n emit statusChanged( newStatus );\n }\n\n if ( newStatus == PositionProviderStatusAvailable ) {\n emit positionChanged( position(), accuracy() );\n }\n}\n\n} \/\/ namespace Marble\n\nQ_EXPORT_PLUGIN2( Marble::QtMobilityPositionProviderPlugin, Marble::QtMobilityPositionProviderPlugin )\n\n#include \"moc_QtPositioningPositionProviderPlugin.cpp\"\nFix typo\/\/\n\/\/ This file is part of the Marble Virtual Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2011 Daniel Marth \n\/\/ Copyright 2012 Bernhard Beschow \n\/\/\n\n#include \"QtPositioningPositionProviderPlugin.h\"\n\n#include \n#include \n#include \n\n#if QT_VERSION < 0x050000\n\nQTM_USE_NAMESPACE\n\n#endif\n\nnamespace Marble {\n\nclass QtPositioningPositionProviderPluginPrivate\n{\npublic:\n QtPositioningPositionProviderPluginPrivate();\n\n QGeoPositionInfoSource *const m_source;\n PositionProviderStatus m_status;\n};\n\nQtPositioningPositionProviderPluginPrivate::QtPositioningPositionProviderPluginPrivate() :\n m_source( QGeoPositionInfoSource::createDefaultSource( 0 ) ),\n m_status( PositionProviderStatusAcquiring )\n{\n}\n\nQString QtPositioningPositionProviderPlugin::name() const\n{\n return tr( \"Qt Positioning Position Provider Plugin\" );\n}\n\nQString QtPositioningPositionProviderPlugin::nameId() const\n{\n return \"QtPositioning\";\n}\n\nQString QtPositioningPositionProviderPlugin::guiString() const\n{\n return tr( \"Qt Positioning Location\" );\n}\n\nQString QtPositioningPositionProviderPlugin::version() const\n{\n return \"1.0\";\n}\n\nQString QtPositioningPositionProviderPlugin::description() const\n{\n return tr( \"Reports the GPS position of a QtPositioning compatible device.\" );\n}\n\nQString QtPositioningPositionProviderPlugin::copyrightYears() const\n{\n return \"2011\";\n}\n\nQList QtPositioningPositionProviderPlugin::pluginAuthors() const\n{\n return QList()\n << PluginAuthor( \"Daniel Marth\", \"danielmarth@gmx.at\" );\n}\n\nQIcon QtPositioningPositionProviderPlugin::icon() const\n{\n return QIcon();\n}\n\nPositionProviderPlugin* QtPositioningPositionProviderPlugin::newInstance() const\n{\n return new QtPositioningPositionProviderPlugin;\n}\n\nPositionProviderStatus QtPositioningPositionProviderPlugin::status() const\n{\n return d->m_status;\n}\n\nGeoDataCoordinates QtPositioningPositionProviderPlugin::position() const\n{\n if ( d->m_source == 0 ) {\n return GeoDataCoordinates();\n }\n\n const QGeoCoordinate p = d->m_source->lastKnownPosition().coordinate();\n if( !p.isValid() ) {\n return GeoDataCoordinates();\n }\n\n return GeoDataCoordinates( p.longitude(), p.latitude(),\n p.altitude(), GeoDataCoordinates::Degree );\n}\n\nGeoDataAccuracy QtPositioningPositionProviderPlugin::accuracy() const\n{\n if ( d->m_source == 0 ) {\n return GeoDataAccuracy();\n }\n\n const QGeoPositionInfo info = d->m_source->lastKnownPosition();\n\n if( !info.hasAttribute( QGeoPositionInfo::HorizontalAccuracy ) ||\n !info.hasAttribute( QGeoPositionInfo::VerticalAccuracy ) ) {\n return GeoDataAccuracy();\n }\n\n const qreal horizontal = info.attribute( QGeoPositionInfo::HorizontalAccuracy );\n const qreal vertical = info.attribute( QGeoPositionInfo::VerticalAccuracy );\n\n return GeoDataAccuracy( GeoDataAccuracy::Detailed, horizontal, vertical );\n}\n\nQtPositioningPositionProviderPlugin::QtPositioningPositionProviderPlugin() :\n d( new QtPositioningPositionProviderPluginPrivate )\n{\n}\n\nQtPositioningPositionProviderPlugin::~QtPositioningPositionProviderPlugin()\n{\n delete d;\n}\n\nvoid QtPositioningPositionProviderPlugin::initialize()\n{\n if( d->m_source ) {\n connect( d->m_source, SIGNAL(positionUpdated(QGeoPositionInfo)), this, SLOT(update()) );\n d->m_source->setUpdateInterval( 1000 );\n d->m_source->startUpdates();\n }\n}\n\nbool QtPositioningPositionProviderPlugin::isInitialized() const\n{\n return d->m_source != 0;\n}\n\nqreal QtPositioningPositionProviderPlugin::speed() const\n{\n if ( d->m_source == 0 ) {\n return 0.0;\n }\n\n if( !d->m_source->lastKnownPosition().hasAttribute( QGeoPositionInfo::GroundSpeed ) ) {\n return 0.0;\n }\n\n return d->m_source->lastKnownPosition().attribute( QGeoPositionInfo::GroundSpeed );\n}\n\nqreal QtPositioningPositionProviderPlugin::direction() const\n{\n if ( d->m_source == 0 ) {\n return 0.0;\n }\n\n if( !d->m_source->lastKnownPosition().hasAttribute( QGeoPositionInfo::Direction ) ) {\n return 0.0;\n }\n\n return d->m_source->lastKnownPosition().attribute( QGeoPositionInfo::Direction );\n}\n\nQDateTime QtPositioningPositionProviderPlugin::timestamp() const\n{\n if ( d->m_source == 0 ) {\n return QDateTime();\n }\n\n return d->m_source->lastKnownPosition().timestamp();\n}\n\nvoid QtPositioningPositionProviderPlugin::update()\n{\n PositionProviderStatus newStatus = PositionProviderStatusAcquiring;\n if ( d->m_source ) {\n if ( d->m_source->lastKnownPosition().isValid() ) {\n newStatus = PositionProviderStatusAvailable;\n }\n else {\n newStatus = PositionProviderStatusError;\n }\n }\n\n if ( newStatus != d->m_status ) {\n d->m_status = newStatus;\n emit statusChanged( newStatus );\n }\n\n if ( newStatus == PositionProviderStatusAvailable ) {\n emit positionChanged( position(), accuracy() );\n }\n}\n\n} \/\/ namespace Marble\n\nQ_EXPORT_PLUGIN2( Marble::QtMobilityPositionProviderPlugin, Marble::QtMobilityPositionProviderPlugin )\n\n#include \"moc_QtPositioningPositionProviderPlugin.cpp\"\n<|endoftext|>"} {"text":"#include \"board.h\"\n#include \"renderer.h\"\n#include \"sound.h\"\n\n#include \n#include \n\n#include \n\n\nint main(int argc, char* argv[])\n{\n \/\/ create world\n Board board(8, 8);\n board.initBallsRandom(5);\n \n Renderer renderer;\n\n \/\/ create window\n sf::ContextSettings contextSettings;\n contextSettings.depthBits = 32;\n\n sf::Window window(sf::VideoMode(800, 600), \"ORDO\", sf::Style::Default, contextSettings);\n window.setVerticalSyncEnabled(true);\n\n \n \/\/ start main loop\n sf::Clock clock;\n \n while (window.isOpen())\n {\n \/\/ process events\n sf::Event event;\n \n while (window.pollEvent(event))\n {\n \/\/ close window -> exit\n if (event.type == sf::Event::Closed) {\n window.close();\n }\n \n \/\/ escape key -> exit\n if (event.type == sf::Event::KeyPressed)\n {\n switch (event.key.code)\n {\n case sf::Keyboard::Escape:\n window.close();\n break;\n \n default:\n break;\n }\n }\n \n \/\/ resize viewport\n if (event.type == sf::Event::Resized) {\n glViewport(0, 0, event.size.width, event.size.height);\n }\n }\n \n \/\/ render everything\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n \n renderer.drawBoard(board);\n \n window.display();\n }\n \n \n \n \n\/\/ FMOD_RESULT result;\n\/\/ \n\/\/ \/\/ init system\n\/\/ FMOD::System* system = 0;\n\/\/ FMOD::System_Create(&system);\n\/\/ \n\/\/ result = system->setOutput(FMOD_OUTPUTTYPE_COREAUDIO); FMOD::check(result);\n\/\/ result = system->setSpeakerMode(FMOD_SPEAKERMODE_STEREO); FMOD::check(result);\n\/\/ result = system->init(64, FMOD_INIT_NORMAL | FMOD_INIT_3D_RIGHTHANDED, 0); FMOD::check(result);\n\/\/ \n\/\/ \/\/ create sound\n\/\/ FMOD_CREATESOUNDEXINFO exinfo;\n\/\/ memset(&exinfo, 0, sizeof(FMOD_CREATESOUNDEXINFO));\n\/\/ \n\/\/ exinfo.cbsize = sizeof(FMOD_CREATESOUNDEXINFO);\n\/\/ exinfo.numchannels = 2;\n\/\/ exinfo.defaultfrequency = 44100;\n\/\/ exinfo.format = FMOD_SOUND_FORMAT_PCMFLOAT;\n\/\/ exinfo.length = exinfo.defaultfrequency * sizeof(float) * exinfo.numchannels * 1.0f;\n\/\/ \n\/\/ FMOD::Sound* sound = 0;\n\/\/ result = system->createSound(0, FMOD_3D | FMOD_SOFTWARE | FMOD_OPENUSER, &exinfo, &sound); FMOD::check(result);\n\/\/\n\/\/ FMOD::DSP* dsp = 0;\n\/\/ result = system->createDSPByType(FMOD_DSP_TYPE_OSCILLATOR, &dsp); FMOD::check(result);\n\/\/ result = dsp->setParameter(FMOD_DSP_OSCILLATOR_RATE, 440.0f); FMOD::check(result);\n\/\/ result = dsp->setParameter(FMOD_DSP_OSCILLATOR_TYPE, 2); FMOD::check(result);\n\/\/ \n\/\/ FMOD::Channel* channel = 0;\n\/\/ result = system->playDSP(FMOD_CHANNEL_FREE, dsp, false, &channel); FMOD::check(result);\n\/\/ \n\/\/ \/\/ create geometry\n\/\/ FMOD::Geometry* geometry;\n\/\/ result = system->setGeometrySettings(100); FMOD::check(result);\n\/\/ result = system->createGeometry(1024, 4096, &geometry); FMOD::check(result);\n\/\/ \n\/\/ int index = 0;\n\/\/\/\/ FMOD_VECTOR vertices[4] = {{-1, -1,-1}, {1, -1,-1}, {1, 1,-1}, {-1, 1,-1}};\n\/\/ FMOD_VECTOR vertices[4] = {{-1, -1, 1}, {1, -1, 1}, {1, 1, 1}, {-1, 1, 1}};\n\/\/ geometry->addPolygon(1.0, 1.0, true, 4, vertices, &index);\n\/\/ geometry->setPolygonAttributes(0, 0.9, 0.9, true);\n\/\/\n\/\/ \/\/ position objects\n\/\/ FMOD_VECTOR lpos = {0, 0, 0};\n\/\/ FMOD_VECTOR lvel = {0, 0, 0};\n\/\/ FMOD_VECTOR lfwd = {0, 0, 1};\n\/\/ FMOD_VECTOR lup = {0, 1, 0};\n\/\/ result = system->set3DListenerAttributes(0, &lpos, &lvel, &lfwd, &lup);\n\/\/ \n\/\/ float angle = 0.0f;\n\/\/ std::random_device rnd;\n\/\/ std::uniform_int_distribution<> uni(0, 1);\n\/\/ int dir = 2 * (uni(rnd)) - 1;\n\/\/ float v0 = dir * 2.0f;\n\/\/ float radius = 10.0f;\n\/\/ \n\/\/ std::cout << dir << std::endl;\n\/\/ \n\/\/ FMOD_VECTOR cpos = {0, 0, radius};\n\/\/ FMOD_VECTOR cvel = {v0, 0, 0};\n\/\/ result = channel->setMode(FMOD_3D); FMOD::check(result);\n\/\/ result = channel->set3DAttributes(&cpos, &cvel); FMOD::check(result);\n\/\/ \n\/\/ \/\/ main simulation\n\/\/ using namespace std::chrono;\n\/\/ high_resolution_clock::time_point t0 = high_resolution_clock::now();\n\/\/ \n\/\/ while (true)\n\/\/ {\n\/\/ if (kbhit()) {\n\/\/ break;\n\/\/ }\n\/\/ \n\/\/ \/\/ update timer\n\/\/ high_resolution_clock::time_point t1 = high_resolution_clock::now();\n\/\/ float dt = duration_cast(t1 - t0).count() \/ 1000.0f;\n\/\/ t0 = t1;\n\/\/ \n\/\/ \/\/ move source\n\/\/ angle = angle + dt * v0;\n\/\/ cpos.x = radius * sinf(angle);\n\/\/ cpos.z = radius * cosf(angle);\n\/\/ cvel.x = v0 * cosf(angle);\n\/\/ cvel.z = v0 * sinf(angle);\n\/\/ \n\/\/ channel->set3DAttributes(&cpos, &cvel);\n\/\/ \n\/\/\/\/ std::cout << cpos << std::endl;\n\/\/ \n\/\/ \/\/ update engine\n\/\/ result = system->update(); FMOD::check(result);\n\/\/ sleep(0.01f);\n\/\/ }\n\/\/\n\/\/ \/\/ release resources\n\/\/ result = dsp->release(); FMOD::check(result);\n\/\/ result = system->release(); FMOD::check(result);\n \n return 0;\n}set up basic main loop. add movement controls#include \"board.h\"\n#include \"renderer.h\"\n#include \"sound.h\"\n\n#include \n\nusing namespace std;\n\n\nint main(int argc, char* argv[])\n{\n \/\/ create world\n Board board(8, 8);\n board.initBallsRandom(5);\n \n Renderer renderer;\n \n \/\/ create window\n bool fullscreen = false;\n \n sf::VideoMode dmode(1440, 900);\n sf::VideoMode fmode = sf::VideoMode::getFullscreenModes()[0];\n string title = \"ORDO\";\n sf::ContextSettings settings(32);\n \n sf::Window window(dmode, title, sf::Style::Default, settings);\n window.setVerticalSyncEnabled(true);\n \n \/\/ start main loop\n sf::Clock clock;\n \n while (window.isOpen())\n {\n \/\/ process events\n sf::Event event;\n \n while (window.pollEvent(event))\n {\n \/\/ close window -> exit\n if (event.type == sf::Event::Closed) {\n window.close();\n }\n \n \/\/ handle keys\n if (event.type == sf::Event::KeyPressed)\n {\n switch (event.key.code)\n {\n \/\/ close on escape\n case sf::Keyboard::Escape:\n window.close();\n break;\n \n \/\/ fullscreen\n case sf::Keyboard::F:\n {\n if (fullscreen) {\n window.create(dmode, title, sf::Style::Default, settings);\n } else {\n window.create(fmode, title, sf::Style::Fullscreen, settings);\n }\n \n fullscreen = !fullscreen;\n break;\n }\n \n \/\/ move player\n case sf::Keyboard::Right:\n board.movePlayerRight();\n break;\n \n case sf::Keyboard::Left:\n board.movePlayerLeft();\n break;\n \n \/\/ shoot\n case sf::Keyboard::Space:\n cout << \"SHOOT!\" << endl;\n break;\n \n default:\n break;\n }\n }\n \n \/\/ resize viewport\n if (event.type == sf::Event::Resized) {\n glViewport(0, 0, event.size.width, event.size.height);\n }\n }\n \n \/\/ render everything\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n \n renderer.drawBoard(board);\n \n window.display();\n }\n \n \n \n \n\/\/ FMOD_RESULT result;\n\/\/ \n\/\/ \/\/ init system\n\/\/ FMOD::System* system = 0;\n\/\/ FMOD::System_Create(&system);\n\/\/ \n\/\/ result = system->setOutput(FMOD_OUTPUTTYPE_COREAUDIO); FMOD::check(result);\n\/\/ result = system->setSpeakerMode(FMOD_SPEAKERMODE_STEREO); FMOD::check(result);\n\/\/ result = system->init(64, FMOD_INIT_NORMAL | FMOD_INIT_3D_RIGHTHANDED, 0); FMOD::check(result);\n\/\/ \n\/\/ \/\/ create sound\n\/\/ FMOD_CREATESOUNDEXINFO exinfo;\n\/\/ memset(&exinfo, 0, sizeof(FMOD_CREATESOUNDEXINFO));\n\/\/ \n\/\/ exinfo.cbsize = sizeof(FMOD_CREATESOUNDEXINFO);\n\/\/ exinfo.numchannels = 2;\n\/\/ exinfo.defaultfrequency = 44100;\n\/\/ exinfo.format = FMOD_SOUND_FORMAT_PCMFLOAT;\n\/\/ exinfo.length = exinfo.defaultfrequency * sizeof(float) * exinfo.numchannels * 1.0f;\n\/\/ \n\/\/ FMOD::Sound* sound = 0;\n\/\/ result = system->createSound(0, FMOD_3D | FMOD_SOFTWARE | FMOD_OPENUSER, &exinfo, &sound); FMOD::check(result);\n\/\/\n\/\/ FMOD::DSP* dsp = 0;\n\/\/ result = system->createDSPByType(FMOD_DSP_TYPE_OSCILLATOR, &dsp); FMOD::check(result);\n\/\/ result = dsp->setParameter(FMOD_DSP_OSCILLATOR_RATE, 440.0f); FMOD::check(result);\n\/\/ result = dsp->setParameter(FMOD_DSP_OSCILLATOR_TYPE, 2); FMOD::check(result);\n\/\/ \n\/\/ FMOD::Channel* channel = 0;\n\/\/ result = system->playDSP(FMOD_CHANNEL_FREE, dsp, false, &channel); FMOD::check(result);\n\/\/ \n\/\/ \/\/ create geometry\n\/\/ FMOD::Geometry* geometry;\n\/\/ result = system->setGeometrySettings(100); FMOD::check(result);\n\/\/ result = system->createGeometry(1024, 4096, &geometry); FMOD::check(result);\n\/\/ \n\/\/ int index = 0;\n\/\/\/\/ FMOD_VECTOR vertices[4] = {{-1, -1,-1}, {1, -1,-1}, {1, 1,-1}, {-1, 1,-1}};\n\/\/ FMOD_VECTOR vertices[4] = {{-1, -1, 1}, {1, -1, 1}, {1, 1, 1}, {-1, 1, 1}};\n\/\/ geometry->addPolygon(1.0, 1.0, true, 4, vertices, &index);\n\/\/ geometry->setPolygonAttributes(0, 0.9, 0.9, true);\n\/\/\n\/\/ \/\/ position objects\n\/\/ FMOD_VECTOR lpos = {0, 0, 0};\n\/\/ FMOD_VECTOR lvel = {0, 0, 0};\n\/\/ FMOD_VECTOR lfwd = {0, 0, 1};\n\/\/ FMOD_VECTOR lup = {0, 1, 0};\n\/\/ result = system->set3DListenerAttributes(0, &lpos, &lvel, &lfwd, &lup);\n\/\/ \n\/\/ float angle = 0.0f;\n\/\/ std::random_device rnd;\n\/\/ std::uniform_int_distribution<> uni(0, 1);\n\/\/ int dir = 2 * (uni(rnd)) - 1;\n\/\/ float v0 = dir * 2.0f;\n\/\/ float radius = 10.0f;\n\/\/ \n\/\/ std::cout << dir << std::endl;\n\/\/ \n\/\/ FMOD_VECTOR cpos = {0, 0, radius};\n\/\/ FMOD_VECTOR cvel = {v0, 0, 0};\n\/\/ result = channel->setMode(FMOD_3D); FMOD::check(result);\n\/\/ result = channel->set3DAttributes(&cpos, &cvel); FMOD::check(result);\n\/\/ \n\/\/ \/\/ main simulation\n\/\/ using namespace std::chrono;\n\/\/ high_resolution_clock::time_point t0 = high_resolution_clock::now();\n\/\/ \n\/\/ while (true)\n\/\/ {\n\/\/ if (kbhit()) {\n\/\/ break;\n\/\/ }\n\/\/ \n\/\/ \/\/ update timer\n\/\/ high_resolution_clock::time_point t1 = high_resolution_clock::now();\n\/\/ float dt = duration_cast(t1 - t0).count() \/ 1000.0f;\n\/\/ t0 = t1;\n\/\/ \n\/\/ \/\/ move source\n\/\/ angle = angle + dt * v0;\n\/\/ cpos.x = radius * sinf(angle);\n\/\/ cpos.z = radius * cosf(angle);\n\/\/ cvel.x = v0 * cosf(angle);\n\/\/ cvel.z = v0 * sinf(angle);\n\/\/ \n\/\/ channel->set3DAttributes(&cpos, &cvel);\n\/\/ \n\/\/\/\/ std::cout << cpos << std::endl;\n\/\/ \n\/\/ \/\/ update engine\n\/\/ result = system->update(); FMOD::check(result);\n\/\/ sleep(0.01f);\n\/\/ }\n\/\/\n\/\/ \/\/ release resources\n\/\/ result = dsp->release(); FMOD::check(result);\n\/\/ result = system->release(); FMOD::check(result);\n \n return 0;\n}<|endoftext|>"} {"text":"\/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \n#include \n\n#include \"llvm\/ADT\/ArrayRef.h\"\n#include \"llvm\/ADT\/Optional.h\"\n#include \"llvm\/ADT\/STLExtras.h\"\n#include \"llvm\/ADT\/SmallVector.h\"\n#include \"llvm\/ADT\/StringRef.h\"\n#include \"llvm\/Support\/Casting.h\"\n#include \"mlir\/IR\/Attributes.h\" \/\/ from @llvm-project\n#include \"mlir\/IR\/Block.h\" \/\/ from @llvm-project\n#include \"mlir\/IR\/Builders.h\" \/\/ from @llvm-project\n#include \"mlir\/IR\/BuiltinAttributes.h\" \/\/ from @llvm-project\n#include \"mlir\/IR\/BuiltinOps.h\" \/\/ from @llvm-project\n#include \"mlir\/IR\/Operation.h\" \/\/ from @llvm-project\n#include \"mlir\/IR\/Value.h\" \/\/ from @llvm-project\n#include \"mlir\/Interfaces\/CallInterfaces.h\" \/\/ from @llvm-project\n#include \"mlir\/Pass\/Pass.h\" \/\/ from @llvm-project\n#include \"mlir\/Pass\/PassRegistry.h\" \/\/ from @llvm-project\n#include \"tensorflow\/compiler\/mlir\/tensorflow\/ir\/tf_device.h\"\n#include \"tensorflow\/compiler\/mlir\/tensorflow\/ir\/tf_ops.h\"\n#include \"tensorflow\/compiler\/mlir\/tensorflow\/utils\/xla_sharding_util.h\"\n#include \"tensorflow\/compiler\/xla\/client\/sharding_builder.h\"\n\nnamespace mlir {\nnamespace TFTPU {\nnamespace {\n\nconstexpr char kShardingAttr[] = \"mhlo.sharding\";\nconstexpr char kReplicateSharding[] = \"\";\n\nstruct TPUShardingIdentificationPass\n : public PassWrapper> {\n void runOnOperation() override;\n};\n\n\/\/ Returns XLA sharding from TPUPartitionedInput op connected to a\n\/\/ `tf_device.cluster_func` operand value. If value is a resource type then\n\/\/ TPUPartitionedInput op will be connected to a ReadVariable op that feeds into\n\/\/ a `tf_device.cluster_func`.\nllvm::Optional GetXlaShardingFromOperand(Value value) {\n Value value_to_visit = value;\n if (auto read_var = llvm::dyn_cast_or_null(\n value_to_visit.getDefiningOp()))\n value_to_visit = read_var.resource();\n\n if (auto partitioned_input =\n llvm::dyn_cast_or_null(\n value_to_visit.getDefiningOp()))\n return partitioned_input._XlaSharding();\n\n return llvm::None;\n}\n\n\/\/ Returns XLA sharding from a XlaSharding op connected to an argument value. If\n\/\/ value is a resource type then XlaSharding op will be connected to a\n\/\/ ReadVariable op. XlaSharding op may be direct user of inputs but it may also\n\/\/ be followed by an Identity op and, in the case where bfloat16 type is used,\n\/\/ Cast op may be added right after the input.\n\/\/\n\/\/ TODO(hongjunchoi): Add logic to parse XlaSharding op inside control flow (If,\n\/\/ Case, While) ops and Caller return values.\n\/\/ TODO(hongjunchoi): Consider explicitly checking op patterns to detect sharded\n\/\/ inputs.\nllvm::Optional GetXlaShardingFromArg(Value value) {\n llvm::SmallPtrSet visited_values;\n llvm::SmallVector values_to_visit{value};\n while (!values_to_visit.empty()) {\n llvm::SmallVector next_values_to_visit;\n for (Value value_to_visit : values_to_visit) {\n if (!visited_values.insert(value_to_visit).second) continue;\n\n for (auto& use : value_to_visit.getUses()) {\n Operation* owner = use.getOwner();\n if (auto sharding = llvm::dyn_cast(owner))\n return sharding._XlaSharding();\n\n if (llvm::isa(owner)) {\n next_values_to_visit.push_back(use.getOwner()->getResult(0));\n continue;\n }\n\n if (auto call_op = llvm::dyn_cast(owner)) {\n FuncOp func = llvm::dyn_cast(call_op.resolveCallable());\n if (!func) continue;\n next_values_to_visit.push_back(\n func.getArgument(use.getOperandNumber()));\n }\n }\n }\n\n values_to_visit.swap(next_values_to_visit);\n }\n\n return llvm::None;\n}\n\n\/\/ Extracts sharding configurations for all inputs by parsing XlaSharding\/\n\/\/ TPUPartitionedInput op connected to the operands\/arguments. If argument to\n\/\/ the `cluster_func` directly feeds into another function call op, then\n\/\/ recursively walk the function definition to find the connected XlaSharding\n\/\/ op.\nvoid IdentifyXlaShardingForComputationInputs(\n StringRef logical_core_0_sharding, bool use_spmd,\n tf_device::ClusterFuncOp cluster_func, FuncOp func, Builder* builder) {\n \/\/ Look up function definition from module.\n Block& function_block = func.front();\n\n llvm::SmallVector sharding_for_args;\n sharding_for_args.reserve(function_block.getNumArguments());\n\n \/\/ Iterate through operands of `cluster_func`.\n \/\/ The computation operand can either be:\n \/\/ 1) a TPUPartitionedInput Op if the input has a non-resource type;\n \/\/ 2) a ReadVariableOp else.\n \/\/\n \/\/ Replicate sharding is used if `use_spmd` is set.\n \/\/\n \/\/ Iterate through input arguments to the entry block of\n \/\/ tf_device.ClusterFunc. For input ops, look for XlaSharding ops.\n \/\/ XlaSharding ops can:\n \/\/ 1) Directly follow the input argument if input argument has non-resource\n \/\/ types.\n \/\/ 2) Follow ReadVariableOp if the input type is of resource type.\n \/\/ 3) Follow IdentityOp or CastOp after above cases (1), (2).\n \/\/\n \/\/ Sharding configurations are added to the tf_device.ClusterFunc as an\n \/\/ attribute and the function as an argument attribute.\n for (auto operand_and_arg :\n llvm::zip(cluster_func.operands(), function_block.getArguments())) {\n Value operand = std::get<0>(operand_and_arg);\n BlockArgument arg = std::get<1>(operand_and_arg);\n const int index = arg.getArgNumber();\n\n if (auto operand_sharding = GetXlaShardingFromOperand(operand)) {\n sharding_for_args.push_back(operand_sharding.getValue());\n func.setArgAttr(index, kShardingAttr,\n builder->getStringAttr(operand_sharding.getValue()));\n continue;\n }\n\n if (use_spmd) {\n \/\/ If XLA SPMD is enabled, host variables or non-variable per-replica\n \/\/ inputs should take on replicate sharding, unless another sharding is\n \/\/ set via a TPUPartitionedInput op.\n sharding_for_args.push_back(kReplicateSharding);\n func.setArgAttr(index, kShardingAttr,\n builder->getStringAttr(kReplicateSharding));\n continue;\n }\n\n auto arg_sharding = GetXlaShardingFromArg(arg);\n if (arg_sharding) {\n sharding_for_args.push_back(arg_sharding.getValue());\n func.setArgAttr(index, kShardingAttr,\n builder->getStringAttr(arg_sharding.getValue()));\n continue;\n }\n\n \/\/ Default to maximal sharding core 0 if no sharding is present.\n sharding_for_args.push_back(logical_core_0_sharding);\n func.setArgAttr(index, kShardingAttr,\n builder->getStringAttr(logical_core_0_sharding));\n }\n\n cluster_func->setAttr(tensorflow::kInputShardingAttr,\n builder->getStrArrayAttr(sharding_for_args));\n}\n\n\/\/ Returns XLA sharding from TPUPartitionedOutput op connected to a\n\/\/ `tf_device.cluster_func` result value.\nllvm::Optional GetXlaShardingFromResult(Value value) {\n if (!value.hasOneUse()) return llvm::None;\n\n Operation* user = *value.getUsers().begin();\n if (auto partitioned_output =\n llvm::dyn_cast(user))\n return partitioned_output._XlaSharding();\n\n return llvm::None;\n}\n\n\/\/ Returns XLA sharding from XlaSharding op connected to a result value.\n\/\/ XlaSharding op may be direct user of inputs but it may also be followed by an\n\/\/ Identity op and, in the case where bfloat16 type is used, Cast op may be\n\/\/ added right after the input.\n\/\/\n\/\/ TODO(hongjunchoi): Add logic to parse XlaSharding op inside control flow (If,\n\/\/ Case, While) ops and Caller argument values.\n\/\/ TODO(hongjunchoi): Consider explicitly checking op patterns to detect sharded\n\/\/ inputs.\nllvm::Optional GetXlaShardingFromRetval(Value value) {\n llvm::SmallPtrSet visited_values;\n Value value_to_visit = value;\n while (value_to_visit) {\n if (!visited_values.insert(value_to_visit).second) return llvm::None;\n\n Operation* def = value_to_visit.getDefiningOp();\n if (auto sharding = llvm::dyn_cast_or_null(def))\n return sharding._XlaSharding();\n\n if (llvm::isa_and_nonnull(def)) {\n value_to_visit = def->getOperand(0);\n continue;\n }\n\n if (auto call_op = llvm::dyn_cast_or_null(def)) {\n FuncOp func = llvm::dyn_cast(call_op.resolveCallable());\n if (!func) continue;\n value_to_visit = func.front().getTerminator()->getOperand(\n value_to_visit.cast().getResultNumber());\n continue;\n }\n\n break;\n }\n\n return llvm::None;\n}\n\n\/\/ Extracts sharding configurations for all outputs by parsing XlaSharding\/\n\/\/ TPUPartitionedOutput op connected to the retvals\/results.\nvoid IdentifyXlaShardingForComputationOutputs(\n StringRef logical_core_0_sharding, bool use_spmd,\n tf_device::ClusterFuncOp cluster_func, FuncOp func, Builder* builder) {\n Block& function_block = func.front();\n Operation* terminator = function_block.getTerminator();\n llvm::SmallVector sharding_for_rets;\n sharding_for_rets.reserve(terminator->getNumOperands());\n\n \/\/ Iterate through results of `cluster_func`. For output ops, look for\n \/\/ TPUPartitionedOutput ops.\n \/\/\n \/\/ Replicate sharding is used if `use_spmd` is set.\n \/\/\n \/\/ Iterate through operands of the terminator. If the preceding op is\n \/\/ XlaShardingOp, then the provided sharding configuration is added to the\n \/\/ tf_device.ClusterFunc as an attribute and the function as a result\n \/\/ attribute.\n for (auto result_and_retval :\n llvm::zip(cluster_func.results(), terminator->getOpOperands())) {\n Value result = std::get<0>(result_and_retval);\n OpOperand& retval = std::get<1>(result_and_retval);\n const int index = retval.getOperandNumber();\n\n if (auto result_sharding = GetXlaShardingFromResult(result)) {\n sharding_for_rets.push_back(result_sharding.getValue());\n func.setResultAttr(index, kShardingAttr,\n builder->getStringAttr(result_sharding.getValue()));\n continue;\n }\n\n if (use_spmd) {\n \/\/ If XLA SPMD is enabled, outputs all should have replicate sharding,\n \/\/ unless another sharding is set via a TPUPartitionedOutput op.\n sharding_for_rets.push_back(kReplicateSharding);\n func.setResultAttr(index, kShardingAttr,\n builder->getStringAttr(kReplicateSharding));\n continue;\n }\n\n if (auto retval_sharding = GetXlaShardingFromRetval(retval.get())) {\n sharding_for_rets.push_back(retval_sharding.getValue());\n func.setResultAttr(index, kShardingAttr,\n builder->getStringAttr(retval_sharding.getValue()));\n continue;\n }\n\n \/\/ Default to maximal sharding core 0 if no sharding is present.\n sharding_for_rets.push_back(logical_core_0_sharding);\n func.setResultAttr(index, kShardingAttr,\n builder->getStringAttr(logical_core_0_sharding));\n }\n\n cluster_func->setAttr(tensorflow::kOutputShardingAttr,\n builder->getStrArrayAttr(sharding_for_rets));\n}\n\n\/\/ Extracts input\/output sharding configuration of `cluster_func` by parsing\n\/\/ XlaSharding ops inside the `cluster_func`.\nvoid IdentifyXlaShardingForTPUComputation(\n Builder* builder, tf_device::ClusterFuncOp cluster_func) {\n \/\/ Look up function definition from module.\n FuncOp func = cluster_func->getParentOfType().lookupSymbol(\n cluster_func.func());\n\n \/\/ By default inputs\/outputs have maximal sharding and are assigned to logical\n \/\/ core 0 if no sharding is defined.\n const std::string logical_core_0_sharding =\n xla::sharding_builder::AssignDevice(0).SerializeAsString();\n\n bool use_spmd = false;\n if (auto use_spmd_attr =\n cluster_func.getAttrOfType(\"use_spmd_for_xla_partitioning\"))\n use_spmd = use_spmd_attr.getValue();\n\n IdentifyXlaShardingForComputationInputs(logical_core_0_sharding, use_spmd,\n cluster_func, func, builder);\n\n IdentifyXlaShardingForComputationOutputs(logical_core_0_sharding, use_spmd,\n cluster_func, func, builder);\n}\n\nvoid TPUShardingIdentificationPass::runOnOperation() {\n Builder builder(getOperation().getContext());\n\n getOperation().walk([&](tf_device::ClusterFuncOp cluster_func) {\n IdentifyXlaShardingForTPUComputation(&builder, cluster_func);\n });\n}\n\n} \/\/ anonymous namespace\n\nstd::unique_ptr> CreateTPUShardingIdentificationPass() {\n return std::make_unique();\n}\n\nstatic PassRegistration pass(\n \"tf-tpu-sharding-identification\",\n \"Identifies and handles inputs\/outputs of TPU computation that is \"\n \"sharded across logical cores.\");\n\n} \/\/ namespace TFTPU\n} \/\/ namespace mlir\nUse mlir::OpState::operator->() to get to methods of mlir::Operation.\/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \n#include \n\n#include \"llvm\/ADT\/ArrayRef.h\"\n#include \"llvm\/ADT\/Optional.h\"\n#include \"llvm\/ADT\/STLExtras.h\"\n#include \"llvm\/ADT\/SmallVector.h\"\n#include \"llvm\/ADT\/StringRef.h\"\n#include \"llvm\/Support\/Casting.h\"\n#include \"mlir\/IR\/Attributes.h\" \/\/ from @llvm-project\n#include \"mlir\/IR\/Block.h\" \/\/ from @llvm-project\n#include \"mlir\/IR\/Builders.h\" \/\/ from @llvm-project\n#include \"mlir\/IR\/BuiltinAttributes.h\" \/\/ from @llvm-project\n#include \"mlir\/IR\/BuiltinOps.h\" \/\/ from @llvm-project\n#include \"mlir\/IR\/Operation.h\" \/\/ from @llvm-project\n#include \"mlir\/IR\/Value.h\" \/\/ from @llvm-project\n#include \"mlir\/Interfaces\/CallInterfaces.h\" \/\/ from @llvm-project\n#include \"mlir\/Pass\/Pass.h\" \/\/ from @llvm-project\n#include \"mlir\/Pass\/PassRegistry.h\" \/\/ from @llvm-project\n#include \"tensorflow\/compiler\/mlir\/tensorflow\/ir\/tf_device.h\"\n#include \"tensorflow\/compiler\/mlir\/tensorflow\/ir\/tf_ops.h\"\n#include \"tensorflow\/compiler\/mlir\/tensorflow\/utils\/xla_sharding_util.h\"\n#include \"tensorflow\/compiler\/xla\/client\/sharding_builder.h\"\n\nnamespace mlir {\nnamespace TFTPU {\nnamespace {\n\nconstexpr char kShardingAttr[] = \"mhlo.sharding\";\nconstexpr char kReplicateSharding[] = \"\";\n\nstruct TPUShardingIdentificationPass\n : public PassWrapper> {\n void runOnOperation() override;\n};\n\n\/\/ Returns XLA sharding from TPUPartitionedInput op connected to a\n\/\/ `tf_device.cluster_func` operand value. If value is a resource type then\n\/\/ TPUPartitionedInput op will be connected to a ReadVariable op that feeds into\n\/\/ a `tf_device.cluster_func`.\nllvm::Optional GetXlaShardingFromOperand(Value value) {\n Value value_to_visit = value;\n if (auto read_var = llvm::dyn_cast_or_null(\n value_to_visit.getDefiningOp()))\n value_to_visit = read_var.resource();\n\n if (auto partitioned_input =\n llvm::dyn_cast_or_null(\n value_to_visit.getDefiningOp()))\n return partitioned_input._XlaSharding();\n\n return llvm::None;\n}\n\n\/\/ Returns XLA sharding from a XlaSharding op connected to an argument value. If\n\/\/ value is a resource type then XlaSharding op will be connected to a\n\/\/ ReadVariable op. XlaSharding op may be direct user of inputs but it may also\n\/\/ be followed by an Identity op and, in the case where bfloat16 type is used,\n\/\/ Cast op may be added right after the input.\n\/\/\n\/\/ TODO(hongjunchoi): Add logic to parse XlaSharding op inside control flow (If,\n\/\/ Case, While) ops and Caller return values.\n\/\/ TODO(hongjunchoi): Consider explicitly checking op patterns to detect sharded\n\/\/ inputs.\nllvm::Optional GetXlaShardingFromArg(Value value) {\n llvm::SmallPtrSet visited_values;\n llvm::SmallVector values_to_visit{value};\n while (!values_to_visit.empty()) {\n llvm::SmallVector next_values_to_visit;\n for (Value value_to_visit : values_to_visit) {\n if (!visited_values.insert(value_to_visit).second) continue;\n\n for (auto& use : value_to_visit.getUses()) {\n Operation* owner = use.getOwner();\n if (auto sharding = llvm::dyn_cast(owner))\n return sharding._XlaSharding();\n\n if (llvm::isa(owner)) {\n next_values_to_visit.push_back(use.getOwner()->getResult(0));\n continue;\n }\n\n if (auto call_op = llvm::dyn_cast(owner)) {\n FuncOp func = llvm::dyn_cast(call_op.resolveCallable());\n if (!func) continue;\n next_values_to_visit.push_back(\n func.getArgument(use.getOperandNumber()));\n }\n }\n }\n\n values_to_visit.swap(next_values_to_visit);\n }\n\n return llvm::None;\n}\n\n\/\/ Extracts sharding configurations for all inputs by parsing XlaSharding\/\n\/\/ TPUPartitionedInput op connected to the operands\/arguments. If argument to\n\/\/ the `cluster_func` directly feeds into another function call op, then\n\/\/ recursively walk the function definition to find the connected XlaSharding\n\/\/ op.\nvoid IdentifyXlaShardingForComputationInputs(\n StringRef logical_core_0_sharding, bool use_spmd,\n tf_device::ClusterFuncOp cluster_func, FuncOp func, Builder* builder) {\n \/\/ Look up function definition from module.\n Block& function_block = func.front();\n\n llvm::SmallVector sharding_for_args;\n sharding_for_args.reserve(function_block.getNumArguments());\n\n \/\/ Iterate through operands of `cluster_func`.\n \/\/ The computation operand can either be:\n \/\/ 1) a TPUPartitionedInput Op if the input has a non-resource type;\n \/\/ 2) a ReadVariableOp else.\n \/\/\n \/\/ Replicate sharding is used if `use_spmd` is set.\n \/\/\n \/\/ Iterate through input arguments to the entry block of\n \/\/ tf_device.ClusterFunc. For input ops, look for XlaSharding ops.\n \/\/ XlaSharding ops can:\n \/\/ 1) Directly follow the input argument if input argument has non-resource\n \/\/ types.\n \/\/ 2) Follow ReadVariableOp if the input type is of resource type.\n \/\/ 3) Follow IdentityOp or CastOp after above cases (1), (2).\n \/\/\n \/\/ Sharding configurations are added to the tf_device.ClusterFunc as an\n \/\/ attribute and the function as an argument attribute.\n for (auto operand_and_arg :\n llvm::zip(cluster_func.operands(), function_block.getArguments())) {\n Value operand = std::get<0>(operand_and_arg);\n BlockArgument arg = std::get<1>(operand_and_arg);\n const int index = arg.getArgNumber();\n\n if (auto operand_sharding = GetXlaShardingFromOperand(operand)) {\n sharding_for_args.push_back(operand_sharding.getValue());\n func.setArgAttr(index, kShardingAttr,\n builder->getStringAttr(operand_sharding.getValue()));\n continue;\n }\n\n if (use_spmd) {\n \/\/ If XLA SPMD is enabled, host variables or non-variable per-replica\n \/\/ inputs should take on replicate sharding, unless another sharding is\n \/\/ set via a TPUPartitionedInput op.\n sharding_for_args.push_back(kReplicateSharding);\n func.setArgAttr(index, kShardingAttr,\n builder->getStringAttr(kReplicateSharding));\n continue;\n }\n\n auto arg_sharding = GetXlaShardingFromArg(arg);\n if (arg_sharding) {\n sharding_for_args.push_back(arg_sharding.getValue());\n func.setArgAttr(index, kShardingAttr,\n builder->getStringAttr(arg_sharding.getValue()));\n continue;\n }\n\n \/\/ Default to maximal sharding core 0 if no sharding is present.\n sharding_for_args.push_back(logical_core_0_sharding);\n func.setArgAttr(index, kShardingAttr,\n builder->getStringAttr(logical_core_0_sharding));\n }\n\n cluster_func->setAttr(tensorflow::kInputShardingAttr,\n builder->getStrArrayAttr(sharding_for_args));\n}\n\n\/\/ Returns XLA sharding from TPUPartitionedOutput op connected to a\n\/\/ `tf_device.cluster_func` result value.\nllvm::Optional GetXlaShardingFromResult(Value value) {\n if (!value.hasOneUse()) return llvm::None;\n\n Operation* user = *value.getUsers().begin();\n if (auto partitioned_output =\n llvm::dyn_cast(user))\n return partitioned_output._XlaSharding();\n\n return llvm::None;\n}\n\n\/\/ Returns XLA sharding from XlaSharding op connected to a result value.\n\/\/ XlaSharding op may be direct user of inputs but it may also be followed by an\n\/\/ Identity op and, in the case where bfloat16 type is used, Cast op may be\n\/\/ added right after the input.\n\/\/\n\/\/ TODO(hongjunchoi): Add logic to parse XlaSharding op inside control flow (If,\n\/\/ Case, While) ops and Caller argument values.\n\/\/ TODO(hongjunchoi): Consider explicitly checking op patterns to detect sharded\n\/\/ inputs.\nllvm::Optional GetXlaShardingFromRetval(Value value) {\n llvm::SmallPtrSet visited_values;\n Value value_to_visit = value;\n while (value_to_visit) {\n if (!visited_values.insert(value_to_visit).second) return llvm::None;\n\n Operation* def = value_to_visit.getDefiningOp();\n if (auto sharding = llvm::dyn_cast_or_null(def))\n return sharding._XlaSharding();\n\n if (llvm::isa_and_nonnull(def)) {\n value_to_visit = def->getOperand(0);\n continue;\n }\n\n if (auto call_op = llvm::dyn_cast_or_null(def)) {\n FuncOp func = llvm::dyn_cast(call_op.resolveCallable());\n if (!func) continue;\n value_to_visit = func.front().getTerminator()->getOperand(\n value_to_visit.cast().getResultNumber());\n continue;\n }\n\n break;\n }\n\n return llvm::None;\n}\n\n\/\/ Extracts sharding configurations for all outputs by parsing XlaSharding\/\n\/\/ TPUPartitionedOutput op connected to the retvals\/results.\nvoid IdentifyXlaShardingForComputationOutputs(\n StringRef logical_core_0_sharding, bool use_spmd,\n tf_device::ClusterFuncOp cluster_func, FuncOp func, Builder* builder) {\n Block& function_block = func.front();\n Operation* terminator = function_block.getTerminator();\n llvm::SmallVector sharding_for_rets;\n sharding_for_rets.reserve(terminator->getNumOperands());\n\n \/\/ Iterate through results of `cluster_func`. For output ops, look for\n \/\/ TPUPartitionedOutput ops.\n \/\/\n \/\/ Replicate sharding is used if `use_spmd` is set.\n \/\/\n \/\/ Iterate through operands of the terminator. If the preceding op is\n \/\/ XlaShardingOp, then the provided sharding configuration is added to the\n \/\/ tf_device.ClusterFunc as an attribute and the function as a result\n \/\/ attribute.\n for (auto result_and_retval :\n llvm::zip(cluster_func.results(), terminator->getOpOperands())) {\n Value result = std::get<0>(result_and_retval);\n OpOperand& retval = std::get<1>(result_and_retval);\n const int index = retval.getOperandNumber();\n\n if (auto result_sharding = GetXlaShardingFromResult(result)) {\n sharding_for_rets.push_back(result_sharding.getValue());\n func.setResultAttr(index, kShardingAttr,\n builder->getStringAttr(result_sharding.getValue()));\n continue;\n }\n\n if (use_spmd) {\n \/\/ If XLA SPMD is enabled, outputs all should have replicate sharding,\n \/\/ unless another sharding is set via a TPUPartitionedOutput op.\n sharding_for_rets.push_back(kReplicateSharding);\n func.setResultAttr(index, kShardingAttr,\n builder->getStringAttr(kReplicateSharding));\n continue;\n }\n\n if (auto retval_sharding = GetXlaShardingFromRetval(retval.get())) {\n sharding_for_rets.push_back(retval_sharding.getValue());\n func.setResultAttr(index, kShardingAttr,\n builder->getStringAttr(retval_sharding.getValue()));\n continue;\n }\n\n \/\/ Default to maximal sharding core 0 if no sharding is present.\n sharding_for_rets.push_back(logical_core_0_sharding);\n func.setResultAttr(index, kShardingAttr,\n builder->getStringAttr(logical_core_0_sharding));\n }\n\n cluster_func->setAttr(tensorflow::kOutputShardingAttr,\n builder->getStrArrayAttr(sharding_for_rets));\n}\n\n\/\/ Extracts input\/output sharding configuration of `cluster_func` by parsing\n\/\/ XlaSharding ops inside the `cluster_func`.\nvoid IdentifyXlaShardingForTPUComputation(\n Builder* builder, tf_device::ClusterFuncOp cluster_func) {\n \/\/ Look up function definition from module.\n FuncOp func = cluster_func->getParentOfType().lookupSymbol(\n cluster_func.func());\n\n \/\/ By default inputs\/outputs have maximal sharding and are assigned to logical\n \/\/ core 0 if no sharding is defined.\n const std::string logical_core_0_sharding =\n xla::sharding_builder::AssignDevice(0).SerializeAsString();\n\n bool use_spmd = false;\n if (auto use_spmd_attr = cluster_func->getAttrOfType(\n \"use_spmd_for_xla_partitioning\"))\n use_spmd = use_spmd_attr.getValue();\n\n IdentifyXlaShardingForComputationInputs(logical_core_0_sharding, use_spmd,\n cluster_func, func, builder);\n\n IdentifyXlaShardingForComputationOutputs(logical_core_0_sharding, use_spmd,\n cluster_func, func, builder);\n}\n\nvoid TPUShardingIdentificationPass::runOnOperation() {\n Builder builder(getOperation().getContext());\n\n getOperation().walk([&](tf_device::ClusterFuncOp cluster_func) {\n IdentifyXlaShardingForTPUComputation(&builder, cluster_func);\n });\n}\n\n} \/\/ anonymous namespace\n\nstd::unique_ptr> CreateTPUShardingIdentificationPass() {\n return std::make_unique();\n}\n\nstatic PassRegistration pass(\n \"tf-tpu-sharding-identification\",\n \"Identifies and handles inputs\/outputs of TPU computation that is \"\n \"sharded across logical cores.\");\n\n} \/\/ namespace TFTPU\n} \/\/ namespace mlir\n<|endoftext|>"} {"text":"5b57ee88-2e4d-11e5-9284-b827eb9e62be5b5cede8-2e4d-11e5-9284-b827eb9e62be5b5cede8-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"d012eef2-2e4e-11e5-9284-b827eb9e62bed017ec9a-2e4e-11e5-9284-b827eb9e62bed017ec9a-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"60ca4c66-2e4e-11e5-9284-b827eb9e62be60cf6a52-2e4e-11e5-9284-b827eb9e62be60cf6a52-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"575740b2-2e4e-11e5-9284-b827eb9e62be575c5868-2e4e-11e5-9284-b827eb9e62be575c5868-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"28ccc28a-2e4e-11e5-9284-b827eb9e62be28d1cf96-2e4e-11e5-9284-b827eb9e62be28d1cf96-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"f1933ffa-2e4e-11e5-9284-b827eb9e62bef19f6dca-2e4e-11e5-9284-b827eb9e62bef19f6dca-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is dual licensed under the MIT and the University of Illinois Open\n\/\/ Source Licenses. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ UNSUPPORTED: libcpp-has-no-threads\n\n\/\/ \n\n\/\/ class thread\n\n\/\/ template thread(F&& f, Args&&... args);\n\n\/\/ UNSUPPORTED: sanitizer-new-delete\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"test_macros.h\"\n\nstd::atomic throw_one(0xFFFF);\nstd::atomic outstanding_new(0);\n\n\nvoid* operator new(std::size_t s) TEST_THROW_SPEC(std::bad_alloc)\n{\n if (throw_one == 0)\n TEST_THROW(std::bad_alloc());\n --throw_one;\n ++outstanding_new;\n void* ret = std::malloc(s);\n if (!ret) std::abort(); \/\/ placate MSVC's unchecked malloc warning\n return ret;\n}\n\nvoid operator delete(void* p) TEST_NOEXCEPT\n{\n --outstanding_new;\n std::free(p);\n}\n\nbool f_run = false;\n\nvoid f()\n{\n f_run = true;\n}\n\nclass G\n{\n int alive_;\npublic:\n static int n_alive;\n static bool op_run;\n\n G() : alive_(1) {++n_alive;}\n G(const G& g) : alive_(g.alive_) {++n_alive;}\n ~G() {alive_ = 0; --n_alive;}\n\n void operator()()\n {\n assert(alive_ == 1);\n assert(n_alive >= 1);\n op_run = true;\n }\n\n void operator()(int i, double j)\n {\n assert(alive_ == 1);\n assert(n_alive >= 1);\n assert(i == 5);\n assert(j == 5.5);\n op_run = true;\n }\n};\n\nint G::n_alive = 0;\nbool G::op_run = false;\n\n#if TEST_STD_VER >= 11\n\nclass MoveOnly\n{\n MoveOnly(const MoveOnly&);\npublic:\n MoveOnly() {}\n MoveOnly(MoveOnly&&) {}\n\n void operator()(MoveOnly&&)\n {\n }\n};\n\n#endif\n\n\/\/ Test throwing std::bad_alloc\n\/\/-----------------------------\n\/\/ Concerns:\n\/\/ A Each allocation performed during thread construction should be performed\n\/\/ in the parent thread so that std::terminate is not called if\n\/\/ std::bad_alloc is thrown by new.\n\/\/ B std::thread's constructor should properly handle exceptions and not leak\n\/\/ memory.\n\/\/ Plan:\n\/\/ 1 Create a thread and count the number of allocations, 'N', it performs.\n\/\/ 2 For each allocation performed run a test where that allocation throws.\n\/\/ 2.1 check that the exception can be caught in the parent thread.\n\/\/ 2.2 Check that the functor has not been called.\n\/\/ 2.3 Check that no memory allocated by the creation of the thread is leaked.\n\/\/ 3 Finally check that a thread runs successfully if we throw after 'N+1'\n\/\/ allocations.\nvoid test_throwing_new_during_thread_creation() {\n#ifndef TEST_HAS_NO_EXCEPTIONS\n throw_one = 0xFFF;\n {\n std::thread t(f);\n t.join();\n }\n const int numAllocs = 0xFFF - throw_one;\n \/\/ i <= numAllocs means the last iteration is expected not to throw.\n for (int i=0; i <= numAllocs; ++i) {\n throw_one = i;\n f_run = false;\n unsigned old_outstanding = outstanding_new;\n try {\n std::thread t(f);\n assert(i == numAllocs); \/\/ Only final iteration will not throw.\n t.join();\n assert(f_run);\n } catch (std::bad_alloc const&) {\n assert(i < numAllocs);\n assert(!f_run); \/\/ (2.2)\n }\n assert(old_outstanding == outstanding_new); \/\/ (2.3)\n }\n f_run = false;\n throw_one = 0xFFF;\n#endif\n}\n\nint main()\n{\n test_throwing_new_during_thread_creation();\n {\n std::thread t(f);\n t.join();\n assert(f_run == true);\n }\n\n {\n assert(G::n_alive == 0);\n assert(!G::op_run);\n std::thread t((G()));\n t.join();\n assert(G::n_alive == 0);\n assert(G::op_run);\n }\n G::op_run = false;\n#ifndef TEST_HAS_NO_EXCEPTIONS\n {\n try\n {\n throw_one = 0;\n assert(G::n_alive == 0);\n assert(!G::op_run);\n std::thread t((G()));\n assert(false);\n }\n catch (...)\n {\n throw_one = 0xFFFF;\n assert(G::n_alive == 0);\n assert(!G::op_run);\n }\n }\n#endif\n#if TEST_STD_VER >= 11\n {\n assert(G::n_alive == 0);\n assert(!G::op_run);\n std::thread t(G(), 5, 5.5);\n t.join();\n assert(G::n_alive == 0);\n assert(G::op_run);\n }\n {\n std::thread t = std::thread(MoveOnly(), MoveOnly());\n t.join();\n }\n#endif\n}\nRepair thread-unsafe modifications of n_alive in F.pass.cpp\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is dual licensed under the MIT and the University of Illinois Open\n\/\/ Source Licenses. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ UNSUPPORTED: libcpp-has-no-threads\n\n\/\/ \n\n\/\/ class thread\n\n\/\/ template thread(F&& f, Args&&... args);\n\n\/\/ UNSUPPORTED: sanitizer-new-delete\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"test_macros.h\"\n\nstd::atomic throw_one(0xFFFF);\nstd::atomic outstanding_new(0);\n\n\nvoid* operator new(std::size_t s) TEST_THROW_SPEC(std::bad_alloc)\n{\n if (throw_one == 0)\n TEST_THROW(std::bad_alloc());\n --throw_one;\n ++outstanding_new;\n void* ret = std::malloc(s);\n if (!ret) std::abort(); \/\/ placate MSVC's unchecked malloc warning\n return ret;\n}\n\nvoid operator delete(void* p) TEST_NOEXCEPT\n{\n --outstanding_new;\n std::free(p);\n}\n\nbool f_run = false;\n\nvoid f()\n{\n f_run = true;\n}\n\nclass G\n{\n int alive_;\npublic:\n static int n_alive;\n static bool op_run;\n\n G() : alive_(1) {++n_alive;}\n G(const G& g) : alive_(g.alive_) {++n_alive;}\n ~G() {alive_ = 0; --n_alive;}\n\n void operator()()\n {\n assert(alive_ == 1);\n assert(n_alive >= 1);\n op_run = true;\n }\n\n void operator()(int i, double j)\n {\n assert(alive_ == 1);\n assert(n_alive >= 1);\n assert(i == 5);\n assert(j == 5.5);\n op_run = true;\n }\n};\n\nint G::n_alive = 0;\nbool G::op_run = false;\n\n#if TEST_STD_VER >= 11\n\nclass MoveOnly\n{\n MoveOnly(const MoveOnly&);\npublic:\n MoveOnly() {}\n MoveOnly(MoveOnly&&) {}\n\n void operator()(MoveOnly&&)\n {\n }\n};\n\n#endif\n\n\/\/ Test throwing std::bad_alloc\n\/\/-----------------------------\n\/\/ Concerns:\n\/\/ A Each allocation performed during thread construction should be performed\n\/\/ in the parent thread so that std::terminate is not called if\n\/\/ std::bad_alloc is thrown by new.\n\/\/ B std::thread's constructor should properly handle exceptions and not leak\n\/\/ memory.\n\/\/ Plan:\n\/\/ 1 Create a thread and count the number of allocations, 'N', it performs.\n\/\/ 2 For each allocation performed run a test where that allocation throws.\n\/\/ 2.1 check that the exception can be caught in the parent thread.\n\/\/ 2.2 Check that the functor has not been called.\n\/\/ 2.3 Check that no memory allocated by the creation of the thread is leaked.\n\/\/ 3 Finally check that a thread runs successfully if we throw after 'N+1'\n\/\/ allocations.\nvoid test_throwing_new_during_thread_creation() {\n#ifndef TEST_HAS_NO_EXCEPTIONS\n throw_one = 0xFFF;\n {\n std::thread t(f);\n t.join();\n }\n const int numAllocs = 0xFFF - throw_one;\n \/\/ i <= numAllocs means the last iteration is expected not to throw.\n for (int i=0; i <= numAllocs; ++i) {\n throw_one = i;\n f_run = false;\n unsigned old_outstanding = outstanding_new;\n try {\n std::thread t(f);\n assert(i == numAllocs); \/\/ Only final iteration will not throw.\n t.join();\n assert(f_run);\n } catch (std::bad_alloc const&) {\n assert(i < numAllocs);\n assert(!f_run); \/\/ (2.2)\n }\n assert(old_outstanding == outstanding_new); \/\/ (2.3)\n }\n f_run = false;\n throw_one = 0xFFF;\n#endif\n}\n\nint main()\n{\n test_throwing_new_during_thread_creation();\n {\n std::thread t(f);\n t.join();\n assert(f_run == true);\n }\n\n {\n assert(G::n_alive == 0);\n assert(!G::op_run);\n {\n G g;\n std::thread t(g);\n t.join();\n }\n assert(G::n_alive == 0);\n assert(G::op_run);\n }\n G::op_run = false;\n#ifndef TEST_HAS_NO_EXCEPTIONS\n {\n try\n {\n throw_one = 0;\n assert(G::n_alive == 0);\n assert(!G::op_run);\n std::thread t((G()));\n assert(false);\n }\n catch (...)\n {\n throw_one = 0xFFFF;\n assert(G::n_alive == 0);\n assert(!G::op_run);\n }\n }\n#endif\n#if TEST_STD_VER >= 11\n {\n assert(G::n_alive == 0);\n assert(!G::op_run);\n {\n G g;\n std::thread t(g, 5, 5.5);\n t.join();\n }\n assert(G::n_alive == 0);\n assert(G::op_run);\n }\n {\n std::thread t = std::thread(MoveOnly(), MoveOnly());\n t.join();\n }\n#endif\n}\n<|endoftext|>"} {"text":"e3aa0514-2e4d-11e5-9284-b827eb9e62bee3af5ba4-2e4d-11e5-9284-b827eb9e62bee3af5ba4-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"bec8cf7e-2e4c-11e5-9284-b827eb9e62bebecdca88-2e4c-11e5-9284-b827eb9e62bebecdca88-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"b61843b8-2e4d-11e5-9284-b827eb9e62beb61d475a-2e4d-11e5-9284-b827eb9e62beb61d475a-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"ecb01244-2e4c-11e5-9284-b827eb9e62beecb50ec0-2e4c-11e5-9284-b827eb9e62beecb50ec0-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"3f2f57c6-2e4f-11e5-9284-b827eb9e62be3f4c95e8-2e4f-11e5-9284-b827eb9e62be3f4c95e8-2e4f-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"c1a5b412-2e4e-11e5-9284-b827eb9e62bec1aaa922-2e4e-11e5-9284-b827eb9e62bec1aaa922-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"dd0fff98-2e4c-11e5-9284-b827eb9e62bedd14f9c6-2e4c-11e5-9284-b827eb9e62bedd14f9c6-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"361eee18-2e4e-11e5-9284-b827eb9e62be3623ea9e-2e4e-11e5-9284-b827eb9e62be3623ea9e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"fe5cda8e-2e4e-11e5-9284-b827eb9e62befe61d87c-2e4e-11e5-9284-b827eb9e62befe61d87c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"d96de214-2e4d-11e5-9284-b827eb9e62bed972ea16-2e4d-11e5-9284-b827eb9e62bed972ea16-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"289f2b0e-2e4e-11e5-9284-b827eb9e62be28a43d38-2e4e-11e5-9284-b827eb9e62be28a43d38-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"5f6ba910-2e4d-11e5-9284-b827eb9e62be5f70beaa-2e4d-11e5-9284-b827eb9e62be5f70beaa-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"eff718e4-2e4c-11e5-9284-b827eb9e62beeffc2276-2e4c-11e5-9284-b827eb9e62beeffc2276-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"4899d3b4-2e4e-11e5-9284-b827eb9e62be489eca90-2e4e-11e5-9284-b827eb9e62be489eca90-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"478d80f2-2e4d-11e5-9284-b827eb9e62be4792916e-2e4d-11e5-9284-b827eb9e62be4792916e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"243fcb36-2e4e-11e5-9284-b827eb9e62be2444d770-2e4e-11e5-9284-b827eb9e62be2444d770-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"17890944-2e4d-11e5-9284-b827eb9e62be178e20be-2e4d-11e5-9284-b827eb9e62be178e20be-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"d09ea726-2e4e-11e5-9284-b827eb9e62bed0a39c54-2e4e-11e5-9284-b827eb9e62bed0a39c54-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"542b6f58-2e4e-11e5-9284-b827eb9e62be5430801a-2e4e-11e5-9284-b827eb9e62be5430801a-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"3c204fa0-2e4e-11e5-9284-b827eb9e62be3c255950-2e4e-11e5-9284-b827eb9e62be3c255950-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"fe58b31a-2e4d-11e5-9284-b827eb9e62befe5dadca-2e4d-11e5-9284-b827eb9e62befe5dadca-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"dfa1c60a-2e4d-11e5-9284-b827eb9e62bedfa6c9ca-2e4d-11e5-9284-b827eb9e62bedfa6c9ca-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"e35e6e42-2e4d-11e5-9284-b827eb9e62bee3637752-2e4d-11e5-9284-b827eb9e62bee3637752-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"395e00cc-2e4f-11e5-9284-b827eb9e62be3962f870-2e4f-11e5-9284-b827eb9e62be3962f870-2e4f-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"77ec4026-2e4d-11e5-9284-b827eb9e62be77f1372a-2e4d-11e5-9284-b827eb9e62be77f1372a-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"b7b81b8e-2e4e-11e5-9284-b827eb9e62beb7bd2cbe-2e4e-11e5-9284-b827eb9e62beb7bd2cbe-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"51b6d6c2-2e4e-11e5-9284-b827eb9e62be51bcbcfe-2e4e-11e5-9284-b827eb9e62be51bcbcfe-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"dd32bcf4-2e4c-11e5-9284-b827eb9e62bedd37ade0-2e4c-11e5-9284-b827eb9e62bedd37ade0-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"1c05b13c-2e4f-11e5-9284-b827eb9e62be1c0ac7da-2e4f-11e5-9284-b827eb9e62be1c0ac7da-2e4f-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"3cd1485a-2e4e-11e5-9284-b827eb9e62be3cd64fee-2e4e-11e5-9284-b827eb9e62be3cd64fee-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"a187d40e-2e4d-11e5-9284-b827eb9e62bea18cd580-2e4d-11e5-9284-b827eb9e62bea18cd580-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"252c2968-2e4e-11e5-9284-b827eb9e62be25313098-2e4e-11e5-9284-b827eb9e62be25313098-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"de87052c-2e4e-11e5-9284-b827eb9e62bede8c09b4-2e4e-11e5-9284-b827eb9e62bede8c09b4-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"3c6a53f8-2e4d-11e5-9284-b827eb9e62be3c6f5876-2e4d-11e5-9284-b827eb9e62be3c6f5876-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"ffebd35c-2e4c-11e5-9284-b827eb9e62befff0cbaa-2e4c-11e5-9284-b827eb9e62befff0cbaa-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"f39d8fe0-2e4d-11e5-9284-b827eb9e62bef3a2ae6c-2e4d-11e5-9284-b827eb9e62bef3a2ae6c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"6a523f2e-2e4d-11e5-9284-b827eb9e62be6a5741d6-2e4d-11e5-9284-b827eb9e62be6a5741d6-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"f09a971a-2e4e-11e5-9284-b827eb9e62bef09f8b4e-2e4e-11e5-9284-b827eb9e62bef09f8b4e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"09f45832-2e4e-11e5-9284-b827eb9e62be09f96840-2e4e-11e5-9284-b827eb9e62be09f96840-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"4c2b8c84-2e4e-11e5-9284-b827eb9e62be4c309ab2-2e4e-11e5-9284-b827eb9e62be4c309ab2-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"d3b89ad6-2e4c-11e5-9284-b827eb9e62bed3bdc09c-2e4c-11e5-9284-b827eb9e62bed3bdc09c-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"d2de000a-2e4d-11e5-9284-b827eb9e62bed2e3119e-2e4d-11e5-9284-b827eb9e62bed2e3119e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"3735b74a-2e4f-11e5-9284-b827eb9e62be373ab83a-2e4f-11e5-9284-b827eb9e62be373ab83a-2e4f-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"eff20b88-2e4c-11e5-9284-b827eb9e62beeff718e4-2e4c-11e5-9284-b827eb9e62beeff718e4-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"ec2b514c-2e4e-11e5-9284-b827eb9e62beec309922-2e4e-11e5-9284-b827eb9e62beec309922-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"6bd914ee-2e4d-11e5-9284-b827eb9e62be6bde24f2-2e4d-11e5-9284-b827eb9e62be6bde24f2-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"05e5f0fc-2e4e-11e5-9284-b827eb9e62be05eaec88-2e4e-11e5-9284-b827eb9e62be05eaec88-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"2013bc3e-2e4e-11e5-9284-b827eb9e62be2018c5f8-2e4e-11e5-9284-b827eb9e62be2018c5f8-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"3dad77b8-2e4d-11e5-9284-b827eb9e62be3db28622-2e4d-11e5-9284-b827eb9e62be3db28622-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"bfba1602-2e4e-11e5-9284-b827eb9e62bebfbf0a0e-2e4e-11e5-9284-b827eb9e62bebfbf0a0e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"1daa9f66-2e4f-11e5-9284-b827eb9e62be1dafaaf6-2e4f-11e5-9284-b827eb9e62be1dafaaf6-2e4f-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"9bd09f6e-2e4d-11e5-9284-b827eb9e62be9bd596ea-2e4d-11e5-9284-b827eb9e62be9bd596ea-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"649b88ce-2e4d-11e5-9284-b827eb9e62be64a09aa8-2e4d-11e5-9284-b827eb9e62be64a09aa8-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"9d586fce-2e4d-11e5-9284-b827eb9e62be9d5d675e-2e4d-11e5-9284-b827eb9e62be9d5d675e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"06dc0344-2e4d-11e5-9284-b827eb9e62be06e2bf18-2e4d-11e5-9284-b827eb9e62be06e2bf18-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"28fd1602-2e4d-11e5-9284-b827eb9e62be290209aa-2e4d-11e5-9284-b827eb9e62be290209aa-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"d7aacdc0-2e4d-11e5-9284-b827eb9e62bed7afcb22-2e4d-11e5-9284-b827eb9e62bed7afcb22-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"36fedfe0-2e4f-11e5-9284-b827eb9e62be3703d7ac-2e4f-11e5-9284-b827eb9e62be3703d7ac-2e4f-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"0bc91562-2e4e-11e5-9284-b827eb9e62be0bce0810-2e4e-11e5-9284-b827eb9e62be0bce0810-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"f90185ea-2e4d-11e5-9284-b827eb9e62bef90693e6-2e4d-11e5-9284-b827eb9e62bef90693e6-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"4c9aa6ec-2e4d-11e5-9284-b827eb9e62be4c9fb664-2e4d-11e5-9284-b827eb9e62be4c9fb664-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"fc11c48e-2e4d-11e5-9284-b827eb9e62befc16ba84-2e4d-11e5-9284-b827eb9e62befc16ba84-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"c58708bc-2e4c-11e5-9284-b827eb9e62bec58bf98a-2e4c-11e5-9284-b827eb9e62bec58bf98a-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"fefe0316-2e4c-11e5-9284-b827eb9e62beff02f1f0-2e4c-11e5-9284-b827eb9e62beff02f1f0-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"cdf56c64-2e4c-11e5-9284-b827eb9e62becdfacd1c-2e4c-11e5-9284-b827eb9e62becdfacd1c-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"39ecbdf4-2e4e-11e5-9284-b827eb9e62be39f1cf88-2e4e-11e5-9284-b827eb9e62be39f1cf88-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"1ccd8c2a-2e4f-11e5-9284-b827eb9e62be1cd2fd36-2e4f-11e5-9284-b827eb9e62be1cd2fd36-2e4f-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"3568076c-2e4d-11e5-9284-b827eb9e62be356d2120-2e4d-11e5-9284-b827eb9e62be356d2120-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"a11855e2-2e4e-11e5-9284-b827eb9e62bea11d513c-2e4e-11e5-9284-b827eb9e62bea11d513c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"bfcf2912-2e4d-11e5-9284-b827eb9e62bebfd41c92-2e4d-11e5-9284-b827eb9e62bebfd41c92-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"a0af65a0-2e4e-11e5-9284-b827eb9e62bea0b45f06-2e4e-11e5-9284-b827eb9e62bea0b45f06-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"d8cc03fa-2e4c-11e5-9284-b827eb9e62bed8d10fe4-2e4c-11e5-9284-b827eb9e62bed8d10fe4-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"94daa6a4-2e4e-11e5-9284-b827eb9e62be94dfa168-2e4e-11e5-9284-b827eb9e62be94dfa168-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"43eb3e12-2e4d-11e5-9284-b827eb9e62be43f03b4c-2e4d-11e5-9284-b827eb9e62be43f03b4c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"e372ae34-2e4d-11e5-9284-b827eb9e62bee377b8e8-2e4d-11e5-9284-b827eb9e62bee377b8e8-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"b3e65fd0-2e4d-11e5-9284-b827eb9e62beb3eb5d14-2e4d-11e5-9284-b827eb9e62beb3eb5d14-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"b8b46d50-2e4c-11e5-9284-b827eb9e62beb8b97a66-2e4c-11e5-9284-b827eb9e62beb8b97a66-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"b506866a-2e4d-11e5-9284-b827eb9e62beb50b7c60-2e4d-11e5-9284-b827eb9e62beb50b7c60-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"0cba43d8-2e4e-11e5-9284-b827eb9e62be0cbf4324-2e4e-11e5-9284-b827eb9e62be0cbf4324-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"eb6c060c-2e4e-11e5-9284-b827eb9e62beeb713c94-2e4e-11e5-9284-b827eb9e62beeb713c94-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"9aa52754-2e4d-11e5-9284-b827eb9e62be9ab1b960-2e4d-11e5-9284-b827eb9e62be9ab1b960-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"3f9a60fe-2e4d-11e5-9284-b827eb9e62be3f9f672a-2e4d-11e5-9284-b827eb9e62be3f9f672a-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"26bd0276-2e4d-11e5-9284-b827eb9e62be26c1f95c-2e4d-11e5-9284-b827eb9e62be26c1f95c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"68d4ce46-2e4d-11e5-9284-b827eb9e62be68dbc214-2e4d-11e5-9284-b827eb9e62be68dbc214-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"df80e5b2-2e4c-11e5-9284-b827eb9e62bedf85d0f4-2e4c-11e5-9284-b827eb9e62bedf85d0f4-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"46eef9b8-2e4e-11e5-9284-b827eb9e62be46f40462-2e4e-11e5-9284-b827eb9e62be46f40462-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"c88e0704-2e4c-11e5-9284-b827eb9e62bec892fbc4-2e4c-11e5-9284-b827eb9e62bec892fbc4-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"d230bfbc-2e4d-11e5-9284-b827eb9e62bed235be18-2e4d-11e5-9284-b827eb9e62bed235be18-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"b97392a0-2e4e-11e5-9284-b827eb9e62beb978b136-2e4e-11e5-9284-b827eb9e62beb978b136-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"87f00e4e-2e4d-11e5-9284-b827eb9e62be87f506ba-2e4d-11e5-9284-b827eb9e62be87f506ba-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"7142fb1a-2e4e-11e5-9284-b827eb9e62be7147f61a-2e4e-11e5-9284-b827eb9e62be7147f61a-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"2c47c398-2e4d-11e5-9284-b827eb9e62be2c4cba2e-2e4d-11e5-9284-b827eb9e62be2c4cba2e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"b31e88c0-2e4d-11e5-9284-b827eb9e62beb32375b0-2e4d-11e5-9284-b827eb9e62beb32375b0-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"56f74582-2e4d-11e5-9284-b827eb9e62be56fc4cc6-2e4d-11e5-9284-b827eb9e62be56fc4cc6-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"db0a53dc-2e4d-11e5-9284-b827eb9e62bedb0f5922-2e4d-11e5-9284-b827eb9e62bedb0f5922-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"2e4201cc-2e4d-11e5-9284-b827eb9e62be2e46f79a-2e4d-11e5-9284-b827eb9e62be2e46f79a-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"4ff55656-2e4e-11e5-9284-b827eb9e62be4ffa8612-2e4e-11e5-9284-b827eb9e62be4ffa8612-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"9161ceda-2e4e-11e5-9284-b827eb9e62be9166ce6c-2e4e-11e5-9284-b827eb9e62be9166ce6c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"dff7fa44-2e4c-11e5-9284-b827eb9e62bedffceb08-2e4c-11e5-9284-b827eb9e62bedffceb08-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"303a3020-2e4e-11e5-9284-b827eb9e62be303f249a-2e4e-11e5-9284-b827eb9e62be303f249a-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"111076e2-2e4d-11e5-9284-b827eb9e62be11156e54-2e4d-11e5-9284-b827eb9e62be11156e54-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"c63f4058-2e4c-11e5-9284-b827eb9e62bec64b5b68-2e4c-11e5-9284-b827eb9e62bec64b5b68-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"fce3dc36-2e4c-11e5-9284-b827eb9e62befce8d6e6-2e4c-11e5-9284-b827eb9e62befce8d6e6-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"bb32740e-2e4d-11e5-9284-b827eb9e62bebb3777ba-2e4d-11e5-9284-b827eb9e62bebb3777ba-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"b0aa4cea-2e4e-11e5-9284-b827eb9e62beb0af44c0-2e4e-11e5-9284-b827eb9e62beb0af44c0-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"41d1cbaa-2e4d-11e5-9284-b827eb9e62be41d71fa6-2e4d-11e5-9284-b827eb9e62be41d71fa6-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"3501845e-2e4f-11e5-9284-b827eb9e62be35067c84-2e4f-11e5-9284-b827eb9e62be35067c84-2e4f-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"255fcc10-2e4d-11e5-9284-b827eb9e62be2564be1e-2e4d-11e5-9284-b827eb9e62be2564be1e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"67c9abf6-2e4e-11e5-9284-b827eb9e62be67ceaa34-2e4e-11e5-9284-b827eb9e62be67ceaa34-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"cbba2b64-2e4d-11e5-9284-b827eb9e62becbbf2718-2e4d-11e5-9284-b827eb9e62becbbf2718-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"19b59100-2e4e-11e5-9284-b827eb9e62be19baec7c-2e4e-11e5-9284-b827eb9e62be19baec7c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"aa806878-2e4d-11e5-9284-b827eb9e62beaa855c66-2e4d-11e5-9284-b827eb9e62beaa855c66-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"12768508-2e4d-11e5-9284-b827eb9e62be127b939a-2e4d-11e5-9284-b827eb9e62be127b939a-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"52fe0060-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"#include \"remoteatcommandresponse.h\"\n#include \"xbeepacket.h\"\n\n#include \n\nnamespace QtXBee {\n\nRemoteATCommandResponse::RemoteATCommandResponse(QObject *parent) :\n ATCommandResponse(parent)\n{\n setFrameType(XBeePacket::RemoteATCommandResponseId);\n}\n\nRemoteATCommandResponse::RemoteATCommandResponse(const QByteArray &data, QObject *parent) :\n ATCommandResponse(parent)\n{\n setFrameType(XBeePacket::RemoteATCommandResponseId);\n setPacket(data);\n}\n\nvoid RemoteATCommandResponse::clear() {\n ATCommandResponse::clear();\n m_sourceAddress64 = 0;\n m_sourceAddress16 = 0;\n}\n\nbool RemoteATCommandResponse::parseApiSpecificData(const QByteArray &data)\nQ_DECL_OVERRIDE\n{\n escapePacket();\n if(data.size() < 13) {\n qDebug() << Q_FUNC_INFO << \"bad data !\";\n return false;\n }\n setFrameId(data.at(0));\n setSourceAddress64(data.mid(1, 8).toHex().toULong(0,16));\n setSourceAddress16(data.mid(9, 2).toHex().toUInt(0,16));\n setATCommand((ATCommand::ATCommandType) data.mid(11, 2).toHex().toUInt(0,16));\n setCommandStatus((CommandStatus) data.at(13));\n if(data.size() > 14) {\n for(int i=14; i < data.size(); i++) {\n m_data.append(data.at(i));\n }\n }\n\n return true;\n}\n\nQString RemoteATCommandResponse::toString()\nQ_DECL_OVERRIDE\n{\n QString str;\n str.append(QString(\"Raw packet : 0x%1\\n\").arg(QString(packet().toHex())));\n str.append(QString(\"Start delimiter : 0x%1\\n\").arg(QString::number(startDelimiter(), 16)));\n str.append(QString(\"Frame type : %1 (0x%2)\\n\").arg(frameTypeToString(frameType())).arg(QString::number(frameType(), 16)));\n str.append(QString(\"Length : %1 bytes\\n\").arg(length()));\n str.append(QString(\"Frame id : %1\\n\").arg(frameId()));\n if(!m_data.isEmpty())\n str.append(QString(\"Data : 0x%1\\n\").arg(QString(m_data.toHex())));\n else\n str.append(QString(\"Data : No data\\n\"));\n str.append(QString(\"Source Address 64bits : 0x%1\\n\").arg(m_sourceAddress64, 0, 16));\n str.append(QString(\"Source Address 16bits : 0x%1\\n\").arg(m_sourceAddress16, 0, 16));\n str.append(QString(\"AT Command : %1 (0x%2)\\n\").arg(ATCommand::atCommandToString(m_atCommand)).arg(m_atCommand, 0,16));\n str.append(QString(\"Command Status : %1 (0x%2)\\n\").arg(statusToString(m_status)).arg(m_status, 0, 16));\n str.append(QString(\"Command Data : 0x%1 (%2)\\n\").arg(QString(m_data.toHex())).arg(QString(m_data)));\n str.append(QString(\"Checksum : %1\\n\").arg(checksum()));\n\n return str;\n}\n\n\/\/ Setters\nvoid RemoteATCommandResponse::setSourceAddress64(const quint64 addr) {\n m_sourceAddress64 = addr;\n}\n\nvoid RemoteATCommandResponse::setSourceAddress16(const quint32 addr) {\n m_sourceAddress16 = addr;\n}\n\n\/\/ Getters\nquint64 RemoteATCommandResponse::sourceAddress64() const {\n return m_sourceAddress64;\n}\n\nquint16 RemoteATCommandResponse::sourceAddress16() const {\n return m_sourceAddress16;\n}\n\n} \/\/ END namepsace\nFixed RemoteATCommandResponse::toString()#include \"remoteatcommandresponse.h\"\n#include \"xbeepacket.h\"\n\n#include \n\nnamespace QtXBee {\n\nRemoteATCommandResponse::RemoteATCommandResponse(QObject *parent) :\n ATCommandResponse(parent)\n{\n setFrameType(XBeePacket::RemoteATCommandResponseId);\n}\n\nRemoteATCommandResponse::RemoteATCommandResponse(const QByteArray &data, QObject *parent) :\n ATCommandResponse(parent)\n{\n setFrameType(XBeePacket::RemoteATCommandResponseId);\n setPacket(data);\n}\n\nvoid RemoteATCommandResponse::clear() {\n ATCommandResponse::clear();\n m_sourceAddress64 = 0;\n m_sourceAddress16 = 0;\n}\n\nbool RemoteATCommandResponse::parseApiSpecificData(const QByteArray &data)\nQ_DECL_OVERRIDE\n{\n if(data.size() < 13) {\n qDebug() << Q_FUNC_INFO << \"bad data !\";\n return false;\n }\n setFrameId(data.at(0));\n setSourceAddress64(data.mid(1, 8).toHex().toULong(0,16));\n setSourceAddress16(data.mid(9, 2).toHex().toUInt(0,16));\n setATCommand((ATCommand::ATCommandType) data.mid(11, 2).toHex().toUInt(0,16));\n setCommandStatus((CommandStatus) data.at(13));\n if(data.size() > 14) {\n for(int i=14; i < data.size(); i++) {\n m_data.append(data.at(i));\n }\n }\n\n return true;\n}\n\nQString RemoteATCommandResponse::toString()\nQ_DECL_OVERRIDE\n{\n QString str;\n str.append(QString(\"Raw packet : 0x%1\\n\").arg(QString(packet().toHex())));\n str.append(QString(\"Start delimiter : 0x%1\\n\").arg(QString::number(startDelimiter(), 16)));\n str.append(QString(\"Frame type : %1 (0x%2)\\n\").arg(frameTypeToString(frameType())).arg(QString::number(frameType(), 16)));\n str.append(QString(\"Length : %1 bytes\\n\").arg(length()));\n str.append(QString(\"Frame id : %1\\n\").arg(frameId()));\n if(!m_data.isEmpty())\n str.append(QString(\"Data : 0x%1 (%2)\\n\").arg(QString(m_data.toHex())).arg(QString(m_data)));\n else\n str.append(QString(\"Data : No data\\n\"));\n str.append(QString(\"Source Address 64bits : 0x%1\\n\").arg(m_sourceAddress64, 0, 16));\n str.append(QString(\"Source Address 16bits : 0x%1\\n\").arg(m_sourceAddress16, 0, 16));\n str.append(QString(\"AT Command : %1 (0x%2)\\n\").arg(ATCommand::atCommandToString(m_atCommand)).arg(m_atCommand, 0,16));\n str.append(QString(\"Command Status : %1 (0x%2)\\n\").arg(statusToString(m_status)).arg(m_status, 0, 16));\n str.append(QString(\"Checksum : %1\\n\").arg(checksum()));\n\n return str;\n}\n\n\/\/ Setters\nvoid RemoteATCommandResponse::setSourceAddress64(const quint64 addr) {\n m_sourceAddress64 = addr;\n}\n\nvoid RemoteATCommandResponse::setSourceAddress16(const quint32 addr) {\n m_sourceAddress16 = addr;\n}\n\n\/\/ Getters\nquint64 RemoteATCommandResponse::sourceAddress64() const {\n return m_sourceAddress64;\n}\n\nquint16 RemoteATCommandResponse::sourceAddress16() const {\n return m_sourceAddress16;\n}\n\n} \/\/ END namepsace\n<|endoftext|>"} {"text":"#ifndef MJOLNIR_OMP_PROTEIN_DNA_NON_SPECIFIC_INTERACTION_HPP\n#define MJOLNIR_OMP_PROTEIN_DNA_NON_SPECIFIC_INTERACTION_HPP\n#include \n#include \n#include \n\nnamespace mjolnir\n{\n\n\/\/ Protein-DNA Non-Specific interaction that represents hydrogen bond between\n\/\/ side chain atoms in proteins and the phosphate residues in DNA.\n\/\/ This is an implementation of the potential developed in the following paper.\n\/\/ - T.Niina, G.B.Brandani, C.Tan, and S.Takada (2017) PLoS. Comp. Biol.\n\/\/\n\/\/ U(r, theta, phi) = k f(r) g(theta) g(phi)\n\/\/\n\/\/ f(r) = exp(-(r-r0)^2 \/ 2sigma^2)\n\/\/ g(phi) = 1 ... |phi - phi0| < delta\n\/\/ 1 - cos^2(pi(phi-phi0) \/ 2delta) ... delta < |phi - phi0| < 2delta\n\/\/ 0 ... otherwise\n\/\/\ntemplate class boundaryT>\nclass ProteinDNANonSpecificInteraction>\n final : public GlobalInteractionBase>\n{\n public:\n\n using traits_type = OpenMPSimulatorTraits;\n using base_type = GlobalInteractionBase;\n using real_type = typename base_type::real_type;\n using coordinate_type = typename base_type::coordinate_type;\n using system_type = typename base_type::system_type;\n using boundary_type = typename base_type::boundary_type;\n using potential_type = ProteinDNANonSpecificPotential;\n using partition_type = SpatialPartition;\n\n public:\n\n ProteinDNANonSpecificInteraction(potential_type&& pot, partition_type&& part)\n : potential_(std::move(pot)), partition_(std::move(part))\n {}\n ~ProteinDNANonSpecificInteraction() {}\n\n void initialize(const system_type& sys) override\n {\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_LOG_FUNCTION();\n MJOLNIR_LOG_INFO(\"potential is PDNS\");\n\n this->potential_.initialize(sys);\n this->partition_.initialize(sys, this->potential_);\n return;\n }\n\n void update(const system_type& sys) override\n {\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_LOG_FUNCTION();\n MJOLNIR_LOG_INFO(\"potential is PDNS\");\n\n this->potential_.update(sys);\n this->partition_.initialize(sys, this->potential_);\n return;\n }\n\n void update_margin(const real_type dmargin, const system_type& sys) override\n {\n this->current_margin_ -= dmargin;\n if(this->current_margin_ < 0)\n {\n this->make_list(sys);\n }\n return ;\n }\n\n void calc_force(system_type& sys) const noexcept override\n {\n MJOLNIR_GET_DEFAULT_LOGGER_DEBUG();\n MJOLNIR_LOG_FUNCTION_DEBUG();\n\n constexpr auto tolerance = math::abs_tolerance();\n \/\/ XXX Note: P is ambiguous because both Protein and Phosphate has `P`.\n \/\/ But this interaction is named as P-D ns, so here it uses `P` for protein\n \/\/ and `D` for DNA.\n\n#pragma omp for nowait\n for(std::size_t i=0; i < this->potential_.contacts().size(); ++i)\n {\n const auto& para = potential_.contacts()[i];\n\n const auto P = para.P;\n const auto& rP = sys.position(P);\n for(const auto& ptnr : this->partition_.partners(P))\n {\n const auto D = ptnr.index; \/\/ DNA phosphate\n const auto S3 = ptnr.parameter().S3; \/\/ 3' Sugar\n const auto& rD = sys.position(D);\n\n MJOLNIR_LOG_DEBUG(\"protein = \", P, \", DNA = \", D, \", r0 = \", para.r0);\n\n \/\/ PC S5' |\n \/\/ o o--o B | theta is an angle formed by the vector\n \/\/ A\\ P D \/ | from the neighboring amino acid residue at\n \/\/ vP | o --> o | the N-term side to the amino acid residue\n \/\/ |\/ `-\\ | at the C-term side (vP in the figure) and\n \/\/ o phi o--o B | the vector from Protein to DNA (phosphate).\n \/\/ PN S3' |\n\n \/\/ ----------------------------------------------------------------\n \/\/ calculates the distance part\n\n const auto rPD = sys.adjust_direction(rD - rP); \/\/ PRO -> DNA\n const auto lPD_sq = math::length_sq(rPD);\n if(para.r_cut_sq < lPD_sq)\n {\n continue;\n }\n const auto rlPD = math::rsqrt(lPD_sq);\n const auto lPD = lPD_sq * rlPD;\n const auto f_df = potential_.f_df(para.r0, lPD);\n\n MJOLNIR_LOG_DEBUG(\"f = \", f_df.first, \", df = \", f_df.second);\n\n \/\/ ----------------------------------------------------------------\n \/\/ calculates the angle part (theta)\n\n const auto& rPC = sys.position(para.PC);\n const auto& rPN = sys.position(para.PN);\n const auto rPNC = sys.adjust_direction(rPC - rPN); \/\/ PN -> PC\n const auto rlPNC = math::rlength(rPNC);\n const auto dotPNC = math::dot_product(rPNC, rPD);\n const auto cosPNC = dotPNC * rlPD * rlPNC;\n const auto theta = std::acos(math::clamp(cosPNC,-1,1));\n\n const auto g_dg_theta = potential_.g_dg(para.theta0, theta);\n\n MJOLNIR_LOG_DEBUG(\"g(theta) = \", g_dg_theta.first,\n \", dg(theta) = \", g_dg_theta.second);\n\n \/\/ ----------------------------------------------------------------\n \/\/ calculates the angle part (phi)\n\n const auto& rS3 = sys.position(S3);\n const auto rS3D = sys.adjust_direction(rD - rS3); \/\/ S3' -> D\n const auto rlS3D = math::rlength(rS3D);\n const auto dotS3D = math::dot_product(rPD, rS3D);\n const auto cosS3D = dotS3D * rlS3D * rlPD;\n const auto phi = std::acos(math::clamp(cosS3D,-1,1));\n\n const auto g_dg_phi = potential_.g_dg(para.phi0, phi);\n\n MJOLNIR_LOG_DEBUG(\"g(phi) = \", g_dg_phi.first,\n \", dg(phi) = \", g_dg_phi.second);\n\n \/\/ ----------------------------------------------------------------\n \/\/ calculate force\n \/\/\n \/\/ d\/dr [kf(r) g(theta) g(phi)]\n \/\/ = k [df(r) g(theta) g(phi) dr\/dr +\n \/\/ f(r) dg(theta) g(phi) dtheta\/dr +\n \/\/ f(r) g(theta) dg(phi) dphi\/dr ]\n const auto k = para.k;\n const auto thread_id = omp_get_thread_num();\n\n \/\/ df(r) g(theta) g(phi)\n if(g_dg_theta.first != 0 && g_dg_phi.first != 0)\n {\n MJOLNIR_LOG_DEBUG(\"calculating distance force\");\n\n const auto coef = rlPD * k *\n f_df.second * g_dg_theta.first * g_dg_phi.first;\n const auto F = -coef * rPD;\n\n sys.force_thread(thread_id, P) -= F;\n sys.force_thread(thread_id, D) += F;\n }\n\n \/\/ f(r) dg(theta) g(phi)\n if(g_dg_theta.second != 0 && g_dg_phi.first != 0)\n {\n MJOLNIR_LOG_DEBUG(\"calculating theta force\");\n\n const auto deriv =\n k * f_df.first * g_dg_theta.second * g_dg_phi.first;\n\n const auto sin_theta = std::sin(theta);\n const auto coef_sin = deriv \/ std::max(sin_theta, tolerance);\n\n const auto rPD_reg = rlPD * rPD;\n const auto rPNC_reg = rlPNC * rPNC;\n\n const auto F_P = -coef_sin * rlPD * (rPNC_reg - cosPNC * rPD_reg );\n const auto F_PN = -coef_sin * rlPNC * (rPD_reg - cosPNC * rPNC_reg);\n\n sys.force_thread(thread_id, D) -= F_P;\n sys.force_thread(thread_id, P) += F_P;\n sys.force_thread(thread_id, para.PN) += F_PN;\n sys.force_thread(thread_id, para.PC) -= F_PN;\n }\n\n \/\/ f(r) dg(theta) g(phi)\n if(g_dg_theta.first != 0 && g_dg_phi.second != 0)\n {\n MJOLNIR_LOG_DEBUG(\"calculating phi force\");\n\n const auto deriv =\n k * f_df.first * g_dg_theta.first * g_dg_phi.second;\n\n const auto sin_phi = std::sin(phi);\n const auto coef_sin = deriv \/ std::max(sin_phi, tolerance);\n\n const auto rPD_reg = rlPD * rPD;\n const auto rS3D_reg = rlS3D * rS3D;\n\n const auto F_P = -coef_sin * rlPD * (rS3D_reg - cosS3D * rPD_reg);\n const auto F_S = -coef_sin * rlS3D * (rPD_reg - cosS3D * rS3D_reg);\n\n sys.force_thread(thread_id, P) += F_P;\n sys.force_thread(thread_id, D) -= F_P + F_S;\n sys.force_thread(thread_id, S3) += F_S;\n }\n }\n }\n return;\n }\n\n real_type calc_energy(const system_type& sys) const noexcept override\n {\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_LOG_FUNCTION();\n \/\/ XXX Note: P is ambiguous because both Protein and Phosphate has `P`.\n \/\/ But this interaction is named as P-D ns, so here it uses `P` for protein\n \/\/ and `D` for DNA.\n\n real_type E = 0.0;\n#pragma omp parallel for reduction(+:E)\n for(std::size_t i=0; i < this->potential_.contacts().size(); ++i)\n {\n const auto& para = potential_.contacts()[i];\n\n const auto P = para.P;\n const auto& rP = sys.position(P);\n for(const auto& ptnr : this->partition_.partners(P))\n {\n const auto D = ptnr.index; \/\/ DNA phosphate\n const auto S3 = ptnr.parameter().S3; \/\/ 3' Sugar\n const auto& rD = sys.position(D);\n\n \/\/ PC S5' |\n \/\/ o o--o B | theta is an angle formed by the vector\n \/\/ A\\ P D \/ | from the neighboring amino acid residue at\n \/\/ vP | o --> o | the N-term side to the amino acid residue\n \/\/ |\/ `-\\ | at the C-term side (vP in the figure) and\n \/\/ o phi o--o B | the vector from Protein to DNA (phosphate).\n \/\/ PN S3' |\n\n \/\/ ----------------------------------------------------------------\n \/\/ calculates the distance part\n\n const auto rPD = sys.adjust_direction(rD - rP); \/\/ PRO -> DNA\n const auto lPD_sq = math::length_sq(rPD);\n if(para.r_cut_sq < lPD_sq)\n {\n continue;\n }\n const auto rlPD = math::rsqrt(lPD_sq);\n const auto lPD = lPD_sq * rlPD;\n const auto f = potential_.f(para.r0, lPD);\n\n \/\/ ----------------------------------------------------------------\n \/\/ calculates the angle part (theta)\n\n const auto& rPC = sys.position(para.PC);\n const auto& rPN = sys.position(para.PN);\n const auto rPNC = sys.adjust_direction(rPC - rPN); \/\/ PN -> PC\n const auto rlPNC = math::rlength(rPNC);\n const auto dotPNC = math::dot_product(rPNC, rPD);\n const auto cosPNC = dotPNC * rlPD * rlPNC;\n const auto theta = std::acos(math::clamp(cosPNC,-1,1));\n const auto g_theta = potential_.g(para.theta0, theta);\n\n if(g_theta == real_type(0)) {continue;}\n\n \/\/ ----------------------------------------------------------------\n \/\/ calculates the angle part (phi)\n\n const auto& rS3 = sys.position(S3);\n const auto rS3D = sys.adjust_direction(rD - rS3); \/\/ S3' -> D\n const auto rlS3D = math::rlength(rS3D);\n const auto dotS3D = math::dot_product(rPD, rS3D);\n const auto cosS3D = dotS3D * rlS3D * rlPD;\n const auto phi = std::acos(math::clamp(cosS3D,-1,1));\n const auto g_phi = potential_.g(para.phi0, phi);\n\n if(g_phi == real_type(0)) {continue;}\n\n \/\/ ----------------------------------------------------------------\n \/\/ calculate energy\n\n const auto k = para.k;\n\n MJOLNIR_LOG_INFO(\"protein = \", P, \", DNA = \", D, \", r0 = \", para.r0);\n\n E += k * f * g_theta * g_phi;\n }\n }\n return E;\n }\n\n std::string name() const override {return \"PDNSInteraction\";}\n\n potential_type const& potential() const noexcept {return potential_;}\n potential_type& potential() noexcept {return potential_;}\n\n private:\n\n potential_type potential_;\n partition_type partition_;\n};\n} \/\/ mjolnir\n\n#ifdef MJOLNIR_SEPARATE_BUILD\n\/\/ explicitly specialize BondAngleInteraction with LocalPotentials\n#include \n\nnamespace mjolnir\n{\nextern template class ProteinDNANonSpecificInteraction >;\nextern template class ProteinDNANonSpecificInteraction >;\nextern template class ProteinDNANonSpecificInteraction>;\nextern template class ProteinDNANonSpecificInteraction>;\n} \/\/ mjolnir\n#endif \/\/ MJOLNIR_SEPARATE_BUILD\n#endif\/\/ MJOLNIR_FORCEFIELD_PDNS_PROTEIN_DNA_NON_SPECIFIC_INTERACTION_HPP\nfix: compilation errors in omp\/PDNS#ifndef MJOLNIR_OMP_PROTEIN_DNA_NON_SPECIFIC_INTERACTION_HPP\n#define MJOLNIR_OMP_PROTEIN_DNA_NON_SPECIFIC_INTERACTION_HPP\n#include \n#include \n#include \n\nnamespace mjolnir\n{\n\n\/\/ Protein-DNA Non-Specific interaction that represents hydrogen bond between\n\/\/ side chain atoms in proteins and the phosphate residues in DNA.\n\/\/ This is an implementation of the potential developed in the following paper.\n\/\/ - T.Niina, G.B.Brandani, C.Tan, and S.Takada (2017) PLoS. Comp. Biol.\n\/\/\n\/\/ U(r, theta, phi) = k f(r) g(theta) g(phi)\n\/\/\n\/\/ f(r) = exp(-(r-r0)^2 \/ 2sigma^2)\n\/\/ g(phi) = 1 ... |phi - phi0| < delta\n\/\/ 1 - cos^2(pi(phi-phi0) \/ 2delta) ... delta < |phi - phi0| < 2delta\n\/\/ 0 ... otherwise\n\/\/\ntemplate class boundaryT>\nclass ProteinDNANonSpecificInteraction>\n final : public GlobalInteractionBase>\n{\n public:\n\n using traits_type = OpenMPSimulatorTraits;\n using base_type = GlobalInteractionBase;\n using real_type = typename base_type::real_type;\n using coordinate_type = typename base_type::coordinate_type;\n using system_type = typename base_type::system_type;\n using boundary_type = typename base_type::boundary_type;\n using potential_type = ProteinDNANonSpecificPotential;\n using partition_type = SpatialPartition;\n\n public:\n\n ProteinDNANonSpecificInteraction(potential_type&& pot, partition_type&& part)\n : potential_(std::move(pot)), partition_(std::move(part))\n {}\n ~ProteinDNANonSpecificInteraction() {}\n\n void initialize(const system_type& sys) override\n {\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_LOG_FUNCTION();\n MJOLNIR_LOG_INFO(\"potential is PDNS\");\n\n this->potential_.initialize(sys);\n this->partition_.initialize(sys, this->potential_);\n return;\n }\n\n void update(const system_type& sys) override\n {\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_LOG_FUNCTION();\n MJOLNIR_LOG_INFO(\"potential is PDNS\");\n\n this->potential_.update(sys);\n this->partition_.initialize(sys, this->potential_);\n return;\n }\n\n void update_margin(const real_type dmargin, const system_type& sys) override\n {\n this->partition_.update(dmargin, sys, this->potential_);\n return ;\n }\n\n void calc_force(system_type& sys) const noexcept override\n {\n MJOLNIR_GET_DEFAULT_LOGGER_DEBUG();\n MJOLNIR_LOG_FUNCTION_DEBUG();\n\n constexpr auto tolerance = math::abs_tolerance();\n \/\/ XXX Note: P is ambiguous because both Protein and Phosphate has `P`.\n \/\/ But this interaction is named as P-D ns, so here it uses `P` for protein\n \/\/ and `D` for DNA.\n\n#pragma omp for nowait\n for(std::size_t i=0; i < this->potential_.contacts().size(); ++i)\n {\n const auto& para = potential_.contacts()[i];\n\n const auto P = para.P;\n const auto& rP = sys.position(P);\n for(const auto& ptnr : this->partition_.partners(P))\n {\n const auto D = ptnr.index; \/\/ DNA phosphate\n const auto S3 = ptnr.parameter().S3; \/\/ 3' Sugar\n const auto& rD = sys.position(D);\n\n MJOLNIR_LOG_DEBUG(\"protein = \", P, \", DNA = \", D, \", r0 = \", para.r0);\n\n \/\/ PC S5' |\n \/\/ o o--o B | theta is an angle formed by the vector\n \/\/ A\\ P D \/ | from the neighboring amino acid residue at\n \/\/ vP | o --> o | the N-term side to the amino acid residue\n \/\/ |\/ `-\\ | at the C-term side (vP in the figure) and\n \/\/ o phi o--o B | the vector from Protein to DNA (phosphate).\n \/\/ PN S3' |\n\n \/\/ ----------------------------------------------------------------\n \/\/ calculates the distance part\n\n const auto rPD = sys.adjust_direction(rD - rP); \/\/ PRO -> DNA\n const auto lPD_sq = math::length_sq(rPD);\n if(para.r_cut_sq < lPD_sq)\n {\n continue;\n }\n const auto rlPD = math::rsqrt(lPD_sq);\n const auto lPD = lPD_sq * rlPD;\n const auto f_df = potential_.f_df(para.r0, lPD);\n\n MJOLNIR_LOG_DEBUG(\"f = \", f_df.first, \", df = \", f_df.second);\n\n \/\/ ----------------------------------------------------------------\n \/\/ calculates the angle part (theta)\n\n const auto& rPC = sys.position(para.PC);\n const auto& rPN = sys.position(para.PN);\n const auto rPNC = sys.adjust_direction(rPC - rPN); \/\/ PN -> PC\n const auto rlPNC = math::rlength(rPNC);\n const auto dotPNC = math::dot_product(rPNC, rPD);\n const auto cosPNC = dotPNC * rlPD * rlPNC;\n const auto theta = std::acos(math::clamp(cosPNC,-1,1));\n\n const auto g_dg_theta = potential_.g_dg(para.theta0, theta);\n\n MJOLNIR_LOG_DEBUG(\"g(theta) = \", g_dg_theta.first,\n \", dg(theta) = \", g_dg_theta.second);\n\n \/\/ ----------------------------------------------------------------\n \/\/ calculates the angle part (phi)\n\n const auto& rS3 = sys.position(S3);\n const auto rS3D = sys.adjust_direction(rD - rS3); \/\/ S3' -> D\n const auto rlS3D = math::rlength(rS3D);\n const auto dotS3D = math::dot_product(rPD, rS3D);\n const auto cosS3D = dotS3D * rlS3D * rlPD;\n const auto phi = std::acos(math::clamp(cosS3D,-1,1));\n\n const auto g_dg_phi = potential_.g_dg(para.phi0, phi);\n\n MJOLNIR_LOG_DEBUG(\"g(phi) = \", g_dg_phi.first,\n \", dg(phi) = \", g_dg_phi.second);\n\n \/\/ ----------------------------------------------------------------\n \/\/ calculate force\n \/\/\n \/\/ d\/dr [kf(r) g(theta) g(phi)]\n \/\/ = k [df(r) g(theta) g(phi) dr\/dr +\n \/\/ f(r) dg(theta) g(phi) dtheta\/dr +\n \/\/ f(r) g(theta) dg(phi) dphi\/dr ]\n const auto k = para.k;\n const auto thread_id = omp_get_thread_num();\n\n \/\/ df(r) g(theta) g(phi)\n if(g_dg_theta.first != 0 && g_dg_phi.first != 0)\n {\n MJOLNIR_LOG_DEBUG(\"calculating distance force\");\n\n const auto coef = rlPD * k *\n f_df.second * g_dg_theta.first * g_dg_phi.first;\n const auto F = -coef * rPD;\n\n sys.force_thread(thread_id, P) -= F;\n sys.force_thread(thread_id, D) += F;\n }\n\n \/\/ f(r) dg(theta) g(phi)\n if(g_dg_theta.second != 0 && g_dg_phi.first != 0)\n {\n MJOLNIR_LOG_DEBUG(\"calculating theta force\");\n\n const auto deriv =\n k * f_df.first * g_dg_theta.second * g_dg_phi.first;\n\n const auto sin_theta = std::sin(theta);\n const auto coef_sin = deriv \/ std::max(sin_theta, tolerance);\n\n const auto rPD_reg = rlPD * rPD;\n const auto rPNC_reg = rlPNC * rPNC;\n\n const auto F_P = -coef_sin * rlPD * (rPNC_reg - cosPNC * rPD_reg );\n const auto F_PN = -coef_sin * rlPNC * (rPD_reg - cosPNC * rPNC_reg);\n\n sys.force_thread(thread_id, D) -= F_P;\n sys.force_thread(thread_id, P) += F_P;\n sys.force_thread(thread_id, para.PN) += F_PN;\n sys.force_thread(thread_id, para.PC) -= F_PN;\n }\n\n \/\/ f(r) dg(theta) g(phi)\n if(g_dg_theta.first != 0 && g_dg_phi.second != 0)\n {\n MJOLNIR_LOG_DEBUG(\"calculating phi force\");\n\n const auto deriv =\n k * f_df.first * g_dg_theta.first * g_dg_phi.second;\n\n const auto sin_phi = std::sin(phi);\n const auto coef_sin = deriv \/ std::max(sin_phi, tolerance);\n\n const auto rPD_reg = rlPD * rPD;\n const auto rS3D_reg = rlS3D * rS3D;\n\n const auto F_P = -coef_sin * rlPD * (rS3D_reg - cosS3D * rPD_reg);\n const auto F_S = -coef_sin * rlS3D * (rPD_reg - cosS3D * rS3D_reg);\n\n sys.force_thread(thread_id, P) += F_P;\n sys.force_thread(thread_id, D) -= F_P + F_S;\n sys.force_thread(thread_id, S3) += F_S;\n }\n }\n }\n return;\n }\n\n real_type calc_energy(const system_type& sys) const noexcept override\n {\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_LOG_FUNCTION();\n \/\/ XXX Note: P is ambiguous because both Protein and Phosphate has `P`.\n \/\/ But this interaction is named as P-D ns, so here it uses `P` for protein\n \/\/ and `D` for DNA.\n\n real_type E = 0.0;\n#pragma omp parallel for reduction(+:E)\n for(std::size_t i=0; i < this->potential_.contacts().size(); ++i)\n {\n const auto& para = potential_.contacts()[i];\n\n const auto P = para.P;\n const auto& rP = sys.position(P);\n for(const auto& ptnr : this->partition_.partners(P))\n {\n const auto D = ptnr.index; \/\/ DNA phosphate\n const auto S3 = ptnr.parameter().S3; \/\/ 3' Sugar\n const auto& rD = sys.position(D);\n\n \/\/ PC S5' |\n \/\/ o o--o B | theta is an angle formed by the vector\n \/\/ A\\ P D \/ | from the neighboring amino acid residue at\n \/\/ vP | o --> o | the N-term side to the amino acid residue\n \/\/ |\/ `-\\ | at the C-term side (vP in the figure) and\n \/\/ o phi o--o B | the vector from Protein to DNA (phosphate).\n \/\/ PN S3' |\n\n \/\/ ----------------------------------------------------------------\n \/\/ calculates the distance part\n\n const auto rPD = sys.adjust_direction(rD - rP); \/\/ PRO -> DNA\n const auto lPD_sq = math::length_sq(rPD);\n if(para.r_cut_sq < lPD_sq)\n {\n continue;\n }\n const auto rlPD = math::rsqrt(lPD_sq);\n const auto lPD = lPD_sq * rlPD;\n const auto f = potential_.f(para.r0, lPD);\n\n \/\/ ----------------------------------------------------------------\n \/\/ calculates the angle part (theta)\n\n const auto& rPC = sys.position(para.PC);\n const auto& rPN = sys.position(para.PN);\n const auto rPNC = sys.adjust_direction(rPC - rPN); \/\/ PN -> PC\n const auto rlPNC = math::rlength(rPNC);\n const auto dotPNC = math::dot_product(rPNC, rPD);\n const auto cosPNC = dotPNC * rlPD * rlPNC;\n const auto theta = std::acos(math::clamp(cosPNC,-1,1));\n const auto g_theta = potential_.g(para.theta0, theta);\n\n if(g_theta == real_type(0)) {continue;}\n\n \/\/ ----------------------------------------------------------------\n \/\/ calculates the angle part (phi)\n\n const auto& rS3 = sys.position(S3);\n const auto rS3D = sys.adjust_direction(rD - rS3); \/\/ S3' -> D\n const auto rlS3D = math::rlength(rS3D);\n const auto dotS3D = math::dot_product(rPD, rS3D);\n const auto cosS3D = dotS3D * rlS3D * rlPD;\n const auto phi = std::acos(math::clamp(cosS3D,-1,1));\n const auto g_phi = potential_.g(para.phi0, phi);\n\n if(g_phi == real_type(0)) {continue;}\n\n \/\/ ----------------------------------------------------------------\n \/\/ calculate energy\n\n const auto k = para.k;\n\n MJOLNIR_LOG_INFO(\"protein = \", P, \", DNA = \", D, \", r0 = \", para.r0);\n\n E += k * f * g_theta * g_phi;\n }\n }\n return E;\n }\n\n std::string name() const override {return \"PDNSInteraction\";}\n\n potential_type const& potential() const noexcept {return potential_;}\n potential_type& potential() noexcept {return potential_;}\n\n private:\n\n potential_type potential_;\n partition_type partition_;\n};\n} \/\/ mjolnir\n\n#ifdef MJOLNIR_SEPARATE_BUILD\n\/\/ explicitly specialize BondAngleInteraction with LocalPotentials\n#include \n\nnamespace mjolnir\n{\nextern template class ProteinDNANonSpecificInteraction >;\nextern template class ProteinDNANonSpecificInteraction >;\nextern template class ProteinDNANonSpecificInteraction>;\nextern template class ProteinDNANonSpecificInteraction>;\n} \/\/ mjolnir\n#endif \/\/ MJOLNIR_SEPARATE_BUILD\n#endif\/\/ MJOLNIR_FORCEFIELD_PDNS_PROTEIN_DNA_NON_SPECIFIC_INTERACTION_HPP\n<|endoftext|>"} {"text":"\/************************************************************************************\n** \n* @copyright (c) 2013-2100, ChengDu Duyer Technology Co., LTD. All Right Reserved.\n*\n*************************************************************************************\/\n\/**\n* @file g_dfs_server_main.h\n* @version \n* @brief \n* @author duye\n* @date 2014-09-28\n* @note \n*\n* 1. 2014-09-28 duye Created this file\n* \n*\/\n\n#include \n#include \n#include \n\nstatic const GInt8* LOG_PREFIX = \"dfs.server.main\";\n\n\/**\n * @brief dfs server process monitor class\n *\/\nclass DfsServerProcessMonitorObserver : public gsys::ProcessMoniterInterface\n{\npublic:\n DfsServerProcessMonitorObserver() {}\n ~DfsServerProcessMonitorObserver() {}\n \n \/**\n * @brief handle system signal, when segmentation fault\n * @param [in] sig : signal \n * @note inherit from base class ProcessMoniterInterface\n *\/\n void onSegmentationFault(const GInt32 sig)\n {\n G_LOG_ERROR(LOG_PREFIX, \"DFS server segmentation fault happened\");\n G_LOG_INFO(LOG_PREFIX, \"DFS server will stopped, waitting for exit\");\n DfsServer::instance().setState(HOST_SERVER_FAULT);\n if (!gsys::ProcessMonitor::instance().exitWait())\n {\n G_LOG_ERROR(LOG_PREFIX, \"DFS server can't normal exit, will force exit\");\n G_LOG_WARN(LOG_PREFIX, \"==============DFS server force exit===========\");\n }\n }\n \n \/**\n * @brief handle system signal, when ctrl+c\n * @param [in] sig : signal \n * @note inherit from base class ProcessMoniterInterface\n *\/\n void onCtrlC(const GInt32 sig)\n {\n G_LOG_INFO(LOG_PREFIX, \"DFS server stop by ctrl + c\");\n G_LOG_INFO(LOG_PREFIX, \"DFS server will stopped, waitting for exit\");\n DfsServer::instance()->setState(HOST_SERVER_STOP);\n if (!gsys::ProcessMonitor::instance().exitWait())\n {\n G_LOG_ERROR(LOG_PREFIX, \"DFS server can't normal exit, will force exit\");\n G_LOG_WARN(LOG_PREFIX, \"==============DFS server force exit==============\");\n }\n }\n}\n\nint main(int argc, char** argv)\n{\n G_LOG_INIT();\n \n G_LOG_INFO(LOG_PREFIX, \"==============DFS server startup===========\");\n \n \/\/ process monitor\n DfsServerProcessMonitorObserver dfs_server_process_monitor_observer;\n gsys::ProcessMonitor::instance().addMonitor(&dfs_server_process_monitor_observer);\n \n if (IS_NO(DfdServer::instance().start()))\n {\n G_LOG_ERROR(LOG_PREFIX, \"DFS server startup fault\");\n return -1;\n }\n \n while (DfsServer::instance().getState() == SERVER_RUNNING)\n {\n gsys::gsystem::sleep(2);\n }\n \n DfsServer::instance().stop();\n exit_condition.broadcast();\n \n G_LOG_INFO(LOG_PREFIX, \"==============DFS server stopped===========\");\n \n G_LOG_UNINIT();\n \n return 0;\n}\nUpdate g_dfs_server_main.cpp\/************************************************************************************\n** \n* @copyright (c) 2013-2100, ChengDu Duyer Technology Co., LTD. All Right Reserved.\n*\n*************************************************************************************\/\n\/**\n* @file g_dfs_server_main.h\n* @version \n* @brief \n* @author duye\n* @date 2014-09-28\n* @note \n*\n* 1. 2014-09-28 duye Created this file\n* \n*\/\n\n#include \n#include \n#include \n\nstatic const GInt8* LOG_PREFIX = \"dfs.server.main\";\n\n\/**\n * @brief dfs server process monitor class\n *\/\nclass DfsServerProcessMonitorObserver : public gsys::ProcessMoniterInterface\n{\npublic:\n DfsServerProcessMonitorObserver() {}\n ~DfsServerProcessMonitorObserver() {}\n \n \/**\n * @brief handle system signal, when segmentation fault\n * @param [in] sig : signal \n * @note inherit from base class ProcessMoniterInterface\n *\/\n void onSegmentationFault(const GInt32 sig)\n {\n G_LOG_ERROR(LOG_PREFIX, \"DFS server segmentation fault happened\");\n G_LOG_INFO(LOG_PREFIX, \"DFS server will stopped, waitting for exit\");\n DfsServer::instance().setState(HOST_SERVER_FAULT);\n if (!gsys::ProcessMonitor::instance().exitWait())\n {\n G_LOG_ERROR(LOG_PREFIX, \"DFS server can't normal exit, will force exit\");\n G_LOG_WARN(LOG_PREFIX, \"==============DFS server force exit===========\");\n }\n }\n \n \/**\n * @brief handle system signal, when ctrl+c\n * @param [in] sig : signal \n * @note inherit from base class ProcessMoniterInterface\n *\/\n void onCtrlC(const GInt32 sig)\n {\n G_LOG_INFO(LOG_PREFIX, \"DFS server stop by ctrl + c\");\n G_LOG_INFO(LOG_PREFIX, \"DFS server will stopped, waitting for exit\");\n DfsServer::instance()->setState(HOST_SERVER_STOP);\n if (!gsys::ProcessMonitor::instance().exitWait())\n {\n G_LOG_ERROR(LOG_PREFIX, \"DFS server can't normal exit, will force exit\");\n G_LOG_WARN(LOG_PREFIX, \"==============DFS server force exit==============\");\n }\n }\n}\n\nint main(int argc, char** argv)\n{\n G_LOG_INIT();\n \n G_LOG_INFO(LOG_PREFIX, \"==============DFS server startup===========\");\n \n \/\/ process monitor\n DfsServerProcessMonitorObserver dfs_server_process_monitor_observer;\n gsys::ProcessMonitor::instance().addMonitor(&dfs_server_process_monitor_observer);\n \n if (IS_NO(DfdServer::instance().start()))\n {\n G_LOG_ERROR(LOG_PREFIX, \"DFS server startup fault\");\n return -1;\n }\n \n while (DfsServer::instance().getState() == SERVER_RUNNING)\n {\n gsys::gsystem::sleep(2);\n }\n \n DfsServer::instance().stop();\n gsys::ProcessMonitor::instance().exitWakeup();\n \n G_LOG_INFO(LOG_PREFIX, \"==============DFS server stopped===========\");\n \n G_LOG_UNINIT();\n \n return 0;\n}\n<|endoftext|>"} {"text":"{\n gROOT->Reset();\n TCanvas *nut = new TCanvas(\"nut\", \"FirstSession\",100,10,700,900);\n nut->Range(0,0,20,24);\n nut->SetFillColor(10);\n nut->SetBorderSize(2);\n\n TPaveLabel *pl = new TPaveLabel(3,22,17,23.7,\"My first ROOT interactive session\",\"br\");\n pl->SetFillColor(18);\n pl->SetTextSize(0.7);\n pl->Draw();\n\n TText t(0,0,\"a\");\n t.SetTextFont(62);\n t.SetTextSize(0.025);\n t.SetTextAlign(12);\n t.DrawText(2,20.3,\"ROOT is based on CINT, a powerful C\/C++ interpreter.\");\n t.DrawText(2,19.3,\"Blocks of lines can be entered within {...}.\");\n t.DrawText(2,18.3,\"Previous typed lines can be recalled.\");\n\n t.SetTextFont(72);\n t.SetTextSize(0.026);\n t.DrawText(3,17,\"Root > float x=5; float y=7;\");\n t.DrawText(3,16,\"Root > x*sqrt(y)\");\n t.DrawText(3,14,\"Root > for (int i=2;i<7;i++) printf(\\\"sqrt(%d) = %f\\\",i,sqrt(i));\");\n t.DrawText(3,10,\"Root > TF1 f1(\\\"f1\\\",\\\"sin(x)\/x\\\",0,10)\");\n t.DrawText(3, 9,\"Root > f1.Draw()\");\n t.SetTextFont(81);\n t.SetTextSize(0.018);\n t.DrawText(4,15,\"(double)1.322875655532e+01\");\n t.DrawText(4,13.3,\"sqrt(2) = 1.414214\");\n t.DrawText(4,12.7,\"sqrt(3) = 1.732051\");\n t.DrawText(4,12.1,\"sqrt(4) = 2.000000\");\n t.DrawText(4,11.5,\"sqrt(5) = 2.236068\");\n t.DrawText(4,10.9,\"sqrt(6) = 2.449490\");\n\n TPad *pad = new TPad(\"pad\",\"pad\",.2,.05,.8,.35);\n pad->Draw();\n pad->cd();\n pad->SetGrid();\n TF1 f1(\"f1\",\"sin(x)\/x\",0,10);\n f1.Draw();\n\n nut.cd();\n \/\/--signature\n TText sig(.2,.2,\"\/user\/brun\/root\/aihep\/first.C\");\n sig.SetTextFont(72);\n sig.SetTextSize(0.020);\n sig.Draw();\n\n nut->Modified();\n nut->Print(\"first.ps\");\n nut->cd();\n nut->Update();\n}\nRemove the line setting the TPaveLabel text size. This is now automatic.{\n gROOT->Reset();\n TCanvas *nut = new TCanvas(\"nut\", \"FirstSession\",100,10,700,900);\n nut->Range(0,0,20,24);\n nut->SetFillColor(10);\n nut->SetBorderSize(2);\n\n TPaveLabel *pl = new TPaveLabel(3,22,17,23.7,\"My first ROOT interactive session\",\"br\");\n pl->SetFillColor(18);\n pl->Draw();\n\n TText t(0,0,\"a\");\n t.SetTextFont(62);\n t.SetTextSize(0.025);\n t.SetTextAlign(12);\n t.DrawText(2,20.3,\"ROOT is based on CINT, a powerful C\/C++ interpreter.\");\n t.DrawText(2,19.3,\"Blocks of lines can be entered within {...}.\");\n t.DrawText(2,18.3,\"Previous typed lines can be recalled.\");\n\n t.SetTextFont(72);\n t.SetTextSize(0.026);\n t.DrawText(3,17,\"Root > float x=5; float y=7;\");\n t.DrawText(3,16,\"Root > x*sqrt(y)\");\n t.DrawText(3,14,\"Root > for (int i=2;i<7;i++) printf(\\\"sqrt(%d) = %f\\\",i,sqrt(i));\");\n t.DrawText(3,10,\"Root > TF1 f1(\\\"f1\\\",\\\"sin(x)\/x\\\",0,10)\");\n t.DrawText(3, 9,\"Root > f1.Draw()\");\n t.SetTextFont(81);\n t.SetTextSize(0.018);\n t.DrawText(4,15,\"(double)1.322875655532e+01\");\n t.DrawText(4,13.3,\"sqrt(2) = 1.414214\");\n t.DrawText(4,12.7,\"sqrt(3) = 1.732051\");\n t.DrawText(4,12.1,\"sqrt(4) = 2.000000\");\n t.DrawText(4,11.5,\"sqrt(5) = 2.236068\");\n t.DrawText(4,10.9,\"sqrt(6) = 2.449490\");\n\n TPad *pad = new TPad(\"pad\",\"pad\",.2,.05,.8,.35);\n pad->Draw();\n pad->cd();\n pad->SetGrid();\n TF1 f1(\"f1\",\"sin(x)\/x\",0,10);\n f1.Draw();\n\n nut.cd();\n \/\/--signature\n TText sig(.2,.2,\"\/user\/brun\/root\/aihep\/first.C\");\n sig.SetTextFont(72);\n sig.SetTextSize(0.020);\n sig.Draw();\n\n nut->Modified();\n nut->Print(\"first.ps\");\n nut->cd();\n nut->Update();\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#define NUM_FIELDS 4\n\n\nnamespace KNearestNeighbors\n{\n struct Entry\n {\n std::array Attributes;\n std::string Class;\n };\n\n using IntDoublePair = std::pair;\n\n struct CompareSecond: std::binary_function\n {\n bool operator()(const IntDoublePair& a, const IntDoublePair& b)\n {\n return a.second < b.second;\n }\n };\n\n bool LoadDataset(const char* filename, std::vector& data)\n {\n std::ifstream filein(filename);\n if (!filein.is_open())\n return false;\n\n while (!filein.eof())\n {\n std::string line;\n std::getline(filein, line);\n if (\"\" == line)\n continue;\n std::istringstream linein(std::move(line));\n Entry entry;\n for (auto& attribute: entry.Attributes)\n {\n std::string value;\n std::getline(linein, value, ',');\n attribute = std::stod(std::move(value), nullptr);\n }\n std::getline(linein, entry.Class);\n data.push_back(std::move(entry));\n }\n\n return true;\n }\n\n void SplitData(const std::vector& data, std::set& trainingSet, std::set& testSet)\n {\n std::default_random_engine generator(std::chrono::system_clock::now().time_since_epoch().count());\n std::uniform_int_distribution<> distribution(0, (int)data.size() - 1);\n while (testSet.size() < 20)\n testSet.insert(distribution(generator));\n while ((int)trainingSet.size() < (int)data.size() - 20)\n {\n int index = distribution(generator);\n if (!testSet.count(index))\n trainingSet.insert(index);\n }\n }\n\n void GetNeighbors(const std::vector& data, const std::set& trainingSet, int testInstance, int k, std::set& neighbors)\n {\n std::set distances;\n auto euclideanDistance = [](const Entry& entry1, const Entry& entry2)\n {\n double sumDeltasSquared = 0;\n for (int i = 0; i < NUM_FIELDS; i++)\n {\n double delta = entry1.Attributes[i] - entry2.Attributes[i];\n sumDeltasSquared += delta * delta;\n }\n return sqrt(sumDeltasSquared);\n };\n for (int trainer: trainingSet)\n distances.insert(std::make_pair(trainer, euclideanDistance(data[testInstance], data[trainer])));\n\n auto i = distances.begin();\n for (int j = 0; j < k; ++j, ++i)\n neighbors.insert(i->first);\n }\n\n std::string GetResponse(const std::vector& data, const std::set& neighbors)\n {\n std::map classVotes;\n for (int neighbor: neighbors)\n {\n auto response = data[neighbor].Class;\n if (classVotes.count(response))\n ++classVotes[response];\n else\n classVotes[response] = 1;\n }\n\n auto compareSecond = [](const auto& a, const auto& b)\n {\n return a.second < b.second;\n };\n auto responsePos = std::max_element(classVotes.begin(), classVotes.end(), compareSecond);\n return responsePos->first;\n }\n}\n\nint main(int argc, const char* const* argv)\n{\n if (argc < 2)\n return 1;\n\n \/\/ preparing data\n std::vector data;\n if (!KNearestNeighbors::LoadDataset(argv[1], data))\n return 2;\n\n std::set trainingSet, testSet;\n KNearestNeighbors::SplitData(data, trainingSet, testSet);\n\n \/\/ generating predictions\n int correctCount = 0;\n\n int k;\n std::cin >> k;\n for (int test: testSet)\n {\n \/\/ finding neighbors\n std::set neighbors;\n KNearestNeighbors::GetNeighbors(data, trainingSet, test, k, neighbors);\n\n \/\/ getting response\n auto response = KNearestNeighbors::GetResponse(data, neighbors);\n std::cout << \"Predicted: \" << response << \", actual: \" << data[test].Class << std::endl;\n if (response == data[test].Class)\n ++correctCount;\n }\n\n \/\/ calculating accuracy\n std::cout << \"Accuracy: \" << 100.0 * correctCount \/ testSet.size() << \"%\" << std::endl;\n return 0;\n}\nknn: added macro constant definition for the number of test instances#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#define NUM_FIELDS 4\n#define NUM_TEST_INSTANCES 20\n\n\nnamespace KNearestNeighbors\n{\n struct Entry\n {\n std::array Attributes;\n std::string Class;\n };\n\n using IntDoublePair = std::pair;\n\n struct CompareSecond: std::binary_function\n {\n bool operator()(const IntDoublePair& a, const IntDoublePair& b)\n {\n return a.second < b.second;\n }\n };\n\n bool LoadDataset(const char* filename, std::vector& data)\n {\n std::ifstream filein(filename);\n if (!filein.is_open())\n return false;\n\n while (!filein.eof())\n {\n std::string line;\n std::getline(filein, line);\n if (\"\" == line)\n continue;\n std::istringstream linein(std::move(line));\n Entry entry;\n for (auto& attribute: entry.Attributes)\n {\n std::string value;\n std::getline(linein, value, ',');\n attribute = std::stod(std::move(value), nullptr);\n }\n std::getline(linein, entry.Class);\n data.push_back(std::move(entry));\n }\n\n return true;\n }\n\n void SplitData(const std::vector& data, std::set& trainingSet, std::set& testSet)\n {\n std::default_random_engine generator(std::chrono::system_clock::now().time_since_epoch().count());\n std::uniform_int_distribution<> distribution(0, (int)data.size() - 1);\n while (testSet.size() < NUM_TEST_INSTANCES)\n testSet.insert(distribution(generator));\n while ((int)trainingSet.size() < (int)data.size() - NUM_TEST_INSTANCES)\n {\n int index = distribution(generator);\n if (!testSet.count(index))\n trainingSet.insert(index);\n }\n }\n\n void GetNeighbors(const std::vector& data, const std::set& trainingSet, int testInstance, int k, std::set& neighbors)\n {\n std::set distances;\n auto euclideanDistance = [](const Entry& entry1, const Entry& entry2)\n {\n double sumDeltasSquared = 0;\n for (int i = 0; i < NUM_FIELDS; i++)\n {\n double delta = entry1.Attributes[i] - entry2.Attributes[i];\n sumDeltasSquared += delta * delta;\n }\n return sqrt(sumDeltasSquared);\n };\n for (int trainer: trainingSet)\n distances.insert(std::make_pair(trainer, euclideanDistance(data[testInstance], data[trainer])));\n\n auto i = distances.begin();\n for (int j = 0; j < k; ++j, ++i)\n neighbors.insert(i->first);\n }\n\n std::string GetResponse(const std::vector& data, const std::set& neighbors)\n {\n std::map classVotes;\n for (int neighbor: neighbors)\n {\n auto response = data[neighbor].Class;\n if (classVotes.count(response))\n ++classVotes[response];\n else\n classVotes[response] = 1;\n }\n\n auto compareSecond = [](const auto& a, const auto& b)\n {\n return a.second < b.second;\n };\n auto responsePos = std::max_element(classVotes.begin(), classVotes.end(), compareSecond);\n return responsePos->first;\n }\n}\n\nint main(int argc, const char* const* argv)\n{\n if (argc < 2)\n return 1;\n\n \/\/ preparing data\n std::vector data;\n if (!KNearestNeighbors::LoadDataset(argv[1], data))\n return 2;\n\n std::set trainingSet, testSet;\n KNearestNeighbors::SplitData(data, trainingSet, testSet);\n\n \/\/ generating predictions\n int correctCount = 0;\n\n int k;\n std::cin >> k;\n for (int test: testSet)\n {\n \/\/ finding neighbors\n std::set neighbors;\n KNearestNeighbors::GetNeighbors(data, trainingSet, test, k, neighbors);\n\n \/\/ getting response\n auto response = KNearestNeighbors::GetResponse(data, neighbors);\n std::cout << \"Predicted: \" << response << \", actual: \" << data[test].Class << std::endl;\n if (response == data[test].Class)\n ++correctCount;\n }\n\n \/\/ calculating accuracy\n std::cout << \"Accuracy: \" << 100.0 * correctCount \/ testSet.size() << \"%\" << std::endl;\n return 0;\n}\n<|endoftext|>"} {"text":"#include \"config.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n\/\/\/\/ parameters\n\n\/\/ for bam file\nint32_t min_bundle_gap = 100;\nint min_num_hits_in_bundle = 20;\nint32_t min_splice_boundary_hits = 1;\nuint32_t min_max_splice_boundary_qual = 3;\ndouble min_average_overlap = 2;\nint min_max_region_overlap = 5;\ndouble min_region_coverage = 0.5;\nint max_num_bundles = -1;\nint slope_bin_size = 5;\nint slope_min_score = 32;\nint slope_extend_score = 20;\nint slope_min_bin_num = 16;\nint slope_min_distance = 100;\nint slope_flexible_bin_num = 2;\ndouble slope_acceptance_sigma = 2.0;\nint32_t average_read_length = 100;\nint32_t average_slope_length = 240;\nint pseudo_length_count = 10;\ndouble min_boundary_edge_weight_ratio = 0.05;\n\n\/\/ for algorithm\nint max_dp_table_size = 10000;\nint max_num_subsetsum_solutions = 10;\ndouble max_equation_error_ratio = 0.2;\n\n\/\/ for simulation\nint simulation_num_vertices = 0;\nint simulation_num_edges = 0;\nint simulation_max_edge_weight = 0;\n\n\/\/\/\/ from command line\nstring algo;\nstring input_file;\nstring output_file;\n\nbool output_tex_files = false;\nstring fixed_gene_name = \"\";\nint min_gtf_transcripts_num = 0;\nbool fast_mode = true;\n\nint print_parameters()\n{\n\t\/\/ for bam file\n\tprintf(\"parameters:\\n\");\n\tprintf(\"min_bundle_gap = %d\\n\", min_bundle_gap);\n\tprintf(\"min_num_hits_in_bundle = %d\\n\", min_num_hits_in_bundle);\n\tprintf(\"min_splice_boundary_hits = %d\\n\", min_splice_boundary_hits);\n\tprintf(\"min_max_splice_boundary_qual = %d\\n\", min_max_splice_boundary_qual);\n\tprintf(\"min_average_overlap = %.2lf\\n\", min_average_overlap);\n\tprintf(\"min_max_region_overlap = %d\\n\", min_max_region_overlap);\n\tprintf(\"min_region_coverage = %.2lf\\n\", min_region_coverage);\n\tprintf(\"max_num_bundles = %d\\n\", max_num_bundles);\n\tprintf(\"slope_bin_size = %d\\n\", slope_bin_size);\n\tprintf(\"slope_min_bin_num = %d\\n\", slope_min_bin_num);\n\tprintf(\"slope_min_distance = %d\\n\", slope_min_distance);\n\tprintf(\"slope_min_score = %d\\n\", slope_min_score);\n\tprintf(\"slope_extend_score = %d\\n\", slope_extend_score);\n\tprintf(\"slope_flexible_bin_num = %d\\n\", slope_flexible_bin_num);\n\tprintf(\"slope_acceptance_sigma = %.2lf\\n\", slope_acceptance_sigma);\n\tprintf(\"average_slope_length = %d\\n\", average_slope_length);\n\tprintf(\"average_read_length = %d\\n\", average_read_length);\n\tprintf(\"pseudo_length_count = %d\\n\", pseudo_length_count);\n\tprintf(\"min_boundary_edge_weight_ratio = %.2lf\\n\", min_boundary_edge_weight_ratio);\n\n\t\/\/ for algorithm\n\tprintf(\"max_dp_table_size = %d\\n\", max_dp_table_size);\n\tprintf(\"max_num_subsetsum_solutions = %d\\n\", max_num_subsetsum_solutions);\n\tprintf(\"max_equation_error_ratio = %.2lf\\n\", max_equation_error_ratio);\n\n\t\/\/ for simulation\n\tprintf(\"simulation_num_vertices = %d\\n\", simulation_num_vertices);\n\tprintf(\"simulation_num_edges = %d\\n\", simulation_num_edges);\n\tprintf(\"simulation_max_edge_weight = %d\\n\", simulation_max_edge_weight);\n\n\t\/\/ for command\n\tprintf(\"algo = %s\\n\", algo.c_str());\n\tprintf(\"input_file = %s\\n\", input_file.c_str());\n\tprintf(\"output_file = %s\\n\", output_file.c_str());\n\tprintf(\"output_tex_files = %c\\n\", output_tex_files ? 'T' : 'F');\n\tprintf(\"fixed_gene_name = %s\\n\", fixed_gene_name.c_str());\n\tprintf(\"min_gtf_transcripts_num = %d\\n\", min_gtf_transcripts_num);\n\tprintf(\"fast_mode = %c\\n\", fast_mode ? 'T' : 'F');\n\tprintf(\"\\n\");\n\n\treturn 0;\n}\n\nbool parse_arguments(int argc, const char ** argv)\n{\n\toutput_tex_files = false;\n\tbool b = false;\n\tfor(int i = 1; i < argc; i++)\n\t{\n\t\tif(string(argv[i]) == \"-a\")\n\t\t{\n\t\t\talgo = string(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"-o\")\n\t\t{\n\t\t\toutput_file = string(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"-i\")\n\t\t{\n\t\t\tinput_file = string(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"-g\")\n\t\t{\n\t\t\tfixed_gene_name = string(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"-t\")\n\t\t{\n\t\t\toutput_tex_files = true;\n\t\t}\n\t\telse if(string(argv[i]) == \"-f\")\n\t\t{\n\t\t\tfast_mode = true;\n\t\t}\n\t\telse if(string(argv[i]) == \"-x\")\n\t\t{\n\t\t\tslope_min_score = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t}\n\n\treturn b;\n}\n\nupdate#include \"config.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n\/\/\/\/ parameters\n\n\/\/ for bam file\nint32_t min_bundle_gap = 100;\nint min_num_hits_in_bundle = 20;\nint32_t min_splice_boundary_hits = 1;\nuint32_t min_max_splice_boundary_qual = 3;\ndouble min_average_overlap = 2;\nint min_max_region_overlap = 5;\ndouble min_region_coverage = 0.5;\nint max_num_bundles = -1;\nint slope_bin_size = 5;\nint slope_min_score = 32;\nint slope_extend_score = 20;\nint slope_min_bin_num = 16;\nint slope_min_distance = 100;\nint slope_flexible_bin_num = 2;\ndouble slope_acceptance_sigma = 2.0;\nint32_t average_read_length = 100;\nint32_t average_slope_length = 240;\nint pseudo_length_count = 10;\ndouble min_boundary_edge_weight_ratio = 0.05;\n\n\/\/ for algorithm\nint max_dp_table_size = 10000;\nint max_num_subsetsum_solutions = 10;\ndouble max_equation_error_ratio = 0.2;\n\n\/\/ for simulation\nint simulation_num_vertices = 0;\nint simulation_num_edges = 0;\nint simulation_max_edge_weight = 0;\n\n\/\/\/\/ from command line\nstring algo;\nstring input_file;\nstring output_file;\n\nbool output_tex_files = false;\nstring fixed_gene_name = \"\";\nint min_gtf_transcripts_num = 0;\nbool fast_mode = true;\n\nint print_parameters()\n{\n\t\/\/ for bam file\n\tprintf(\"parameters:\\n\");\n\tprintf(\"min_bundle_gap = %d\\n\", min_bundle_gap);\n\tprintf(\"min_num_hits_in_bundle = %d\\n\", min_num_hits_in_bundle);\n\tprintf(\"min_splice_boundary_hits = %d\\n\", min_splice_boundary_hits);\n\tprintf(\"min_max_splice_boundary_qual = %d\\n\", min_max_splice_boundary_qual);\n\tprintf(\"min_average_overlap = %.2lf\\n\", min_average_overlap);\n\tprintf(\"min_max_region_overlap = %d\\n\", min_max_region_overlap);\n\tprintf(\"min_region_coverage = %.2lf\\n\", min_region_coverage);\n\tprintf(\"max_num_bundles = %d\\n\", max_num_bundles);\n\tprintf(\"slope_bin_size = %d\\n\", slope_bin_size);\n\tprintf(\"slope_min_bin_num = %d\\n\", slope_min_bin_num);\n\tprintf(\"slope_min_distance = %d\\n\", slope_min_distance);\n\tprintf(\"slope_min_score = %d\\n\", slope_min_score);\n\tprintf(\"slope_extend_score = %d\\n\", slope_extend_score);\n\tprintf(\"slope_flexible_bin_num = %d\\n\", slope_flexible_bin_num);\n\tprintf(\"slope_acceptance_sigma = %.2lf\\n\", slope_acceptance_sigma);\n\tprintf(\"average_slope_length = %d\\n\", average_slope_length);\n\tprintf(\"average_read_length = %d\\n\", average_read_length);\n\tprintf(\"pseudo_length_count = %d\\n\", pseudo_length_count);\n\tprintf(\"min_boundary_edge_weight_ratio = %.2lf\\n\", min_boundary_edge_weight_ratio);\n\n\t\/\/ for algorithm\n\tprintf(\"max_dp_table_size = %d\\n\", max_dp_table_size);\n\tprintf(\"max_num_subsetsum_solutions = %d\\n\", max_num_subsetsum_solutions);\n\tprintf(\"max_equation_error_ratio = %.2lf\\n\", max_equation_error_ratio);\n\n\t\/\/ for simulation\n\tprintf(\"simulation_num_vertices = %d\\n\", simulation_num_vertices);\n\tprintf(\"simulation_num_edges = %d\\n\", simulation_num_edges);\n\tprintf(\"simulation_max_edge_weight = %d\\n\", simulation_max_edge_weight);\n\n\t\/\/ for command\n\tprintf(\"algo = %s\\n\", algo.c_str());\n\tprintf(\"input_file = %s\\n\", input_file.c_str());\n\tprintf(\"output_file = %s\\n\", output_file.c_str());\n\tprintf(\"output_tex_files = %c\\n\", output_tex_files ? 'T' : 'F');\n\tprintf(\"fixed_gene_name = %s\\n\", fixed_gene_name.c_str());\n\tprintf(\"min_gtf_transcripts_num = %d\\n\", min_gtf_transcripts_num);\n\tprintf(\"fast_mode = %c\\n\", fast_mode ? 'T' : 'F');\n\tprintf(\"\\n\");\n\n\treturn 0;\n}\n\nbool parse_arguments(int argc, const char ** argv)\n{\n\toutput_tex_files = false;\n\tbool b = false;\n\tfor(int i = 1; i < argc; i++)\n\t{\n\t\tif(string(argv[i]) == \"-a\")\n\t\t{\n\t\t\talgo = string(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"-o\")\n\t\t{\n\t\t\toutput_file = string(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"-i\")\n\t\t{\n\t\t\tinput_file = string(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"-g\")\n\t\t{\n\t\t\tfixed_gene_name = string(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"-t\")\n\t\t{\n\t\t\toutput_tex_files = true;\n\t\t}\n\t\telse if(string(argv[i]) == \"-f\")\n\t\t{\n\t\t\tfast_mode = true;\n\t\t}\n\t\telse if(string(argv[i]) == \"-x\")\n\t\t{\n\t\t\tslope_min_score = atoi(argv[i + 1]);\n\t\t\tslope_extend_score = (int)(0.8 * slope_min_score);\n\t\t\ti++;\n\t\t}\n\t}\n\n\treturn b;\n}\n\n<|endoftext|>"} {"text":"\/\/ compilation\n\/\/ $ g++ -std=c++11 main.cpp -o main\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\ntypedef std::vector NeptunIds;\n\nNeptunIds readFile(const std::string& filename)\n{\n NeptunIds ids;\n std::ifstream input(filename);\n unsigned int lineCount;\n\n input >> lineCount;\n\n for (int i = 0; i < lineCount; i++)\n {\n std::string id;\n\n input >> id;\n ids.push_back(id);\n }\n\n input.close();\n return ids;\n}\n\nvoid writeFile(const std::string& filename, NeptunIds& ids)\n{\n std::ofstream output(filename);\n\n for (auto const& id : ids)\n {\n output << id << std::endl;\n }\n\n output.close();\n}\n\ntemplate \nvoid bubbleSort(std::vector& v)\n{\n bool swapped = true;\n\n for (unsigned j = 1; swapped && j < v.size(); ++j)\n {\n swapped = false;\n\n for (unsigned i = 0; i < v.size() - j; ++i)\n {\n if (v[i] > v[i + 1])\n {\n std::swap(v[i], v[i + 1]);\n swapped = true;\n }\n }\n }\n}\n\ntemplate \nvoid merge(std::vector& v, std::vector& v1, std::vector& v2) {\n int i, j, k;\n v.clear();\n\n for (i = 0, j = 0, k = 0; i < v1.size() && j < v2.size(); ++k)\n {\n if (v1.at(i) <= v2.at(j))\n {\n v.push_back(v1.at(i));\n ++i;\n }\n else if (v1.at(i) > v2.at(j))\n {\n v.push_back(v2.at(j));\n ++j;\n }\n ++k;\n }\n\n while(i < v1.size())\n {\n v.push_back(v1.at(i));\n ++i;\n }\n\n while(j < v2.size())\n {\n v.push_back(v2.at(j));\n ++j;\n }\n}\n\ntemplate \nvoid mergeSort(std::vector& v) {\n if (v.size() <= 64)\n {\n bubbleSort(v);\n return;\n }\n\n std::vector v1(v.begin(), v.begin() + v.size() \/ 2);\n std::vector v2(v.begin() + v.size() \/ 2, v.end());\n\n auto future = std::async([&v1]() mutable {\n mergeSort(v1);\n });\n\n mergeSort(v2);\n\n future.wait();\n\n merge(v, v1, v2);\n}\n\nint main()\n{\n using namespace std::chrono;\n\n NeptunIds ids = readFile(\"input.txt\");\n\n time_point t0, t1;\n t0 = system_clock::now();\n\n mergeSort(ids);\n\n t1 = system_clock::now();\n std::cout << duration_cast(t1 - t0).count() << \"ms\\n\";\n\n writeFile(\"output.txt\", ids);\n\n return 0;\n}\nbead2: iterators\/\/ compilation\n\/\/ $ g++ -std=c++11 main.cpp -o main\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\ntypedef std::vector NeptunIds;\n\nNeptunIds readFile(const std::string& filename)\n{\n NeptunIds ids;\n std::ifstream input(filename);\n unsigned int lineCount;\n\n input >> lineCount;\n\n for (int i = 0; i < lineCount; i++)\n {\n std::string id;\n\n input >> id;\n ids.push_back(id);\n }\n\n input.close();\n return ids;\n}\n\nvoid writeFile(const std::string& filename, NeptunIds& ids)\n{\n std::ofstream output(filename);\n\n for (auto const& id : ids)\n {\n output << id << std::endl;\n }\n\n output.close();\n}\n\ntemplate\nvoid bubbleSort(Iter begin, Iter end)\n{\n for (Iter i = begin; i != end; ++i)\n {\n for (Iter j = begin; j < i; ++j)\n {\n if (*i < *j)\n {\n std::iter_swap(i, j);\n }\n }\n }\n}\n\ntemplate\nstd::vector merge(Iter begin, Iter middle, Iter end) {\n std::vector buffer;\n buffer.reserve(std::distance(begin, end));\n\n Iter left(begin);\n Iter right(middle);\n\n const Iter &left_end = middle;\n const Iter &right_end = end;\n\n while (left != left_end && right != right_end)\n {\n buffer.push_back((*left <= *right) ? *left++ : *right++);\n }\n\n buffer.insert(buffer.end(), left, left_end);\n buffer.insert(buffer.end(), right, right_end);\n\n return buffer;\n}\n\ntemplate\nvoid mergeSort(Iter begin, Iter end) {\n auto length = std::distance(begin, end);\n\n if (length <= 64)\n {\n bubbleSort(begin, end);\n return;\n }\n\n Iter middle = std::next(begin, length \/ 2);\n\n auto future = std::async(mergeSort, begin, middle);\n mergeSort(middle, end);\n\n future.wait();\n\n auto &&v = merge(begin, middle, end);\n std::move(v.cbegin(), v.cend(), begin);\n}\n\nint main()\n{\n using namespace std::chrono;\n\n NeptunIds ids = readFile(\"input.txt\");\n\n time_point t0, t1;\n t0 = system_clock::now();\n\n mergeSort(ids.begin(), ids.end());\n\n t1 = system_clock::now();\n std::cout << duration_cast(t1 - t0).count() << \"ms\\n\";\n\n writeFile(\"output.txt\", ids);\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \n\n#include \"headless\/svpinst.hxx\"\n#include \"headless\/svpframe.hxx\"\n#include \"headless\/svpdummies.hxx\"\n#include \"headless\/svpvd.hxx\"\n#ifdef IOS\n#include \"headless\/svpgdi.hxx\"\n#include \"quartz\/salbmp.h\"\n#include \"quartz\/salgdi.h\"\n#include \"quartz\/salvd.h\"\n#endif\n#include \"headless\/svpbmp.hxx\"\n\n#include \n#include \n#include \n#include \n\/\/ FIXME: remove when we re-work the svp mainloop\n#include \n\nusing namespace basebmp;\n\nbool SvpSalInstance::isFrameAlive( const SalFrame* pFrame ) const\n{\n for( std::list< SalFrame* >::const_iterator it = m_aFrames.begin();\n it != m_aFrames.end(); ++it )\n {\n if( *it == pFrame )\n {\n return true;\n }\n }\n return false;\n}\n\nSvpSalInstance* SvpSalInstance::s_pDefaultInstance = NULL;\n\nSvpSalInstance::SvpSalInstance( SalYieldMutex *pMutex ) :\n SalGenericInstance( pMutex )\n{\n m_aTimeout.tv_sec = 0;\n m_aTimeout.tv_usec = 0;\n m_nTimeoutMS = 0;\n\n m_pTimeoutFDS[0] = m_pTimeoutFDS[1] = -1;\n if (pipe (m_pTimeoutFDS) != -1)\n {\n \/\/ initialize 'wakeup' pipe.\n int flags;\n\n \/\/ set close-on-exec descriptor flag.\n if ((flags = fcntl (m_pTimeoutFDS[0], F_GETFD)) != -1)\n {\n flags |= FD_CLOEXEC;\n fcntl (m_pTimeoutFDS[0], F_SETFD, flags);\n }\n if ((flags = fcntl (m_pTimeoutFDS[1], F_GETFD)) != -1)\n {\n flags |= FD_CLOEXEC;\n fcntl (m_pTimeoutFDS[1], F_SETFD, flags);\n }\n\n \/\/ set non-blocking I\/O flag.\n if ((flags = fcntl (m_pTimeoutFDS[0], F_GETFL)) != -1)\n {\n flags |= O_NONBLOCK;\n fcntl (m_pTimeoutFDS[0], F_SETFL, flags);\n }\n if ((flags = fcntl (m_pTimeoutFDS[1], F_GETFL)) != -1)\n {\n flags |= O_NONBLOCK;\n fcntl (m_pTimeoutFDS[1], F_SETFL, flags);\n }\n }\n m_aEventGuard = osl_createMutex();\n if( s_pDefaultInstance == NULL )\n s_pDefaultInstance = this;\n}\n\nSvpSalInstance::~SvpSalInstance()\n{\n if( s_pDefaultInstance == this )\n s_pDefaultInstance = NULL;\n\n \/\/ close 'wakeup' pipe.\n close (m_pTimeoutFDS[0]);\n close (m_pTimeoutFDS[1]);\n osl_destroyMutex( m_aEventGuard );\n}\n\nvoid SvpSalInstance::PostEvent( const SalFrame* pFrame, void* pData, sal_uInt16 nEvent )\n{\n if( osl_acquireMutex( m_aEventGuard ) )\n {\n m_aUserEvents.push_back( SalUserEvent( pFrame, pData, nEvent ) );\n osl_releaseMutex( m_aEventGuard );\n }\n Wakeup();\n}\n\nbool SvpSalInstance::PostedEventsInQueue()\n{\n bool result = false;\n if( osl_acquireMutex( m_aEventGuard ) )\n {\n result = m_aUserEvents.size() > 0;\n osl_releaseMutex( m_aEventGuard );\n }\n return result;\n}\n\nvoid SvpSalInstance::deregisterFrame( SalFrame* pFrame )\n{\n m_aFrames.remove( pFrame );\n\n if( osl_acquireMutex( m_aEventGuard ) )\n {\n \/\/ cancel outstanding events for this frame\n if( ! m_aUserEvents.empty() )\n {\n std::list< SalUserEvent >::iterator it = m_aUserEvents.begin();\n do\n {\n if( it->m_pFrame == pFrame )\n {\n it = m_aUserEvents.erase( it );\n }\n else\n ++it;\n } while( it != m_aUserEvents.end() );\n }\n osl_releaseMutex( m_aEventGuard );\n }\n}\n\nvoid SvpSalInstance::Wakeup()\n{\n OSL_VERIFY(write (m_pTimeoutFDS[1], \"\", 1) == 1);\n}\n\nbool SvpSalInstance::CheckTimeout( bool bExecuteTimers )\n{\n bool bRet = false;\n if( m_aTimeout.tv_sec ) \/\/ timer is started\n {\n timeval aTimeOfDay;\n gettimeofday( &aTimeOfDay, 0 );\n if( aTimeOfDay >= m_aTimeout )\n {\n bRet = true;\n if( bExecuteTimers )\n {\n \/\/ timed out, update timeout\n m_aTimeout = aTimeOfDay;\n m_aTimeout += m_nTimeoutMS;\n\n osl::Guard< comphelper::SolarMutex > aGuard( mpSalYieldMutex );\n\n \/\/ notify\n ImplSVData* pSVData = ImplGetSVData();\n if( pSVData->mpSalTimer )\n pSVData->mpSalTimer->CallCallback();\n }\n }\n }\n return bRet;\n}\n\nSalFrame* SvpSalInstance::CreateChildFrame( SystemParentData* pParent, sal_uLong nStyle )\n{\n return new SvpSalFrame( this, NULL, nStyle, false, SVP_DEFAULT_BITMAP_FORMAT, pParent );\n}\n\nSalFrame* SvpSalInstance::CreateFrame( SalFrame* pParent, sal_uLong nStyle )\n{\n return new SvpSalFrame( this, pParent, nStyle, false, SVP_DEFAULT_BITMAP_FORMAT );\n}\n\nvoid SvpSalInstance::DestroyFrame( SalFrame* pFrame )\n{\n delete pFrame;\n}\n\nSalObject* SvpSalInstance::CreateObject( SalFrame*, SystemWindowData*, bool )\n{\n return new SvpSalObject();\n}\n\nvoid SvpSalInstance::DestroyObject( SalObject* pObject )\n{\n delete pObject;\n}\n\n#ifndef IOS\n\nSalVirtualDevice* SvpSalInstance::CreateVirtualDevice( SalGraphics* \/* pGraphics *\/,\n long nDX, long nDY,\n sal_uInt16 nBitCount,\n const SystemGraphicsData* \/* pData *\/ )\n{\n SvpSalVirtualDevice* pNew = new SvpSalVirtualDevice( nBitCount );\n pNew->SetSize( nDX, nDY );\n return pNew;\n}\n\n#endif\n\nSalTimer* SvpSalInstance::CreateSalTimer()\n{\n return new SvpSalTimer( this );\n}\n\nSalI18NImeStatus* SvpSalInstance::CreateI18NImeStatus()\n{\n return new SvpImeStatus();\n}\n\nSalSystem* SvpSalInstance::CreateSalSystem()\n{\n return new SvpSalSystem();\n}\n\nSalBitmap* SvpSalInstance::CreateSalBitmap()\n{\n#ifdef IOS\n return new QuartzSalBitmap();\n#else\n return new SvpSalBitmap();\n#endif\n}\n\nvoid SvpSalInstance::Yield( bool bWait, bool bHandleAllCurrentEvents )\n{\n \/\/ first, check for already queued events.\n\n \/\/ release yield mutex\n std::list< SalUserEvent > aEvents;\n sal_uLong nAcquireCount = ReleaseYieldMutex();\n if( osl_acquireMutex( m_aEventGuard ) )\n {\n if( ! m_aUserEvents.empty() )\n {\n if( bHandleAllCurrentEvents )\n {\n aEvents = m_aUserEvents;\n m_aUserEvents.clear();\n }\n else\n {\n aEvents.push_back( m_aUserEvents.front() );\n m_aUserEvents.pop_front();\n }\n }\n osl_releaseMutex( m_aEventGuard );\n }\n \/\/ acquire yield mutex again\n AcquireYieldMutex( nAcquireCount );\n\n bool bEvent = !aEvents.empty();\n if( bEvent )\n {\n for( std::list::const_iterator it = aEvents.begin(); it != aEvents.end(); ++it )\n {\n if ( isFrameAlive( it->m_pFrame ) )\n {\n it->m_pFrame->CallCallback( it->m_nEvent, it->m_pData );\n if( it->m_nEvent == SALEVENT_RESIZE )\n {\n \/\/ this would be a good time to post a paint\n const SvpSalFrame* pSvpFrame = static_cast(it->m_pFrame);\n pSvpFrame->PostPaint(false);\n }\n }\n }\n }\n\n bEvent = CheckTimeout() || bEvent;\n\n if (bWait && ! bEvent )\n {\n int nTimeoutMS = 0;\n if (m_aTimeout.tv_sec) \/\/ Timer is started.\n {\n timeval Timeout;\n \/\/ determine remaining timeout.\n gettimeofday (&Timeout, 0);\n nTimeoutMS = m_aTimeout.tv_sec*1000 + m_aTimeout.tv_usec\/1000\n - Timeout.tv_sec*1000 - Timeout.tv_usec\/1000;\n if( nTimeoutMS < 0 )\n nTimeoutMS = 0;\n }\n else\n nTimeoutMS = -1; \/\/ wait until something happens\n\n DoReleaseYield(nTimeoutMS);\n }\n}\n\nvoid SvpSalInstance::DoReleaseYield( int nTimeoutMS )\n{\n \/\/ poll\n struct pollfd aPoll;\n aPoll.fd = m_pTimeoutFDS[0];\n aPoll.events = POLLIN;\n aPoll.revents = 0;\n\n \/\/ release yield mutex\n sal_uLong nAcquireCount = ReleaseYieldMutex();\n\n (void)poll( &aPoll, 1, nTimeoutMS );\n\n \/\/ acquire yield mutex again\n AcquireYieldMutex( nAcquireCount );\n\n \/\/ clean up pipe\n if( (aPoll.revents & POLLIN) != 0 )\n {\n int buffer;\n while (read (m_pTimeoutFDS[0], &buffer, sizeof(buffer)) > 0)\n continue;\n }\n}\n\nbool SvpSalInstance::AnyInput( sal_uInt16 nType )\n{\n if( (nType & VCL_INPUT_TIMER) != 0 )\n return CheckTimeout( false );\n return false;\n}\n\nSalSession* SvpSalInstance::CreateSalSession()\n{\n return NULL;\n}\n\nvoid* SvpSalInstance::GetConnectionIdentifier( ConnectionIdentifierType& rReturnedType, int& rReturnedBytes )\n{\n rReturnedBytes = 1;\n rReturnedType = AsciiCString;\n return const_cast(\"\");\n}\n\nvoid SvpSalInstance::StopTimer()\n{\n m_aTimeout.tv_sec = 0;\n m_aTimeout.tv_usec = 0;\n m_nTimeoutMS = 0;\n}\n\nvoid SvpSalInstance::StartTimer( sal_uLong nMS )\n{\n timeval aPrevTimeout (m_aTimeout);\n gettimeofday (&m_aTimeout, 0);\n\n m_nTimeoutMS = nMS;\n m_aTimeout += m_nTimeoutMS;\n\n if ((aPrevTimeout > m_aTimeout) || (aPrevTimeout.tv_sec == 0))\n {\n \/\/ Wakeup from previous timeout (or stopped timer).\n Wakeup();\n }\n}\n\nvoid SvpSalInstance::AddToRecentDocumentList(const OUString&, const OUString&, const OUString&)\n{\n}\n\nSvpSalTimer::~SvpSalTimer()\n{\n}\n\nvoid SvpSalTimer::Stop()\n{\n m_pInstance->StopTimer();\n}\n\nvoid SvpSalTimer::Start( sal_uLong nMS )\n{\n m_pInstance->StartTimer( nMS );\n}\n\nvoid SvpSalInstance::setBitCountFormatMapping( sal_uInt16 nBitCount,\n Format aFormat )\n{\n m_aBitCountFormatMap[nBitCount] = aFormat;\n}\n\nFormat SvpSalInstance::getFormatForBitCount( sal_uInt16 nBitCount )\n{\n BitCountFormatMap::iterator aIt;\n if ( (aIt = m_aBitCountFormatMap.find( nBitCount )) != m_aBitCountFormatMap.end() )\n {\n return aIt->second;\n }\n\n switch( nBitCount )\n {\n case 1:\n return FORMAT_ONE_BIT_MSB_PAL;\n case 4:\n return FORMAT_FOUR_BIT_MSB_PAL;\n case 8:\n return FORMAT_EIGHT_BIT_PAL;\n case 16:\n#ifdef OSL_BIGENDIAN\n return FORMAT_SIXTEEN_BIT_MSB_TC_MASK;\n#else\n return FORMAT_SIXTEEN_BIT_LSB_TC_MASK;\n#endif\n case 24:\n return FORMAT_TWENTYFOUR_BIT_TC_MASK;\n case 32:\n return FORMAT_THIRTYTWO_BIT_TC_MASK_BGRA;\n case 0:\n#ifdef ANDROID\n return FORMAT_THIRTYTWO_BIT_TC_MASK_RGBA;\n#else\n return FORMAT_TWENTYFOUR_BIT_TC_MASK;\n#endif\n default:\n return SVP_DEFAULT_BITMAP_FORMAT;\n }\n\n}\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\ncoverity#735342 silence Unchecked return value from library\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \n\n#include \"headless\/svpinst.hxx\"\n#include \"headless\/svpframe.hxx\"\n#include \"headless\/svpdummies.hxx\"\n#include \"headless\/svpvd.hxx\"\n#ifdef IOS\n#include \"headless\/svpgdi.hxx\"\n#include \"quartz\/salbmp.h\"\n#include \"quartz\/salgdi.h\"\n#include \"quartz\/salvd.h\"\n#endif\n#include \"headless\/svpbmp.hxx\"\n\n#include \n#include \n#include \n#include \n\/\/ FIXME: remove when we re-work the svp mainloop\n#include \n\nusing namespace basebmp;\n\nbool SvpSalInstance::isFrameAlive( const SalFrame* pFrame ) const\n{\n for( std::list< SalFrame* >::const_iterator it = m_aFrames.begin();\n it != m_aFrames.end(); ++it )\n {\n if( *it == pFrame )\n {\n return true;\n }\n }\n return false;\n}\n\nSvpSalInstance* SvpSalInstance::s_pDefaultInstance = NULL;\n\nSvpSalInstance::SvpSalInstance( SalYieldMutex *pMutex ) :\n SalGenericInstance( pMutex )\n{\n m_aTimeout.tv_sec = 0;\n m_aTimeout.tv_usec = 0;\n m_nTimeoutMS = 0;\n\n m_pTimeoutFDS[0] = m_pTimeoutFDS[1] = -1;\n if (pipe (m_pTimeoutFDS) != -1)\n {\n \/\/ initialize 'wakeup' pipe.\n int flags;\n\n \/\/ set close-on-exec descriptor flag.\n if ((flags = fcntl (m_pTimeoutFDS[0], F_GETFD)) != -1)\n {\n flags |= FD_CLOEXEC;\n fcntl (m_pTimeoutFDS[0], F_SETFD, flags);\n }\n if ((flags = fcntl (m_pTimeoutFDS[1], F_GETFD)) != -1)\n {\n flags |= FD_CLOEXEC;\n fcntl (m_pTimeoutFDS[1], F_SETFD, flags);\n }\n\n \/\/ set non-blocking I\/O flag.\n if ((flags = fcntl (m_pTimeoutFDS[0], F_GETFL)) != -1)\n {\n flags |= O_NONBLOCK;\n (void)fcntl(m_pTimeoutFDS[0], F_SETFL, flags);\n }\n if ((flags = fcntl (m_pTimeoutFDS[1], F_GETFL)) != -1)\n {\n flags |= O_NONBLOCK;\n (void)fcntl(m_pTimeoutFDS[1], F_SETFL, flags);\n }\n }\n m_aEventGuard = osl_createMutex();\n if( s_pDefaultInstance == NULL )\n s_pDefaultInstance = this;\n}\n\nSvpSalInstance::~SvpSalInstance()\n{\n if( s_pDefaultInstance == this )\n s_pDefaultInstance = NULL;\n\n \/\/ close 'wakeup' pipe.\n close (m_pTimeoutFDS[0]);\n close (m_pTimeoutFDS[1]);\n osl_destroyMutex( m_aEventGuard );\n}\n\nvoid SvpSalInstance::PostEvent( const SalFrame* pFrame, void* pData, sal_uInt16 nEvent )\n{\n if( osl_acquireMutex( m_aEventGuard ) )\n {\n m_aUserEvents.push_back( SalUserEvent( pFrame, pData, nEvent ) );\n osl_releaseMutex( m_aEventGuard );\n }\n Wakeup();\n}\n\nbool SvpSalInstance::PostedEventsInQueue()\n{\n bool result = false;\n if( osl_acquireMutex( m_aEventGuard ) )\n {\n result = m_aUserEvents.size() > 0;\n osl_releaseMutex( m_aEventGuard );\n }\n return result;\n}\n\nvoid SvpSalInstance::deregisterFrame( SalFrame* pFrame )\n{\n m_aFrames.remove( pFrame );\n\n if( osl_acquireMutex( m_aEventGuard ) )\n {\n \/\/ cancel outstanding events for this frame\n if( ! m_aUserEvents.empty() )\n {\n std::list< SalUserEvent >::iterator it = m_aUserEvents.begin();\n do\n {\n if( it->m_pFrame == pFrame )\n {\n it = m_aUserEvents.erase( it );\n }\n else\n ++it;\n } while( it != m_aUserEvents.end() );\n }\n osl_releaseMutex( m_aEventGuard );\n }\n}\n\nvoid SvpSalInstance::Wakeup()\n{\n OSL_VERIFY(write (m_pTimeoutFDS[1], \"\", 1) == 1);\n}\n\nbool SvpSalInstance::CheckTimeout( bool bExecuteTimers )\n{\n bool bRet = false;\n if( m_aTimeout.tv_sec ) \/\/ timer is started\n {\n timeval aTimeOfDay;\n gettimeofday( &aTimeOfDay, 0 );\n if( aTimeOfDay >= m_aTimeout )\n {\n bRet = true;\n if( bExecuteTimers )\n {\n \/\/ timed out, update timeout\n m_aTimeout = aTimeOfDay;\n m_aTimeout += m_nTimeoutMS;\n\n osl::Guard< comphelper::SolarMutex > aGuard( mpSalYieldMutex );\n\n \/\/ notify\n ImplSVData* pSVData = ImplGetSVData();\n if( pSVData->mpSalTimer )\n pSVData->mpSalTimer->CallCallback();\n }\n }\n }\n return bRet;\n}\n\nSalFrame* SvpSalInstance::CreateChildFrame( SystemParentData* pParent, sal_uLong nStyle )\n{\n return new SvpSalFrame( this, NULL, nStyle, false, SVP_DEFAULT_BITMAP_FORMAT, pParent );\n}\n\nSalFrame* SvpSalInstance::CreateFrame( SalFrame* pParent, sal_uLong nStyle )\n{\n return new SvpSalFrame( this, pParent, nStyle, false, SVP_DEFAULT_BITMAP_FORMAT );\n}\n\nvoid SvpSalInstance::DestroyFrame( SalFrame* pFrame )\n{\n delete pFrame;\n}\n\nSalObject* SvpSalInstance::CreateObject( SalFrame*, SystemWindowData*, bool )\n{\n return new SvpSalObject();\n}\n\nvoid SvpSalInstance::DestroyObject( SalObject* pObject )\n{\n delete pObject;\n}\n\n#ifndef IOS\n\nSalVirtualDevice* SvpSalInstance::CreateVirtualDevice( SalGraphics* \/* pGraphics *\/,\n long nDX, long nDY,\n sal_uInt16 nBitCount,\n const SystemGraphicsData* \/* pData *\/ )\n{\n SvpSalVirtualDevice* pNew = new SvpSalVirtualDevice( nBitCount );\n pNew->SetSize( nDX, nDY );\n return pNew;\n}\n\n#endif\n\nSalTimer* SvpSalInstance::CreateSalTimer()\n{\n return new SvpSalTimer( this );\n}\n\nSalI18NImeStatus* SvpSalInstance::CreateI18NImeStatus()\n{\n return new SvpImeStatus();\n}\n\nSalSystem* SvpSalInstance::CreateSalSystem()\n{\n return new SvpSalSystem();\n}\n\nSalBitmap* SvpSalInstance::CreateSalBitmap()\n{\n#ifdef IOS\n return new QuartzSalBitmap();\n#else\n return new SvpSalBitmap();\n#endif\n}\n\nvoid SvpSalInstance::Yield( bool bWait, bool bHandleAllCurrentEvents )\n{\n \/\/ first, check for already queued events.\n\n \/\/ release yield mutex\n std::list< SalUserEvent > aEvents;\n sal_uLong nAcquireCount = ReleaseYieldMutex();\n if( osl_acquireMutex( m_aEventGuard ) )\n {\n if( ! m_aUserEvents.empty() )\n {\n if( bHandleAllCurrentEvents )\n {\n aEvents = m_aUserEvents;\n m_aUserEvents.clear();\n }\n else\n {\n aEvents.push_back( m_aUserEvents.front() );\n m_aUserEvents.pop_front();\n }\n }\n osl_releaseMutex( m_aEventGuard );\n }\n \/\/ acquire yield mutex again\n AcquireYieldMutex( nAcquireCount );\n\n bool bEvent = !aEvents.empty();\n if( bEvent )\n {\n for( std::list::const_iterator it = aEvents.begin(); it != aEvents.end(); ++it )\n {\n if ( isFrameAlive( it->m_pFrame ) )\n {\n it->m_pFrame->CallCallback( it->m_nEvent, it->m_pData );\n if( it->m_nEvent == SALEVENT_RESIZE )\n {\n \/\/ this would be a good time to post a paint\n const SvpSalFrame* pSvpFrame = static_cast(it->m_pFrame);\n pSvpFrame->PostPaint(false);\n }\n }\n }\n }\n\n bEvent = CheckTimeout() || bEvent;\n\n if (bWait && ! bEvent )\n {\n int nTimeoutMS = 0;\n if (m_aTimeout.tv_sec) \/\/ Timer is started.\n {\n timeval Timeout;\n \/\/ determine remaining timeout.\n gettimeofday (&Timeout, 0);\n nTimeoutMS = m_aTimeout.tv_sec*1000 + m_aTimeout.tv_usec\/1000\n - Timeout.tv_sec*1000 - Timeout.tv_usec\/1000;\n if( nTimeoutMS < 0 )\n nTimeoutMS = 0;\n }\n else\n nTimeoutMS = -1; \/\/ wait until something happens\n\n DoReleaseYield(nTimeoutMS);\n }\n}\n\nvoid SvpSalInstance::DoReleaseYield( int nTimeoutMS )\n{\n \/\/ poll\n struct pollfd aPoll;\n aPoll.fd = m_pTimeoutFDS[0];\n aPoll.events = POLLIN;\n aPoll.revents = 0;\n\n \/\/ release yield mutex\n sal_uLong nAcquireCount = ReleaseYieldMutex();\n\n (void)poll( &aPoll, 1, nTimeoutMS );\n\n \/\/ acquire yield mutex again\n AcquireYieldMutex( nAcquireCount );\n\n \/\/ clean up pipe\n if( (aPoll.revents & POLLIN) != 0 )\n {\n int buffer;\n while (read (m_pTimeoutFDS[0], &buffer, sizeof(buffer)) > 0)\n continue;\n }\n}\n\nbool SvpSalInstance::AnyInput( sal_uInt16 nType )\n{\n if( (nType & VCL_INPUT_TIMER) != 0 )\n return CheckTimeout( false );\n return false;\n}\n\nSalSession* SvpSalInstance::CreateSalSession()\n{\n return NULL;\n}\n\nvoid* SvpSalInstance::GetConnectionIdentifier( ConnectionIdentifierType& rReturnedType, int& rReturnedBytes )\n{\n rReturnedBytes = 1;\n rReturnedType = AsciiCString;\n return const_cast(\"\");\n}\n\nvoid SvpSalInstance::StopTimer()\n{\n m_aTimeout.tv_sec = 0;\n m_aTimeout.tv_usec = 0;\n m_nTimeoutMS = 0;\n}\n\nvoid SvpSalInstance::StartTimer( sal_uLong nMS )\n{\n timeval aPrevTimeout (m_aTimeout);\n gettimeofday (&m_aTimeout, 0);\n\n m_nTimeoutMS = nMS;\n m_aTimeout += m_nTimeoutMS;\n\n if ((aPrevTimeout > m_aTimeout) || (aPrevTimeout.tv_sec == 0))\n {\n \/\/ Wakeup from previous timeout (or stopped timer).\n Wakeup();\n }\n}\n\nvoid SvpSalInstance::AddToRecentDocumentList(const OUString&, const OUString&, const OUString&)\n{\n}\n\nSvpSalTimer::~SvpSalTimer()\n{\n}\n\nvoid SvpSalTimer::Stop()\n{\n m_pInstance->StopTimer();\n}\n\nvoid SvpSalTimer::Start( sal_uLong nMS )\n{\n m_pInstance->StartTimer( nMS );\n}\n\nvoid SvpSalInstance::setBitCountFormatMapping( sal_uInt16 nBitCount,\n Format aFormat )\n{\n m_aBitCountFormatMap[nBitCount] = aFormat;\n}\n\nFormat SvpSalInstance::getFormatForBitCount( sal_uInt16 nBitCount )\n{\n BitCountFormatMap::iterator aIt;\n if ( (aIt = m_aBitCountFormatMap.find( nBitCount )) != m_aBitCountFormatMap.end() )\n {\n return aIt->second;\n }\n\n switch( nBitCount )\n {\n case 1:\n return FORMAT_ONE_BIT_MSB_PAL;\n case 4:\n return FORMAT_FOUR_BIT_MSB_PAL;\n case 8:\n return FORMAT_EIGHT_BIT_PAL;\n case 16:\n#ifdef OSL_BIGENDIAN\n return FORMAT_SIXTEEN_BIT_MSB_TC_MASK;\n#else\n return FORMAT_SIXTEEN_BIT_LSB_TC_MASK;\n#endif\n case 24:\n return FORMAT_TWENTYFOUR_BIT_TC_MASK;\n case 32:\n return FORMAT_THIRTYTWO_BIT_TC_MASK_BGRA;\n case 0:\n#ifdef ANDROID\n return FORMAT_THIRTYTWO_BIT_TC_MASK_RGBA;\n#else\n return FORMAT_TWENTYFOUR_BIT_TC_MASK;\n#endif\n default:\n return SVP_DEFAULT_BITMAP_FORMAT;\n }\n\n}\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"\/*************** **************\n *\n * VR Juggler is (C) Copyright 1998-2005 by Iowa State University\n *\n * Original Authors:\n * Allen Bierbaum, Christopher Just,\n * Patrick Hartling, Kevin Meinert,\n * Carolina Cruz-Neira, Albert Baker\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n *\n * -----------------------------------------------------------------\n * File: $RCSfile$\n * Date modified: $Date$\n * Version: $Revision$\n * -----------------------------------------------------------------\n *\n *************** ***************\/\n\n#include \n\nnamespace vrj\n{\n\nPfInputHandler::PfInputHandler(pfPipeWindow* pWin, const std::string& displayName)\n{\n#ifdef VPR_OS_Win32\n mWinHandle = pWin->getWSWindow();\n#else\n \/\/ Get the XWindow from that we are going to recieve events from.\n mXWindow = pWin->getWSWindow();\n\n \/\/ Create a new display connection to the X server.\n mXDisplay = XOpenDisplay( displayName.c_str());\n#endif\n}\n\n#ifdef VPR_OS_Win32\nvoid PfInputHandler::handlePerformerEvent(MSG message)\n{\n \/\/ If we have a valid KeyboardMouseDevice, process\n \/\/ all keyboard\/mouse events\n if ( NULL != mKeyboardMouseDevice )\n {\n \/\/ Forward events on to subclass. The magic of inheritance :)\n InputAreaWin32::updKeys( message );\n }\n}\n#else\nvoid PfInputHandler::handlePerformerEvent(::XEvent& event)\n{\n \/\/ If we have a valid KeyboardMouseDevice, process\n \/\/ all keyboard\/mouse events\n if ( NULL != mKeyboardMouseDevice )\n {\n \/\/ Forward events on to subclass. The magic of inheritance :)\n InputAreaXWin::handleEvent( event );\n }\n}\n#endif\n\n} \/\/ End of vrj namespace\nBug fixed:\tCompile failure with MIPSpro Compilers SF Bug#:\t1097225\/*************** **************\n *\n * VR Juggler is (C) Copyright 1998-2005 by Iowa State University\n *\n * Original Authors:\n * Allen Bierbaum, Christopher Just,\n * Patrick Hartling, Kevin Meinert,\n * Carolina Cruz-Neira, Albert Baker\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n *\n * -----------------------------------------------------------------\n * File: $RCSfile$\n * Date modified: $Date$\n * Version: $Revision$\n * -----------------------------------------------------------------\n *\n *************** ***************\/\n\n#include \n\nnamespace vrj\n{\n\nPfInputHandler::PfInputHandler(pfPipeWindow* pWin, const std::string& displayName)\n{\n#ifdef VPR_OS_Win32\n mWinHandle = pWin->getWSWindow();\n#else\n \/\/ Get the XWindow from that we are going to recieve events from.\n mXWindow = pWin->getWSWindow();\n\n \/\/ Create a new display connection to the X server.\n mXDisplay = XOpenDisplay( displayName.c_str());\n#endif\n}\n\n#ifdef VPR_OS_Win32\nvoid PfInputHandler::handlePerformerEvent(MSG message)\n{\n \/\/ If we have a valid KeyboardMouseDevice, process\n \/\/ all keyboard\/mouse events\n if ( NULL != mKeyboardMouseDevice )\n {\n \/\/ Forward events on to subclass. The magic of inheritance :)\n InputAreaWin32::updKeys( message );\n }\n}\n#else\nvoid PfInputHandler::handlePerformerEvent(::XEvent& event)\n{\n \/\/ If we have a valid KeyboardMouseDevice, process\n \/\/ all keyboard\/mouse events\n if ( NULL != mKeyboardMouseDevice )\n {\n \/\/ Forward events on to subclass. The magic of inheritance :)\n handleEvent(event);\n }\n}\n#endif\n\n} \/\/ End of vrj namespace\n<|endoftext|>"} {"text":"Remove a duplicate declaration of default_histogram_levels.<|endoftext|>"} {"text":"#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\"utils.h\"\n#include\"sandbox.h\"\n#include\"config.h\"\n#include\"testsuite.h\"\n#include\"server_io.h\"\n\nusing namespace std;\n\nint compile(const submission& target, int boxid, int spBoxid);\nvoid eval(submission &sub, int td, int boxid, int spBoxid);\nvoid getExitStatus(submission &sub, int td);\n\nint MAXPARNUM = 1;\nint BOXOFFSET = 10;\nbool AGGUPDATE = false;\n\nint testsuite(submission &sub)\n{\n system(\"rm -f .\/testzone\/*\");\n const int testBoxid = BOXOFFSET + 0, spBoxid = BOXOFFSET + 1;\n sandboxInit(testBoxid);\n sandboxInit(spBoxid);\n int status = compile(sub, testBoxid, spBoxid);\n if(status != OK) return status;\n \n \/\/anyway, only have batch judge right now\n map proc;\n int procnum = 0;\n int problem_id = sub.problem_id;\n int* time_limit = sub.time_limit;\n int* mem_limit = sub.mem_limit;\n\n for(int i = 0; i < sub.testdata_count; ++i){\n while(procnum >= MAXPARNUM){\n int status;\n pid_t cid = waitpid(-1, &status, 0);\n if(cid == -1){\n perror(\"[ERROR] in testsuite, `waitpid()` failed :\");\n return ER;\n }\n int td = proc[cid];\n eval(sub, td, BOXOFFSET + 10 + td, spBoxid);\n if(AGGUPDATE){\n sendResult(sub, OK, false);\n }\n \/\/cerr << \"td\" << td << \" : \" << sub.verdict[td] << endl;\n sandboxDele(BOXOFFSET + 10 + td);\n --procnum;\n }\n\n if(procnum < MAXPARNUM){\n \/\/batch judge\n ostringstream command;\n command << \"batchjudge \" << problem_id;\n command << \" \" << i;\n command << \" \" << BOXOFFSET + 10 + i;\n command << \" \" << time_limit[i];\n command << \" \" << mem_limit[i];\n command << \" \" << testBoxid;\n \/\/\n pid_t pid = fork();\n if(pid == -1){\n perror(\"[ERROR] in testsuite, `fork()` failed :\");\n return ER;\n }\n if(pid == 0){\n \/\/child proc\n execl(\"\/bin\/sh\", \"sh\", \"-c\", command.str().c_str(), NULL);\n perror(\"[ERROR] in testsuite, `execl()` failed :\");\n exit(0);\n }\n proc[pid] = i;\n ++procnum;\n }\n }\n while(procnum >= 1){\n int status;\n pid_t cid = waitpid(-1, &status, 0);\n if(cid == -1){\n perror(\"[ERROR] in testsuite, `waitpid()` failed :\");\n return ER;\n }\n const int td = proc[cid];\n \/\/sub.verdict[td] = eval(problem_id, td);\n eval(sub, td, BOXOFFSET + 10 + td, spBoxid);\n if(AGGUPDATE){\n sendResult(sub, OK, false);\n }\n \/\/cerr << \"td\" << td << \" : \" << sub.verdict[td] << endl;\n sandboxDele(BOXOFFSET + 10 + td);\n --procnum;\n }\n \/\/clear box-10\n sandboxDele(testBoxid);\n sandboxDele(spBoxid);\n return OK;\n}\n\nvoid setExitStatus(submission &sub, int td)\n{\n ostringstream sout;\n sout << \".\/testzone\/META\" << td;\n ifstream fin(sout.str());\n string line;\n map META;\n while(!fin.eof() && getline(fin, line)){\n for(int i = 0; i < line.size(); ++i)\n if(line[i] == ':')\n line[i] = ' ';\n istringstream in(line);\n string a, b;\n in >> a >> b;\n META[a] = b;\n }\n\n \/\/mem_used\n sub.mem[td] = cast(META[\"max-rss\"]).to();\n \/\/time_used\n sub.time[td] = 1000 * cast(META[\"time\"]).to();\n \/\/verdict\n if(META[\"status\"] == \"\"){\n sub.verdict[td] = OK;\n }else if(META[\"status\"] == \"TO\"){\n sub.verdict[td] = TLE;\n }else if(META[\"status\"] == \"SG\"){\n switch(cast(META[\"exitsig\"]).to()){\n case 11:\n sub.verdict[td] = MLE;\n break;\n default :\n sub.verdict[td] = RE;\n }\n }else if(META[\"status\"] == \"RE\"){\n sub.verdict[td] = RE;\n }else{\n \/\/ \"XX\"\n sub.verdict[td] = ER;\n }\n return ;\n}\n\nvoid eval(submission &sub, int td, int boxid, int spBoxid)\n{\n int problem_id = sub.problem_id;\n setExitStatus(sub, td);\n if(sub.verdict[td] != OK){\n return ;\n }\n \n if(sub.problem_type == 1){\n ostringstream sout;\n sout << \"\/tmp\/box\/\" << spBoxid << \"\/box\/sj.out \";\n string sjpath(sout.str());\n sout.str(\"\");\n sout << \".\/testdata\" << setfill('0') << setw(4) << problem_id << \"\/input\" << setw(3) << td << ' ';\n string tdin(sout.str());\n sout.str(\"\");\n sout << \".\/testdata\" << setfill('0') << setw(4) << problem_id << \"\/output\" << setw(3) << td << ' ';\n string tdout(sout.str());\n sout.str(\"\");\n sout << \"\/tmp\/box\/\" << boxid << \"\/box\/output \";\n string ttout(sout.str());\n FILE* Pipe = popen((sjpath+ttout+tdin+tdout).c_str(), \"r\");\n int result = 1;\n fscanf(Pipe, \"%d\", &result);\n pclose(Pipe);\n if(result == 0)\n sub.verdict[td] = AC;\n else\n sub.verdict[td] = WA;\n return ;\n }\n\n int status = AC;\n string s, t;\n \/\/solution output\n ostringstream sout;\n sout << \".\/testdata\/\" << setfill('0') << setw(4) << problem_id\n << \"\/output\" << setw(3) << td;\n fstream tsol(sout.str());\n \/\/user output\n sout.str(\"\");\n sout << \"\/tmp\/box\/\" << boxid << \"\/box\/output\";\n fstream mout(sout.str());\n while(1){\n s=\"\";\n t=\"\";\n getline(tsol,s);\n getline(mout,t);\n if(t==\"\"&&s!=\"\"){\n status = WA;\n break;\n }\n if(t!=\"\"&&s==\"\"){\n status = WA;\n break;\n }\n if(t==\"\"&&s==\"\"){\n break;\n }\n s.erase(s.find_last_not_of(\" \\n\\r\\t\")+1);\n t.erase(t.find_last_not_of(\" \\n\\r\\t\")+1);\n if(s!=t){\n status = WA;\n break;\n }\n }\n sub.verdict[td] = status;\n return ;\n}\n\nint compile(const submission& target, int boxid, int spBoxid)\n{\n ostringstream sout;\n sout << \"\/tmp\/box\/\" << boxid << \"\/box\/\";\n string boxdir(sout.str());\n \n ofstream fout;\n if(target.lang == \"c++\"){\n fout.open(boxdir + \"main.cpp\");\n }else{\n fout.open(boxdir + \"main.c\");\n }\n fout << target.code << flush;\n fout.close();\n \n if(target.problem_type == 2){\n sout.str(\"\");\n sout << boxdir << \"lib\" << setw(4) << setfill('0') << target.problem_id << \".h\";\n fout.open(sout.str());\n fout << target.interlib << flush;\n fout.close();\n }\n\n sout.str(\"\");\n if(target.lang == \"c++\"){\n sout << \"\/usr\/bin\/g++ .\/main.cpp -o .\/main.out -O2 \";\n }else{\n sout << \"\/usr\/bin\/gcc .\/main.c -o .\/main.out -O2 -ansi \";\n }\n if(!target.std.empty()){\n sout << \"-std=\" << target.std << \" \";\n }\n string comm(sout.str());\n sandboxOptions opt;\n opt.dirs.push_back(\"\/etc\/\");\n opt.procs = 50;\n opt.preserve_env = true;\n opt.errout = \"compile_error\";\n opt.timeout = 60 * 1000;\n opt.meta = \".\/testzone\/metacomp\";\n\n sandboxExec(boxid, opt, comm);\n if(access((boxdir+\"main.out\").c_str(), F_OK) == -1){\n return CE;\n }\n \n if(target.problem_type == 1){\n sout.str(\"\");\n sout << \"\/tmp\/box\/\" << spBoxid << \"\/box\/\";\n string spBoxdir = sout.str();\n \n fout.open(spBoxdir + \"sj.cpp\");\n fout << target.sjcode << flush;\n fout.close();\n \n sout.str(\"\");\n sout << \"\/usr\/bin\/g++ .\/sj.cpp -o .\/sj.out -O2 -std=c++11 \";\n \n opt.meta = \".\/testzone\/metacompsj\";\n\n sandboxExec(spBoxid, opt, sout.str());\n if(access((spBoxdir+\"sj.out\").c_str(), F_OK) == -1){\n return ER;\n }\n }\n \n return OK;\n}\njizzzzzzzzzzzzz#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\"utils.h\"\n#include\"sandbox.h\"\n#include\"config.h\"\n#include\"testsuite.h\"\n#include\"server_io.h\"\n\nusing namespace std;\n\nint compile(const submission& target, int boxid, int spBoxid);\nvoid eval(submission &sub, int td, int boxid, int spBoxid);\nvoid getExitStatus(submission &sub, int td);\n\nint MAXPARNUM = 1;\nint BOXOFFSET = 10;\nbool AGGUPDATE = false;\n\nint testsuite(submission &sub)\n{\n system(\"rm -f .\/testzone\/*\");\n const int testBoxid = BOXOFFSET + 0, spBoxid = BOXOFFSET + 1;\n sandboxInit(testBoxid);\n sandboxInit(spBoxid);\n int status = compile(sub, testBoxid, spBoxid);\n if(status != OK) return status;\n \n \/\/anyway, only have batch judge right now\n map proc;\n int procnum = 0;\n int problem_id = sub.problem_id;\n int* time_limit = sub.time_limit;\n int* mem_limit = sub.mem_limit;\n\n for(int i = 0; i < sub.testdata_count; ++i){\n while(procnum >= MAXPARNUM){\n int status;\n pid_t cid = waitpid(-1, &status, 0);\n if(cid == -1){\n perror(\"[ERROR] in testsuite, `waitpid()` failed :\");\n return ER;\n }\n int td = proc[cid];\n eval(sub, td, BOXOFFSET + 10 + td, spBoxid);\n if(AGGUPDATE){\n sendResult(sub, OK, false);\n }\n \/\/cerr << \"td\" << td << \" : \" << sub.verdict[td] << endl;\n sandboxDele(BOXOFFSET + 10 + td);\n --procnum;\n }\n\n if(procnum < MAXPARNUM){\n \/\/batch judge\n ostringstream command;\n command << \"batchjudge \" << problem_id;\n command << \" \" << i;\n command << \" \" << BOXOFFSET + 10 + i;\n command << \" \" << time_limit[i];\n command << \" \" << mem_limit[i];\n command << \" \" << testBoxid;\n \/\/\n pid_t pid = fork();\n if(pid == -1){\n perror(\"[ERROR] in testsuite, `fork()` failed :\");\n return ER;\n }\n if(pid == 0){\n \/\/child proc\n execl(\"\/bin\/sh\", \"sh\", \"-c\", command.str().c_str(), NULL);\n perror(\"[ERROR] in testsuite, `execl()` failed :\");\n exit(0);\n }\n proc[pid] = i;\n ++procnum;\n }\n }\n while(procnum >= 1){\n int status;\n pid_t cid = waitpid(-1, &status, 0);\n if(cid == -1){\n perror(\"[ERROR] in testsuite, `waitpid()` failed :\");\n return ER;\n }\n const int td = proc[cid];\n \/\/sub.verdict[td] = eval(problem_id, td);\n eval(sub, td, BOXOFFSET + 10 + td, spBoxid);\n if(AGGUPDATE){\n sendResult(sub, OK, false);\n }\n \/\/cerr << \"td\" << td << \" : \" << sub.verdict[td] << endl;\n sandboxDele(BOXOFFSET + 10 + td);\n --procnum;\n }\n \/\/clear box-10\n sandboxDele(testBoxid);\n sandboxDele(spBoxid);\n return OK;\n}\n\nvoid setExitStatus(submission &sub, int td)\n{\n ostringstream sout;\n sout << \".\/testzone\/META\" << td;\n ifstream fin(sout.str());\n string line;\n map META;\n while(!fin.eof() && getline(fin, line)){\n for(int i = 0; i < line.size(); ++i)\n if(line[i] == ':')\n line[i] = ' ';\n istringstream in(line);\n string a, b;\n in >> a >> b;\n META[a] = b;\n }\n\n \/\/mem_used\n sub.mem[td] = cast(META[\"max-rss\"]).to();\n \/\/time_used\n sub.time[td] = 1000 * cast(META[\"time\"]).to();\n \/\/verdict\n if(META[\"status\"] == \"\"){\n sub.verdict[td] = OK;\n }else if(META[\"status\"] == \"TO\"){\n sub.verdict[td] = TLE;\n }else if(META[\"status\"] == \"SG\"){\n switch(cast(META[\"exitsig\"]).to()){\n case 11:\n sub.verdict[td] = MLE;\n break;\n default :\n sub.verdict[td] = RE;\n }\n }else if(META[\"status\"] == \"RE\"){\n sub.verdict[td] = RE;\n }else{\n \/\/ \"XX\"\n sub.verdict[td] = ER;\n }\n return ;\n}\n\nvoid eval(submission &sub, int td, int boxid, int spBoxid)\n{\n int problem_id = sub.problem_id;\n setExitStatus(sub, td);\n if(sub.verdict[td] != OK){\n return ;\n }\n \n if(sub.problem_type == 1){\n ostringstream sout;\n sout << \"\/tmp\/box\/\" << spBoxid << \"\/box\/sj.out \";\n string sjpath(sout.str());\n sout.str(\"\");\n sout << \".\/testdata\" << setfill('0') << setw(4) << problem_id << \"\/input\" << setw(3) << td << ' ';\n string tdin(sout.str());\n sout.str(\"\");\n sout << \".\/testdata\" << setfill('0') << setw(4) << problem_id << \"\/output\" << setw(3) << td << ' ';\n string tdout(sout.str());\n sout.str(\"\");\n sout << \"\/tmp\/box\/\" << boxid << \"\/box\/output \";\n string ttout(sout.str());\n FILE* Pipe = popen((sjpath+ttout+tdin+tdout).c_str(), \"r\");\n int result = 1;\n fscanf(Pipe, \"%d\", &result);\n pclose(Pipe);\n if(result == 0)\n sub.verdict[td] = AC;\n else\n sub.verdict[td] = WA;\n return ;\n }\n\n int status = AC;\n \/\/solution output\n ostringstream sout;\n sout << \".\/testdata\/\" << setfill('0') << setw(4) << problem_id\n << \"\/output\" << setw(3) << td;\n fstream tsol(sout.str());\n \/\/user output\n sout.str(\"\");\n sout << \"\/tmp\/box\/\" << boxid << \"\/box\/output\";\n fstream mout(sout.str());\n while(true){\n if(tsol.eof() != mout.eof()){\n status = WA;\n break;\n }\n if(tsol.eof() && mout.eof()){\n break;\n }\n string s, t;\n getline(tsol,s);\n getline(mout,t);\n s.erase(s.find_last_not_of(\" \\n\\r\\t\")+1);\n t.erase(t.find_last_not_of(\" \\n\\r\\t\")+1);\n if(s != t){\n status = WA;\n break;\n }\n }\n sub.verdict[td] = status;\n return ;\n}\n\nint compile(const submission& target, int boxid, int spBoxid)\n{\n ostringstream sout;\n sout << \"\/tmp\/box\/\" << boxid << \"\/box\/\";\n string boxdir(sout.str());\n \n ofstream fout;\n if(target.lang == \"c++\"){\n fout.open(boxdir + \"main.cpp\");\n }else{\n fout.open(boxdir + \"main.c\");\n }\n fout << target.code << flush;\n fout.close();\n \n if(target.problem_type == 2){\n sout.str(\"\");\n sout << boxdir << \"lib\" << setw(4) << setfill('0') << target.problem_id << \".h\";\n fout.open(sout.str());\n fout << target.interlib << flush;\n fout.close();\n }\n\n sout.str(\"\");\n if(target.lang == \"c++\"){\n sout << \"\/usr\/bin\/g++ .\/main.cpp -o .\/main.out -O2 \";\n }else{\n sout << \"\/usr\/bin\/gcc .\/main.c -o .\/main.out -O2 -ansi \";\n }\n if(!target.std.empty()){\n sout << \"-std=\" << target.std << \" \";\n }\n string comm(sout.str());\n sandboxOptions opt;\n opt.dirs.push_back(\"\/etc\/\");\n opt.procs = 50;\n opt.preserve_env = true;\n opt.errout = \"compile_error\";\n opt.timeout = 60 * 1000;\n opt.meta = \".\/testzone\/metacomp\";\n\n sandboxExec(boxid, opt, comm);\n if(access((boxdir+\"main.out\").c_str(), F_OK) == -1){\n return CE;\n }\n \n if(target.problem_type == 1){\n sout.str(\"\");\n sout << \"\/tmp\/box\/\" << spBoxid << \"\/box\/\";\n string spBoxdir = sout.str();\n \n fout.open(spBoxdir + \"sj.cpp\");\n fout << target.sjcode << flush;\n fout.close();\n \n sout.str(\"\");\n sout << \"\/usr\/bin\/g++ .\/sj.cpp -o .\/sj.out -O2 -std=c++11 \";\n \n opt.meta = \".\/testzone\/metacompsj\";\n\n sandboxExec(spBoxid, opt, sout.str());\n if(access((spBoxdir+\"sj.out\").c_str(), F_OK) == -1){\n return ER;\n }\n }\n \n return OK;\n}\n<|endoftext|>"} {"text":"\/*\n* Client Key Exchange Message\n* (C) 2004-2010 Jack Lloyd\n*\n* Released under the terms of the Botan license\n*\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace Botan {\n\nnamespace TLS {\n\nnamespace {\n\nSecureVector strip_leading_zeros(const MemoryRegion& input)\n {\n size_t leading_zeros = 0;\n\n for(size_t i = 0; i != input.size(); ++i)\n {\n if(input[i] != 0)\n break;\n ++leading_zeros;\n }\n\n SecureVector output(&input[leading_zeros],\n input.size() - leading_zeros);\n return output;\n }\n\n}\n\n\/*\n* Create a new Client Key Exchange message\n*\/\nClient_Key_Exchange::Client_Key_Exchange(Record_Writer& writer,\n Handshake_State* state,\n const std::vector& peer_certs,\n RandomNumberGenerator& rng)\n {\n if(state->server_kex)\n {\n TLS_Data_Reader reader(state->server_kex->params());\n\n if(state->suite.kex_algo() == \"DH\")\n {\n BigInt p = BigInt::decode(reader.get_range(2, 1, 65535));\n BigInt g = BigInt::decode(reader.get_range(2, 1, 65535));\n BigInt Y = BigInt::decode(reader.get_range(2, 1, 65535));\n\n if(reader.remaining_bytes())\n throw Decoding_Error(\"Bad params size for DH key exchange\");\n\n DL_Group group(p, g);\n\n if(!group.verify_group(rng, true))\n throw Internal_Error(\"DH group failed validation, possible attack\");\n\n DH_PublicKey counterparty_key(group, Y);\n\n \/\/ FIXME Check that public key is residue?\n\n DH_PrivateKey priv_key(rng, group);\n\n PK_Key_Agreement ka(priv_key, \"Raw\");\n\n pre_master = strip_leading_zeros(\n ka.derive_key(0, counterparty_key.public_value()).bits_of());\n\n append_tls_length_value(key_material, priv_key.public_value(), 2);\n }\n else if(state->suite.kex_algo() == \"ECDH\")\n {\n const byte curve_type = reader.get_byte();\n\n if(curve_type != 3)\n throw Decoding_Error(\"Server sent non-named ECC curve\");\n\n const u16bit curve_id = reader.get_u16bit();\n\n const std::string name = Supported_Elliptic_Curves::curve_id_to_name(curve_id);\n\n if(name == \"\")\n throw Decoding_Error(\"Server sent unknown named curve \" + to_string(curve_id));\n\n EC_Group group(name);\n\n MemoryVector ecdh_key = reader.get_range(1, 1, 255);\n\n ECDH_PublicKey counterparty_key(group, OS2ECP(ecdh_key, group.get_curve()));\n\n ECDH_PrivateKey priv_key(rng, group);\n\n PK_Key_Agreement ka(priv_key, \"Raw\");\n\n pre_master = strip_leading_zeros(\n ka.derive_key(0, counterparty_key.public_value()).bits_of());\n\n append_tls_length_value(key_material, priv_key.public_value(), 1);\n }\n else\n throw Internal_Error(\"Server key exchange type \" + state->suite.kex_algo() +\n \" not known\");\n }\n else\n {\n \/\/ No server key exchange msg better mean a RSA key in the cert\n\n std::auto_ptr pub_key(peer_certs[0].subject_public_key());\n\n if(peer_certs.empty())\n throw Internal_Error(\"No certificate and no server key exchange\");\n\n if(const RSA_PublicKey* rsa_pub = dynamic_cast(pub_key.get()))\n {\n const Protocol_Version pref_version = state->client_hello->version();\n\n pre_master = rng.random_vec(48);\n pre_master[0] = pref_version.major_version();\n pre_master[1] = pref_version.minor_version();\n\n PK_Encryptor_EME encryptor(*rsa_pub, \"PKCS1v15\");\n\n MemoryVector encrypted_key = encryptor.encrypt(pre_master, rng);\n\n if(state->version == Protocol_Version::SSL_V3)\n key_material = encrypted_key; \/\/ no length field\n else\n append_tls_length_value(key_material, encrypted_key, 2);\n }\n else\n throw TLS_Exception(HANDSHAKE_FAILURE,\n \"Expected a RSA key in server cert but got \" +\n pub_key->algo_name());\n }\n\n send(writer, state->hash);\n }\n\n\/*\n* Read a Client Key Exchange message\n*\/\nClient_Key_Exchange::Client_Key_Exchange(const MemoryRegion& contents,\n const Ciphersuite& suite,\n Protocol_Version using_version)\n {\n if(suite.kex_algo() == \"\" && using_version == Protocol_Version::SSL_V3)\n key_material = contents;\n else\n {\n TLS_Data_Reader reader(contents);\n\n if(suite.kex_algo() == \"\" || suite.kex_algo() == \"DH\")\n key_material = reader.get_range(2, 0, 65535);\n else if(suite.kex_algo() == \"ECDH\")\n key_material = reader.get_range(1, 1, 255);\n else\n throw Internal_Error(\"Unknown client key exch type \" + suite.kex_algo());\n }\n }\n\n\/*\n* Return the pre_master_secret\n*\/\nSecureVector\nClient_Key_Exchange::pre_master_secret(RandomNumberGenerator& rng,\n const Private_Key* priv_key,\n Protocol_Version client_version)\n {\n\n if(const DH_PrivateKey* dh_priv = dynamic_cast(priv_key))\n {\n try {\n PK_Key_Agreement ka(*dh_priv, \"Raw\");\n\n pre_master = strip_leading_zeros(ka.derive_key(0, key_material).bits_of());\n }\n catch(...)\n {\n \/*\n * Something failed in the DH computation. To avoid possible\n * timing attacks, randomize the pre-master output and carry\n * on, allowing the protocol to fail later in the finished\n * checks.\n *\/\n pre_master = rng.random_vec(dh_priv->public_value().size());\n }\n\n return pre_master;\n }\n else if(const RSA_PrivateKey* rsa_priv = dynamic_cast(priv_key))\n {\n PK_Decryptor_EME decryptor(*rsa_priv, \"PKCS1v15\");\n\n try {\n pre_master = decryptor.decrypt(key_material);\n\n if(pre_master.size() != 48 ||\n client_version.major_version() != pre_master[0] ||\n client_version.minor_version() != pre_master[1])\n {\n throw Decoding_Error(\"Client_Key_Exchange: Secret corrupted\");\n }\n }\n catch(...)\n {\n pre_master = rng.random_vec(48);\n pre_master[0] = client_version.major_version();\n pre_master[1] = client_version.minor_version();\n }\n\n return pre_master;\n }\n else\n throw Invalid_Argument(\"Client_Key_Exchange: Bad key for decrypt\");\n }\n\n}\n\n}\nRead ECDH client key exchange messages\/*\n* Client Key Exchange Message\n* (C) 2004-2010 Jack Lloyd\n*\n* Released under the terms of the Botan license\n*\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace Botan {\n\nnamespace TLS {\n\nnamespace {\n\nSecureVector strip_leading_zeros(const MemoryRegion& input)\n {\n size_t leading_zeros = 0;\n\n for(size_t i = 0; i != input.size(); ++i)\n {\n if(input[i] != 0)\n break;\n ++leading_zeros;\n }\n\n SecureVector output(&input[leading_zeros],\n input.size() - leading_zeros);\n return output;\n }\n\n}\n\n\/*\n* Create a new Client Key Exchange message\n*\/\nClient_Key_Exchange::Client_Key_Exchange(Record_Writer& writer,\n Handshake_State* state,\n const std::vector& peer_certs,\n RandomNumberGenerator& rng)\n {\n if(state->server_kex)\n {\n TLS_Data_Reader reader(state->server_kex->params());\n\n if(state->suite.kex_algo() == \"DH\")\n {\n BigInt p = BigInt::decode(reader.get_range(2, 1, 65535));\n BigInt g = BigInt::decode(reader.get_range(2, 1, 65535));\n BigInt Y = BigInt::decode(reader.get_range(2, 1, 65535));\n\n if(reader.remaining_bytes())\n throw Decoding_Error(\"Bad params size for DH key exchange\");\n\n DL_Group group(p, g);\n\n if(!group.verify_group(rng, true))\n throw Internal_Error(\"DH group failed validation, possible attack\");\n\n DH_PublicKey counterparty_key(group, Y);\n\n \/\/ FIXME Check that public key is residue?\n\n DH_PrivateKey priv_key(rng, group);\n\n PK_Key_Agreement ka(priv_key, \"Raw\");\n\n pre_master = strip_leading_zeros(\n ka.derive_key(0, counterparty_key.public_value()).bits_of());\n\n append_tls_length_value(key_material, priv_key.public_value(), 2);\n }\n else if(state->suite.kex_algo() == \"ECDH\")\n {\n const byte curve_type = reader.get_byte();\n\n if(curve_type != 3)\n throw Decoding_Error(\"Server sent non-named ECC curve\");\n\n const u16bit curve_id = reader.get_u16bit();\n\n const std::string name = Supported_Elliptic_Curves::curve_id_to_name(curve_id);\n\n if(name == \"\")\n throw Decoding_Error(\"Server sent unknown named curve \" + to_string(curve_id));\n\n EC_Group group(name);\n\n MemoryVector ecdh_key = reader.get_range(1, 1, 255);\n\n ECDH_PublicKey counterparty_key(group, OS2ECP(ecdh_key, group.get_curve()));\n\n ECDH_PrivateKey priv_key(rng, group);\n\n PK_Key_Agreement ka(priv_key, \"Raw\");\n\n pre_master = strip_leading_zeros(\n ka.derive_key(0, counterparty_key.public_value()).bits_of());\n\n append_tls_length_value(key_material, priv_key.public_value(), 1);\n }\n else\n throw Internal_Error(\"Server key exchange type \" + state->suite.kex_algo() +\n \" not known\");\n }\n else\n {\n \/\/ No server key exchange msg better mean a RSA key in the cert\n\n std::auto_ptr pub_key(peer_certs[0].subject_public_key());\n\n if(peer_certs.empty())\n throw Internal_Error(\"No certificate and no server key exchange\");\n\n if(const RSA_PublicKey* rsa_pub = dynamic_cast(pub_key.get()))\n {\n const Protocol_Version pref_version = state->client_hello->version();\n\n pre_master = rng.random_vec(48);\n pre_master[0] = pref_version.major_version();\n pre_master[1] = pref_version.minor_version();\n\n PK_Encryptor_EME encryptor(*rsa_pub, \"PKCS1v15\");\n\n MemoryVector encrypted_key = encryptor.encrypt(pre_master, rng);\n\n if(state->version == Protocol_Version::SSL_V3)\n key_material = encrypted_key; \/\/ no length field\n else\n append_tls_length_value(key_material, encrypted_key, 2);\n }\n else\n throw TLS_Exception(HANDSHAKE_FAILURE,\n \"Expected a RSA key in server cert but got \" +\n pub_key->algo_name());\n }\n\n send(writer, state->hash);\n }\n\n\/*\n* Read a Client Key Exchange message\n*\/\nClient_Key_Exchange::Client_Key_Exchange(const MemoryRegion& contents,\n const Ciphersuite& suite,\n Protocol_Version using_version)\n {\n if(suite.kex_algo() == \"\" && using_version == Protocol_Version::SSL_V3)\n key_material = contents;\n else\n {\n TLS_Data_Reader reader(contents);\n\n if(suite.kex_algo() == \"\" || suite.kex_algo() == \"DH\")\n key_material = reader.get_range(2, 0, 65535);\n else if(suite.kex_algo() == \"ECDH\")\n key_material = reader.get_range(1, 1, 255);\n else\n throw Internal_Error(\"Unknown client key exch type \" + suite.kex_algo());\n }\n }\n\n\/*\n* Return the pre_master_secret\n*\/\nSecureVector\nClient_Key_Exchange::pre_master_secret(RandomNumberGenerator& rng,\n const Private_Key* priv_key,\n Protocol_Version client_version)\n {\n if(const RSA_PrivateKey* rsa = dynamic_cast(priv_key))\n {\n PK_Decryptor_EME decryptor(*rsa, \"PKCS1v15\");\n\n try {\n pre_master = decryptor.decrypt(key_material);\n\n if(pre_master.size() != 48 ||\n client_version.major_version() != pre_master[0] ||\n client_version.minor_version() != pre_master[1])\n {\n throw Decoding_Error(\"Client_Key_Exchange: Secret corrupted\");\n }\n }\n catch(...)\n {\n pre_master = rng.random_vec(48);\n pre_master[0] = client_version.major_version();\n pre_master[1] = client_version.minor_version();\n }\n\n return pre_master;\n }\n\n \/\/ DH or ECDH\n if(const PK_Key_Agreement_Key* dh = dynamic_cast(priv_key))\n {\n try {\n PK_Key_Agreement ka(*dh, \"Raw\");\n\n pre_master = strip_leading_zeros(ka.derive_key(0, key_material).bits_of());\n }\n catch(...)\n {\n \/*\n * Something failed in the DH computation. To avoid possible\n * timing attacks, randomize the pre-master output and carry\n * on, allowing the protocol to fail later in the finished\n * checks.\n *\/\n pre_master = rng.random_vec(dh->public_value().size());\n }\n\n return pre_master;\n }\n\n throw Invalid_Argument(\"Client_Key_Exchange: Unknown key type \" + priv_key->algo_name());\n }\n\n}\n\n}\n<|endoftext|>"} {"text":"#pragma once\n#include \"..\/common.hpp\"\n#include \n#include \n#include \n#include \"..\/generic\/simple-set.hpp\"\n#include \"..\/collector.hpp\"\n#include \"nodes.hpp\"\n\nnamespace Mirb\n{\n\tclass Block;\n\n\tnamespace CodeGen\n\t{\n\t\tclass Block;\n\t};\n\t\n\tnamespace Tree\n\t{\n\t\tclass Chunk\n\t\t{\n\t\t\tpublic:\n\t\t\t\tstatic const size_t main_size = 512;\n\t\t\t\tstatic const size_t block_size = 256;\n\t\t\t\tstatic const size_t allocation_limit = 128;\n\t\t\t\t\n\t\t\t\tstatic Chunk *create(size_t bytes);\n\t\t\t\t\n\t\t\t\tuint8_t *current;\n\t\t\t\tuint8_t *end;\n\t\t\t\t\n\t\t\t\tListEntry entry;\n\t\t\t\t\n\t\t\t\tvoid *allocate(size_t bytes);\n\t\t};\n\t\t\n\t\tclass Fragment:\n\t\t\tpublic WithReferenceProvider\n\t\t{\n\t\t\tpublic:\n\t\t\t\tstatic const bool can_free = false;\n\n\t\t\t\tFragment(Fragment *parent, size_t chunk_size);\n\t\t\t\t\n\t\t\t\tVector fragments;\n\t\t\t\t\n\t\t\t\tvoid *allocate(size_t bytes);\n\t\t\t\tvoid *reallocate(void *memory, size_t old_size, size_t new_size);\n\t\t\t\tvoid free(void *memory)\n\t\t\t\t{\n\t\t\t\t}\n\t\t\t\t\n\t\t\tprivate:\n\t\t\t\tsize_t chunk_size;\n\t\t\t\t\n\t\t\t\tChunk *current;\n\t\t\t\t\n\t\t\t\tFastList chunks;\n\t\t};\n\t\t\n\t\tstruct Node;\n\t\t\n\t\tstruct SuperNode;\n\n\t\tclass Variable\n\t\t{\n\t\t\tpublic:\n\t\t\t\tenum Type\n\t\t\t\t{\n\t\t\t\t\tTemporary,\n\t\t\t\t\tLocal,\n\t\t\t\t\tHeap,\n\t\t\t\t\tTypes\n\t\t\t\t};\n\n\t\t\t\tType type;\n\t\t\t\tScope *owner; \/\/ Only valid for heap variables\n\t\t\t\t\n\t\t\t\tVariable(Type type)\n\t\t\t\t\t: type(type)\n\t\t\t\t\t#ifdef DEBUG\n\t\t\t\t\t\t, group(0)\n\t\t\t\t\t#endif\n\t\t\t\t{\n\t\t\t\t}\n\n\t\t\t\tsize_t loc;\n\n\t\t\t\t#ifdef DEBUG\n\t\t\t\t\tVariable *group;\n\t\t\t\t#endif\n\t\t};\n\n\t\tclass NamedVariable:\n\t\t\tpublic Variable\n\t\t{\n\t\t\tpublic:\n\t\t\t\tNamedVariable(Type type) : Variable(type) {}\n\t\t\t\t\n\t\t\t\tSymbol *name;\n\t\t\t\tNamedVariable *next;\n\t\t};\n\n\t\tclass Parameter:\n\t\t\tpublic NamedVariable\n\t\t{\n\t\t\tpublic:\n\t\t\t\tParameter(Type type) : NamedVariable(type) {}\n\t\t\t\t\n\t\t\t\tListEntry parameter_entry;\n\t\t};\n\n\t\tclass VariableMapFunctions:\n\t\t\tpublic HashTableFunctions\n\t\t{\n\t\t\tpublic:\n\t\t\t\tstatic bool compare_key_value(Symbol *key, NamedVariable *value)\n\t\t\t\t{\n\t\t\t\t\treturn key == value->name;\n\t\t\t\t}\n\n\t\t\t\tstatic Symbol *get_key(NamedVariable *value)\n\t\t\t\t{\n\t\t\t\t\treturn value->name;\n\t\t\t\t}\n\n\t\t\t\tstatic NamedVariable *get_value_next(NamedVariable *value)\n\t\t\t\t{\n\t\t\t\t\treturn value->next;\n\t\t\t\t}\n\n\t\t\t\tstatic void set_value_next(NamedVariable *value, NamedVariable *next)\n\t\t\t\t{\n\t\t\t\t\tvalue->next = next;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tstatic size_t hash_key(Symbol *key)\n\t\t\t\t{\n\t\t\t\t\treturn (size_t)key;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tstatic bool valid_key(Symbol *key)\n\t\t\t\t{\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t};\n\t\t\n\t\ttypedef HashTable VariableMap;\n\t\t\n\t\tclass Scope:\n\t\t\tpublic PinnedHeader\n\t\t{\n\t\t\tpublic:\n\t\t\t\tenum Type\n\t\t\t\t{\n\t\t\t\t\tTop,\n\t\t\t\t\tMethod,\n\t\t\t\t\tClass,\n\t\t\t\t\tModule,\n\t\t\t\t\tClosure\n\t\t\t\t};\n\t\t\t\t\n\t\t\t\tScope(Document *document, Fragment *fragment, Scope *parent, Type type);\n\t\t\t\t\n\t\t\t\tDocument *document;\n\t\t\t\tBlock *final;\n\t\t\t\tFragment *fragment;\n\t\t\t\tType type;\n\t\t\t\tScope *parent; \/\/ The scope enclosing this one\n\t\t\t\tScope *owner; \/\/ The first parent that isn't a closure. This field can point to itself.\n\t\t\t\tNode *group;\n\t\t\t\t\n\t\t\t\t\/*\n\t\t\t\t * Break related fields\n\t\t\t\t *\/\n\t\t\t\tsize_t break_id; \/\/ Which of the parent's break targets this block belongs to.\n\t\t\t\tsize_t break_targets; \/\/ Number of child blocks that can raise a break exception.\n\t\t\t\tvar_t break_dst; \/\/ The variable in the parent that the break will override.\n\t\t\t\t\n\t\t\t\tstatic const size_t no_break_id = (size_t)-1;\n\n\t\t\t\t\/*\n\t\t\t\t * Exception related fields\n\t\t\t\t *\/\n\t\t\t\tbool require_exceptions;\n\n\t\t\t\t\/*\n\t\t\t\t * Variable related fields\n\t\t\t\t *\/\n\t\t\t\tVariableMap variables; \/\/ A hash of the variables in this scope.\n\t\t\t\tsize_t heap_vars; \/\/ The number of the variables that must be stored on a heap scope.\n\t\t\t\tParameter *block_parameter; \/\/ Pointer to a named or unnamed block variable.\n\t\t\t\tVector referenced_scopes; \/\/ A list of all the scopes this scope requires.\n\n\t\t\t\tVector children; \/\/ A list of all the immediate children. To keep them alive...\n\t\t\t\t\n\t\t\t\tVector variable_list; \/\/ A list of all variables in this scope.\n\n\t\t\t\tCountedList parameters;\n\t\t\t\t\n\t\t\t\tVector zsupers;\n\t\t\t\t\n\t\t\t\ttemplate void mark(F mark)\n\t\t\t\t{\n\t\t\t\t\tmark(final);\n\t\t\t\t\tmark(document);\n\t\t\t\t\t\n\t\t\t\t\treferenced_scopes.mark_content(mark);\n\t\t\t\t\tchildren.mark_content(mark);\n\t\t\t\t\tzsupers.mark_content(mark);\n\n\t\t\t\t\tif(parent)\n\t\t\t\t\t\tmark(parent);\n\t\t\t\t\t\n\t\t\t\t\tmark(owner);\n\t\t\t\t}\n\n\t\t\t\ttemplate T *alloc_var(Variable::Type type = Variable::Local)\n\t\t\t\t{\n\t\t\t\t\tT *result = new (fragment) T(type);\n\t\t\t\t\t\n\t\t\t\t\tresult->loc = variable_list.size();\n\t\t\t\t\t\n\t\t\t\t\tresult->type = type;\n\n\t\t\t\t\tvariable_list.push(result);\n\t\t\t\t\t\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\ttemplate T *define(Symbol *name)\n\t\t\t\t{\n\t\t\t\t\tT *result = (T *)variables.get(name);\n\t\t\t\t\t\n\t\t\t\t\tif(result)\n\t\t\t\t\t\treturn result;\n\t\t\t\t\t\n\t\t\t\t\tresult = alloc_var();\n\t\t\t\t\t\n\t\t\t\t\tresult->name = name;\n\n\t\t\t\t\tvariables.set(name, result);\n\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\ttemplate T *get_var(Symbol *name)\n\t\t\t\t{\n\t\t\t\t\tScope *defined_scope = defined(name, true);\n\n\t\t\t\t\tif(defined_scope == this)\n\t\t\t\t\t{\n\t\t\t\t\t\treturn variables.get(name);\n\t\t\t\t\t}\n\t\t\t\t\telse if(defined_scope)\n\t\t\t\t\t{\n\t\t\t\t\t\tauto result = defined_scope->variables.get(name);\n\t\t\t\t\t\t\n\t\t\t\t\t\trequire_var(defined_scope, result);\n\t\t\t\t\t\t\n\t\t\t\t\t\treturn result;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\treturn define(name);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tvoid require_args(Scope *owner);\n\t\t\t\tvoid require_scope(Scope *scope);\n\t\t\t\tvoid require_var(Scope *owner, Variable *var);\n\n\t\t\t\tScope *defined(Symbol *name, bool recursive);\n\t\t};\n\t};\n};\n\nvoid *operator new(size_t bytes, Mirb::Tree::Fragment *fragment) throw();\nvoid operator delete(void *, Mirb::Tree::Fragment *fragment) throw();\nvoid *operator new[](size_t bytes, Mirb::Tree::Fragment *fragment) throw();\nvoid operator delete[](void *, Mirb::Tree::Fragment *fragment) throw();\nTest suite passes!#pragma once\n#include \"..\/common.hpp\"\n#include \n#include \n#include \n#include \"..\/generic\/simple-set.hpp\"\n#include \"..\/collector.hpp\"\n#include \"nodes.hpp\"\n\nnamespace Mirb\n{\n\tclass Block;\n\n\tnamespace CodeGen\n\t{\n\t\tclass Block;\n\t};\n\t\n\tnamespace Tree\n\t{\n\t\tclass Chunk\n\t\t{\n\t\t\tpublic:\n\t\t\t\tstatic const size_t main_size = 512;\n\t\t\t\tstatic const size_t block_size = 256;\n\t\t\t\tstatic const size_t allocation_limit = 128;\n\t\t\t\t\n\t\t\t\tstatic Chunk *create(size_t bytes);\n\t\t\t\t\n\t\t\t\tuint8_t *current;\n\t\t\t\tuint8_t *end;\n\t\t\t\t\n\t\t\t\tListEntry entry;\n\t\t\t\t\n\t\t\t\tvoid *allocate(size_t bytes);\n\t\t};\n\t\t\n\t\tclass Fragment:\n\t\t\tpublic WithReferenceProvider\n\t\t{\n\t\t\tpublic:\n\t\t\t\tstatic const bool can_free = false;\n\n\t\t\t\tFragment(Fragment *parent, size_t chunk_size);\n\t\t\t\t\n\t\t\t\tVector fragments;\n\t\t\t\t\n\t\t\t\tvoid *allocate(size_t bytes);\n\t\t\t\tvoid *reallocate(void *memory, size_t old_size, size_t new_size);\n\t\t\t\tvoid free(void *memory)\n\t\t\t\t{\n\t\t\t\t}\n\t\t\t\t\n\t\t\tprivate:\n\t\t\t\tsize_t chunk_size;\n\t\t\t\t\n\t\t\t\tChunk *current;\n\t\t\t\t\n\t\t\t\tFastList chunks;\n\t\t};\n\t\t\n\t\tstruct Node;\n\t\t\n\t\tstruct SuperNode;\n\n\t\tclass Variable\n\t\t{\n\t\t\tpublic:\n\t\t\t\tenum Type\n\t\t\t\t{\n\t\t\t\t\tTemporary,\n\t\t\t\t\tLocal,\n\t\t\t\t\tHeap,\n\t\t\t\t\tTypes\n\t\t\t\t};\n\n\t\t\t\tType type;\n\t\t\t\tScope *owner; \/\/ Only valid for heap variables\n\t\t\t\t\n\t\t\t\tVariable(Type type)\n\t\t\t\t\t: type(type)\n\t\t\t\t\t#ifdef DEBUG\n\t\t\t\t\t\t, group(0)\n\t\t\t\t\t#endif\n\t\t\t\t{\n\t\t\t\t}\n\n\t\t\t\tsize_t loc;\n\n\t\t\t\t#ifdef DEBUG\n\t\t\t\t\tVariable *group;\n\t\t\t\t#endif\n\t\t};\n\n\t\tclass NamedVariable:\n\t\t\tpublic Variable\n\t\t{\n\t\t\tpublic:\n\t\t\t\tNamedVariable(Type type) : Variable(type) {}\n\t\t\t\t\n\t\t\t\tSymbol *name;\n\t\t\t\tNamedVariable *next;\n\t\t};\n\n\t\tclass Parameter:\n\t\t\tpublic NamedVariable\n\t\t{\n\t\t\tpublic:\n\t\t\t\tParameter(Type type) : NamedVariable(type) {}\n\t\t\t\t\n\t\t\t\tListEntry parameter_entry;\n\t\t};\n\n\t\tclass VariableMapFunctions:\n\t\t\tpublic HashTableFunctions\n\t\t{\n\t\t\tpublic:\n\t\t\t\tstatic bool compare_key_value(Symbol *key, NamedVariable *value)\n\t\t\t\t{\n\t\t\t\t\treturn key == value->name;\n\t\t\t\t}\n\n\t\t\t\tstatic Symbol *get_key(NamedVariable *value)\n\t\t\t\t{\n\t\t\t\t\treturn value->name;\n\t\t\t\t}\n\n\t\t\t\tstatic NamedVariable *get_value_next(NamedVariable *value)\n\t\t\t\t{\n\t\t\t\t\treturn value->next;\n\t\t\t\t}\n\n\t\t\t\tstatic void set_value_next(NamedVariable *value, NamedVariable *next)\n\t\t\t\t{\n\t\t\t\t\tvalue->next = next;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tstatic size_t hash_key(Symbol *key)\n\t\t\t\t{\n\t\t\t\t\treturn (size_t)key;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tstatic bool valid_key(Symbol *key)\n\t\t\t\t{\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t};\n\t\t\n\t\ttypedef HashTable VariableMap;\n\t\t\n\t\tclass Scope:\n\t\t\tpublic PinnedHeader\n\t\t{\n\t\t\tpublic:\n\t\t\t\tenum Type\n\t\t\t\t{\n\t\t\t\t\tTop,\n\t\t\t\t\tMethod,\n\t\t\t\t\tClass,\n\t\t\t\t\tModule,\n\t\t\t\t\tClosure\n\t\t\t\t};\n\t\t\t\t\n\t\t\t\tScope(Document *document, Fragment *fragment, Scope *parent, Type type);\n\t\t\t\t\n\t\t\t\tDocument *document;\n\t\t\t\tBlock *final;\n\t\t\t\tFragment *fragment;\n\t\t\t\tType type;\n\t\t\t\tScope *parent; \/\/ The scope enclosing this one\n\t\t\t\tScope *owner; \/\/ The first parent that isn't a closure. This field can point to itself.\n\t\t\t\tNode *group;\n\t\t\t\t\n\t\t\t\t\/*\n\t\t\t\t * Break related fields\n\t\t\t\t *\/\n\t\t\t\tsize_t break_id; \/\/ Which of the parent's break targets this block belongs to.\n\t\t\t\tsize_t break_targets; \/\/ Number of child blocks that can raise a break exception.\n\t\t\t\tvar_t break_dst; \/\/ The variable in the parent that the break will override.\n\t\t\t\t\n\t\t\t\tstatic const size_t no_break_id = (size_t)-1;\n\n\t\t\t\t\/*\n\t\t\t\t * Exception related fields\n\t\t\t\t *\/\n\t\t\t\tbool require_exceptions;\n\n\t\t\t\t\/*\n\t\t\t\t * Variable related fields\n\t\t\t\t *\/\n\t\t\t\tVariableMap variables; \/\/ A hash of the variables in this scope.\n\t\t\t\tsize_t heap_vars; \/\/ The number of the variables that must be stored on a heap scope.\n\t\t\t\tParameter *block_parameter; \/\/ Pointer to a named or unnamed block variable.\n\t\t\t\tVector referenced_scopes; \/\/ A list of all the scopes this scope requires.\n\n\t\t\t\tVector children; \/\/ A list of all the immediate children. To keep them alive...\n\t\t\t\t\n\t\t\t\tVector variable_list; \/\/ A list of all variables in this scope.\n\n\t\t\t\tCountedList parameters;\n\t\t\t\t\n\t\t\t\tVector zsupers;\n\t\t\t\t\n\t\t\t\ttemplate void mark(F mark)\n\t\t\t\t{\n\t\t\t\t\tif(final)\n\t\t\t\t\t\tmark(final);\n\n\t\t\t\t\tmark(document);\n\t\t\t\t\t\n\t\t\t\t\treferenced_scopes.mark_content(mark);\n\t\t\t\t\tchildren.mark_content(mark);\n\t\t\t\t\tzsupers.mark_content(mark);\n\n\t\t\t\t\tif(parent)\n\t\t\t\t\t\tmark(parent);\n\t\t\t\t\t\n\t\t\t\t\tmark(owner);\n\t\t\t\t}\n\n\t\t\t\ttemplate T *alloc_var(Variable::Type type = Variable::Local)\n\t\t\t\t{\n\t\t\t\t\tT *result = new (fragment) T(type);\n\t\t\t\t\t\n\t\t\t\t\tresult->loc = variable_list.size();\n\t\t\t\t\t\n\t\t\t\t\tresult->type = type;\n\n\t\t\t\t\tvariable_list.push(result);\n\t\t\t\t\t\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\ttemplate T *define(Symbol *name)\n\t\t\t\t{\n\t\t\t\t\tT *result = (T *)variables.get(name);\n\t\t\t\t\t\n\t\t\t\t\tif(result)\n\t\t\t\t\t\treturn result;\n\t\t\t\t\t\n\t\t\t\t\tresult = alloc_var();\n\t\t\t\t\t\n\t\t\t\t\tresult->name = name;\n\n\t\t\t\t\tvariables.set(name, result);\n\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\ttemplate T *get_var(Symbol *name)\n\t\t\t\t{\n\t\t\t\t\tScope *defined_scope = defined(name, true);\n\n\t\t\t\t\tif(defined_scope == this)\n\t\t\t\t\t{\n\t\t\t\t\t\treturn variables.get(name);\n\t\t\t\t\t}\n\t\t\t\t\telse if(defined_scope)\n\t\t\t\t\t{\n\t\t\t\t\t\tauto result = defined_scope->variables.get(name);\n\t\t\t\t\t\t\n\t\t\t\t\t\trequire_var(defined_scope, result);\n\t\t\t\t\t\t\n\t\t\t\t\t\treturn result;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\treturn define(name);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tvoid require_args(Scope *owner);\n\t\t\t\tvoid require_scope(Scope *scope);\n\t\t\t\tvoid require_var(Scope *owner, Variable *var);\n\n\t\t\t\tScope *defined(Symbol *name, bool recursive);\n\t\t};\n\t};\n};\n\nvoid *operator new(size_t bytes, Mirb::Tree::Fragment *fragment) throw();\nvoid operator delete(void *, Mirb::Tree::Fragment *fragment) throw();\nvoid *operator new[](size_t bytes, Mirb::Tree::Fragment *fragment) throw();\nvoid operator delete[](void *, Mirb::Tree::Fragment *fragment) throw();\n<|endoftext|>"} {"text":"\/*** tws_strat.cpp -- TWS strategy module\n *\n * Copyright (C) 2012 Ruediger Meier\n *\n * Author: Ruediger Meier \n *\n * This file is part of twstools.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * 3. Neither the name of the author nor the names of any contributors\n * may be used to endorse or promote products derived from this\n * software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR \"AS IS\" AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\n * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN\n * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n ***\/\n\n#include \"tws_strat.h\"\n#include \"tws_query.h\"\n#include \"tws_meta.h\"\n#include \"twsdo.h\"\n#include \"debug.h\"\n#include \n\n\nbuy_sell_oid::buy_sell_oid() :\n\tsell_oid(0),\n\tbuy_oid(0)\n{\n}\n\n\nStrat::Strat( TwsDL& _twsdo) :\n\ttwsdo(_twsdo)\n{\n}\n\nStrat::~Strat()\n{\n}\n\nvoid Strat::adjustOrders()\n{\n\tstatic int fuck = -1;\n\tfuck++;\n\tif( fuck <= 30 || twsdo.p_orders.size() > 0 ) {\n\t\treturn;\n\t}\n\n\tDEBUG_PRINTF( \"Adjust orders.\" );\n\tPlaceOrder pO;\n\tint i;\n\n\tconst MktDataTodo &mtodo = twsdo.workTodo->getMktDataTodo();\n\tfor( int i=0; i < mtodo.mktDataRequests.size(); i++ ) {\n\t\tpO.contract = mtodo.mktDataRequests[i].ibContract;\n\t\tpO.order.orderType = \"LMT\";\n\t\tpO.order.action = \"BUY\";\n\t\tpO.order.lmtPrice = twsdo.quotes->at(i).val[IB::BID] - 0.1;\n\t\tpO.order.totalQuantity = pO.contract.secType == \"CASH\" ? 25000 : 1;\n\t\ttwsdo.workTodo->placeOrderTodo()->add(pO);\n\t}\n\tDEBUG_PRINTF( \"Adjust orders. %d\",\n\t\ttwsdo.workTodo->placeOrderTodo()->countLeft());\n}Strat, prepare order id handling\/*** tws_strat.cpp -- TWS strategy module\n *\n * Copyright (C) 2012 Ruediger Meier\n *\n * Author: Ruediger Meier \n *\n * This file is part of twstools.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * 3. Neither the name of the author nor the names of any contributors\n * may be used to endorse or promote products derived from this\n * software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR \"AS IS\" AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\n * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN\n * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n ***\/\n\n#include \"tws_strat.h\"\n#include \"tws_query.h\"\n#include \"tws_meta.h\"\n#include \"twsdo.h\"\n#include \"debug.h\"\n#include \n\n\nbuy_sell_oid::buy_sell_oid() :\n\tsell_oid(0),\n\tbuy_oid(0)\n{\n}\n\n\nStrat::Strat( TwsDL& _twsdo) :\n\ttwsdo(_twsdo)\n{\n}\n\nStrat::~Strat()\n{\n}\n\nvoid Strat::adjustOrders()\n{\n\tstatic int fuck = -1;\n\tfuck++;\n\tif( fuck <= 30 || twsdo.p_orders.size() > 0 ) {\n\t\treturn;\n\t}\n\n\tDEBUG_PRINTF( \"strat, adjust orders\" );\n\n\tconst MktDataTodo &mtodo = twsdo.workTodo->getMktDataTodo();\n\tfor( int i=0; i < mtodo.mktDataRequests.size(); i++ ) {\n\t\tPlaceOrder pO;\n\t\tpO.contract = mtodo.mktDataRequests[i].ibContract;\n\t\tpO.order.orderType = \"LMT\";\n\t\tpO.order.totalQuantity = pO.contract.secType == \"CASH\" ? 25000 : 1;\n\t\tconst char *symbol = pO.contract.symbol.c_str();\n\n\t\t\/* here we also initialize zero order ids *\/\n\t\tbuy_sell_oid &oids = map_data_order[i];\n\t\tif( twsdo.p_orders.find(oids.buy_oid) == twsdo.p_orders.end() ) {\n\t\t\t\/* new buy order *\/\n\t\t\tDEBUG_PRINTF( \"strat, new buy order %s\", symbol );\n\t\t} else {\n\t\t\t\/* modify buy order *\/\n\t\t\tDEBUG_PRINTF( \"strat, modify buy order %s\", symbol );\n\t\t}\n\t\tif( twsdo.p_orders.find(oids.sell_oid) == twsdo.p_orders.end() ) {\n\t\t\t\/* new sell order *\/\n\t\t\tDEBUG_PRINTF( \"strat, new sell order %s\", symbol );\n\t\t} else {\n\t\t\t\/* modify sell order *\/\n\t\t\tDEBUG_PRINTF( \"strat, modify sell order %s\", symbol );\n\t\t}\n\n\t\tpO.order.action = \"BUY\";\n\t\tpO.order.lmtPrice = twsdo.quotes->at(i).val[IB::BID] - 0.1;\n\t\ttwsdo.workTodo->placeOrderTodo()->add(pO);\n\t}\n\tDEBUG_PRINTF( \"strat, place\/modify %d orders\",\n\t\ttwsdo.workTodo->placeOrderTodo()->countLeft());\n\tassert( mtodo.mktDataRequests.size() == map_data_order.size() );\n}<|endoftext|>"} {"text":"\/\/ SuperCard Pro flux file format:\n\/\/ http:\/\/www.cbmstuff.com\/downloads\/scp\/scp_image_specs.txt\n\n#include \"SAMdisk.h\"\n#include \"DemandDisk.h\"\n\nenum\n{\n FLAG_INDEX = 1 << 0, \/\/ set for index-synchronised, clear if not\n FLAG_TPI = 1 << 1, \/\/ set for 96tpi, clear for 48tpi\n FLAG_RPM = 1 << 2, \/\/ set for 360rpm, clear for 300rpm\n FLAG_TYPE = 1 << 3, \/\/ set for normalised flux, clear for preservation quality\n FLAG_MODE = 1 << 4, \/\/ set for read\/write image, clear for read-only\n FLAG_FOOTER = 1 << 5 \/\/ set if footer block present, clear if absent\n};\n\nstruct SCP_FILE_HEADER\n{\n char signature[3]; \/\/ SCP\n uint8_t revision; \/\/ (version << 4) | revision, 0x39 = v3.9\n uint8_t disk_type;\n uint8_t revolutions; \/\/ number of stored revolutions\n uint8_t start_track;\n uint8_t end_track;\n uint8_t flags;\n uint8_t bitcell_width; \/\/ 0 = 16 bits, non-zero = number of bits\n uint8_t heads; \/\/ 0 = both heads, 1 = head 0 only, 2 = head 1 only\n uint8_t reserved; \/\/ should be zero?\n uint32_t checksum; \/\/ 32-bit checksum from after header to EOF (unless FLAG_MODE is set)\n};\n\nstruct SCP_FILE_FOOTER\n{\n uint32_t manufacturer_offset;\n uint32_t model_offset;\n uint32_t serial_offset;\n uint32_t creator_offset;\n uint32_t application_offset;\n uint32_t comments_offset;\n uint64_t creation_time;\n uint64_t modification_time;\n uint8_t application_version;\n uint8_t hardware_version;\n uint8_t firmware_version;\n uint8_t format_revision;\n char sig[4];\n};\n\nstruct TRACK_DATA_HEADER\n{\n char signature[3]; \/\/ TRK\n uint8_t tracknr;\n};\n\nstd::string FooterString(MemFile& file, uint32_t offset)\n{\n uint16_t len = 0;\n if (!offset || !file.seek(static_cast(offset)) || !file.read(&len, sizeof(len)))\n return \"\";\n\n len = util::letoh(len);\n if (static_cast(offset + len) >= file.size())\n return \"\";\n\n std::vector str;\n str.resize(len);\n\n if (!file.read(str.data(), static_cast(str.size())))\n return \"\";\n\n return std::string(str.data(), str.size());\n}\n\nstd::string FooterVersion(uint32_t version)\n{\n std::stringstream ss;\n if (version)\n ss << (version >> 4) << \".\" << (version & 0xf);\n return ss.str();\n}\n\nstd::string FooterTime(uint64_t unix_time)\n{\n auto t = static_cast(unix_time);\n auto tm = *std::gmtime(&t);\n\n std::stringstream ss;\n if (unix_time)\n ss << std::put_time(&tm, \"%Y-%m-%d %T\");\n return ss.str();\n}\n\n\nclass SCPDisk final : public DemandDisk\n{\npublic:\n SCPDisk(bool normalised) : m_normalised(normalised) {}\n\n void add_track_data(const CylHead& cylhead, std::vector>&& trackdata)\n {\n m_data[cylhead] = std::move(trackdata);\n extend(cylhead);\n }\n\nprotected:\n TrackData load(const CylHead& cylhead, bool \/*first_read*\/) override\n {\n FluxData flux_revs;\n\n auto it = m_data.find(cylhead);\n if (it == m_data.end())\n return TrackData(cylhead);\n\n for (auto& rev_times : it->second)\n {\n std::vector flux_times;\n flux_times.reserve(rev_times.size());\n\n uint32_t total_time = 0;\n for (auto time : rev_times) \/\/ note: big endian times!\n {\n if (!time)\n total_time += 0x10000;\n else\n {\n total_time += util::betoh(time);\n flux_times.push_back(total_time * 25); \/\/ 25ns sampling time\n total_time = 0;\n }\n }\n\n flux_revs.push_back(std::move(flux_times));\n }\n\n return TrackData(cylhead, std::move(flux_revs), m_normalised);\n }\n\nprivate:\n std::map>> m_data{};\n bool m_normalised = false;\n};\n\nbool ReadSCP(MemFile& file, std::shared_ptr& disk)\n{\n SCP_FILE_HEADER fh{};\n\n if (!file.rewind() || !file.read(&fh, sizeof(fh)) || std::string(fh.signature, 3) != \"SCP\")\n return false;\n\n if (!(fh.flags & FLAG_MODE) && fh.checksum)\n {\n auto checksum = std::accumulate(file.data().begin() + 0x10, file.data().end(), uint32_t(0));\n if (checksum != util::letoh(fh.checksum))\n Message(msgWarning, \"file checksum is incorrect!\");\n }\n\n \/*if (!(fh.flags & FLAG_INDEX))\n throw util::exception(\"not an index-synchronised image\");\n else*\/ if (fh.revolutions == 0 || fh.revolutions > 10)\n throw util::exception(\"invalid revolution count (\", fh.revolutions, \")\");\n else if (fh.bitcell_width != 0 && fh.bitcell_width != 16)\n throw util::exception(\"unsupported bit cell width (\", fh.bitcell_width, \")\");\n else if (fh.start_track > fh.end_track)\n throw util::exception(\"start track (\", fh.start_track, \") > end track (\", fh.end_track, \")\");\n\n std::vector tdh_offsets(fh.end_track + 1);\n if (!file.read(tdh_offsets))\n throw util::exception(\"short file reading track offset index\");\n\n auto scp_disk = std::make_shared((fh.flags & FLAG_TYPE) != 0);\n\n for (auto tracknr = fh.start_track; tracknr <= fh.end_track; ++tracknr)\n {\n TRACK_DATA_HEADER tdh;\n auto cyl = fh.heads == 0 ? (tracknr >> 1) : tracknr;\n auto head = fh.heads == 0 ? (tracknr & 1) : (fh.heads - 1);\n CylHead cylhead(cyl, head);\n\n if (!tdh_offsets[tracknr])\n continue;\n\n if (!file.seek(tdh_offsets[tracknr]) || !file.read(&tdh, sizeof(tdh)))\n throw util::exception(\"short file reading \", cylhead, \" track header\");\n else if (std::string(tdh.signature, 3) != \"TRK\")\n throw util::exception(\"invalid track signature on \", cylhead);\n else if (tdh.tracknr != tracknr)\n throw util::exception(\"track number mismatch (\", tdh.tracknr, \" != \", tracknr, \") in \", cylhead, \" header\");\n\n std::vector rev_index(fh.revolutions * 3);\n if (!file.read(rev_index))\n throw util::exception(\"short file reading \", cylhead, \" track index\");\n\n std::vector> revs_data;\n revs_data.reserve(fh.revolutions);\n\n for (uint8_t rev = 0; rev < fh.revolutions; ++rev)\n {\n \/\/ auto index_time = util::letoh(rev_index[rev * 3 + 0]);\n auto flux_count = util::letoh(rev_index[rev * 3 + 1]);\n auto data_offset = util::letoh(rev_index[rev * 3 + 2]);\n\n std::vector flux_data(flux_count);\n if (!file.seek(tdh_offsets[tracknr] + data_offset) || !file.read(flux_data))\n throw util::exception(\"short error reading \", cylhead, \" data\");\n\n revs_data.push_back(std::move(flux_data));\n }\n\n scp_disk->add_track_data(cylhead, std::move(revs_data));\n }\n\n auto footer_offset = file.size() - static_cast(sizeof(SCP_FILE_FOOTER));\n if ((fh.flags & FLAG_FOOTER) && footer_offset >= file.tell())\n {\n SCP_FILE_FOOTER ff{};\n\n if (file.seek(footer_offset) && file.read(&ff, sizeof(ff)) &&\n std::string(ff.sig, sizeof(ff.sig)) == \"FPCS\")\n {\n scp_disk->metadata[\"manufacturer\"] = FooterString(file, ff.manufacturer_offset);\n scp_disk->metadata[\"model\"] = FooterString(file, ff.model_offset);\n scp_disk->metadata[\"serial\"] = FooterString(file, ff.serial_offset);\n scp_disk->metadata[\"creator\"] = FooterString(file, ff.creator_offset);\n scp_disk->metadata[\"application\"] = FooterString(file, ff.application_offset);\n scp_disk->metadata[\"comment\"] = FooterString(file, ff.comments_offset);\n\n scp_disk->metadata[\"app_version\"] = FooterVersion(ff.application_version);\n scp_disk->metadata[\"hw_version\"] = FooterVersion(ff.hardware_version);\n scp_disk->metadata[\"fw_version\"] = FooterVersion(ff.firmware_version);\n scp_disk->metadata[\"scp_version\"] = FooterVersion(ff.format_revision);\n\n scp_disk->metadata[\"created\"] = FooterTime(ff.creation_time);\n if (ff.modification_time != ff.creation_time)\n scp_disk->metadata[\"modified\"] = FooterTime(ff.modification_time);\n }\n }\n else\n {\n scp_disk->metadata[\"app_version\"] = FooterVersion(fh.revision);\n scp_disk->metadata[\"application\"] = \"SuperCard Pro software\";\n\n std::stringstream ss;\n for (uint8_t b; file.read(&b, sizeof(b)) && std::isprint(b); )\n ss << static_cast(b);\n scp_disk->metadata[\"created\"] = ss.str();\n }\n\n scp_disk->metadata[\"index\"] = (fh.flags & FLAG_INDEX) ? \"synchronised\" : \"unsynchronised\";\n scp_disk->metadata[\"tpi\"] = (fh.flags & FLAG_TPI) ? \"96 tpi\" : \"48 tpi\";\n scp_disk->metadata[\"rpm\"] = (fh.flags & FLAG_RPM) ? \"360 rpm\" : \"300 rpm\";\n scp_disk->metadata[\"quality\"] = (fh.flags & FLAG_TYPE) ? \"normalised\" : \"preservation\";\n scp_disk->metadata[\"mode\"] = (fh.flags & FLAG_MODE) ? \"read\/write\" : \"read-only\";\n\n scp_disk->strType = \"SCP\";\n disk = scp_disk;\n\n return true;\n}\nChanged SCP reading to scan all TDH entries\/\/ SuperCard Pro flux file format:\n\/\/ http:\/\/www.cbmstuff.com\/downloads\/scp\/scp_image_specs.txt\n\n#include \"SAMdisk.h\"\n#include \"DemandDisk.h\"\n\nconstexpr auto DEFAULT_TDH_ENTRIES = 166;\nconstexpr auto MAX_TDH_ENTRIES = 168;\n\nenum\n{\n FLAG_INDEX = 1 << 0, \/\/ set for index-synchronised, clear if not\n FLAG_TPI = 1 << 1, \/\/ set for 96tpi, clear for 48tpi\n FLAG_RPM = 1 << 2, \/\/ set for 360rpm, clear for 300rpm\n FLAG_TYPE = 1 << 3, \/\/ set for normalised flux, clear for preservation quality\n FLAG_MODE = 1 << 4, \/\/ set for read\/write image, clear for read-only\n FLAG_FOOTER = 1 << 5 \/\/ set if footer block present, clear if absent\n};\n\nstruct SCP_FILE_HEADER\n{\n char signature[3]; \/\/ SCP\n uint8_t revision; \/\/ (version << 4) | revision, 0x39 = v3.9\n uint8_t disk_type;\n uint8_t revolutions; \/\/ number of stored revolutions\n uint8_t start_track;\n uint8_t end_track;\n uint8_t flags;\n uint8_t bitcell_width; \/\/ 0 = 16 bits, non-zero = number of bits\n uint8_t heads; \/\/ 0 = both heads, 1 = head 0 only, 2 = head 1 only\n uint8_t reserved; \/\/ should be zero?\n uint32_t checksum; \/\/ 32-bit checksum from after header to EOF (unless FLAG_MODE is set)\n};\n\nstruct SCP_FILE_FOOTER\n{\n uint32_t manufacturer_offset;\n uint32_t model_offset;\n uint32_t serial_offset;\n uint32_t creator_offset;\n uint32_t application_offset;\n uint32_t comments_offset;\n uint64_t creation_time;\n uint64_t modification_time;\n uint8_t application_version;\n uint8_t hardware_version;\n uint8_t firmware_version;\n uint8_t format_revision;\n char sig[4];\n};\n\nstruct TRACK_DATA_HEADER\n{\n char signature[3]; \/\/ TRK\n uint8_t tracknr;\n};\n\nstd::string FooterString(MemFile& file, uint32_t offset)\n{\n uint16_t len = 0;\n if (!offset || !file.seek(static_cast(offset)) || !file.read(&len, sizeof(len)))\n return \"\";\n\n len = util::letoh(len);\n if (static_cast(offset + len) >= file.size())\n return \"\";\n\n std::vector str;\n str.resize(len);\n\n if (!file.read(str.data(), static_cast(str.size())))\n return \"\";\n\n return std::string(str.data(), str.size());\n}\n\nstd::string FooterVersion(uint32_t version)\n{\n std::stringstream ss;\n if (version)\n ss << (version >> 4) << \".\" << (version & 0xf);\n return ss.str();\n}\n\nstd::string FooterTime(uint64_t unix_time)\n{\n auto t = static_cast(unix_time);\n auto tm = *std::gmtime(&t);\n\n std::stringstream ss;\n if (unix_time)\n ss << std::put_time(&tm, \"%Y-%m-%d %T\");\n return ss.str();\n}\n\n\nclass SCPDisk final : public DemandDisk\n{\npublic:\n SCPDisk(bool normalised) : m_normalised(normalised) {}\n\n void add_track_data(const CylHead& cylhead, std::vector>&& trackdata)\n {\n m_data[cylhead] = std::move(trackdata);\n extend(cylhead);\n }\n\nprotected:\n TrackData load(const CylHead& cylhead, bool \/*first_read*\/) override\n {\n FluxData flux_revs;\n\n auto it = m_data.find(cylhead);\n if (it == m_data.end())\n return TrackData(cylhead);\n\n for (auto& rev_times : it->second)\n {\n std::vector flux_times;\n flux_times.reserve(rev_times.size());\n\n uint32_t total_time = 0;\n for (auto time : rev_times) \/\/ note: big endian times!\n {\n if (!time)\n total_time += 0x10000;\n else\n {\n total_time += util::betoh(time);\n flux_times.push_back(total_time * 25); \/\/ 25ns sampling time\n total_time = 0;\n }\n }\n\n flux_revs.push_back(std::move(flux_times));\n }\n\n return TrackData(cylhead, std::move(flux_revs), m_normalised);\n }\n\nprivate:\n std::map>> m_data{};\n bool m_normalised = false;\n};\n\nbool ReadSCP(MemFile& file, std::shared_ptr& disk)\n{\n SCP_FILE_HEADER fh{};\n\n if (!file.rewind() || !file.read(&fh, sizeof(fh)) || std::string(fh.signature, 3) != \"SCP\")\n return false;\n\n if (!(fh.flags & FLAG_MODE) && fh.checksum)\n {\n auto checksum = std::accumulate(file.data().begin() + 0x10, file.data().end(), uint32_t(0));\n if (checksum != util::letoh(fh.checksum))\n Message(msgWarning, \"file checksum is incorrect!\");\n }\n\n \/*if (!(fh.flags & FLAG_INDEX))\n throw util::exception(\"not an index-synchronised image\");\n else*\/ if (fh.revolutions == 0 || fh.revolutions > 10)\n throw util::exception(\"invalid revolution count (\", fh.revolutions, \")\");\n else if (fh.bitcell_width != 0 && fh.bitcell_width != 16)\n throw util::exception(\"unsupported bit cell width (\", fh.bitcell_width, \")\");\n\n auto entries = (fh.end_track == MAX_TDH_ENTRIES - 1) ? MAX_TDH_ENTRIES : DEFAULT_TDH_ENTRIES;\n std::vector tdh_offsets(entries);\n if (!file.read(tdh_offsets))\n throw util::exception(\"short file reading track offset index\");\n\n auto scp_disk = std::make_shared((fh.flags & FLAG_TYPE) != 0);\n\n for (int tracknr = 0; tracknr < static_cast(tdh_offsets.size()); ++tracknr)\n {\n TRACK_DATA_HEADER tdh;\n CylHead cylhead(tracknr \/ 2, tracknr & 1);\n\n if (!tdh_offsets[tracknr])\n continue;\n\n if (!file.seek(tdh_offsets[tracknr]) || !file.read(&tdh, sizeof(tdh)))\n throw util::exception(\"short file reading \", cylhead, \" track header\");\n else if (std::string(tdh.signature, 3) != \"TRK\")\n throw util::exception(\"invalid track signature on \", cylhead);\n else if (tdh.tracknr != tracknr)\n throw util::exception(\"track number mismatch (\", tdh.tracknr, \" != \", tracknr, \") in \", cylhead, \" header\");\n\n std::vector rev_index(fh.revolutions * 3);\n if (!file.read(rev_index))\n throw util::exception(\"short file reading \", cylhead, \" track index\");\n\n std::vector> revs_data;\n revs_data.reserve(fh.revolutions);\n\n for (uint8_t rev = 0; rev < fh.revolutions; ++rev)\n {\n \/\/ auto index_time = util::letoh(rev_index[rev * 3 + 0]);\n auto flux_count = util::letoh(rev_index[rev * 3 + 1]);\n auto data_offset = util::letoh(rev_index[rev * 3 + 2]);\n\n std::vector flux_data(flux_count);\n if (!file.seek(tdh_offsets[tracknr] + data_offset) || !file.read(flux_data))\n throw util::exception(\"short error reading \", cylhead, \" data\");\n\n revs_data.push_back(std::move(flux_data));\n }\n\n scp_disk->add_track_data(cylhead, std::move(revs_data));\n }\n\n auto footer_offset = file.size() - static_cast(sizeof(SCP_FILE_FOOTER));\n if ((fh.flags & FLAG_FOOTER) && footer_offset >= file.tell())\n {\n SCP_FILE_FOOTER ff{};\n\n if (file.seek(footer_offset) && file.read(&ff, sizeof(ff)) &&\n std::string(ff.sig, sizeof(ff.sig)) == \"FPCS\")\n {\n scp_disk->metadata[\"manufacturer\"] = FooterString(file, ff.manufacturer_offset);\n scp_disk->metadata[\"model\"] = FooterString(file, ff.model_offset);\n scp_disk->metadata[\"serial\"] = FooterString(file, ff.serial_offset);\n scp_disk->metadata[\"creator\"] = FooterString(file, ff.creator_offset);\n scp_disk->metadata[\"application\"] = FooterString(file, ff.application_offset);\n scp_disk->metadata[\"comment\"] = FooterString(file, ff.comments_offset);\n\n scp_disk->metadata[\"app_version\"] = FooterVersion(ff.application_version);\n scp_disk->metadata[\"hw_version\"] = FooterVersion(ff.hardware_version);\n scp_disk->metadata[\"fw_version\"] = FooterVersion(ff.firmware_version);\n scp_disk->metadata[\"scp_version\"] = FooterVersion(ff.format_revision);\n\n scp_disk->metadata[\"created\"] = FooterTime(ff.creation_time);\n if (ff.modification_time != ff.creation_time)\n scp_disk->metadata[\"modified\"] = FooterTime(ff.modification_time);\n }\n }\n else\n {\n scp_disk->metadata[\"app_version\"] = FooterVersion(fh.revision);\n scp_disk->metadata[\"application\"] = \"SuperCard Pro software\";\n\n std::stringstream ss;\n for (uint8_t b; file.read(&b, sizeof(b)) && std::isprint(b); )\n ss << static_cast(b);\n scp_disk->metadata[\"created\"] = ss.str();\n }\n\n scp_disk->metadata[\"index\"] = (fh.flags & FLAG_INDEX) ? \"synchronised\" : \"unsynchronised\";\n scp_disk->metadata[\"tpi\"] = (fh.flags & FLAG_TPI) ? \"96 tpi\" : \"48 tpi\";\n scp_disk->metadata[\"rpm\"] = (fh.flags & FLAG_RPM) ? \"360 rpm\" : \"300 rpm\";\n scp_disk->metadata[\"quality\"] = (fh.flags & FLAG_TYPE) ? \"normalised\" : \"preservation\";\n scp_disk->metadata[\"mode\"] = (fh.flags & FLAG_MODE) ? \"read\/write\" : \"read-only\";\n\n scp_disk->strType = \"SCP\";\n disk = scp_disk;\n\n return true;\n}\n<|endoftext|>"} {"text":"#include \"StdAfx.h\"\n\n#define BUFFERSIZE (2 * 1024 * 1024)\nchar gBuffer[BUFFERSIZE];\nint lastFrame = -1;\n\n\n\/*\n Construct Ultracomm object, connect to server,\n and set\/check parameters.\n*\/\nUltracomm::Ultracomm(const UltracommOptions& myuopt)\n : uopt(myuopt),\n address(myuopt.opt[\"address\"].as()),\n acqmode(myuopt.opt[\"acqmode\"].as()),\n datatype(myuopt.opt[\"datatype\"].as()),\n verbose(myuopt.opt[\"verbose\"].as())\n{\n connect();\n if (verbose) {\n cerr << \"Setting data to acquire to datatype \" << datatype << \".\\n\";\n }\n ult.setDataToAcquire(datatype);\n set_int_imaging_params();\n check_int_imaging_params();\n const int compstat = uopt.opt[\"compression_status\"].as();\n if (verbose) {\n cerr << \"Setting compression status to \" << compstat << \".\\n\";\n }\n if (acqmode == \"continuous\") {\n ult.setCallback(frame_callback);\n }\n if (! ult.setCompressionStatus(compstat)) {\n cerr << \"Failed to set compression status to \" << compstat << \".\\n\";\n throw ParameterMismatchError();\n }\n}\n\n\/*\n Connect to the Ultrasonix.\n*\/\nvoid Ultracomm::connect()\n{\n if (verbose) {\n cerr << \"Connecting to ultrasonix at address \" << address << \".\\n\";\n }\n if (!ult.connect(address.c_str()))\n {\n throw ConnectionError();\n }\n\/*\nTODO: throw different errors depending on problem. Note that FD_CONNECT error\nis when server address is bad (e.g. 123), and SOCKET_ERROR is when we couldn't connect\n(address good but not in research mode). Should also test when address is good\nbut ultrasound machine not running):\n\nC:\\build\\ultracomm\\bin\\Debug>ultracomm --address 123 --output asdf\nmonitorConnection(): FD_CONNECT had ERROR\nCould not connect to Ultrasonix.\n\nC:\\build\\ultracomm\\bin\\Debug>ultracomm --address 192.168.1.200 --output asdf\nmonitorConnection(): WSAEnumNetworkEvents() ret SOCKET_ERROR (10093)\nCmonitorConnection(): CONNECTION_COMM lost\n\nould not connect to Ultrasonix.\n*\/\n}\n\n\/*\n Disconnect from Ultrasonix.\n*\/\nvoid Ultracomm::disconnect()\n{\n if (ult.isConnected())\n {\n if (verbose) {\n cerr << \"Disconnecting from Ultrasonix.\\n\";\n }\n ult.disconnect();\n }\n else\n {\n if (verbose) {\n cerr << \"Already disconnected from Ultrasonix.\\n\";\n }\n }\n}\n\n\/*\n Put Ultrasonix into freeze state and wait for confirmation.\n*\/\nvoid Ultracomm::wait_for_freeze()\n{\n \/\/ 1 = FROZEN; 0 = IMAGING\n if (ult.getFreezeState() != 1)\n {\n if (verbose) {\n cerr << \"Freezing Ultrasonix.\\n\";\n }\n ult.toggleFreeze();\n }\n else\n {\n if (verbose) {\n cerr << \"Ultrasonix already frozen.\\n\";\n }\n }\n \/\/ Wait for server to acknowledge it has frozen.\n \/\/ TODO: this would be safer with a timeout.\n while (ult.getFreezeState() != 1)\n {\n if (verbose) {\n cerr << \"Waiting for confirmation that Ultrasonix has frozen.\\n\";\n }\n }\n \/*\n FIXME: Occasionally we get the message\n\n sendAndWait(): WaitForSingleObject() ret WAIT_TIMEOUT \n\n when retrieving cine data. When --verbose is turned on this message\n usually appears in save_data() after the call to getCineData() and\n before write(). According to the discussion at\n http:\/\/research.ultrasonix.com\/viewtopic.php?f=5&t=1100&p=4245&hilit=delay#p4245\n adding a delay after toggleFreeze() can prevent this condition, so\n we add it here.\n\n Possibly this delay is not necessary when used with newer versions of\n the Ultrasonix library.\n *\/\n if (\n uopt.opt[\"ms_delay_after_freeze\"].as() > 0 &&\n !uopt.opt.count(\"freeze-only\")\n )\n {\n Sleep(uopt.opt[\"ms_delay_after_freeze\"].as());\n }\n}\n\n\/*\n Put ultrasonix into imaging state.\n*\/\nvoid Ultracomm::wait_for_unfreeze()\n{\n \/\/ 1 = FROZEN; 0 = IMAGING\n if (ult.getFreezeState() != 0)\n {\n if (verbose) {\n cerr << \"Unfreezing Ultrasonix.\\n\";\n }\n ult.toggleFreeze();\n }\n else\n {\n if (verbose) {\n cerr << \"Ultrasonix already imaging.\\n\";\n }\n }\n \/\/ Wait for server to acknowledge it has switched to imaging.\n \/\/ TODO: this would be safer with a timeout.\n while (ult.getFreezeState() != 0)\n {\n if (verbose) {\n cerr << \"Waiting for confirmation that Ultrasonix is imaging.\\n\";\n }\n }\n}\n\n\/*\n Print all ultrasonix parameters.\n*\/\nvoid Ultracomm::dump_params()\n{\n int i = 0;\n int val;\n uParam param;\n while (ult.getParam(i++, param))\n {\n ult.getParamValue(param.name, val);\n printf(\"%d\\t%s\\t%s\\t%d\\n\", i, param.id, param.name, val);\n }\n}\n\n\/*\n Set all integer-type Ultrasonix imaging parameters, as specified on the\n command line or in the parameter file.\n*\/\nvoid Ultracomm::set_int_imaging_params()\n{\n po::variables_map params = uopt.opt;\n po::options_description iopts = uopt.int_imaging_params;\n for ( auto iter = iopts.options().begin(); iter != iopts.options().end(); ++iter)\n {\n \/*\n Ultracomm program options do not contain spaces. Some of the\n parameters used by the ulterius setParamValue() call do contain\n spaces, and none appear to use underscore. The convention is that\n ultracomm program options containing underscore correspond to\n ulterius parameters that have the same name, but with the\n underscores replaced with spaces (' ').\n\n optname: the name as used in ultracomm program options (underscores)\n ultname: the name as used by ulterius setParamValue() (spaces)\n *\/\n string optname = (*iter)->long_name();\n string ultname = boost::replace_all_copy(optname, \"_\", \" \");\n if (params.count(optname)) {\n int val = params[optname].as();\n if (verbose) {\n cerr << \"Setting '\" << ultname << \"' to value \" << val << \".\\n\";\n }\n ult.setParamValue(ultname.c_str(), val);\n }\n }\n}\n\n\/*\n Verify that integer-type Ultrasonix imaging parameters have value as\n specified by user.\n*\/\nvoid Ultracomm::check_int_imaging_params()\n{\n po::variables_map params = uopt.opt;\n po::options_description iopts = uopt.int_imaging_params;\n for ( auto iter = iopts.options().begin(); iter != iopts.options().end(); ++iter)\n {\n \/*\n See comments in set_int_imaging_params() for mangling of\n parameter names.\n *\/\n string optname = (*iter)->long_name();\n string ultname = boost::replace_all_copy(optname, \"_\", \" \");\n if (params.count(optname)) {\n int expected, got;\n expected = params[optname].as();\n if (verbose) {\n cerr << \"Getting value of '\" << ultname << \"'. Expecting \" << expected << \".\\n\";\n }\n ult.getParamValue(ultname.c_str(), got);\n if (got != expected) {\n cerr << \"Parameter '\" << ultname << \"' expected \" << expected << \" and got \" << got << \".\\n\";\n throw ParameterMismatchError();\n }\n }\n }\n}\n\n\/*\n Get data from Ultrasonix and save to file.\n*\/\nvoid Ultracomm::save_data()\n{\n po::variables_map params = uopt.opt;\n const string outname = params[\"output\"].as();\n int num_frames = ult.getCineDataCount((uData)datatype);\n uDataDesc desc;\n if (! ult.getDataDescriptor((uData)datatype, desc))\n {\n throw DataDescriptorError();\n }\n if (! ult.isDataAvailable((uData)datatype))\n {\n throw DataError();\n }\n ofstream outfile (outname, ios::out | ios::binary);\n write_header(outfile, desc, num_frames);\n\n \/\/ TODO: figure out why buffer and sz makes program crash\n \/\/const int sz = 2 * 1024 * 1024;\n \/\/char buffer[BUFFERSIZE]; \/\/ TODO: determine appropriate sizes on the fly\n\/\/ int num_frames = ult.getCineDataCount((uData)datatype);\n\n \/\/ TODO: framesize assumes desc.ss is always a multiple of 8, and that might not be safe.\n int framesize = (desc.ss \/ 8) * desc.w * desc.h;\n for (int idx = 0; idx < num_frames; idx++)\n {\n if (verbose) {\n cerr << \"Getting cine data for frame \" << idx << \".\\n\";\n }\n ult.getCineData((uData)datatype, idx, false, (char**)&gBuffer, BUFFERSIZE);\n outfile.write(gBuffer, framesize);\n if (verbose) {\n cerr << \"Wrote cine data for frame \" << idx << \".\\n\";\n }\n }\n outfile.close();\n}\n\n\/*\n TODO: header information is probably correct for .bpr files but possibly\n not for other datatypes.\n*\/\nvoid Ultracomm::write_header(ofstream& outfile, const uDataDesc& desc, const int& num_frames)\n{\n if (verbose) {\n cerr << \"Writing header.\\n\";\n }\n \/\/ Integer fields that we can write directly. Luckily these all are\n \/\/ consecutive fields in the header.\n const int isize = sizeof(__int32);\n static const int fields[] = {\n datatype,\n num_frames,\n desc.w,\n desc.h,\n desc.ss,\n desc.roi.ulx,\n desc.roi.uly,\n desc.roi.urx,\n desc.roi.ury,\n desc.roi.brx,\n desc.roi.bry,\n desc.roi.blx,\n desc.roi.bly,\n uopt.opt[\"probe-id\"].as()\n };\n for (int i = 0; i < sizeof(fields) \/ sizeof(fields[0]); ++i) {\n outfile.write(reinterpret_cast(&(__int32)fields[i]), isize);\n }\n\n \/\/ Integer fields that we have to query from Ultrasonix. These are also\n \/\/ consecutive in the header.\n \/\/ FIXME: Determine if these are the correct params to put in the header.\n static const string queries[] = {\n \"b-freq\",\n \"vec-freq\",\n \"frame rate\",\n \"b-ldensity\"\n };\n for (int i = 0; i < sizeof(queries) \/ sizeof(queries[0]); ++i) {\n int val;\n ult.getParamValue(queries[i].c_str(), val);\n outfile.write(reinterpret_cast(&(__int32)val), isize);\n }\n \/\/ FIXME: Figure out how to determine the value of the 'extra' field.\n \/\/ It will probably be added to queries[], but I don't know the param name.\n \/\/ For now we'll hard code it with value 0.\n int extra = 0;\n outfile.write(reinterpret_cast(&(__int32)extra), isize);\n}\n\n\/*\n Callback.\n*\/\nbool Ultracomm::frame_callback(void* data, int type, int sz, bool cine, int frmnum)\n{\n\/*\n if (verbose) {\n cerr << \"In callback.\\n\";\n }\n\n if (!data || !sz)\n {\n\/\/ TODO: proper error\n printf(\"Error: no actual frame data received\\n\");\n return false;\n }\n\n if (BUFFERSIZE < sz)\n {\n\/\/ TODO: proper error\n printf(\"Error: frame too large for current buffer\\n\");\n return false;\n }\n*\/\n\n \/\/printf(\"[Rx] type:(%d) size:(%d) cine:(%d) gBuffer:(%d) frame:(%d)\\n\", type, sz, cine, &gBuffer, frmnum);\n if (frmnum != lastFrame + 1) {\n printf(\"Skipped frame(s) %d - %d.\\n\", lastFrame + 1, frmnum - 1);\n }\n lastFrame = frmnum;\n \/\/ make sure we dont do an operation that takes longer than the acquisition frame rate\n memcpy(gBuffer, data, sz);\n\n return true;\n}\nFix dump_params().#include \"StdAfx.h\"\n\n#define BUFFERSIZE (2 * 1024 * 1024)\nchar gBuffer[BUFFERSIZE];\nint lastFrame = -1;\n\n\n\/*\n Construct Ultracomm object, connect to server,\n and set\/check parameters.\n*\/\nUltracomm::Ultracomm(const UltracommOptions& myuopt)\n : uopt(myuopt),\n address(myuopt.opt[\"address\"].as()),\n acqmode(myuopt.opt[\"acqmode\"].as()),\n datatype(myuopt.opt[\"datatype\"].as()),\n verbose(myuopt.opt[\"verbose\"].as())\n{\n connect();\n if (verbose) {\n cerr << \"Setting data to acquire to datatype \" << datatype << \".\\n\";\n }\n ult.setDataToAcquire(datatype);\n set_int_imaging_params();\n check_int_imaging_params();\n const int compstat = uopt.opt[\"compression_status\"].as();\n if (verbose) {\n cerr << \"Setting compression status to \" << compstat << \".\\n\";\n }\n if (acqmode == \"continuous\") {\n ult.setCallback(frame_callback);\n }\n if (! ult.setCompressionStatus(compstat)) {\n cerr << \"Failed to set compression status to \" << compstat << \".\\n\";\n throw ParameterMismatchError();\n }\n}\n\n\/*\n Connect to the Ultrasonix.\n*\/\nvoid Ultracomm::connect()\n{\n if (verbose) {\n cerr << \"Connecting to ultrasonix at address \" << address << \".\\n\";\n }\n if (!ult.connect(address.c_str()))\n {\n throw ConnectionError();\n }\n\/*\nTODO: throw different errors depending on problem. Note that FD_CONNECT error\nis when server address is bad (e.g. 123), and SOCKET_ERROR is when we couldn't connect\n(address good but not in research mode). Should also test when address is good\nbut ultrasound machine not running):\n\nC:\\build\\ultracomm\\bin\\Debug>ultracomm --address 123 --output asdf\nmonitorConnection(): FD_CONNECT had ERROR\nCould not connect to Ultrasonix.\n\nC:\\build\\ultracomm\\bin\\Debug>ultracomm --address 192.168.1.200 --output asdf\nmonitorConnection(): WSAEnumNetworkEvents() ret SOCKET_ERROR (10093)\nCmonitorConnection(): CONNECTION_COMM lost\n\nould not connect to Ultrasonix.\n*\/\n}\n\n\/*\n Disconnect from Ultrasonix.\n*\/\nvoid Ultracomm::disconnect()\n{\n if (ult.isConnected())\n {\n if (verbose) {\n cerr << \"Disconnecting from Ultrasonix.\\n\";\n }\n ult.disconnect();\n }\n else\n {\n if (verbose) {\n cerr << \"Already disconnected from Ultrasonix.\\n\";\n }\n }\n}\n\n\/*\n Put Ultrasonix into freeze state and wait for confirmation.\n*\/\nvoid Ultracomm::wait_for_freeze()\n{\n \/\/ 1 = FROZEN; 0 = IMAGING\n if (ult.getFreezeState() != 1)\n {\n if (verbose) {\n cerr << \"Freezing Ultrasonix.\\n\";\n }\n ult.toggleFreeze();\n }\n else\n {\n if (verbose) {\n cerr << \"Ultrasonix already frozen.\\n\";\n }\n }\n \/\/ Wait for server to acknowledge it has frozen.\n \/\/ TODO: this would be safer with a timeout.\n while (ult.getFreezeState() != 1)\n {\n if (verbose) {\n cerr << \"Waiting for confirmation that Ultrasonix has frozen.\\n\";\n }\n }\n \/*\n FIXME: Occasionally we get the message\n\n sendAndWait(): WaitForSingleObject() ret WAIT_TIMEOUT \n\n when retrieving cine data. When --verbose is turned on this message\n usually appears in save_data() after the call to getCineData() and\n before write(). According to the discussion at\n http:\/\/research.ultrasonix.com\/viewtopic.php?f=5&t=1100&p=4245&hilit=delay#p4245\n adding a delay after toggleFreeze() can prevent this condition, so\n we add it here.\n\n Possibly this delay is not necessary when used with newer versions of\n the Ultrasonix library.\n *\/\n if (\n uopt.opt[\"ms_delay_after_freeze\"].as() > 0 &&\n !uopt.opt.count(\"freeze-only\")\n )\n {\n Sleep(uopt.opt[\"ms_delay_after_freeze\"].as());\n }\n}\n\n\/*\n Put ultrasonix into imaging state.\n*\/\nvoid Ultracomm::wait_for_unfreeze()\n{\n \/\/ 1 = FROZEN; 0 = IMAGING\n if (ult.getFreezeState() != 0)\n {\n if (verbose) {\n cerr << \"Unfreezing Ultrasonix.\\n\";\n }\n ult.toggleFreeze();\n }\n else\n {\n if (verbose) {\n cerr << \"Ultrasonix already imaging.\\n\";\n }\n }\n \/\/ Wait for server to acknowledge it has switched to imaging.\n \/\/ TODO: this would be safer with a timeout.\n while (ult.getFreezeState() != 0)\n {\n if (verbose) {\n cerr << \"Waiting for confirmation that Ultrasonix is imaging.\\n\";\n }\n }\n}\n\n\/*\n Print all ultrasonix parameters.\n*\/\nvoid Ultracomm::dump_params()\n{\n int i = 0;\n int val;\n uParam param;\n cout << \"index\\tparam.id\\tvalue\\tparam.name\\tparam.source\\tparam.type\\n\";\n while (ult.getParam(i++, param))\n {\n \/\/ TODO: Learn about different param types and how to get their values.\n \/\/ This probably doesn't work properly for non-integer param values.\n \/\/ Have not been able to get getParamValue() to return false either.\n if (ult.getParamValue(param.id, val))\n {\n cout << i << \"\\t\" << param.id << \"\\t\" << val << \"\\t\" << param.name << \"\\t\" << param.source << \"\\t\" << param.type << \"\\t\" << param.unit << \"\\n\";\n }\n else\n {\n cerr << i << \"\\t'\" << param.id << \"'\\t\" << param.name << \"\\tFAILED\\n\";\n }\n }\n}\n\n\/*\n Set all integer-type Ultrasonix imaging parameters, as specified on the\n command line or in the parameter file.\n*\/\nvoid Ultracomm::set_int_imaging_params()\n{\n po::variables_map params = uopt.opt;\n po::options_description iopts = uopt.int_imaging_params;\n for ( auto iter = iopts.options().begin(); iter != iopts.options().end(); ++iter)\n {\n \/*\n Ultracomm program options do not contain spaces. Some of the\n parameters used by the ulterius setParamValue() call do contain\n spaces, and none appear to use underscore. The convention is that\n ultracomm program options containing underscore correspond to\n ulterius parameters that have the same name, but with the\n underscores replaced with spaces (' ').\n\n optname: the name as used in ultracomm program options (underscores)\n ultname: the name as used by ulterius setParamValue() (spaces)\n *\/\n string optname = (*iter)->long_name();\n string ultname = boost::replace_all_copy(optname, \"_\", \" \");\n if (params.count(optname)) {\n int val = params[optname].as();\n if (verbose) {\n cerr << \"Setting '\" << ultname << \"' to value \" << val << \".\\n\";\n }\n ult.setParamValue(ultname.c_str(), val);\n }\n }\n}\n\n\/*\n Verify that integer-type Ultrasonix imaging parameters have value as\n specified by user.\n*\/\nvoid Ultracomm::check_int_imaging_params()\n{\n po::variables_map params = uopt.opt;\n po::options_description iopts = uopt.int_imaging_params;\n for ( auto iter = iopts.options().begin(); iter != iopts.options().end(); ++iter)\n {\n \/*\n See comments in set_int_imaging_params() for mangling of\n parameter names.\n *\/\n string optname = (*iter)->long_name();\n string ultname = boost::replace_all_copy(optname, \"_\", \" \");\n if (params.count(optname)) {\n int expected, got;\n expected = params[optname].as();\n ult.getParamValue(ultname.c_str(), got);\n if (verbose) {\n cerr << \"Got value of '\" << ultname << \"'. Expected \" << expected << \" and got \" << got << \".\\n\";\n }\n if (got != expected) {\n cerr << \"Parameter '\" << ultname << \"' expected \" << expected << \" and got \" << got << \".\\n\";\n throw ParameterMismatchError();\n }\n }\n }\n}\n\n\/*\n Get data from Ultrasonix and save to file.\n*\/\nvoid Ultracomm::save_data()\n{\n po::variables_map params = uopt.opt;\n const string outname = params[\"output\"].as();\n int num_frames = ult.getCineDataCount((uData)datatype);\n uDataDesc desc;\n if (! ult.getDataDescriptor((uData)datatype, desc))\n {\n throw DataDescriptorError();\n }\n if (! ult.isDataAvailable((uData)datatype))\n {\n throw DataError();\n }\n ofstream outfile (outname, ios::out | ios::binary);\n write_header(outfile, desc, num_frames);\n\n \/\/ TODO: figure out why buffer and sz makes program crash\n \/\/const int sz = 2 * 1024 * 1024;\n \/\/char buffer[BUFFERSIZE]; \/\/ TODO: determine appropriate sizes on the fly\n\/\/ int num_frames = ult.getCineDataCount((uData)datatype);\n\n \/\/ TODO: framesize assumes desc.ss is always a multiple of 8, and that might not be safe.\n int framesize = (desc.ss \/ 8) * desc.w * desc.h;\n for (int idx = 0; idx < num_frames; idx++)\n {\n if (verbose) {\n cerr << \"Getting cine data for frame \" << idx << \".\\n\";\n }\n ult.getCineData((uData)datatype, idx, false, (char**)&gBuffer, BUFFERSIZE);\n outfile.write(gBuffer, framesize);\n if (verbose) {\n cerr << \"Wrote cine data for frame \" << idx << \".\\n\";\n }\n }\n outfile.close();\n}\n\n\/*\n TODO: header information is probably correct for .bpr files but possibly\n not for other datatypes.\n*\/\nvoid Ultracomm::write_header(ofstream& outfile, const uDataDesc& desc, const int& num_frames)\n{\n if (verbose) {\n cerr << \"Writing header.\\n\";\n }\n \/\/ Integer fields that we can write directly. Luckily these all are\n \/\/ consecutive fields in the header.\n const int isize = sizeof(__int32);\n static const int fields[] = {\n datatype,\n num_frames,\n desc.w,\n desc.h,\n desc.ss,\n desc.roi.ulx,\n desc.roi.uly,\n desc.roi.urx,\n desc.roi.ury,\n desc.roi.brx,\n desc.roi.bry,\n desc.roi.blx,\n desc.roi.bly,\n uopt.opt[\"probe-id\"].as()\n };\n for (int i = 0; i < sizeof(fields) \/ sizeof(fields[0]); ++i) {\n outfile.write(reinterpret_cast(&(__int32)fields[i]), isize);\n }\n\n \/\/ Integer fields that we have to query from Ultrasonix. These are also\n \/\/ consecutive in the header.\n \/\/ FIXME: Determine if these are the correct params to put in the header.\n static const string queries[] = {\n \"b-freq\",\n \"vec-freq\",\n \"frame rate\",\n \"b-ldensity\"\n };\n for (int i = 0; i < sizeof(queries) \/ sizeof(queries[0]); ++i) {\n int val;\n ult.getParamValue(queries[i].c_str(), val);\n outfile.write(reinterpret_cast(&(__int32)val), isize);\n }\n \/\/ FIXME: Figure out how to determine the value of the 'extra' field.\n \/\/ It will probably be added to queries[], but I don't know the param name.\n \/\/ For now we'll hard code it with value 0.\n int extra = 0;\n outfile.write(reinterpret_cast(&(__int32)extra), isize);\n}\n\n\/*\n Callback.\n*\/\nbool Ultracomm::frame_callback(void* data, int type, int sz, bool cine, int frmnum)\n{\n\/*\n if (verbose) {\n cerr << \"In callback.\\n\";\n }\n\n if (!data || !sz)\n {\n\/\/ TODO: proper error\n printf(\"Error: no actual frame data received\\n\");\n return false;\n }\n\n if (BUFFERSIZE < sz)\n {\n\/\/ TODO: proper error\n printf(\"Error: frame too large for current buffer\\n\");\n return false;\n }\n*\/\n\n \/\/printf(\"[Rx] type:(%d) size:(%d) cine:(%d) gBuffer:(%d) frame:(%d)\\n\", type, sz, cine, &gBuffer, frmnum);\n if (frmnum != lastFrame + 1) {\n printf(\"Skipped frame(s) %d - %d.\\n\", lastFrame + 1, frmnum - 1);\n }\n lastFrame = frmnum;\n \/\/ make sure we dont do an operation that takes longer than the acquisition frame rate\n memcpy(gBuffer, data, sz);\n\n return true;\n}\n<|endoftext|>"} {"text":"#include \"iocoom_performance_model.h\"\n\n#include \"log.h\"\n#include \"dynamic_instruction_info.h\"\n#include \"config.hpp\"\n#include \"simulator.h\"\n#include \"branch_predictor.h\"\n\nIOCOOMPerformanceModel::IOCOOMPerformanceModel()\n : m_instruction_count(0)\n , m_cycle_count(0)\n , m_register_scoreboard(512)\n , m_store_buffer(0)\n , m_load_unit(0)\n , m_l1_icache(0)\n , m_l1_dcache(0)\n{\n config::Config *cfg = Sim()->getCfg();\n\n try\n {\n m_store_buffer = new StoreBuffer(cfg->getInt(\"perf_model\/core\/num_store_buffer_entries\",1));\n m_load_unit = new ExecutionUnit(cfg->getInt(\"perf_model\/core\/num_outstanding_loads\",3));\n\n if (cfg->getBool(\"perf_model\/l1_icache\/enable\", false))\n {\n m_l1_icache = new ModeledCache(cfg->getInt(\"perf_model\/l1_icache\/line_size\"),\n cfg->getInt(\"perf_model\/l1_icache\/num_sets\"),\n cfg->getInt(\"perf_model\/l1_icache\/associativity\"),\n cfg->getInt(\"perf_model\/l1_icache\/victim_cache_size\"),\n cfg->getString(\"perf_model\/l1_icache\/replacement_policy\") == \"lru\" ? ModeledCache::LRU : ModeledCache::RANDOM);\n m_l1_icache_miss_penalty = cfg->getInt(\"perf_model\/l1_icache\/miss_penalty\");\n }\n\n if (cfg->getBool(\"perf_model\/l1_dcache\/enable\", false))\n {\n m_l1_dcache = new ModeledCache(cfg->getInt(\"perf_model\/l1_dcache\/line_size\"),\n cfg->getInt(\"perf_model\/l1_dcache\/num_sets\"),\n cfg->getInt(\"perf_model\/l1_dcache\/associativity\"),\n cfg->getInt(\"perf_model\/l1_dcache\/victim_cache_size\"),\n cfg->getString(\"perf_model\/l1_dcache\/replacement_policy\") == \"lru\" ? ModeledCache::LRU : ModeledCache::RANDOM);\n m_l1_dcache_access_time = cfg->getInt(\"perf_model\/l1_dcache\/access_time\");\n }\n }\n catch (...)\n {\n LOG_PRINT_ERROR(\"Config info not available.\");\n }\n\n for (unsigned int i = 0; i < m_register_scoreboard.size(); i++)\n {\n m_register_scoreboard[i] = 0;\n }\n}\n\nIOCOOMPerformanceModel::~IOCOOMPerformanceModel()\n{\n delete m_l1_dcache;\n delete m_l1_icache;\n delete m_load_unit;\n delete m_store_buffer;\n}\n\nvoid IOCOOMPerformanceModel::outputSummary(std::ostream &os)\n{\n os << \" Instructions: \" << m_instruction_count << std::endl\n << \" Cycles: \" << m_cycle_count << std::endl;\n\n if (getBranchPredictor())\n getBranchPredictor()->outputSummary(os);\n}\n\nUInt64 IOCOOMPerformanceModel::getCycleCount()\n{\n return m_cycle_count;\n}\n\nvoid IOCOOMPerformanceModel::setCycleCount(UInt64 time)\n{\n m_cycle_count = time;\n}\n\nvoid IOCOOMPerformanceModel::handleInstruction(Instruction *instruction)\n{\n \/\/ icache modeling\n modelIcache(instruction->getAddress());\n\n \/* \n model instruction in the following steps:\n - find when read operations are available\n - find latency of instruction\n - update write operands\n *\/\n const OperandList &ops = instruction->getOperands();\n\n \/\/ buffer write operands to be updated after instruction executes\n DynamicInstructionInfoQueue write_info;\n\n \/\/ find when read operands are available\n UInt64 operands_ready = m_cycle_count;\n UInt64 write_operands_ready = m_cycle_count;\n\n for (unsigned int i = 0; i < ops.size(); i++)\n {\n const Operand &o = ops[i];\n\n if (o.m_type == Operand::MEMORY)\n {\n DynamicInstructionInfo &info = getDynamicInstructionInfo();\n\n if (o.m_direction == Operand::READ)\n {\n LOG_ASSERT_ERROR(info.type == DynamicInstructionInfo::MEMORY_READ,\n \"Expected memory read info, got: %d.\", info.type);\n\n UInt64 load_ready = executeLoad(info) - m_cycle_count;\n\n if (load_ready > operands_ready)\n operands_ready = load_ready;\n }\n else\n {\n LOG_ASSERT_ERROR(info.type == DynamicInstructionInfo::MEMORY_WRITE,\n \"Expected memory write info, got: %d.\", info.type);\n\n write_info.push(info);\n }\n\n popDynamicInstructionInfo();\n }\n else if (o.m_type == Operand::REG)\n {\n LOG_ASSERT_ERROR(o.m_value < m_register_scoreboard.size(),\n \"Register value out of range: %llu\", o.m_value);\n\n if (o.m_direction == Operand::READ)\n {\n if (m_register_scoreboard[o.m_value] > operands_ready)\n operands_ready = m_register_scoreboard[o.m_value];\n }\n else\n {\n if (m_register_scoreboard[o.m_value] > write_operands_ready)\n write_operands_ready = m_register_scoreboard[o.m_value];\n }\n }\n else\n {\n \/\/ immediate -- do nothing\n }\n }\n\n \/\/ update cycle count with instruction cost\n UInt64 cost = instruction->getCost();\n\n m_instruction_count++;\n m_cycle_count = operands_ready + cost;\n\n \/\/ update write memory operands. this is done before doing register\n \/\/ operands to make sure the scoreboard is updated correctly\n for (unsigned int i = 0; i < ops.size(); i++)\n {\n const Operand &o = ops[i];\n\n if (o.m_direction != Operand::WRITE)\n continue;\n\n if (o.m_type != Operand::MEMORY)\n continue;\n\n const DynamicInstructionInfo &info = write_info.front();\n UInt64 store_time = executeStore(info);\n write_info.pop();\n\n if (store_time > m_cycle_count)\n m_cycle_count = store_time;\n\n if (store_time > write_operands_ready)\n write_operands_ready = store_time;\n }\n\n \/\/ because we are modeling an in-order machine, if we encounter a\n \/\/ register that is being updated out-of-order by a memory\n \/\/ reference, we must stall until we can write the register\n if (write_operands_ready > m_cycle_count)\n m_cycle_count = write_operands_ready;\n\n \/\/ update write register operands.\n for (unsigned int i = 0; i < ops.size(); i++)\n {\n const Operand &o = ops[i];\n\n if (o.m_direction != Operand::WRITE)\n continue;\n\n if (o.m_type != Operand::REG)\n continue;\n\n LOG_ASSERT_ERROR(m_register_scoreboard[o.m_value] <= m_cycle_count,\n \"Expected cycle count to exceed destination register times, %llu < %llu.\", m_register_scoreboard[o.m_value], m_cycle_count);\n\n m_register_scoreboard[o.m_value] = m_cycle_count;\n }\n\n LOG_ASSERT_ERROR(write_info.empty(), \"Some write info left over?\");\n}\n\nUInt64 IOCOOMPerformanceModel::executeLoad(const DynamicInstructionInfo &info)\n{\n bool l2_hit = info.memory_info.num_misses == 0;\n\n \/\/ similarly, a miss in the l2 with a completed entry in the store\n \/\/ buffer is treated as an invalidation\n StoreBuffer::Status status = m_store_buffer->isAddressAvailable(m_cycle_count, info.memory_info.addr);\n\n if ((status == StoreBuffer::VALID) || (l2_hit && status == StoreBuffer::COMPLETED))\n return m_cycle_count;\n\n \/\/ a miss in the l2 forces a miss in the l1 and store buffer since\n \/\/ we assume an inclusive l2 cache (a miss in the l2 generally\n \/\/ means the block has been invalidated)\n bool l1_hit = m_l1_dcache && m_l1_dcache->access(info.memory_info.addr);\n l1_hit = l1_hit && l2_hit;\n\n UInt64 latency = l1_hit ? m_l1_dcache_access_time : info.memory_info.latency;\n\n return m_load_unit->execute(m_cycle_count, latency);\n}\n\nUInt64 IOCOOMPerformanceModel::executeStore(const DynamicInstructionInfo &info)\n{\n bool l2_hit = info.memory_info.num_misses == 0;\n bool l1_hit = m_l1_dcache && m_l1_dcache->access(info.memory_info.addr);\n l1_hit = l1_hit && l2_hit;\n\n UInt64 latency = l1_hit ? m_l1_dcache_access_time : info.memory_info.latency;\n\n return m_store_buffer->executeStore(m_cycle_count, latency, info.memory_info.addr);\n}\n\nvoid IOCOOMPerformanceModel::modelIcache(IntPtr addr)\n{\n if (!m_l1_icache)\n return;\n\n bool hit = m_l1_icache->access(addr);\n if (!hit)\n m_cycle_count += m_l1_icache_miss_penalty;\n}\n\n\/\/ Helper classes \n\nIOCOOMPerformanceModel::ExecutionUnit::ExecutionUnit(unsigned int num_units)\n : m_scoreboard(num_units)\n{\n for (unsigned int i = 0; i < m_scoreboard.size(); i++)\n {\n m_scoreboard[i] = 0;\n }\n}\n\nIOCOOMPerformanceModel::ExecutionUnit::~ExecutionUnit()\n{\n}\n\nUInt64 IOCOOMPerformanceModel::ExecutionUnit::execute(UInt64 time, UInt64 occupancy)\n{\n UInt64 unit = 0;\n\n for (unsigned int i = 0; i < m_scoreboard.size(); i++)\n {\n if (m_scoreboard[i] <= time)\n {\n \/\/ a unit is available\n m_scoreboard[i] = time + occupancy;\n return time;\n }\n else\n {\n if (m_scoreboard[i] < m_scoreboard[unit])\n unit = i;\n }\n }\n\n \/\/ update unit, return time available\n m_scoreboard[unit] += occupancy;\n return m_scoreboard[unit] - occupancy;\n}\n\nIOCOOMPerformanceModel::StoreBuffer::StoreBuffer(unsigned int num_entries)\n : m_scoreboard(num_entries)\n , m_addresses(num_entries)\n{\n for (unsigned int i = 0; i < m_scoreboard.size(); i++)\n {\n m_scoreboard[i] = 0;\n m_addresses[i] = 0;\n }\n}\n\nIOCOOMPerformanceModel::StoreBuffer::~StoreBuffer()\n{\n}\n\nUInt64 IOCOOMPerformanceModel::StoreBuffer::executeStore(UInt64 time, UInt64 occupancy, IntPtr addr)\n{\n \/\/ Note: basically identical to ExecutionUnit, except we need to\n \/\/ track addresses as well\n\n \/\/ is address already in buffer?\n for (unsigned int i = 0; i < m_scoreboard.size(); i++)\n {\n if (m_addresses[i] == addr)\n {\n m_scoreboard[i] = time + occupancy;\n return time;\n }\n }\n\n \/\/ if not, find earliest available entry\n unsigned int unit = 0;\n\n for (unsigned int i = 0; i < m_scoreboard.size(); i++)\n {\n if (m_scoreboard[i] <= time)\n {\n \/\/ a unit is available\n m_scoreboard[i] = time + occupancy;\n m_addresses[i] = addr;\n return time;\n }\n else\n {\n if (m_scoreboard[i] < m_scoreboard[unit])\n unit = i;\n }\n }\n\n \/\/ update unit, return time available\n m_scoreboard[unit] += occupancy;\n m_addresses[unit] = addr;\n return m_scoreboard[unit] - occupancy;\n}\n\nIOCOOMPerformanceModel::StoreBuffer::Status IOCOOMPerformanceModel::StoreBuffer::isAddressAvailable(UInt64 time, IntPtr addr)\n{\n for (unsigned int i = 0; i < m_scoreboard.size(); i++)\n {\n if (m_addresses[i] == addr)\n {\n if (m_scoreboard[i] >= time)\n return VALID;\n else\n return COMPLETED;\n }\n }\n \n return NOT_FOUND;\n}\n[perf] Don't model dynamic instructions in the icache.#include \"iocoom_performance_model.h\"\n\n#include \"log.h\"\n#include \"dynamic_instruction_info.h\"\n#include \"config.hpp\"\n#include \"simulator.h\"\n#include \"branch_predictor.h\"\n\nIOCOOMPerformanceModel::IOCOOMPerformanceModel()\n : m_instruction_count(0)\n , m_cycle_count(0)\n , m_register_scoreboard(512)\n , m_store_buffer(0)\n , m_load_unit(0)\n , m_l1_icache(0)\n , m_l1_dcache(0)\n{\n config::Config *cfg = Sim()->getCfg();\n\n try\n {\n m_store_buffer = new StoreBuffer(cfg->getInt(\"perf_model\/core\/num_store_buffer_entries\",1));\n m_load_unit = new ExecutionUnit(cfg->getInt(\"perf_model\/core\/num_outstanding_loads\",3));\n\n if (cfg->getBool(\"perf_model\/l1_icache\/enable\", false))\n {\n m_l1_icache = new ModeledCache(cfg->getInt(\"perf_model\/l1_icache\/line_size\"),\n cfg->getInt(\"perf_model\/l1_icache\/num_sets\"),\n cfg->getInt(\"perf_model\/l1_icache\/associativity\"),\n cfg->getInt(\"perf_model\/l1_icache\/victim_cache_size\"),\n cfg->getString(\"perf_model\/l1_icache\/replacement_policy\") == \"lru\" ? ModeledCache::LRU : ModeledCache::RANDOM);\n m_l1_icache_miss_penalty = cfg->getInt(\"perf_model\/l1_icache\/miss_penalty\");\n }\n\n if (cfg->getBool(\"perf_model\/l1_dcache\/enable\", false))\n {\n m_l1_dcache = new ModeledCache(cfg->getInt(\"perf_model\/l1_dcache\/line_size\"),\n cfg->getInt(\"perf_model\/l1_dcache\/num_sets\"),\n cfg->getInt(\"perf_model\/l1_dcache\/associativity\"),\n cfg->getInt(\"perf_model\/l1_dcache\/victim_cache_size\"),\n cfg->getString(\"perf_model\/l1_dcache\/replacement_policy\") == \"lru\" ? ModeledCache::LRU : ModeledCache::RANDOM);\n m_l1_dcache_access_time = cfg->getInt(\"perf_model\/l1_dcache\/access_time\");\n }\n }\n catch (...)\n {\n LOG_PRINT_ERROR(\"Config info not available.\");\n }\n\n for (unsigned int i = 0; i < m_register_scoreboard.size(); i++)\n {\n m_register_scoreboard[i] = 0;\n }\n}\n\nIOCOOMPerformanceModel::~IOCOOMPerformanceModel()\n{\n delete m_l1_dcache;\n delete m_l1_icache;\n delete m_load_unit;\n delete m_store_buffer;\n}\n\nvoid IOCOOMPerformanceModel::outputSummary(std::ostream &os)\n{\n os << \" Instructions: \" << m_instruction_count << std::endl\n << \" Cycles: \" << m_cycle_count << std::endl;\n\n if (getBranchPredictor())\n getBranchPredictor()->outputSummary(os);\n}\n\nUInt64 IOCOOMPerformanceModel::getCycleCount()\n{\n return m_cycle_count;\n}\n\nvoid IOCOOMPerformanceModel::setCycleCount(UInt64 time)\n{\n m_cycle_count = time;\n}\n\nvoid IOCOOMPerformanceModel::handleInstruction(Instruction *instruction)\n{\n \/\/ icache modeling\n modelIcache(instruction->getAddress());\n\n \/* \n model instruction in the following steps:\n - find when read operations are available\n - find latency of instruction\n - update write operands\n *\/\n const OperandList &ops = instruction->getOperands();\n\n \/\/ buffer write operands to be updated after instruction executes\n DynamicInstructionInfoQueue write_info;\n\n \/\/ find when read operands are available\n UInt64 operands_ready = m_cycle_count;\n UInt64 write_operands_ready = m_cycle_count;\n\n for (unsigned int i = 0; i < ops.size(); i++)\n {\n const Operand &o = ops[i];\n\n if (o.m_type == Operand::MEMORY)\n {\n DynamicInstructionInfo &info = getDynamicInstructionInfo();\n\n if (o.m_direction == Operand::READ)\n {\n LOG_ASSERT_ERROR(info.type == DynamicInstructionInfo::MEMORY_READ,\n \"Expected memory read info, got: %d.\", info.type);\n\n UInt64 load_ready = executeLoad(info) - m_cycle_count;\n\n if (load_ready > operands_ready)\n operands_ready = load_ready;\n }\n else\n {\n LOG_ASSERT_ERROR(info.type == DynamicInstructionInfo::MEMORY_WRITE,\n \"Expected memory write info, got: %d.\", info.type);\n\n write_info.push(info);\n }\n\n popDynamicInstructionInfo();\n }\n else if (o.m_type == Operand::REG)\n {\n LOG_ASSERT_ERROR(o.m_value < m_register_scoreboard.size(),\n \"Register value out of range: %llu\", o.m_value);\n\n if (o.m_direction == Operand::READ)\n {\n if (m_register_scoreboard[o.m_value] > operands_ready)\n operands_ready = m_register_scoreboard[o.m_value];\n }\n else\n {\n if (m_register_scoreboard[o.m_value] > write_operands_ready)\n write_operands_ready = m_register_scoreboard[o.m_value];\n }\n }\n else\n {\n \/\/ immediate -- do nothing\n }\n }\n\n \/\/ update cycle count with instruction cost\n UInt64 cost = instruction->getCost();\n\n m_instruction_count++;\n m_cycle_count = operands_ready + cost;\n\n \/\/ update write memory operands. this is done before doing register\n \/\/ operands to make sure the scoreboard is updated correctly\n for (unsigned int i = 0; i < ops.size(); i++)\n {\n const Operand &o = ops[i];\n\n if (o.m_direction != Operand::WRITE)\n continue;\n\n if (o.m_type != Operand::MEMORY)\n continue;\n\n const DynamicInstructionInfo &info = write_info.front();\n UInt64 store_time = executeStore(info);\n write_info.pop();\n\n if (store_time > m_cycle_count)\n m_cycle_count = store_time;\n\n if (store_time > write_operands_ready)\n write_operands_ready = store_time;\n }\n\n \/\/ because we are modeling an in-order machine, if we encounter a\n \/\/ register that is being updated out-of-order by a memory\n \/\/ reference, we must stall until we can write the register\n if (write_operands_ready > m_cycle_count)\n m_cycle_count = write_operands_ready;\n\n \/\/ update write register operands.\n for (unsigned int i = 0; i < ops.size(); i++)\n {\n const Operand &o = ops[i];\n\n if (o.m_direction != Operand::WRITE)\n continue;\n\n if (o.m_type != Operand::REG)\n continue;\n\n LOG_ASSERT_ERROR(m_register_scoreboard[o.m_value] <= m_cycle_count,\n \"Expected cycle count to exceed destination register times, %llu < %llu.\", m_register_scoreboard[o.m_value], m_cycle_count);\n\n m_register_scoreboard[o.m_value] = m_cycle_count;\n }\n\n LOG_ASSERT_ERROR(write_info.empty(), \"Some write info left over?\");\n}\n\nUInt64 IOCOOMPerformanceModel::executeLoad(const DynamicInstructionInfo &info)\n{\n bool l2_hit = info.memory_info.num_misses == 0;\n\n \/\/ similarly, a miss in the l2 with a completed entry in the store\n \/\/ buffer is treated as an invalidation\n StoreBuffer::Status status = m_store_buffer->isAddressAvailable(m_cycle_count, info.memory_info.addr);\n\n if ((status == StoreBuffer::VALID) || (l2_hit && status == StoreBuffer::COMPLETED))\n return m_cycle_count;\n\n \/\/ a miss in the l2 forces a miss in the l1 and store buffer since\n \/\/ we assume an inclusive l2 cache (a miss in the l2 generally\n \/\/ means the block has been invalidated)\n bool l1_hit = m_l1_dcache && m_l1_dcache->access(info.memory_info.addr);\n l1_hit = l1_hit && l2_hit;\n\n UInt64 latency = l1_hit ? m_l1_dcache_access_time : info.memory_info.latency;\n\n return m_load_unit->execute(m_cycle_count, latency);\n}\n\nUInt64 IOCOOMPerformanceModel::executeStore(const DynamicInstructionInfo &info)\n{\n bool l2_hit = info.memory_info.num_misses == 0;\n bool l1_hit = m_l1_dcache && m_l1_dcache->access(info.memory_info.addr);\n l1_hit = l1_hit && l2_hit;\n\n UInt64 latency = l1_hit ? m_l1_dcache_access_time : info.memory_info.latency;\n\n return m_store_buffer->executeStore(m_cycle_count, latency, info.memory_info.addr);\n}\n\nvoid IOCOOMPerformanceModel::modelIcache(IntPtr addr)\n{\n if (!m_l1_icache || addr == 0)\n return;\n\n bool hit = m_l1_icache->access(addr);\n if (!hit)\n m_cycle_count += m_l1_icache_miss_penalty;\n}\n\n\/\/ Helper classes \n\nIOCOOMPerformanceModel::ExecutionUnit::ExecutionUnit(unsigned int num_units)\n : m_scoreboard(num_units)\n{\n for (unsigned int i = 0; i < m_scoreboard.size(); i++)\n {\n m_scoreboard[i] = 0;\n }\n}\n\nIOCOOMPerformanceModel::ExecutionUnit::~ExecutionUnit()\n{\n}\n\nUInt64 IOCOOMPerformanceModel::ExecutionUnit::execute(UInt64 time, UInt64 occupancy)\n{\n UInt64 unit = 0;\n\n for (unsigned int i = 0; i < m_scoreboard.size(); i++)\n {\n if (m_scoreboard[i] <= time)\n {\n \/\/ a unit is available\n m_scoreboard[i] = time + occupancy;\n return time;\n }\n else\n {\n if (m_scoreboard[i] < m_scoreboard[unit])\n unit = i;\n }\n }\n\n \/\/ update unit, return time available\n m_scoreboard[unit] += occupancy;\n return m_scoreboard[unit] - occupancy;\n}\n\nIOCOOMPerformanceModel::StoreBuffer::StoreBuffer(unsigned int num_entries)\n : m_scoreboard(num_entries)\n , m_addresses(num_entries)\n{\n for (unsigned int i = 0; i < m_scoreboard.size(); i++)\n {\n m_scoreboard[i] = 0;\n m_addresses[i] = 0;\n }\n}\n\nIOCOOMPerformanceModel::StoreBuffer::~StoreBuffer()\n{\n}\n\nUInt64 IOCOOMPerformanceModel::StoreBuffer::executeStore(UInt64 time, UInt64 occupancy, IntPtr addr)\n{\n \/\/ Note: basically identical to ExecutionUnit, except we need to\n \/\/ track addresses as well\n\n \/\/ is address already in buffer?\n for (unsigned int i = 0; i < m_scoreboard.size(); i++)\n {\n if (m_addresses[i] == addr)\n {\n m_scoreboard[i] = time + occupancy;\n return time;\n }\n }\n\n \/\/ if not, find earliest available entry\n unsigned int unit = 0;\n\n for (unsigned int i = 0; i < m_scoreboard.size(); i++)\n {\n if (m_scoreboard[i] <= time)\n {\n \/\/ a unit is available\n m_scoreboard[i] = time + occupancy;\n m_addresses[i] = addr;\n return time;\n }\n else\n {\n if (m_scoreboard[i] < m_scoreboard[unit])\n unit = i;\n }\n }\n\n \/\/ update unit, return time available\n m_scoreboard[unit] += occupancy;\n m_addresses[unit] = addr;\n return m_scoreboard[unit] - occupancy;\n}\n\nIOCOOMPerformanceModel::StoreBuffer::Status IOCOOMPerformanceModel::StoreBuffer::isAddressAvailable(UInt64 time, IntPtr addr)\n{\n for (unsigned int i = 0; i < m_scoreboard.size(); i++)\n {\n if (m_addresses[i] == addr)\n {\n if (m_scoreboard[i] >= time)\n return VALID;\n else\n return COMPLETED;\n }\n }\n \n return NOT_FOUND;\n}\n<|endoftext|>"} {"text":"\/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n#include \n\n#include \"tensorflow\/contrib\/lite\/toco\/graph_transformations\/graph_transformations.h\"\n#include \"tensorflow\/contrib\/lite\/toco\/model.h\"\n#include \"tensorflow\/contrib\/lite\/toco\/tooling_util.h\"\n#include \"tensorflow\/core\/platform\/logging.h\"\n\nnamespace toco {\n\nbool ConvertTrivialTransposeToReshape::Run(Model* model, std::size_t op_index) {\n auto transpose_it = model->operators.begin() + op_index;\n if (transpose_it->get()->type != OperatorType::kTranspose) {\n return false;\n }\n TransposeOperator* transpose_op =\n static_cast(transpose_it->get());\n\n const auto& output_array = model->GetArray(transpose_op->outputs[0]);\n if (!output_array.has_shape()) {\n \/\/ Yield until PropagateFixedSizes has been run on this op.\n return false;\n }\n \/\/ Note: We can assume we have error checked inputs in PropagateFixedSizes.\n\n \/\/ This transpose is trivial if we only have one non-unitary dimension.\n std::vector const& dims = output_array.shape().dims();\n unsigned non_unitary_axis_count = 0;\n for (int i = 0; i < dims.size(); i++) {\n if (dims[i] != 1) {\n non_unitary_axis_count++;\n }\n }\n if (non_unitary_axis_count > 1) {\n \/\/ Transpose is not trivial\n return false;\n }\n\n \/\/ This transpose is trivial. Replace it with a Reshape op.\n auto* reshape_op = new TensorFlowReshapeOperator;\n\n \/\/ Copy input and output\n reshape_op->inputs.push_back(transpose_op->inputs[0]);\n reshape_op->outputs = transpose_op->outputs;\n\n \/\/ Create a new input array for the shape input\n string perm_array_name = transpose_op->inputs[1];\n string shape_array_name = toco::AvailableArrayName(*model, perm_array_name);\n Array& shape_array = model->GetOrCreateArray(shape_array_name);\n *(shape_array.mutable_shape()->mutable_dims()) = {\n 1, static_cast(dims.size())};\n reshape_op->inputs.push_back(shape_array_name);\n shape_array.data_type = ArrayDataType::kInt32;\n auto& shape_buffer = shape_array.GetMutableBuffer();\n shape_buffer.data = dims;\n\n \/\/ Delete perm array if unused\n if (IsDiscardableArray(*model, perm_array_name) &&\n CountOpsWithInput(*model, perm_array_name) == 1) {\n model->EraseArray(perm_array_name);\n }\n\n \/\/ Replace the operator in the graph.\n const auto reshape_it = model->operators.emplace(transpose_it, reshape_op);\n transpose_it = reshape_it + 1;\n CHECK_EQ(transpose_it->get(), transpose_op);\n model->operators.erase(transpose_it);\n\n return true;\n}\n\n} \/\/ namespace toco\nTransposes are can be merged into reshapes when the ordering of non-one dimensions remains unchanged.\/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n#include \n\n#include \"tensorflow\/contrib\/lite\/toco\/graph_transformations\/graph_transformations.h\"\n#include \"tensorflow\/contrib\/lite\/toco\/model.h\"\n#include \"tensorflow\/contrib\/lite\/toco\/tooling_util.h\"\n#include \"tensorflow\/core\/platform\/logging.h\"\n\nnamespace toco {\n\nnamespace {\n\nbool TransposeAffectsMemoryOrder(std::vector perm,\n std::vector in_shape) {\n CHECK_EQ(perm.size(), in_shape.size());\n \/\/ See what the ordering of the non-unary columns are before and after\n \/\/ transpose permutation. If the major indices stay in the same order (not\n \/\/ just the shape) then the flat buffer representation shouldn't change.\n std::vector old_major_index_ordering;\n std::vector new_major_index_ordering;\n for (int i = 0; i < in_shape.size(); i++) {\n if (in_shape[i] != 1) {\n old_major_index_ordering.push_back(i);\n }\n\n if (in_shape[perm[i]] != 1) {\n new_major_index_ordering.push_back(perm[i]);\n }\n }\n\n CHECK_EQ(new_major_index_ordering.size(), old_major_index_ordering.size());\n\n return old_major_index_ordering != new_major_index_ordering;\n}\n\n} \/\/ namespace\n\nbool ConvertTrivialTransposeToReshape::Run(Model* model, std::size_t op_index) {\n auto transpose_it = model->operators.begin() + op_index;\n if (transpose_it->get()->type != OperatorType::kTranspose) {\n return false;\n }\n TransposeOperator* transpose_op =\n static_cast(transpose_it->get());\n\n const auto& input_array = model->GetArray(transpose_op->inputs[0]);\n const auto& output_array = model->GetArray(transpose_op->outputs[0]);\n if (!input_array.has_shape() || !output_array.has_shape()) {\n \/\/ Yield until PropagateFixedSizes has been run on this op.\n return false;\n }\n \/\/ Note: We can assume we have error checked inputs in PropagateFixedSizes.\n\n \/\/ Check that the permutation has propogated.\n std::vector const& perm = transpose_op->perm;\n if (perm.empty()) {\n return false;\n }\n\n \/\/ This transpose is trivial if non-unitary dimensions remain in the same\n \/\/ order.\n std::vector const& input_dims = input_array.shape().dims();\n std::vector const& output_dims = output_array.shape().dims();\n\n if (TransposeAffectsMemoryOrder(perm, input_dims)) {\n return false;\n }\n\n \/\/ This transpose is trivial. Replace it with a Reshape op.\n auto* reshape_op = new TensorFlowReshapeOperator;\n\n \/\/ Copy input and output\n reshape_op->inputs.push_back(transpose_op->inputs[0]);\n reshape_op->outputs = transpose_op->outputs;\n\n \/\/ Create a new input array for the shape input\n string perm_array_name = transpose_op->inputs[1];\n string shape_array_name = toco::AvailableArrayName(*model, perm_array_name);\n Array& shape_array = model->GetOrCreateArray(shape_array_name);\n *(shape_array.mutable_shape()->mutable_dims()) = {\n 1, static_cast(output_dims.size())};\n reshape_op->inputs.push_back(shape_array_name);\n shape_array.data_type = ArrayDataType::kInt32;\n auto& shape_buffer = shape_array.GetMutableBuffer();\n shape_buffer.data = output_dims;\n\n \/\/ Delete perm array if unused\n if (IsDiscardableArray(*model, perm_array_name) &&\n CountOpsWithInput(*model, perm_array_name) == 1) {\n model->EraseArray(perm_array_name);\n }\n\n \/\/ Replace the operator in the graph.\n const auto reshape_it = model->operators.emplace(transpose_it, reshape_op);\n transpose_it = reshape_it + 1;\n CHECK_EQ(transpose_it->get(), transpose_op);\n model->operators.erase(transpose_it);\n\n return true;\n}\n\n} \/\/ namespace toco\n<|endoftext|>"} {"text":"\/\/==============================================================================\n\/\/ CellML annotation view metadata edit details widget\n\/\/==============================================================================\n\n#include \"cellmlannotationviewlistswidget.h\"\n#include \"cellmlannotationviewmetadataeditdetailswidget.h\"\n#include \"cellmlannotationviewmetadatalistwidget.h\"\n#include \"cellmlannotationviewwidget.h\"\n#include \"coreutils.h\"\n#include \"treeview.h\"\n\n\/\/==============================================================================\n\n#include \"ui_cellmlannotationviewmetadataeditdetailswidget.h\"\n\n\/\/==============================================================================\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/==============================================================================\n\n#include \n\n\/\/==============================================================================\n\nnamespace OpenCOR {\nnamespace CellMLAnnotationView {\n\n\/\/==============================================================================\n\nCellmlAnnotationViewMetadataEditDetailsWidget::CellmlAnnotationViewMetadataEditDetailsWidget(CellmlAnnotationViewWidget *pParent) :\n QScrollArea(pParent),\n CommonWidget(pParent),\n mGui(new Ui::CellmlAnnotationViewMetadataEditDetailsWidget),\n mMainWidget(0),\n mMainLayout(0),\n mFormWidget(0),\n mFormLayout(0),\n mGridWidget(0),\n mGridLayout(0),\n mErrorMsg(QString()),\n mTerm(QString()),\n mTermUrl(QString()),\n mOtherTermUrl(QString())\n{\n \/\/ Set up the GUI\n\n mGui->setupUi(this);\n\n \/\/ Create a stacked widget which will contain our GUI\n\n mWidget = new QStackedWidget(this);\n\n \/\/ Add our stacked widget to our scroll area\n\n setWidget(mWidget);\n\n \/\/ Create a network access manager so that we can then retrieve a list of\n \/\/ CellML models from the CellML Model Repository\n\n mNetworkAccessManager = new QNetworkAccessManager(this);\n\n \/\/ Make sure that we get told when the download of our Internet file is\n \/\/ complete\n\n connect(mNetworkAccessManager, SIGNAL(finished(QNetworkReply *)),\n this, SLOT(finished(QNetworkReply *)) );\n}\n\n\/\/==============================================================================\n\nCellmlAnnotationViewMetadataEditDetailsWidget::~CellmlAnnotationViewMetadataEditDetailsWidget()\n{\n \/\/ Delete the GUI\n\n delete mGui;\n}\n\n\/\/==============================================================================\n\nvoid CellmlAnnotationViewMetadataEditDetailsWidget::retranslateUi()\n{\n \/\/ Retranslate our GUI\n\n mGui->retranslateUi(this);\n\n \/\/ For the rest of our GUI, it's easier to just update it, so...\n\n updateGui();\n}\n\n\/\/==============================================================================\n\nvoid CellmlAnnotationViewMetadataEditDetailsWidget::updateGui(const bool &pPopulate)\n{\n \/\/ Note: we are using certain layouts to dislay the contents of our view,\n \/\/ but this unfortunately results in some very bad flickering on Mac\n \/\/ OS X. This can, however, be addressed using a stacked widget, so...\n\n \/\/ Prevent ourselves from being updated (to avoid any flickering)\n\n setUpdatesEnabled(false);\n\n \/\/ Create a widget which will contain our GUI\n\n QWidget *newMainWidget = new QWidget(this);\n QVBoxLayout *newMainLayout = new QVBoxLayout(newMainWidget);\n\n newMainLayout->setMargin(0);\n\n newMainWidget->setLayout(newMainLayout);\n\n \/\/ Populate our GUI, but only if requested\n\n QWidget *newFormWidget = 0;\n QFormLayout *newFormLayout = 0;\n QWidget *newGridWidget = 0;\n QGridLayout *newGridLayout = 0;\n\n if (pPopulate) {\n \/\/ Deal with the form part of our GUI\n\n \/\/ Create a form widget which will contain our qualifier and term fields\n\n newFormWidget = new QWidget(newMainWidget);\n newFormLayout = new QFormLayout(newFormWidget);\n\n newFormWidget->setLayout(newFormLayout);\n\n \/\/ Add our qualifier and term fields\n\n QComboBox *qualifierValue = new QComboBox(newFormWidget);\n\n qualifierValue->addItems(CellMLSupport::CellmlFileRdfTriple::qualifiersAsStringList());\n\n newFormLayout->addRow(Core::newLabel(newFormWidget, tr(\"Qualifier:\"), true),\n qualifierValue);\n\n QLineEdit *termValue = new QLineEdit(newFormWidget);\n\n termValue->setText(mTerm);\n\n connect(termValue, SIGNAL(textChanged(const QString &)),\n this, SLOT(lookupTerm(const QString &)));\n\n newFormLayout->addRow(Core::newLabel(newFormWidget, tr(\"Term:\"), true),\n termValue);\n\n \/\/ Let people know that the GUI has been populated\n\n emit guiPopulated(qualifierValue, termValue);\n\n \/\/ Deal with the grid part of our GUI\n\n \/\/ Create a new widget and layout\n\n newGridWidget = new QWidget(newMainWidget);\n newGridLayout = new QGridLayout(newGridWidget);\n\n newGridWidget->setLayout(newGridLayout);\n\n \/\/ Populate our new layout, but only if there is at least one RDF triple\n \/\/ Note: the two calls to setRowStretch() ensures that our grid layout\n \/\/ takes as much vertical space as possible (otherwise our form\n \/\/ layout might take some vertical space making it look a bit odd\n \/\/ if there are no data available)...\n\n newGridLayout->setRowStretch(0, 1);\n\n newGridLayout->addWidget(Core::newLabel(newMainWidget,\n tr(\"No data available...\"),\n false, 1.25, Qt::AlignCenter),\n 1, 0);\n\n newGridLayout->setRowStretch(2, 1);\n\n \/\/ Add our 'internal' widgets to our new main widget\n\n newMainLayout->addWidget(newFormWidget);\n newMainLayout->addWidget(Core::newLineWidget(newMainWidget));\n newMainLayout->addWidget(newGridWidget);\n }\n\n \/\/ Add our new widget to our stacked widget\n\n mWidget->addWidget(newMainWidget);\n\n \/\/ Remove the contents of our old form layout\n\n if (mFormWidget)\n for (int i = 0, iMax = mFormLayout->count(); i < iMax; ++i) {\n QLayoutItem *item = mFormLayout->takeAt(0);\n\n delete item->widget();\n delete item;\n }\n\n \/\/ Remove the contents of our old grid layout\n\n if (mGridWidget)\n for (int i = 0, iMax = mGridLayout->count(); i < iMax; ++i) {\n QLayoutItem *item = mGridLayout->takeAt(0);\n\n delete item->widget();\n delete item;\n }\n\n \/\/ Get rid of our old main widget and layout (and its contents)\n\n if (mMainWidget) {\n mWidget->removeWidget(mMainWidget);\n\n for (int i = 0, iMax = mMainLayout->count(); i < iMax; ++i) {\n QLayoutItem *item = mMainLayout->takeAt(0);\n\n delete item->widget();\n delete item;\n }\n\n delete mMainWidget;\n }\n\n \/\/ Keep track of our new main widgets and layouts\n\n mMainWidget = newMainWidget;\n mMainLayout = newMainLayout;\n\n mFormWidget = newFormWidget;\n mFormLayout = newFormLayout;\n\n mGridWidget = newGridWidget;\n mGridLayout = newGridLayout;\n\n \/\/ Allow ourselves to be updated again\n\n setUpdatesEnabled(true);\n}\n\n\/\/==============================================================================\n\nvoid CellmlAnnotationViewMetadataEditDetailsWidget::lookupTerm(const QString &pTerm)\n{\n \/\/ Keep track of the term to lookup\n\n mTerm = pTerm;\n\n \/\/ Retrieve some possible ontological terms based on the given term\n\n QString termUrl = QString(\"http:\/\/www.semanticsbml.org\/semanticSBML\/annotate\/search.json?q=%1&full_info=1\").arg(pTerm);\n\n if (mTermUrl.isEmpty()) {\n \/\/ No other term is being looked up, so keep track of the given term and\n \/\/ look it up\n\n mTermUrl = termUrl;\n\n mNetworkAccessManager->get(QNetworkRequest(termUrl));\n } else {\n \/\/ Another term is already being looked up, so keep track of the given\n \/\/ term for later\n\n mOtherTermUrl = termUrl;\n }\n}\n\n\/\/==============================================================================\n\nvoid CellmlAnnotationViewMetadataEditDetailsWidget::finished(QNetworkReply *pNetworkReply)\n{\n \/\/ Output the list of models, should we have retrieved it without any\n \/\/ problem\n\n if (pNetworkReply->error() == QNetworkReply::NoError) {\n \/\/ Parse the JSON code\n\n QJson::Parser jsonParser;\n bool parsingOk;\n\n QVariantMap resultMap = jsonParser.parse(pNetworkReply->readAll(), &parsingOk).toMap();\n\nstatic int counter = 0;\nqDebug(\"---[%03d]--------------------------------------\", ++counter);\nqDebug(\"URL: %s\", qPrintable(pNetworkReply->url().toString()));\n\n if (parsingOk) {\n \/\/ Retrieve the list of CellML models\n\n foreach (const QVariant &ontologicalsTermVariant, resultMap[\"result\"].toList()) {\n QVariantList ontologicalTermVariant = ontologicalsTermVariant.toList();\n\n for (int i = 0, iMax = ontologicalTermVariant.count(); i < iMax; ++i) {\n QVariantMap ontologicalTermMap = ontologicalTermVariant[i].toMap();\n\nqDebug(\">>> %s ---> %s\", qPrintable(ontologicalTermMap[\"uri\"].toString()),\n qPrintable(ontologicalTermMap[\"name\"].toString()));\n }\n }\n\n \/\/ Everything went fine, so...\n\n mErrorMsg = QString();\n } else {\n \/\/ Something went wrong, so...\n\n mErrorMsg = jsonParser.errorString();\n }\n } else {\n \/\/ Something went wrong, so...\n\n mErrorMsg = pNetworkReply->errorString();\n }\n\n \/\/ We are done, so...\n\n mTermUrl = QString();\n\n \/\/ Check whether there is another term to look up\n\n if (!mOtherTermUrl.isEmpty()) {\n mNetworkAccessManager->get(QNetworkRequest(mOtherTermUrl));\n\n mOtherTermUrl = QString();\n }\n}\n\n\/\/==============================================================================\n\n} \/\/ namespace CellMLAnnotationView\n} \/\/ namespace OpenCOR\n\n\/\/==============================================================================\n\/\/ End of file\n\/\/==============================================================================\nSome work on the addition of RDF triples (#90).\/\/==============================================================================\n\/\/ CellML annotation view metadata edit details widget\n\/\/==============================================================================\n\n#include \"cellmlannotationviewlistswidget.h\"\n#include \"cellmlannotationviewmetadataeditdetailswidget.h\"\n#include \"cellmlannotationviewmetadatalistwidget.h\"\n#include \"cellmlannotationviewwidget.h\"\n#include \"coreutils.h\"\n#include \"treeview.h\"\n\n\/\/==============================================================================\n\n#include \"ui_cellmlannotationviewmetadataeditdetailswidget.h\"\n\n\/\/==============================================================================\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/==============================================================================\n\n#include \n\n\/\/==============================================================================\n\nnamespace OpenCOR {\nnamespace CellMLAnnotationView {\n\n\/\/==============================================================================\n\nCellmlAnnotationViewMetadataEditDetailsWidget::CellmlAnnotationViewMetadataEditDetailsWidget(CellmlAnnotationViewWidget *pParent) :\n QScrollArea(pParent),\n CommonWidget(pParent),\n mGui(new Ui::CellmlAnnotationViewMetadataEditDetailsWidget),\n mMainWidget(0),\n mMainLayout(0),\n mFormWidget(0),\n mFormLayout(0),\n mGridWidget(0),\n mGridLayout(0),\n mErrorMsg(QString()),\n mTerm(QString()),\n mTermUrl(QString()),\n mOtherTermUrl(QString())\n{\n \/\/ Set up the GUI\n\n mGui->setupUi(this);\n\n \/\/ Create a stacked widget which will contain our GUI\n\n mWidget = new QStackedWidget(this);\n\n \/\/ Add our stacked widget to our scroll area\n\n setWidget(mWidget);\n\n \/\/ Create a network access manager so that we can then retrieve a list of\n \/\/ CellML models from the CellML Model Repository\n\n mNetworkAccessManager = new QNetworkAccessManager(this);\n\n \/\/ Make sure that we get told when the download of our Internet file is\n \/\/ complete\n\n connect(mNetworkAccessManager, SIGNAL(finished(QNetworkReply *)),\n this, SLOT(finished(QNetworkReply *)) );\n}\n\n\/\/==============================================================================\n\nCellmlAnnotationViewMetadataEditDetailsWidget::~CellmlAnnotationViewMetadataEditDetailsWidget()\n{\n \/\/ Delete the GUI\n\n delete mGui;\n}\n\n\/\/==============================================================================\n\nvoid CellmlAnnotationViewMetadataEditDetailsWidget::retranslateUi()\n{\n \/\/ Retranslate our GUI\n\n mGui->retranslateUi(this);\n\n \/\/ For the rest of our GUI, it's easier to just update it, so...\n\n updateGui();\n}\n\n\/\/==============================================================================\n\nvoid CellmlAnnotationViewMetadataEditDetailsWidget::updateGui(const bool &pPopulate)\n{\n \/\/ Note: we are using certain layouts to dislay the contents of our view,\n \/\/ but this unfortunately results in some very bad flickering on Mac\n \/\/ OS X. This can, however, be addressed using a stacked widget, so...\n\n \/\/ Prevent ourselves from being updated (to avoid any flickering)\n\n setUpdatesEnabled(false);\n\n \/\/ Create a widget which will contain our GUI\n\n QWidget *newMainWidget = new QWidget(this);\n QVBoxLayout *newMainLayout = new QVBoxLayout(newMainWidget);\n\n newMainLayout->setMargin(0);\n\n newMainWidget->setLayout(newMainLayout);\n\n \/\/ Populate our GUI, but only if requested\n\n QWidget *newFormWidget = 0;\n QFormLayout *newFormLayout = 0;\n QWidget *newGridWidget = 0;\n QGridLayout *newGridLayout = 0;\n\n QLineEdit *termValue = 0;\n\n if (pPopulate) {\n \/\/ Deal with the form part of our GUI\n\n \/\/ Create a form widget which will contain our qualifier and term fields\n\n newFormWidget = new QWidget(newMainWidget);\n newFormLayout = new QFormLayout(newFormWidget);\n\n newFormWidget->setLayout(newFormLayout);\n\n \/\/ Add our qualifier and term fields\n\n QComboBox *qualifierValue = new QComboBox(newFormWidget);\n\n qualifierValue->addItems(CellMLSupport::CellmlFileRdfTriple::qualifiersAsStringList());\n\n newFormLayout->addRow(Core::newLabel(newFormWidget, tr(\"Qualifier:\"), true),\n qualifierValue);\n\n termValue = new QLineEdit(newFormWidget);\n\n connect(termValue, SIGNAL(textChanged(const QString &)),\n this, SLOT(lookupTerm(const QString &)));\n\n newFormLayout->addRow(Core::newLabel(newFormWidget, tr(\"Term:\"), true),\n termValue);\n\n \/\/ Let people know that the GUI has been populated\n\n emit guiPopulated(qualifierValue, termValue);\n\n \/\/ Deal with the grid part of our GUI\n\n \/\/ Create a new widget and layout\n\n newGridWidget = new QWidget(newMainWidget);\n newGridLayout = new QGridLayout(newGridWidget);\n\n newGridWidget->setLayout(newGridLayout);\n\n \/\/ Populate our new layout, but only if there is at least one RDF triple\n \/\/ Note: the two calls to setRowStretch() ensures that our grid layout\n \/\/ takes as much vertical space as possible (otherwise our form\n \/\/ layout might take some vertical space making it look a bit odd\n \/\/ if there are no data available)...\n\n newGridLayout->setRowStretch(0, 1);\n\n newGridLayout->addWidget(Core::newLabel(newMainWidget,\n tr(\"No data available...\"),\n false, 1.25, Qt::AlignCenter),\n 1, 0);\n\n newGridLayout->setRowStretch(2, 1);\n\n \/\/ Add our 'internal' widgets to our new main widget\n\n newMainLayout->addWidget(newFormWidget);\n newMainLayout->addWidget(Core::newLineWidget(newMainWidget));\n newMainLayout->addWidget(newGridWidget);\n }\n\n \/\/ Add our new widget to our stacked widget\n\n mWidget->addWidget(newMainWidget);\n\n \/\/ Remove the contents of our old form layout\n\n if (mFormWidget)\n for (int i = 0, iMax = mFormLayout->count(); i < iMax; ++i) {\n QLayoutItem *item = mFormLayout->takeAt(0);\n\n delete item->widget();\n delete item;\n }\n\n \/\/ Remove the contents of our old grid layout\n\n if (mGridWidget)\n for (int i = 0, iMax = mGridLayout->count(); i < iMax; ++i) {\n QLayoutItem *item = mGridLayout->takeAt(0);\n\n delete item->widget();\n delete item;\n }\n\n \/\/ Get rid of our old main widget and layout (and its contents)\n\n if (mMainWidget) {\n mWidget->removeWidget(mMainWidget);\n\n for (int i = 0, iMax = mMainLayout->count(); i < iMax; ++i) {\n QLayoutItem *item = mMainLayout->takeAt(0);\n\n delete item->widget();\n delete item;\n }\n\n delete mMainWidget;\n }\n\n \/\/ Keep track of our new main widgets and layouts\n\n mMainWidget = newMainWidget;\n mMainLayout = newMainLayout;\n\n mFormWidget = newFormWidget;\n mFormLayout = newFormLayout;\n\n mGridWidget = newGridWidget;\n mGridLayout = newGridLayout;\n\n \/\/ Reset the term which was being looked up, if any\n\n if (termValue)\n termValue->setText(mTerm);\n\n \/\/ Allow ourselves to be updated again\n\n setUpdatesEnabled(true);\n}\n\n\/\/==============================================================================\n\nvoid CellmlAnnotationViewMetadataEditDetailsWidget::lookupTerm(const QString &pTerm)\n{\n \/\/ Keep track of the term to lookup\n\n mTerm = pTerm;\n\n \/\/ Retrieve some possible ontological terms based on the given term\n\n QString termUrl = QString(\"http:\/\/www.semanticsbml.org\/semanticSBML\/annotate\/search.json?q=%1&full_info=1\").arg(pTerm);\n\n if (mTermUrl.isEmpty()) {\n \/\/ No other term is being looked up, so keep track of the given term and\n \/\/ look it up\n\n mTermUrl = termUrl;\n\n mNetworkAccessManager->get(QNetworkRequest(termUrl));\n } else {\n \/\/ Another term is already being looked up, so keep track of the given\n \/\/ term for later\n\n mOtherTermUrl = termUrl;\n }\n}\n\n\/\/==============================================================================\n\nvoid CellmlAnnotationViewMetadataEditDetailsWidget::finished(QNetworkReply *pNetworkReply)\n{\n \/\/ Output the list of models, should we have retrieved it without any\n \/\/ problem\n\n if (pNetworkReply->error() == QNetworkReply::NoError) {\n \/\/ Parse the JSON code\n\n QJson::Parser jsonParser;\n bool parsingOk;\n\n QVariantMap resultMap = jsonParser.parse(pNetworkReply->readAll(), &parsingOk).toMap();\n\nstatic int counter = 0;\nqDebug(\"---[%03d]--------------------------------------\", ++counter);\nqDebug(\"URL: %s\", qPrintable(pNetworkReply->url().toString()));\n\n if (parsingOk) {\n \/\/ Retrieve the list of CellML models\n\n foreach (const QVariant &ontologicalsTermVariant, resultMap[\"result\"].toList()) {\n QVariantList ontologicalTermVariant = ontologicalsTermVariant.toList();\n\n for (int i = 0, iMax = ontologicalTermVariant.count(); i < iMax; ++i) {\n QVariantMap ontologicalTermMap = ontologicalTermVariant[i].toMap();\n\nqDebug(\">>> %s ---> %s\", qPrintable(ontologicalTermMap[\"uri\"].toString()),\n qPrintable(ontologicalTermMap[\"name\"].toString()));\n }\n }\n\n \/\/ Everything went fine, so...\n\n mErrorMsg = QString();\n } else {\n \/\/ Something went wrong, so...\n\n mErrorMsg = jsonParser.errorString();\n }\n } else {\n \/\/ Something went wrong, so...\n\n mErrorMsg = pNetworkReply->errorString();\n }\n\n \/\/ We are done, so...\n\n mTermUrl = QString();\n\n \/\/ Check whether there is another term to look up\n\n if (!mOtherTermUrl.isEmpty()) {\n mNetworkAccessManager->get(QNetworkRequest(mOtherTermUrl));\n\n mOtherTermUrl = QString();\n }\n}\n\n\/\/==============================================================================\n\n} \/\/ namespace CellMLAnnotationView\n} \/\/ namespace OpenCOR\n\n\/\/==============================================================================\n\/\/ End of file\n\/\/==============================================================================\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: navibar.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: vg $ $Date: 2007-09-18 13:53:07 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#include \n#include \"navibar.hxx\"\n\n\n\/\/ NOT FULLY DEFINED SERVICES\n#include \n#include \"nav_main.hxx\"\n#include \"opageenv.hxx\"\n\n\nusing namespace csi::xml;\nusing namespace csi::html;\n\n\nnamespace\n{\n\n\/\/************************ SubRowItem ***************************\/\/\n\nclass SubRowItem\n{\n public:\n SubRowItem(\n const char * i_sText,\n const char * i_sLink,\n bool i_bActive,\n bool i_bFirstOfRow = false );\n ~SubRowItem();\n\n void Write2(\n Element & o_rOut ) const;\n private:\n udmstri sText;\n udmstri sLink;\n bool bIsActive;\n bool bFirstOfRow;\n};\n\nSubRowItem::SubRowItem( const char * i_sText,\n const char * i_sLink,\n bool i_bActive,\n bool i_bFirstOfRow )\n : sText(i_sText),\n sLink(i_sLink),\n bIsActive(i_bActive),\n bFirstOfRow(i_bFirstOfRow)\n{\n csv_assert( NOT csv::no_str(i_sLink) );\n}\n\nSubRowItem::~SubRowItem()\n{\n}\n\nvoid\nSubRowItem::Write2( Element & o_rOut ) const\n{\n o_rOut << new Sbr;\n if ( NOT bFirstOfRow )\n o_rOut << new XmlCode( \"| \" );\n else\n o_rOut << new XmlCode( \" \" );\n\n if ( bIsActive )\n {\n o_rOut\n >> *new Link( sLink.c_str() )\n >> *new AnElement( \"font\" )\n << new AnAttribute(\"size\",\"-2\")\n >> *new Bold\n << sText.c_str();\n }\n else\n {\n o_rOut\n >> *new AnElement( \"font\" )\n << new AnAttribute(\"size\",\"-2\")\n << sText.c_str();\n }\n}\n\n\n\n\/\/************************ SubRow ***************************\/\/\n\nclass SubRow\n{\n public:\n SubRow(\n const char * i_sTitle );\n ~SubRow();\n\n void AddItem(\n const char * i_sText,\n const char * i_sLink,\n bool i_bActive );\n void Write2(\n Table & o_rOut ) const;\n private:\n typedef std::vector< DYN SubRowItem * > List_Items;\n\n List_Items aItemList;\n udmstri sTitle;\n};\n\nSubRow::SubRow( const char * i_sTitle )\n\/\/ : \/\/ aItemList,\n \/\/ sTitle\n{\n StreamStr sUp(i_sTitle,0);\n sUp.to_upper();\n sTitle = sUp.c_str();\n}\n\nSubRow::~SubRow()\n{\n}\n\ninline void\nSubRow::AddItem( const char * i_sText,\n const char * i_sLink,\n bool i_bActive )\n{\n aItemList.push_back( new SubRowItem(i_sText, i_sLink, i_bActive, aItemList.empty()) );\n}\n\nvoid\nSubRow::Write2( Table & o_rOut ) const\n{\n TableRow * pRow = new TableRow;\n o_rOut << pRow;\n\n if (sTitle.length() > 0)\n {\n Element & rCell1 = pRow->AddCell();\n rCell1\n << new WidthAttr(\"20%\")\n >> *new AnElement( \"font\" )\n << new AnAttribute(\"size\",\"-2\")\n << sTitle\n << \":\";\n }\n\n Element & rCell2 = pRow->AddCell();\n for ( List_Items::const_iterator it = aItemList.begin();\n it != aItemList.end();\n ++it )\n {\n (*it)->Write2( rCell2 );\n }\n}\n\n\n} \/\/ anonymous namespace\n\n\n\n\/\/************************* CheshireCat ***********************\/\/\n\n\ntypedef std::vector< DYN SubRow * > List_SubRows;\n\nstruct NavigationBar::CheshireCat\n{\n MainRow aMainRow;\n List_SubRows aSubRows;\n const OuputPage_Environment *\n pEnv;\n\n\n CheshireCat(\n const OuputPage_Environment &\n i_rEnv );\n ~CheshireCat();\n};\n\nNavigationBar::\nCheshireCat::CheshireCat( const OuputPage_Environment & i_rEnv )\n : aMainRow( i_rEnv ),\n pEnv( & i_rEnv )\n{\n}\n\nNavigationBar::\nCheshireCat::~CheshireCat()\n{\n csv::erase_container_of_heap_ptrs( aSubRows );\n}\n\n\n\/\/************************ NavigationBar *******************\/\/\n\nNavigationBar::NavigationBar( const OuputPage_Environment & i_rEnv,\n E_GlobalLocation i_eLocation )\n : pi( new CheshireCat(i_rEnv) )\n{\n switch (i_eLocation)\n {\n case LOC_Overview: pi->aMainRow.SetupItems_Overview(); break;\n case LOC_AllDefs: pi->aMainRow.SetupItems_AllDefs(); break;\n case LOC_Index: pi->aMainRow.SetupItems_Index(); break;\n case LOC_Help: pi->aMainRow.SetupItems_Help(); break;\n default:\n csv_assert(false);\n }\n}\n\nNavigationBar::NavigationBar( const OuputPage_Environment & i_rEnv,\n const ary::CodeEntity & i_rCe )\n : pi( new CheshireCat(i_rEnv) )\n{\n pi->aMainRow.SetupItems_Ce( i_rCe );\n}\n\nNavigationBar::NavigationBar( const OuputPage_Environment & i_rEnv,\n E_CeGatheringType i_eCeGatheringType,\n const ary::cpp::FileGroup * i_pFile )\n : pi( new CheshireCat(i_rEnv) )\n{\n if ( i_rEnv.CurClass() != 0 )\n {\n switch (i_eCeGatheringType)\n {\n case CEGT_operations: pi->aMainRow.SetupItems_FunctionGroup(); break;\n case CEGT_data: pi->aMainRow.SetupItems_DataGroup(); break;\n default:\n csv_assert(false);\n }\n }\n else\n {\n csv_assert( i_pFile != 0 );\n switch (i_eCeGatheringType)\n {\n case CEGT_operations: pi->aMainRow.SetupItems_FunctionGroup(*i_pFile); break;\n case CEGT_data: pi->aMainRow.SetupItems_DataGroup(*i_pFile); break;\n default:\n csv_assert(false);\n }\n }\n}\n\nNavigationBar::NavigationBar( const OuputPage_Environment & i_rEnv,\n const ary::cpp::ProjectGroup * i_pPrj,\n const ary::cpp::FileGroup * i_pFile )\n : pi( new CheshireCat(i_rEnv) )\n{\n if ( i_pPrj == 0 )\n {\n pi->aMainRow.SetupItems_Project();\n return;\n }\n if ( i_pFile == 0 )\n {\n pi->aMainRow.SetupItems_File( *i_pPrj );\n return;\n }\n\n pi->aMainRow.SetupItems_DefinitionsGroup( *i_pPrj, *i_pFile );\n}\n\nNavigationBar::~NavigationBar()\n{\n csv::erase_container_of_heap_ptrs( pi->aSubRows );\n}\n\nvoid\nNavigationBar::MakeSubRow( const char * i_sTitle )\n{\n pi->aSubRows.push_back( new SubRow(i_sTitle) );\n}\n\nvoid\nNavigationBar::AddItem( const char * i_sName,\n const char * i_sLink,\n bool i_bValid )\n{\n csv_assert( pi->aSubRows.size() > 0 );\n StreamStr sName(i_sName, 0);\n sName.to_upper();\n\n StreamLock aSum(100);\n pi->aSubRows.back()->AddItem( sName.c_str(),\n aSum() << \"#\" << i_sLink << c_str,\n i_bValid );\n}\n\nvoid\nNavigationBar::Write( Element & o_rOut,\n bool i_bWithSubRows ) const\n{\n pi->aMainRow.Write2( o_rOut );\n\n const_cast< NavigationBar* >(this)->pSubRowsTable = new Table;\n o_rOut << pSubRowsTable;\n *pSubRowsTable\n << new AnAttribute(\"class\", \"navisub\")\n << new AnAttribute( \"cellpadding\", \"0\" )\n << new AnAttribute( \"cellspacing\", \"3\" );\n\n if (i_bWithSubRows)\n {\n o_rOut >> *new TableRow >> *new Paragraph << \" \";\n Write_SubRows();\n }\n}\n\nvoid\nNavigationBar::Write_SubRows() const\n{\n for ( List_SubRows::const_iterator it = pi->aSubRows.begin();\n it != pi->aSubRows.end();\n ++it )\n {\n (*it)->Write2( *pSubRowsTable );\n }\n}\n\n\n\n\n\nINTEGRATION: CWS adc18 (1.5.2); FILE MERGED 2007\/10\/17 13:28:03 np 1.5.2.1: #i82716#\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: navibar.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: hr $ $Date: 2007-11-02 16:28:54 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#include \n#include \"navibar.hxx\"\n\n\n\/\/ NOT FULLY DEFINED SERVICES\n#include \n#include \"nav_main.hxx\"\n#include \"opageenv.hxx\"\n\n\nusing namespace csi::xml;\nusing namespace csi::html;\n\n\nnamespace\n{\n\n\/\/************************ SubRowItem ***************************\/\/\n\nclass SubRowItem\n{\n public:\n SubRowItem(\n const char * i_sText,\n const char * i_sLink,\n bool i_bActive,\n bool i_bFirstOfRow = false );\n ~SubRowItem();\n\n void Write2(\n Element & o_rOut ) const;\n private:\n String sText;\n String sLink;\n bool bIsActive;\n bool bFirstOfRow;\n};\n\nSubRowItem::SubRowItem( const char * i_sText,\n const char * i_sLink,\n bool i_bActive,\n bool i_bFirstOfRow )\n : sText(i_sText),\n sLink(i_sLink),\n bIsActive(i_bActive),\n bFirstOfRow(i_bFirstOfRow)\n{\n csv_assert( NOT csv::no_str(i_sLink) );\n}\n\nSubRowItem::~SubRowItem()\n{\n}\n\nvoid\nSubRowItem::Write2( Element & o_rOut ) const\n{\n o_rOut << new Sbr;\n if ( NOT bFirstOfRow )\n o_rOut << new XmlCode( \"| \" );\n else\n o_rOut << new XmlCode( \" \" );\n\n if ( bIsActive )\n {\n o_rOut\n >> *new Link( sLink.c_str() )\n >> *new AnElement( \"font\" )\n << new AnAttribute(\"size\",\"-2\")\n >> *new Bold\n << sText.c_str();\n }\n else\n {\n o_rOut\n >> *new AnElement( \"font\" )\n << new AnAttribute(\"size\",\"-2\")\n << sText.c_str();\n }\n}\n\n\n\n\/\/************************ SubRow ***************************\/\/\n\nclass SubRow\n{\n public:\n SubRow(\n const char * i_sTitle );\n ~SubRow();\n\n void AddItem(\n const char * i_sText,\n const char * i_sLink,\n bool i_bActive );\n void Write2(\n Table & o_rOut ) const;\n private:\n typedef std::vector< DYN SubRowItem * > List_Items;\n\n List_Items aItemList;\n String sTitle;\n};\n\nSubRow::SubRow( const char * i_sTitle )\n\/\/ : \/\/ aItemList,\n \/\/ sTitle\n{\n StreamStr sUp(i_sTitle,0);\n sUp.to_upper();\n sTitle = sUp.c_str();\n}\n\nSubRow::~SubRow()\n{\n}\n\ninline void\nSubRow::AddItem( const char * i_sText,\n const char * i_sLink,\n bool i_bActive )\n{\n aItemList.push_back( new SubRowItem(i_sText, i_sLink, i_bActive, aItemList.empty()) );\n}\n\nvoid\nSubRow::Write2( Table & o_rOut ) const\n{\n TableRow * pRow = new TableRow;\n o_rOut << pRow;\n\n if (sTitle.length() > 0)\n {\n Element & rCell1 = pRow->AddCell();\n rCell1\n << new WidthAttr(\"20%\")\n >> *new AnElement( \"font\" )\n << new AnAttribute(\"size\",\"-2\")\n << sTitle\n << \":\";\n }\n\n Element & rCell2 = pRow->AddCell();\n for ( List_Items::const_iterator it = aItemList.begin();\n it != aItemList.end();\n ++it )\n {\n (*it)->Write2( rCell2 );\n }\n}\n\n\n} \/\/ anonymous namespace\n\n\n\n\/\/************************* CheshireCat ***********************\/\/\n\n\ntypedef std::vector< DYN SubRow * > List_SubRows;\n\nstruct NavigationBar::CheshireCat\n{\n MainRow aMainRow;\n List_SubRows aSubRows;\n const OuputPage_Environment *\n pEnv;\n\n\n CheshireCat(\n const OuputPage_Environment &\n i_rEnv );\n ~CheshireCat();\n};\n\nNavigationBar::\nCheshireCat::CheshireCat( const OuputPage_Environment & i_rEnv )\n : aMainRow( i_rEnv ),\n pEnv( & i_rEnv )\n{\n}\n\nNavigationBar::\nCheshireCat::~CheshireCat()\n{\n csv::erase_container_of_heap_ptrs( aSubRows );\n}\n\n\n\/\/************************ NavigationBar *******************\/\/\n\nNavigationBar::NavigationBar( const OuputPage_Environment & i_rEnv,\n E_GlobalLocation i_eLocation )\n : pi( new CheshireCat(i_rEnv) )\n{\n switch (i_eLocation)\n {\n case LOC_Overview: pi->aMainRow.SetupItems_Overview(); break;\n case LOC_AllDefs: pi->aMainRow.SetupItems_AllDefs(); break;\n case LOC_Index: pi->aMainRow.SetupItems_Index(); break;\n case LOC_Help: pi->aMainRow.SetupItems_Help(); break;\n default:\n csv_assert(false);\n }\n}\n\nNavigationBar::NavigationBar( const OuputPage_Environment & i_rEnv,\n const ary::cpp::CodeEntity & i_rCe )\n : pi( new CheshireCat(i_rEnv) )\n{\n pi->aMainRow.SetupItems_Ce( i_rCe );\n}\n\nNavigationBar::NavigationBar( const OuputPage_Environment & i_rEnv,\n E_CeGatheringType i_eCeGatheringType )\n : pi( new CheshireCat(i_rEnv) )\n{\n switch (i_eCeGatheringType)\n {\n case CEGT_operations: pi->aMainRow.SetupItems_FunctionGroup(); break;\n case CEGT_data: pi->aMainRow.SetupItems_DataGroup(); break;\n default:\n csv_assert(false);\n }\n}\n\nNavigationBar::~NavigationBar()\n{\n csv::erase_container_of_heap_ptrs( pi->aSubRows );\n}\n\nvoid\nNavigationBar::MakeSubRow( const char * i_sTitle )\n{\n pi->aSubRows.push_back( new SubRow(i_sTitle) );\n}\n\nvoid\nNavigationBar::AddItem( const char * i_sName,\n const char * i_sLink,\n bool i_bValid )\n{\n csv_assert( pi->aSubRows.size() > 0 );\n StreamStr sName(i_sName, 0);\n sName.to_upper();\n\n StreamLock aSum(100);\n pi->aSubRows.back()->AddItem( sName.c_str(),\n aSum() << \"#\" << i_sLink << c_str,\n i_bValid );\n}\n\nvoid\nNavigationBar::Write( Element & o_rOut,\n bool i_bWithSubRows ) const\n{\n pi->aMainRow.Write2( o_rOut );\n\n const_cast< NavigationBar* >(this)->pSubRowsTable = new Table;\n o_rOut << pSubRowsTable;\n *pSubRowsTable\n << new AnAttribute( \"class\", \"navisub\" )\n << new AnAttribute( \"cellpadding\", \"0\" )\n << new AnAttribute( \"cellspacing\", \"3\" );\n\n if (i_bWithSubRows)\n {\n Write_SubRows();\n }\n}\n\nvoid\nNavigationBar::Write_SubRows() const\n{\n for ( List_SubRows::const_iterator it = pi->aSubRows.begin();\n it != pi->aSubRows.end();\n ++it )\n {\n (*it)->Write2( *pSubRowsTable );\n }\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n \n Program: Medical Imaging & Interaction Toolkit\n Language: C++\n Date: $Date: 2010-03-31 16:40:27 +0200 (Mi, 31 Mrz 2010) $\n Version: $Revision: 21975 $\n \n Copyright (c) German Cancer Research Center, Division of Medical and\n Biological Informatics. All rights reserved.\n See MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n \n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n \n =========================================================================*\/\n\n\n\/\/ Blueberry\n#include \n#include \n\n\n\n\/\/ Qmitk\n#include \"QmitkFiberBundleDeveloperView.h\"\n#include \n\n\/\/ Qt\n\n\/\/ VTK\n#include \n#include \n\n\nconst std::string QmitkFiberBundleDeveloperView::VIEW_ID = \"org.mitk.views.fiberbundledeveloper\";\nconst std::string id_DataManager = \"org.mitk.views.datamanager\";\nusing namespace berry;\n\n\nQmitkFiberBundleDeveloperView::QmitkFiberBundleDeveloperView()\n: QmitkFunctionality()\n, m_Controls( 0 )\n, m_MultiWidget( NULL )\n{\n \n}\n\n\/\/ Destructor\nQmitkFiberBundleDeveloperView::~QmitkFiberBundleDeveloperView()\n{\n \n}\n\n\nvoid QmitkFiberBundleDeveloperView::CreateQtPartControl( QWidget *parent )\n{\n \/\/ build up qt view, unless already done in QtDesigner, etc.\n if ( !m_Controls )\n {\n \/\/ create GUI widgets from the Qt Designer's .ui file\n m_Controls = new Ui::QmitkFiberBundleDeveloperViewControls;\n m_Controls->setupUi( parent );\n \n connect( m_Controls->buttonGenerateFibers, SIGNAL(clicked()), this, SLOT(DoGenerateFibers()) );\n \n \n }\n \n \/\/ Checkpoint for fiber ORIENTATION\n if ( m_DirectionRadios.empty() )\n {\n m_DirectionRadios.insert(0, m_Controls->radioButton_directionRandom);\n m_DirectionRadios.insert(1, m_Controls->radioButton_directionX);\n m_DirectionRadios.insert(2, m_Controls->radioButton_directionY);\n m_DirectionRadios.insert(3, m_Controls->radioButton_directionZ);\n }\n \n}\n\nvoid QmitkFiberBundleDeveloperView::DoGenerateFibers()\n{\n \n \/\/ GET SELECTED FIBER DIRECTION\n QString fibDirection;\n QVector::const_iterator i;\n for (i = m_DirectionRadios.begin(); i != m_DirectionRadios.end(); ++i) \n {\n \n QRadioButton* rdbtn = *i;\n if (rdbtn->isChecked())\n fibDirection = rdbtn->objectName();\n \n }\n \n} \n\nvoid QmitkFiberBundleDeveloperView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget)\n{\n m_MultiWidget = &stdMultiWidget;\n}\n\n\nvoid QmitkFiberBundleDeveloperView::StdMultiWidgetNotAvailable()\n{\n m_MultiWidget = NULL;\n}\n\n\/* OnSelectionChanged is registered to SelectionService, therefore no need to\n implement SelectionService Listener explicitly *\/\n\nvoid QmitkFiberBundleDeveloperView::OnSelectionChanged( std::vector nodes )\n{\n \n \n}\n\nvoid QmitkFiberBundleDeveloperView::Activated()\n{\n \n MITK_INFO << \"FB OPerations ACTIVATED()\";\n \n \n}\n\n\n\nadded methods returning vtkSmartPointer PolyData of fiberstructure\/*=========================================================================\n \n Program: Medical Imaging & Interaction Toolkit\n Language: C++\n Date: $Date: 2010-03-31 16:40:27 +0200 (Mi, 31 Mrz 2010) $\n Version: $Revision: 21975 $\n \n Copyright (c) German Cancer Research Center, Division of Medical and\n Biological Informatics. All rights reserved.\n See MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n \n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n \n =========================================================================*\/\n\n\n\/\/ Blueberry\n#include \n#include \n\n\n\n\/\/ Qmitk\n#include \"QmitkFiberBundleDeveloperView.h\"\n#include \n\n\/\/ Qt\n\n\/\/ VTK\n#include \n\n\nconst std::string QmitkFiberBundleDeveloperView::VIEW_ID = \"org.mitk.views.fiberbundledeveloper\";\nconst std::string id_DataManager = \"org.mitk.views.datamanager\";\nusing namespace berry;\n\n\nQmitkFiberBundleDeveloperView::QmitkFiberBundleDeveloperView()\n: QmitkFunctionality()\n, m_Controls( 0 )\n, m_MultiWidget( NULL )\n{\n \n}\n\n\/\/ Destructor\nQmitkFiberBundleDeveloperView::~QmitkFiberBundleDeveloperView()\n{\n \n}\n\n\nvoid QmitkFiberBundleDeveloperView::CreateQtPartControl( QWidget *parent )\n{\n \/\/ build up qt view, unless already done in QtDesigner, etc.\n if ( !m_Controls )\n {\n \/\/ create GUI widgets from the Qt Designer's .ui file\n m_Controls = new Ui::QmitkFiberBundleDeveloperViewControls;\n m_Controls->setupUi( parent );\n \n connect( m_Controls->buttonGenerateFibers, SIGNAL(clicked()), this, SLOT(DoGenerateFibers()) );\n \n \n }\n \n \/\/ Checkpoint for fiber ORIENTATION\n if ( m_DirectionRadios.empty() )\n {\n m_DirectionRadios.insert(0, m_Controls->radioButton_directionRandom);\n m_DirectionRadios.insert(1, m_Controls->radioButton_directionX);\n m_DirectionRadios.insert(2, m_Controls->radioButton_directionY);\n m_DirectionRadios.insert(3, m_Controls->radioButton_directionZ);\n }\n \n}\n\nvoid QmitkFiberBundleDeveloperView::DoGenerateFibers()\n{\n \n \/\/ GET SELECTED FIBER DIRECTION\n QString fibDirection;\n QVector::const_iterator i;\n for (i = m_DirectionRadios.begin(); i != m_DirectionRadios.end(); ++i) \n {\n \n QRadioButton* rdbtn = *i;\n if (rdbtn->isChecked())\n fibDirection = rdbtn->objectName();\n \n }\n \n} \n\nvtkSmartPointer QmitkFiberBundleDeveloperView::GenerateVtkFibersRandom()\n{\n vtkSmartPointer PDRandom = vtkSmartPointer::New();\n \/\/todo\n \n \n \n return PDRandom;\n}\n\nvtkSmartPointer QmitkFiberBundleDeveloperView::GenerateVtkFibersDirectionX()\n{\n vtkSmartPointer PDX = vtkSmartPointer::New();\n \/\/todo\n \n \n \n return PDX;\n}\n\nvtkSmartPointer QmitkFiberBundleDeveloperView::GenerateVtkFibersDirectionY()\n{\n vtkSmartPointer PDY = vtkSmartPointer::New();\n \/\/todo\n \n \n \n return PDY;\n}\n\n\nvtkSmartPointer QmitkFiberBundleDeveloperView::GenerateVtkFibersDirectionZ()\n{\n vtkSmartPointer PDZ = vtkSmartPointer::New();\n \/\/todo\n \n \n \n return PDZ;\n}\n\n\n\nvoid QmitkFiberBundleDeveloperView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget)\n{\n m_MultiWidget = &stdMultiWidget;\n}\n\n\nvoid QmitkFiberBundleDeveloperView::StdMultiWidgetNotAvailable()\n{\n m_MultiWidget = NULL;\n}\n\n\/* OnSelectionChanged is registered to SelectionService, therefore no need to\n implement SelectionService Listener explicitly *\/\n\nvoid QmitkFiberBundleDeveloperView::OnSelectionChanged( std::vector nodes )\n{\n \n \n}\n\nvoid QmitkFiberBundleDeveloperView::Activated()\n{\n \n MITK_INFO << \"FB OPerations ACTIVATED()\";\n \n \n}\n\n\n\n<|endoftext|>"} {"text":"#ifndef __INCLUDED_BITFIELD_HPP__\n#define __INCLUDED_BITFIELD_HPP__\n\n#include \n#include \n\nnamespace bitfield {\n class bit_type {\n uint8_t v;\n \n public:\n constexpr bit_type(uint8_t v) : v(v) {}\n \n constexpr bit_type floor() const {\n return bit_type(this->v >> 3 << 3);\n }\n \n constexpr bit_type ceil() const {\n return bit_type((this->v + 7) >> 3 << 3);\n }\n \n constexpr uint32_t bit() const {\n return this->v;\n }\n \n constexpr uint32_t byte() const {\n return this->v >> 3;\n }\n \n constexpr uint32_t max_value() const {\n return this->v >= 32 ? 0xffffffff : (0x01 << this->v) - 0x01;\n }\n \n constexpr bit_type diff(bit_type target) const {\n return bit_type(this->v < target.v ? target.v - this->v\n : this->v - target.v);\n };\n \n template\n constexpr uint8_t * addr(const T * addr) const {\n return (uint8_t *)addr + this->byte();\n }\n };\n \n template\n class bitfield {\n public:\n static constexpr uint32_t SIZE = Size;\n static constexpr uint32_t OFFSET = Offset;\n static constexpr uint32_t NEXT_OFFSET = SIZE + OFFSET;\n \n static constexpr uint32_t BYTE = bit_type(SIZE).ceil().byte();\n static constexpr uint32_t PADDING = bit_type(NEXT_OFFSET).ceil().diff(NEXT_OFFSET).bit();\n static constexpr uint32_t MASK = bit_type(SIZE).max_value() << PADDING;\n \n template\n using next_bitfield = bitfield;\n using container_type = std::array;\n \n \/\/ for Little-Endian\n uint32_t get() const {\n uint8_t * addr = bit_type(OFFSET).addr(this);\n uint32_t value = 0x00;\n \n for (uint32_t i=0; i < BYTE; ++i) {\n value |= addr[i] << ((BYTE-i-1)<<3);\n }\n \n value &= MASK;\n value >>= PADDING;\n return value;\n }\n \n \/\/ for Little-Endian\n void set(uint32_t value) {\n static constexpr uint32_t clear_mask = ~MASK;\n \n value <<= PADDING;\n value &= MASK;\n \n uint8_t * addr = bit_type(OFFSET).addr(this);\n uint8_t * value_addr = (uint8_t *)&value;\n uint8_t * clear_mask_addr = (uint8_t *)&clear_mask;\n \n for (uint32_t i=0; i < BYTE; ++i) {\n uint32_t j = BYTE-i-1;\n addr[i] &= clear_mask_addr[j];\n addr[i] |= value_addr[j];\n }\n }\n \n operator uint32_t() const {\n return this->get();\n }\n \n bitfield & operator =(uint32_t value) {\n this->set(value);\n return *this;\n }\n \n friend std::ostream & operator <<(std::ostream & out, const bitfield & v) {\n return out << v.get();\n }\n };\n}\n\n#endif \/\/ __INCLUDED_BITFIELD_HPP__\nFix bitfield#get().#ifndef __INCLUDED_BITFIELD_HPP__\n#define __INCLUDED_BITFIELD_HPP__\n\n#include \n#include \n\nnamespace bitfield {\n class bit_type {\n uint8_t v;\n \n public:\n constexpr bit_type(uint8_t v) : v(v) {}\n \n constexpr bit_type floor() const {\n return bit_type(this->v >> 3 << 3);\n }\n \n constexpr bit_type ceil() const {\n return bit_type((this->v + 7) >> 3 << 3);\n }\n \n constexpr uint32_t bit() const {\n return this->v;\n }\n \n constexpr uint32_t byte() const {\n return this->v >> 3;\n }\n \n constexpr uint32_t max_value() const {\n return this->v >= 32 ? 0xffffffff : (0x01 << this->v) - 0x01;\n }\n \n constexpr bit_type diff(bit_type target) const {\n return bit_type(this->v < target.v ? target.v - this->v\n : this->v - target.v);\n };\n \n template\n constexpr uint8_t * addr(const T * addr) const {\n return (uint8_t *)addr + this->byte();\n }\n };\n \n template\n class bitfield {\n public:\n static constexpr uint32_t SIZE = Size;\n static constexpr uint32_t OFFSET = Offset;\n static constexpr uint32_t NEXT_OFFSET = SIZE + OFFSET;\n \n static constexpr uint32_t BYTE = bit_type(SIZE).ceil().byte();\n static constexpr uint32_t PADDING = bit_type(NEXT_OFFSET).ceil().diff(NEXT_OFFSET).bit();\n static constexpr uint32_t MASK = bit_type(SIZE).max_value() << PADDING;\n \n template\n using next_bitfield = bitfield;\n using container_type = std::array;\n \n \/\/ for Little-Endian\n uint32_t get() const {\n uint32_t value = 0x00;\n uint8_t * addr = bit_type(OFFSET).addr(this);\n uint8_t * value_addr = (uint8_t *)&value;\n \n for (uint32_t i=0; i < BYTE; ++i) {\n value_addr[BYTE-i-1] = addr[i];\n }\n \n value &= MASK;\n value >>= PADDING;\n return value;\n }\n \n \/\/ for Little-Endian\n void set(uint32_t value) {\n static constexpr uint32_t clear_mask = ~MASK;\n \n value <<= PADDING;\n value &= MASK;\n \n uint8_t * addr = bit_type(OFFSET).addr(this);\n uint8_t * value_addr = (uint8_t *)&value;\n uint8_t * clear_mask_addr = (uint8_t *)&clear_mask;\n \n for (uint32_t i=0; i < BYTE; ++i) {\n uint32_t j = BYTE-i-1;\n addr[i] &= clear_mask_addr[j];\n addr[i] |= value_addr[j];\n }\n }\n \n operator uint32_t() const {\n return this->get();\n }\n \n bitfield & operator =(uint32_t value) {\n this->set(value);\n return *this;\n }\n \n friend std::ostream & operator <<(std::ostream & out, const bitfield & v) {\n return out << v.get();\n }\n };\n}\n\n#endif \/\/ __INCLUDED_BITFIELD_HPP__\n<|endoftext|>"} {"text":"\/*****************************************************************************\n * This file is part of the Gluon Development Platform *\n * Copyright (c) 2011 Laszlo Papp *\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n * This program is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU General Public License for more details. *\n * *\n * You should have received a copy of the GNU General Public License along *\n * with this program; if not, write to the Free Software Foundation, Inc., *\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *\n *****************************************************************************\/\n\n#include \"mainwindow.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace GluonPlayer;\n\nclass MainWindow::MainWindowPrivate\n{\n public:\n MainWindowPrivate() {}\n\n GluonEngine::GameProject* project;\n GluonGraphics::RenderWidget* widget;\n\n KRecentFilesAction* recentFiles;\n\n QAbstractItemModel* model;\n\n QString title;\n QString fileName;\n\n int msecElapsed;\n int frameCount;\n};\n\nMainWindow::MainWindow(const QString& filename )\n : KMainWindow()\n , d( new MainWindowPrivate )\n{\n d->msecElapsed = 0;\n d->frameCount = 0;\n\n if( !filename.isEmpty() )\n {\n d->fileName = filename;\n QTimer::singleShot( 0, this, SLOT( openProject() ) );\n }\n else\n {\n QWidget* base = new QWidget( this );\n QVBoxLayout* layout = new QVBoxLayout();\n base->setLayout( layout );\n setCentralWidget( base );\n\n QLabel* header = new QLabel( i18n( \"Please select a Project\" ), base );\n header->setAlignment( Qt::AlignCenter );\n QFont font;\n font.setBold( true );\n header->setFont( font );\n layout->addWidget( header );\n\n QListView* view = new QListView( base );\n layout->addWidget( view );\n d->model = new GamesModel( view );\n view->setModel( d->model );\n connect( view, SIGNAL( activated( QModelIndex ) ), SLOT( activated( QModelIndex ) ) );\n\n KPushButton* button = new KPushButton( i18n( \"Open other project...\" ), base );\n layout->addWidget( button );\n connect( button, SIGNAL( clicked( bool ) ), SLOT( openClicked( bool ) ) );\n }\n resize( 500, 500 );\n}\n\nMainWindow::~MainWindow ( )\n{\n}\n\nvoid MainWindow::activated( QModelIndex index )\n{\n if( index.isValid() )\n {\n openProject( d->model->data( index ).toString() );\n }\n}\n\nvoid MainWindow::openClicked( bool toggled )\n{\n Q_UNUSED( toggled )\n\n QString fileName = KFileDialog::getOpenFileName( KUrl() , i18n( \"Select a Project\" ), this, QString( \"*.gluon|Gluon Project Files\" ) );\n if( !fileName.isEmpty() )\n openProject( fileName );\n}\n\nvoid MainWindow::openProject( const QString& fileName )\n{\n QString file = fileName;\n if( file.isEmpty() )\n file = d->fileName;\n\n d->widget = new GluonGraphics::RenderWidget( this );\n setCentralWidget( d->widget );\n connect( GluonEngine::Game::instance(), SIGNAL( painted( int ) ), d->widget, SLOT( updateGL() ) );\n connect( GluonEngine::Game::instance(), SIGNAL( painted( int ) ), SLOT( countFrames( int ) ) );\n connect( GluonEngine::Game::instance(), SIGNAL( updated( int ) ), SLOT( updateTitle( int ) ) );\n\n QTimer::singleShot( 100, this, SLOT( startGame() ) );\n\n d->fileName = file;\n}\n\nvoid MainWindow::startGame()\n{\n GluonCore::GluonObjectFactory::instance()->loadPlugins();\n\n d->project = new GluonEngine::GameProject();\n d->project->loadFromFile( QUrl( d->fileName ) );\n\n setWindowFilePath( d->fileName );\n d->title = windowTitle();\n\n GluonEngine::Game::instance()->setGameProject( d->project );\n GluonEngine::Game::instance()->setCurrentScene( d->project->entryPoint() );\n\n GluonEngine::Game::instance()->runGame();\n}\n\nvoid MainWindow::closeEvent( QCloseEvent* event )\n{\n GluonEngine::Game::instance()->stopGame();\n QWidget::closeEvent( event );\n}\n\nvoid MainWindow::updateTitle( int msec )\n{\n d->msecElapsed += msec;\n\n static int fps = 0;\n if( d->msecElapsed > 1000 )\n {\n fps = d->frameCount;\n d->frameCount = 0;\n d->msecElapsed = 0;\n }\n\n setWindowTitle( d->title + QString( \" (%1 FPS)\" ).arg( fps ) );\n}\n\nvoid MainWindow::countFrames( int time )\n{\n Q_UNUSED( time )\n d->frameCount++;\n}\nKDE Simple Player: add the setFocus() method before running the game.\/*****************************************************************************\n * This file is part of the Gluon Development Platform *\n * Copyright (c) 2011 Laszlo Papp *\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n * This program is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU General Public License for more details. *\n * *\n * You should have received a copy of the GNU General Public License along *\n * with this program; if not, write to the Free Software Foundation, Inc., *\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *\n *****************************************************************************\/\n\n#include \"mainwindow.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace GluonPlayer;\n\nclass MainWindow::MainWindowPrivate\n{\n public:\n MainWindowPrivate() {}\n\n GluonEngine::GameProject* project;\n GluonGraphics::RenderWidget* widget;\n\n KRecentFilesAction* recentFiles;\n\n QAbstractItemModel* model;\n\n QString title;\n QString fileName;\n\n int msecElapsed;\n int frameCount;\n};\n\nMainWindow::MainWindow(const QString& filename )\n : KMainWindow()\n , d( new MainWindowPrivate )\n{\n d->msecElapsed = 0;\n d->frameCount = 0;\n\n if( !filename.isEmpty() )\n {\n d->fileName = filename;\n QTimer::singleShot( 0, this, SLOT( openProject() ) );\n }\n else\n {\n QWidget* base = new QWidget( this );\n QVBoxLayout* layout = new QVBoxLayout();\n base->setLayout( layout );\n setCentralWidget( base );\n\n QLabel* header = new QLabel( i18n( \"Please select a Project\" ), base );\n header->setAlignment( Qt::AlignCenter );\n QFont font;\n font.setBold( true );\n header->setFont( font );\n layout->addWidget( header );\n\n QListView* view = new QListView( base );\n layout->addWidget( view );\n d->model = new GamesModel( view );\n view->setModel( d->model );\n connect( view, SIGNAL( activated( QModelIndex ) ), SLOT( activated( QModelIndex ) ) );\n\n KPushButton* button = new KPushButton( i18n( \"Open other project...\" ), base );\n layout->addWidget( button );\n connect( button, SIGNAL( clicked( bool ) ), SLOT( openClicked( bool ) ) );\n }\n resize( 500, 500 );\n}\n\nMainWindow::~MainWindow ( )\n{\n}\n\nvoid MainWindow::activated( QModelIndex index )\n{\n if( index.isValid() )\n {\n openProject( d->model->data( index ).toString() );\n }\n}\n\nvoid MainWindow::openClicked( bool toggled )\n{\n Q_UNUSED( toggled )\n\n QString fileName = KFileDialog::getOpenFileName( KUrl() , i18n( \"Select a Project\" ), this, QString( \"*.gluon|Gluon Project Files\" ) );\n if( !fileName.isEmpty() )\n openProject( fileName );\n}\n\nvoid MainWindow::openProject( const QString& fileName )\n{\n QString file = fileName;\n if( file.isEmpty() )\n file = d->fileName;\n\n d->widget = new GluonGraphics::RenderWidget( this );\n setCentralWidget( d->widget );\n connect( GluonEngine::Game::instance(), SIGNAL( painted( int ) ), d->widget, SLOT( updateGL() ) );\n connect( GluonEngine::Game::instance(), SIGNAL( painted( int ) ), SLOT( countFrames( int ) ) );\n connect( GluonEngine::Game::instance(), SIGNAL( updated( int ) ), SLOT( updateTitle( int ) ) );\n\n QTimer::singleShot( 100, this, SLOT( startGame() ) );\n\n d->fileName = file;\n}\n\nvoid MainWindow::startGame()\n{\n GluonCore::GluonObjectFactory::instance()->loadPlugins();\n\n d->project = new GluonEngine::GameProject();\n d->project->loadFromFile( QUrl( d->fileName ) );\n\n setWindowFilePath( d->fileName );\n d->title = windowTitle();\n\n GluonEngine::Game::instance()->setGameProject( d->project );\n GluonEngine::Game::instance()->setCurrentScene( d->project->entryPoint() );\n\n d->widget->setFocus();\n GluonEngine::Game::instance()->runGame();\n}\n\nvoid MainWindow::closeEvent( QCloseEvent* event )\n{\n GluonEngine::Game::instance()->stopGame();\n QWidget::closeEvent( event );\n}\n\nvoid MainWindow::updateTitle( int msec )\n{\n d->msecElapsed += msec;\n\n static int fps = 0;\n if( d->msecElapsed > 1000 )\n {\n fps = d->frameCount;\n d->frameCount = 0;\n d->msecElapsed = 0;\n }\n\n setWindowTitle( d->title + QString( \" (%1 FPS)\" ).arg( fps ) );\n}\n\nvoid MainWindow::countFrames( int time )\n{\n Q_UNUSED( time )\n d->frameCount++;\n}\n<|endoftext|>"} {"text":"#ifndef __MEMORY_ANALYSIS_HH_\n#define __MEMORY_ANALYSIS_HH_\n\n\/* Wrapper for a datastructure analysis*\/\n\n#include \"llvm\/IR\/Function.h\"\n#include \"llvm\/IR\/Value.h\"\n#include \"llvm\/IR\/Instructions.h\"\n\n#include \"boost\/tuple\/tuple.hpp\"\n\n#include \"crab_llvm\/config.h\"\n#include \n\n#ifdef HAVE_DSA\n#include \"boost\/range\/algorithm\/set_algorithm.hpp\"\n#include \"dsa\/DataStructure.h\"\n#include \"dsa\/DSGraph.h\"\n#include \"dsa\/DSNode.h\"\n\nnamespace crab_llvm\n{\n using namespace std;\n using namespace llvm;\n using namespace crab::cfg;\n\n class MemAnalysis\n {\n \/* \n * The goal of the memory analysis is to split the whole heap into\n * disjoint arrays (i.e., contiguous sequence of bytes)\n *\n * Each DSA node is translated into an array. A DSA node may not\n * correspond directly to a llvm Value so we map DSA node to\n * id's.\n *\/\n\n public:\n\n typedef int array_id_t; \/\/ if < 0 then error\n\n private:\n\n DataStructures* m_dsa;\n TrackedPrecision m_tracklev;\n \n \/\/\/ map from DSNode to ids\n DenseMap m_node_ids;\n boost::unordered_map m_rev_node_ids;\n\n \/\/\/ reach - all reachable nodes from this function\n std::set m_reach;\n \/\/\/ outReach - subset of reach that is only reachable from the\n \/\/\/ return node\n std::set m_retReach;\n\n \/\/ template\n \/\/ struct getSecond : public std::unary_function, Second> {\n \/\/ getSecond () { }\n \/\/ Second operator () (const pair &p) const { return p.second; }\n \/\/ }; \n\n \/\/ typedef boost::transform_iterator< getSecond, \n \/\/ typename DenseMap::iterator > iterator;\n\n array_id_t getId (const DSNode *n)\n {\n auto it = m_node_ids.find (n);\n if (it != m_node_ids.end ()) return it->second;\n unsigned id = m_node_ids.size ();\n m_node_ids[n] = id;\n m_rev_node_ids[id] = n;\n return id;\n }\n\n template \n void markReachableNodes (const DSNode *n, Set &set)\n {\n if (!n) return;\n \n assert (!n->isForwarding () && \"Cannot mark a forwarded node\");\n if (set.insert (n).second)\n for (auto &edg : boost::make_iterator_range (n->edge_begin (), n->edge_end ()))\n markReachableNodes (edg.second.getNode (), set);\n }\n \n template \n void inputReachableNodes (const DSCallSite &cs, DSGraph &dsg, Set &set)\n {\n markReachableNodes (cs.getVAVal().getNode (), set);\n if (cs.isIndirectCall ()) markReachableNodes (cs.getCalleeNode (), set);\n for (unsigned i = 0, e = cs.getNumPtrArgs (); i != e; ++i)\n markReachableNodes (cs.getPtrArg (i).getNode (), set);\n \n \/\/ globals\n DSScalarMap &sm = dsg.getScalarMap ();\n for (auto &gv : boost::make_iterator_range (sm.global_begin(), sm.global_end ()))\n markReachableNodes (sm[gv].getNode (), set);\n }\n \n template \n void retReachableNodes (const DSCallSite &cs, Set &set) \n {markReachableNodes (cs.getRetVal ().getNode (), set);}\n \n template \n void set_difference (Set &s1, Set &s2)\n {\n Set s3;\n boost::set_difference (s1, s2, std::inserter (s3, s3.end ()));\n std::swap (s3, s1);\n }\n \n template \n void set_union (Set &s1, Set &s2)\n {\n Set s3;\n boost::set_union (s1, s2, std::inserter (s3, s3.end ()));\n std::swap (s3, s1);\n }\n \n \/\/\/ Computes DSNode reachable from the call arguments\n \/\/\/ reach - all reachable nodes\n \/\/\/ outReach - subset of reach that is only reachable from the return node\n template \n void argReachableNodes (DSCallSite CS, DSGraph &dsg, \n Set1 &reach, Set2 &outReach)\n {\n inputReachableNodes (CS, dsg, reach);\n retReachableNodes (CS, outReach);\n set_difference (outReach, reach);\n set_union (reach, outReach);\n }\n\n template \n void argReachableNodes (Function&f, Set1 &reach, Set2 &outReach)\n {\n DSGraph *cdsg = m_dsa->getDSGraph (f);\n if (cdsg)\n {\n DSCallSite CCS = cdsg->getCallSiteForArguments (f);\n argReachableNodes (CCS, *cdsg, reach, outReach);\n }\n }\n\n \/\/ \/\/! return begin iterator to node id's\n \/\/ iterator begin () { \n \/\/ return boost::make_transform_iterator \n \/\/ (m_node_ids.begin (), \n \/\/ getSecond ());\n \/\/ }\n\n \/\/ \/\/! return end iterator to node id's\n \/\/ iterator end () { \n \/\/ return boost::make_transform_iterator \n \/\/ (m_node_ids.end (), \n \/\/ getSecond ());\n \/\/ }\n\n \n public:\n \n MemAnalysis (): m_dsa (0), m_tracklev (INT) { }\n\n MemAnalysis (DataStructures * dsa, \n TrackedPrecision tracklev): \n m_dsa (dsa), m_tracklev (tracklev) { }\n \n TrackedPrecision getTrackLevel () const { return m_tracklev; }\n \n \/\/! return < 0 if no array associated with ptr is found\n array_id_t getArrayId (Function& f, Value* ptr) \n {\n if (!m_dsa) return -1;\n\n DSGraph* dsg = m_dsa->getDSGraph (f);\n if (!dsg) return -1;\n\n DSGraph* gDsg = dsg->getGlobalsGraph ();\n DSNode* n = dsg->getNodeForValue (ptr).getNode ();\n if (!n) n = gDsg->getNodeForValue (ptr).getNode ();\n\n if (!n) return -1;\n\n return getId (n); \n }\n\n \/\/! return true if the array corresponds to a single memory cell.\n bool isSingleton (array_id_t array_id)\n {\n auto it = m_rev_node_ids.find (array_id);\n if (it == m_rev_node_ids.end ()) return false;\n\n return it->second->getUniqueScalar ();\n }\n\n \/\/ Return the set of ref, mod and new nodes such that mod nodes\n \/\/ are a subset of the ref nodes and the new nodes are disjoint\n \/\/ from mod nodes.\n boost::tuple< set, set, set > \n getRefModNewArrays (Function& f) {\n std::set reach, retReach;\n argReachableNodes (f, reach, retReach);\n\n set refs, mods, news;\n for (const DSNode* n : reach) {\n if (!n->isReadNode () && !n->isModifiedNode ())\n continue;\n\n if ((n->isReadNode () || n->isModifiedNode ()) && retReach.count (n) <= 0) \n refs.insert (getId (n));\n \n if (n->isModifiedNode () && retReach.count (n) <= 0)\n mods.insert (getId (n));\n\n if (n->isModifiedNode () && retReach.count (n))\n news.insert (getId (n));\n }\n return boost::make_tuple (refs, mods, news);\n }\n\n \/\/ Return the set of ref, mod and new nodes such that mod nodes\n \/\/ are a subset of the ref nodes and the new nodes are disjoint\n \/\/ from mod nodes.\n boost::tuple< set, set, set > \n getRefModNewArrays (CallInst& I) {\n set refs, mods, news;\n\n \/\/\/ ignore inline assembly\n if (I.isInlineAsm ())\n return boost::make_tuple (refs, mods, news); \n \n DSGraph *dsg = m_dsa->getDSGraph (*(I.getParent ()->getParent ()));\n DSCallSite CS = dsg->getDSCallSiteForCallSite (CallSite (&I));\n \n if (!CS.isDirectCall ()) \n return boost::make_tuple (refs, mods, news); \n \n if (!m_dsa->hasDSGraph (*CS.getCalleeFunc ())) \n return boost::make_tuple (refs, mods, news); \n \n const Function &CF = *CS.getCalleeFunc ();\n DSGraph *cdsg = m_dsa->getDSGraph (CF);\n if (!cdsg) \n return boost::make_tuple (refs, mods, news); \n \n \/\/ -- compute callee nodes reachable from arguments and returns\n DSCallSite CCS = cdsg->getCallSiteForArguments (CF);\n std::set reach;\n std::set retReach;\n argReachableNodes (CCS, *cdsg, reach, retReach);\n DSGraph::NodeMapTy nodeMap;\n dsg->computeCalleeCallerMapping (CS, CF, *cdsg, nodeMap);\n \n for (const DSNode* n : reach) {\n if (!n->isReadNode () && !n->isModifiedNode ())\n continue;\n\n if ((n->isReadNode () || n->isModifiedNode ()) && retReach.count (n) <= 0) \n refs.insert (getId (n));\n \n if (n->isModifiedNode () && retReach.count (n) <= 0)\n mods.insert (getId (n));\n\n if (n->isModifiedNode () && retReach.count (n))\n news.insert (getId (n));\n\n }\n \/\/ -- add the node of the lhs of the call site\n int ret = getArrayId (*(I.getParent ()->getParent ()), &I);\n if (ret >=0) \n mods.insert (ret);\n\n return boost::make_tuple (refs, mods, news); \n }\n \n }; \n\n} \/\/ end namespace\n#else\nnamespace crab_llvm\n{\n using namespace crab::cfg;\n struct MemAnalysis {\n typedef int array_id_t; \n TrackedPrecision m_tracklev;\n MemAnalysis (): m_tracklev (INT) { }\n TrackedPrecision getTrackLevel () const { return m_tracklev; }\n int getArrayId (llvm::Function&, llvm::Value*) { return -1; }\n bool isSingleton (int) { return false; }\n boost::tuple,set, set > \n getRefModNewArrays (llvm::Function&) { \n return boost::make_tuple (set (), set (), set ()); \n } \n boost::tuple,set, set > \n getRefModNewArrays (llvm::CallInst&) { \n return boost::make_tuple (set (), set (), set ()); \n } \n }; \n} \/\/ end namespace\n#endif \n\n#endif \/*__MEMORY_ANALYSIS_HH_*\/\n[NEW] memory abstraction: keep track only of arrays which are known, complete, and non-collapsed.#ifndef __MEMORY_ANALYSIS_HH_\n#define __MEMORY_ANALYSIS_HH_\n\n\/* Wrapper for a datastructure analysis*\/\n\n#include \"llvm\/IR\/Function.h\"\n#include \"llvm\/IR\/Value.h\"\n#include \"llvm\/IR\/Instructions.h\"\n\n#include \"boost\/tuple\/tuple.hpp\"\n\n#include \"crab_llvm\/config.h\"\n#include \n\n#ifdef HAVE_DSA\n#include \"boost\/range\/algorithm\/set_algorithm.hpp\"\n#include \"dsa\/DataStructure.h\"\n#include \"dsa\/DSGraph.h\"\n#include \"dsa\/DSNode.h\"\n\nnamespace crab_llvm\n{\n using namespace std;\n using namespace llvm;\n using namespace crab::cfg;\n\n class MemAnalysis\n {\n \/* \n * The goal of the memory analysis is to split the whole heap into\n * disjoint arrays (i.e., contiguous sequence of bytes)\n *\n * Each DSA node is translated into an array. A DSA node may not\n * correspond directly to a llvm Value so we map DSA node to\n * id's.\n *\/\n\n public:\n\n typedef int array_id_t; \/\/ if < 0 then error\n\n private:\n \n DataStructures* m_dsa;\n TrackedPrecision m_tracklev;\n \n \/\/\/ map from DSNode to ids\n DenseMap m_node_ids;\n boost::unordered_map m_rev_node_ids;\n\n \/\/\/ reach - all reachable nodes from this function\n std::set m_reach;\n \/\/\/ outReach - subset of reach that is only reachable from the\n \/\/\/ return node\n std::set m_retReach;\n\n array_id_t getId (const DSNode *n) {\n auto it = m_node_ids.find (n);\n if (it != m_node_ids.end ()) return it->second;\n unsigned id = m_node_ids.size ();\n m_node_ids[n] = id;\n m_rev_node_ids[id] = n;\n return id;\n }\n\n template \n void markReachableNodes (const DSNode *n, Set &set) {\n if (!n) return;\n \n assert (!n->isForwarding () && \"Cannot mark a forwarded node\");\n if (set.insert (n).second)\n for (auto &edg : boost::make_iterator_range (n->edge_begin (), n->edge_end ()))\n markReachableNodes (edg.second.getNode (), set);\n }\n \n template \n void inputReachableNodes (const DSCallSite &cs, DSGraph &dsg, Set &set) {\n markReachableNodes (cs.getVAVal().getNode (), set);\n if (cs.isIndirectCall ()) markReachableNodes (cs.getCalleeNode (), set);\n for (unsigned i = 0, e = cs.getNumPtrArgs (); i != e; ++i)\n markReachableNodes (cs.getPtrArg (i).getNode (), set);\n \n \/\/ globals\n DSScalarMap &sm = dsg.getScalarMap ();\n for (auto &gv : boost::make_iterator_range (sm.global_begin(), sm.global_end ()))\n markReachableNodes (sm[gv].getNode (), set);\n }\n \n template \n void retReachableNodes (const DSCallSite &cs, Set &set) \n {markReachableNodes (cs.getRetVal ().getNode (), set);}\n \n template \n void set_difference (Set &s1, Set &s2) {\n Set s3;\n boost::set_difference (s1, s2, std::inserter (s3, s3.end ()));\n std::swap (s3, s1);\n }\n \n template \n void set_union (Set &s1, Set &s2) {\n Set s3;\n boost::set_union (s1, s2, std::inserter (s3, s3.end ()));\n std::swap (s3, s1);\n }\n \n \/\/\/ Computes DSNode reachable from the call arguments\n \/\/\/ reach - all reachable nodes\n \/\/\/ outReach - subset of reach that is only reachable from the return node\n template \n void argReachableNodes (DSCallSite CS, DSGraph &dsg, \n Set1 &reach, Set2 &outReach) {\n inputReachableNodes (CS, dsg, reach);\n retReachableNodes (CS, outReach);\n set_difference (outReach, reach);\n set_union (reach, outReach);\n }\n\n template \n void argReachableNodes (Function&f, Set1 &reach, Set2 &outReach) {\n DSGraph *cdsg = m_dsa->getDSGraph (f);\n if (cdsg) {\n DSCallSite CCS = cdsg->getCallSiteForArguments (f);\n argReachableNodes (CCS, *cdsg, reach, outReach);\n }\n }\n\n \/\/ - a node is complete if all its uses have been seen.\n \/\/ - a node is unknown if an integer is cast to a pointer or when\n \/\/ unanalyzable address arithmetic is seen.\n \/\/ - a node is collapsed if all its uses have compatible type or\n \/\/ compatible types but misaligned.\n bool isTrackable (const DSNode* n) const {\n return (n->isCompleteNode () && \n !n->isUnknownNode () && \n !n->isCollapsedNode () &&\n (n->isAllocaNode () || n->isHeapNode () || n->isGlobalNode ()));\n }\n\n public:\n \n MemAnalysis (): m_dsa (0), m_tracklev (INT) { }\n\n MemAnalysis (DataStructures * dsa, \n TrackedPrecision tracklev): \n m_dsa (dsa), m_tracklev (tracklev) { }\n \n TrackedPrecision getTrackLevel () const { return m_tracklev; }\n \n \/\/! return < 0 if no array associated with ptr is found\n array_id_t getArrayId (Function& f, Value* ptr) {\n if (!m_dsa) return -1;\n\n DSGraph* dsg = m_dsa->getDSGraph (f);\n if (!dsg) return -1;\n\n DSGraph* gDsg = dsg->getGlobalsGraph ();\n DSNode* n = dsg->getNodeForValue (ptr).getNode ();\n if (!n) n = gDsg->getNodeForValue (ptr).getNode ();\n\n if (!n || !isTrackable (n)) return -1;\n\n return getId (n); \n }\n\n \/\/! return true if the array corresponds to a single memory cell.\n bool isSingleton (array_id_t array_id) {\n auto it = m_rev_node_ids.find (array_id);\n if (it == m_rev_node_ids.end ()) return false;\n\n return it->second->getUniqueScalar ();\n }\n\n \/\/ Return the set of ref, mod and new nodes such that mod nodes\n \/\/ are a subset of the ref nodes and the new nodes are disjoint\n \/\/ from mod nodes.\n boost::tuple< set, set, set > \n getRefModNewArrays (Function& f) {\n std::set reach, retReach;\n argReachableNodes (f, reach, retReach);\n\n set refs, mods, news;\n for (const DSNode* n : reach) {\n\n if (!isTrackable (n))\n continue;\n\n if (!n->isReadNode () && !n->isModifiedNode ())\n continue;\n\n if ((n->isReadNode () || n->isModifiedNode ()) && retReach.count (n) <= 0) \n refs.insert (getId (n));\n \n if (n->isModifiedNode () && retReach.count (n) <= 0)\n mods.insert (getId (n));\n\n if (n->isModifiedNode () && retReach.count (n))\n news.insert (getId (n));\n }\n return boost::make_tuple (refs, mods, news);\n }\n\n \/\/ Return the set of ref, mod and new nodes such that mod nodes\n \/\/ are a subset of the ref nodes and the new nodes are disjoint\n \/\/ from mod nodes.\n boost::tuple< set, set, set > \n getRefModNewArrays (CallInst& I) {\n set refs, mods, news;\n\n \/\/\/ ignore inline assembly\n if (I.isInlineAsm ())\n return boost::make_tuple (refs, mods, news); \n \n DSGraph *dsg = m_dsa->getDSGraph (*(I.getParent ()->getParent ()));\n DSCallSite CS = dsg->getDSCallSiteForCallSite (CallSite (&I));\n \n if (!CS.isDirectCall ()) \n return boost::make_tuple (refs, mods, news); \n \n if (!m_dsa->hasDSGraph (*CS.getCalleeFunc ())) \n return boost::make_tuple (refs, mods, news); \n \n const Function &CF = *CS.getCalleeFunc ();\n DSGraph *cdsg = m_dsa->getDSGraph (CF);\n if (!cdsg) \n return boost::make_tuple (refs, mods, news); \n \n \/\/ -- compute callee nodes reachable from arguments and returns\n DSCallSite CCS = cdsg->getCallSiteForArguments (CF);\n std::set reach;\n std::set retReach;\n argReachableNodes (CCS, *cdsg, reach, retReach);\n DSGraph::NodeMapTy nodeMap;\n dsg->computeCalleeCallerMapping (CS, CF, *cdsg, nodeMap);\n \n for (const DSNode* n : reach) {\n\n if (!isTrackable (n))\n continue;\n\n if (!n->isReadNode () && !n->isModifiedNode ())\n continue;\n\n if ((n->isReadNode () || n->isModifiedNode ()) && retReach.count (n) <= 0) \n refs.insert (getId (n));\n \n if (n->isModifiedNode () && retReach.count (n) <= 0)\n mods.insert (getId (n));\n\n if (n->isModifiedNode () && retReach.count (n))\n news.insert (getId (n));\n\n }\n \/\/ -- add the node of the lhs of the call site\n int ret = getArrayId (*(I.getParent ()->getParent ()), &I);\n if (ret >=0) \n mods.insert (ret);\n\n return boost::make_tuple (refs, mods, news); \n }\n \n }; \n\n} \/\/ end namespace\n#else\n\nnamespace crab_llvm\n{\n using namespace crab::cfg;\n \/\/ Empty memory analysis\n struct MemAnalysis {\n typedef int array_id_t; \n TrackedPrecision m_tracklev;\n MemAnalysis (): m_tracklev (INT) { }\n TrackedPrecision getTrackLevel () const { return m_tracklev; }\n int getArrayId (llvm::Function&, llvm::Value*) { return -1; }\n bool isSingleton (int) { return false;}\n boost::tuple,set, set > \n getRefModNewArrays (llvm::Function&) { \n return boost::make_tuple (set (), set (), set ()); \n } \n boost::tuple,set, set > \n getRefModNewArrays (llvm::CallInst&) { \n return boost::make_tuple (set (), set (), set ()); \n } \n }; \n} \/\/ end namespace\n#endif \n\n#endif \/*__MEMORY_ANALYSIS_HH_*\/\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\/\n\n#include \"ReadableNativeMap.h\"\n\nusing namespace facebook::jni;\n\nnamespace facebook {\nnamespace react {\n\nvoid ReadableNativeMap::mapException(const std::exception &ex) {\n if (dynamic_cast(&ex) != nullptr) {\n throwNewJavaException(\n exceptions::gUnexpectedNativeTypeExceptionClass, ex.what());\n }\n}\n\nvoid addDynamicToJArray(\n local_ref> jarray,\n jint index,\n const folly::dynamic &dyn) {\n switch (dyn.type()) {\n case folly::dynamic::Type::NULLT: {\n jarray->setElement(index, nullptr);\n break;\n }\n case folly::dynamic::Type::BOOL: {\n (*jarray)[index] = JBoolean::valueOf(dyn.getBool());\n break;\n }\n case folly::dynamic::Type::INT64: {\n (*jarray)[index] = JDouble::valueOf(dyn.getInt());\n break;\n }\n case folly::dynamic::Type::DOUBLE: {\n (*jarray)[index] = JDouble::valueOf(dyn.getDouble());\n break;\n }\n case folly::dynamic::Type::STRING: {\n (*jarray)[index] = make_jstring(dyn.getString());\n break;\n }\n case folly::dynamic::Type::OBJECT: {\n (*jarray)[index] = ReadableNativeMap::newObjectCxxArgs(dyn);\n break;\n }\n case folly::dynamic::Type::ARRAY: {\n (*jarray)[index] = ReadableNativeArray::newObjectCxxArgs(dyn);\n break;\n }\n default:\n jarray->setElement(index, nullptr);\n break;\n }\n}\n\nlocal_ref> ReadableNativeMap::importKeys() {\n keys_ = folly::dynamic::array();\n if (map_ == nullptr) {\n return JArrayClass::newArray(0);\n }\n auto pairs = map_.items();\n for (auto &pair : pairs) {\n keys_.value().push_back(pair.first.asString());\n }\n jint size = keys_.value().size();\n auto jarray = JArrayClass::newArray(size);\n for (jint ii = 0; ii < size; ii++) {\n (*jarray)[ii] = make_jstring(keys_.value()[ii].getString());\n }\n return jarray;\n}\n\nlocal_ref> ReadableNativeMap::importValues() {\n jint size = keys_.value().size();\n auto jarray = JArrayClass::newArray(size);\n for (jint ii = 0; ii < size; ii++) {\n const std::string &key = keys_.value()[ii].getString();\n addDynamicToJArray(jarray, ii, map_.at(key));\n }\n return jarray;\n}\n\nlocal_ref> ReadableNativeMap::importTypes() {\n jint size = keys_.value().size();\n auto jarray = JArrayClass::newArray(size);\n for (jint ii = 0; ii < size; ii++) {\n const std::string &key = keys_.value()[ii].getString();\n (*jarray)[ii] = ReadableType::getType(map_.at(key).type());\n }\n return jarray;\n}\n\nlocal_ref\nReadableNativeMap::createWithContents(folly::dynamic &&map) {\n if (map.isNull()) {\n return local_ref(nullptr);\n }\n\n if (!map.isObject()) {\n throwNewJavaException(\n exceptions::gUnexpectedNativeTypeExceptionClass,\n \"expected Map, got a %s\",\n map.typeName());\n }\n\n return newObjectCxxArgs(std::move(map));\n}\n\nvoid ReadableNativeMap::registerNatives() {\n registerHybrid({\n makeNativeMethod(\"importKeys\", ReadableNativeMap::importKeys),\n makeNativeMethod(\"importValues\", ReadableNativeMap::importValues),\n makeNativeMethod(\"importTypes\", ReadableNativeMap::importTypes),\n });\n}\n\n} \/\/ namespace react\n} \/\/ namespace facebook\nMicro-optimization in ReadableNativeMaps\/*\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\/\n\n#include \"ReadableNativeMap.h\"\n\nusing namespace facebook::jni;\n\nnamespace facebook {\nnamespace react {\n\nvoid ReadableNativeMap::mapException(const std::exception &ex) {\n if (dynamic_cast(&ex) != nullptr) {\n throwNewJavaException(\n exceptions::gUnexpectedNativeTypeExceptionClass, ex.what());\n }\n}\n\nvoid addDynamicToJArray(\n local_ref> jarray,\n jint index,\n const folly::dynamic &dyn) {\n switch (dyn.type()) {\n case folly::dynamic::Type::NULLT: {\n jarray->setElement(index, nullptr);\n break;\n }\n case folly::dynamic::Type::BOOL: {\n (*jarray)[index] = JBoolean::valueOf(dyn.getBool());\n break;\n }\n case folly::dynamic::Type::INT64: {\n (*jarray)[index] = JDouble::valueOf(dyn.getInt());\n break;\n }\n case folly::dynamic::Type::DOUBLE: {\n (*jarray)[index] = JDouble::valueOf(dyn.getDouble());\n break;\n }\n case folly::dynamic::Type::STRING: {\n (*jarray)[index] = make_jstring(dyn.getString());\n break;\n }\n case folly::dynamic::Type::OBJECT: {\n (*jarray)[index] = ReadableNativeMap::newObjectCxxArgs(dyn);\n break;\n }\n case folly::dynamic::Type::ARRAY: {\n (*jarray)[index] = ReadableNativeArray::newObjectCxxArgs(dyn);\n break;\n }\n default:\n jarray->setElement(index, nullptr);\n break;\n }\n}\n\nlocal_ref> ReadableNativeMap::importKeys() {\n keys_ = folly::dynamic::array();\n if (map_ == nullptr) {\n return JArrayClass::newArray(0);\n }\n auto pairs = map_.items();\n jint size = map_.size();\n auto jarray = JArrayClass::newArray(size);\n jint i = 0;\n for (auto &pair : pairs) {\n auto value = pair.first.asString();\n keys_.value().push_back(value);\n (*jarray)[i++] = make_jstring(value);\n }\n\n return jarray;\n}\n\nlocal_ref> ReadableNativeMap::importValues() {\n jint size = keys_.value().size();\n auto jarray = JArrayClass::newArray(size);\n for (jint ii = 0; ii < size; ii++) {\n const std::string &key = keys_.value()[ii].getString();\n addDynamicToJArray(jarray, ii, map_.at(key));\n }\n return jarray;\n}\n\nlocal_ref> ReadableNativeMap::importTypes() {\n jint size = keys_.value().size();\n auto jarray = JArrayClass::newArray(size);\n for (jint ii = 0; ii < size; ii++) {\n const std::string &key = keys_.value()[ii].getString();\n (*jarray)[ii] = ReadableType::getType(map_.at(key).type());\n }\n return jarray;\n}\n\nlocal_ref\nReadableNativeMap::createWithContents(folly::dynamic &&map) {\n if (map.isNull()) {\n return local_ref(nullptr);\n }\n\n if (!map.isObject()) {\n throwNewJavaException(\n exceptions::gUnexpectedNativeTypeExceptionClass,\n \"expected Map, got a %s\",\n map.typeName());\n }\n\n return newObjectCxxArgs(std::move(map));\n}\n\nvoid ReadableNativeMap::registerNatives() {\n registerHybrid({\n makeNativeMethod(\"importKeys\", ReadableNativeMap::importKeys),\n makeNativeMethod(\"importValues\", ReadableNativeMap::importValues),\n makeNativeMethod(\"importTypes\", ReadableNativeMap::importTypes),\n });\n}\n\n} \/\/ namespace react\n} \/\/ namespace facebook\n<|endoftext|>"} {"text":"#include \"cinder\/app\/AppBasic.h\"\n#include \n#include \"cinder\/params\/Params.h\"\n#include \"cinder\/Font.h\"\n#include \"cinder\/Utilities.h\"\n#include \"cinder\/Rand.h\"\n\n#include \n\nusing namespace ci;\nusing namespace ci::app;\nusing namespace ci::box2d;\nusing namespace std;\n\n\nclass BasicBox2DApp : public AppBasic {\n public:\n\tvoid mouseDrag( MouseEvent event );\n\tvoid mouseDown( MouseEvent event );\n\tvoid update();\n\tvoid prepareSettings(Settings* settings);\n\tvoid setup();\n\tvoid draw();\n\t\nprivate:\t\n\tvoid addBox();\n\t\n\tSandbox mSandbox;\n\tFont mFont;\n};\n\nvoid BasicBox2DApp::prepareSettings(Settings* settings)\n{\n\tsettings->setWindowSize(1024, 768);\n\tsettings->setFrameRate(60.0f);\n}\n\nvoid BasicBox2DApp::setup()\n{\n\tmSandbox.init();\n\tmSandbox.enableMouseInteraction(this);\n\t\n\tmFont = Font( \"Hoefler Text\", 12.0f );\n}\n\nvoid BasicBox2DApp::mouseDrag( MouseEvent event )\n{\n\tif ( event.isAltDown() )\n\t{\n\t\taddBox();\n\t}\n\/\/\tmSandbox.addBox( getMousePos(), Vec2f( Rand::randFloat(10.0f,40.0f), Rand::randFloat(10.0f,40.0f) ) );\n}\n\nvoid BasicBox2DApp::mouseDown( MouseEvent event )\n{\n\tif( event.isAltDown() ) \n\t{\n\t\taddBox();\n\t}\n\n}\n\nvoid BasicBox2DApp::update()\n{\n\tmSandbox.update();\n}\n\nvoid BasicBox2DApp::addBox()\n{\n\tBoxElement* b = new BoxElement( getMousePos(), Vec2f( Rand::randFloat(10.0f,40.0f), Rand::randFloat(10.0f,40.0f) ) );\n\tb->setColor( Color( CM_HSV, Rand::randFloat(0.0f,0.19f), 0.9f, 1.0f ) );\n\tmSandbox.addElement(b);\n}\n\nvoid BasicBox2DApp::draw()\n{\n\tgl::clear( Color::white() );\n\tgl::enableAlphaBlending();\n\t\n\t\/\/draw all physics elements\n\tmSandbox.draw();\n\t\/\/only draw the contact points in debug\n\tmSandbox.debugDraw(false, true);\n\t\n\tgl::drawString( \"Framerate: \" + toString(getAverageFps()), Vec2f( 10.0f, 10.0f ), Color::black(), mFont );\n\tgl::drawString( \"Num bodies: \" + toString(mSandbox.getBodyCount() ), Vec2f( 10.0f, 22.0f ), Color::black(), mFont );\n\tgl::drawString( \"Num contacts: \" + toString(mSandbox.getContactCount() ), Vec2f( 10.0f, 34.0f ), Color::black(), mFont );\n\t\n\/\/\tparams::InterfaceGl::draw();\n}\n\n\/\/ This line tells Cinder to actually create the application\nCINDER_APP_BASIC( BasicBox2DApp, RendererGl )\nbasic demo now adds boxes unless alt\/option is held.#include \"cinder\/app\/AppBasic.h\"\n#include \n#include \"cinder\/params\/Params.h\"\n#include \"cinder\/Font.h\"\n#include \"cinder\/Utilities.h\"\n#include \"cinder\/Rand.h\"\n\n#include \n\nusing namespace ci;\nusing namespace ci::app;\nusing namespace ci::box2d;\nusing namespace std;\n\n\nclass BasicBox2DApp : public AppBasic {\n public:\n\tvoid mouseDrag( MouseEvent event );\n\tvoid mouseDown( MouseEvent event );\n\tvoid update();\n\tvoid prepareSettings(Settings* settings);\n\tvoid setup();\n\tvoid draw();\n\t\nprivate:\t\n\tvoid addBox();\n\t\n\tSandbox mSandbox;\n\tFont mFont;\n};\n\nvoid BasicBox2DApp::prepareSettings(Settings* settings)\n{\n\tsettings->setWindowSize(1024, 768);\n\tsettings->setFrameRate(60.0f);\n}\n\nvoid BasicBox2DApp::setup()\n{\n\tmSandbox.init();\n\tmSandbox.enableMouseInteraction(this);\n\t\n\tmFont = Font( \"Hoefler Text\", 12.0f );\n}\n\nvoid BasicBox2DApp::mouseDrag( MouseEvent event )\n{\n\tif ( !event.isAltDown() )\n\t{\n\t\taddBox();\n\t}\n\/\/\tmSandbox.addBox( getMousePos(), Vec2f( Rand::randFloat(10.0f,40.0f), Rand::randFloat(10.0f,40.0f) ) );\n}\n\nvoid BasicBox2DApp::mouseDown( MouseEvent event )\n{\n\tif( !event.isAltDown() ) \n\t{\n\t\taddBox();\n\t}\n\n}\n\nvoid BasicBox2DApp::update()\n{\n\tmSandbox.update();\n}\n\nvoid BasicBox2DApp::addBox()\n{\n\tBoxElement* b = new BoxElement( getMousePos(), Vec2f( Rand::randFloat(10.0f,40.0f), Rand::randFloat(10.0f,40.0f) ) );\n\tb->setColor( Color( CM_HSV, Rand::randFloat(0.0f,0.19f), 0.9f, 1.0f ) );\n\tmSandbox.addElement(b);\n}\n\nvoid BasicBox2DApp::draw()\n{\n\tgl::clear( Color::white() );\n\tgl::enableAlphaBlending();\n\t\n\t\/\/draw all physics elements\n\tmSandbox.draw();\n\t\/\/only draw the contact points in debug\n\tmSandbox.debugDraw(false, true);\n\t\n\tgl::drawString( \"Framerate: \" + toString(getAverageFps()), Vec2f( 10.0f, 10.0f ), Color::black(), mFont );\n\tgl::drawString( \"Num bodies: \" + toString(mSandbox.getBodyCount() ), Vec2f( 10.0f, 22.0f ), Color::black(), mFont );\n\tgl::drawString( \"Num contacts: \" + toString(mSandbox.getContactCount() ), Vec2f( 10.0f, 34.0f ), Color::black(), mFont );\n\t\n\/\/\tparams::InterfaceGl::draw();\n}\n\n\/\/ This line tells Cinder to actually create the application\nCINDER_APP_BASIC( BasicBox2DApp, RendererGl )\n<|endoftext|>"} {"text":"#include \"text_file.hpp\"\n#include \"to_utf16.hpp\"\n#include \"to_utf8.hpp\"\n#include \"current_dir.hpp\"\n#include \n\nstatic std::string getFullFileName(std::string fileName)\n{\n if (fileName.empty() || fileName[0] == L'\/') \n return fileName;\n else \n return getCurrentDir() + '\/' + fileName;\n}\n\nstatic std::string baseName(std::string fileName)\n{\n auto p = fileName.rfind('\/');\n if (p != std::string::npos)\n return std::string{ begin(fileName) + p + 1, end(fileName) };\n else\n return fileName;\n}\n\nTextFile::TextFile(std::string fileName):\n fileName_(getFullFileName(fileName))\n{\n if (!fileName.empty())\n setName(toUtf16(baseName(fileName)));\n else\n setName(L\"Untitled\");\n \n std::ifstream f(fileName_);\n if (f.is_open())\n while (!f.eof())\n {\n std::string line;\n std::getline(f, line);\n buffer_.push_back(toUtf16(line));\n }\n else\n buffer_.push_back(L\"\");\n}\n\nstd::string TextFile::fileName() const\n{\n return fileName_;\n}\n\nvoid TextFile::save()\n{\n if (!fileName_.empty())\n saveAs(fileName_);\n}\n\nvoid TextFile::saveAs(std::string fileName)\n{\n fileName_ = fileName;\n setName(toUtf16(baseName(fileName)));\n std::ofstream f(fileName_);\n for (const auto &l: buffer_)\n f << toUtf8(l) << std::endl;\n clearModified();\n}\nFix bug when the application adds the empty line to the end of the file after saving#include \"text_file.hpp\"\n#include \"to_utf16.hpp\"\n#include \"to_utf8.hpp\"\n#include \"current_dir.hpp\"\n#include \n\nstatic std::string getFullFileName(std::string fileName)\n{\n if (fileName.empty() || fileName[0] == L'\/') \n return fileName;\n else \n return getCurrentDir() + '\/' + fileName;\n}\n\nstatic std::string baseName(std::string fileName)\n{\n auto p = fileName.rfind('\/');\n if (p != std::string::npos)\n return std::string{ begin(fileName) + p + 1, end(fileName) };\n else\n return fileName;\n}\n\nTextFile::TextFile(std::string fileName):\n fileName_(getFullFileName(fileName))\n{\n if (!fileName.empty())\n setName(toUtf16(baseName(fileName)));\n else\n setName(L\"Untitled\");\n \n std::ifstream f(fileName_);\n if (f.is_open())\n while (!f.eof())\n {\n std::string line;\n std::getline(f, line);\n buffer_.push_back(toUtf16(line));\n }\n else\n buffer_.push_back(L\"\");\n}\n\nstd::string TextFile::fileName() const\n{\n return fileName_;\n}\n\nvoid TextFile::save()\n{\n if (!fileName_.empty())\n saveAs(fileName_);\n}\n\nvoid TextFile::saveAs(std::string fileName)\n{\n fileName_ = fileName;\n setName(toUtf16(baseName(fileName)));\n std::ofstream f(fileName_);\n bool first = true;\n for (const auto &l: buffer_)\n {\n if (first)\n first = false;\n else\n f << std::endl;\n f << toUtf8(l);\n }\n clearModified();\n}\n<|endoftext|>"} {"text":"\/**\n * @file TimePointTest.cpp\n * @brief TimePoint class tester.\n * @author zer0\n * @date 2017-04-12\n *\/\n\n#include \n#include \n\n#include \n\nusing namespace libtbag;\nusing namespace libtbag::time;\n\nTEST(TimePointTest, Default)\n{\n TimePoint tp;\n ASSERT_EQ(1970, tp.year());\n ASSERT_EQ( 1, tp.month());\n ASSERT_EQ( 1, tp.day());\n ASSERT_EQ( 0, tp.hours());\n ASSERT_EQ( 0, tp.minutes());\n ASSERT_EQ( 0, tp.seconds());\n ASSERT_EQ( 0, tp.millisec());\n ASSERT_EQ( 0, tp.microsec());\n}\n\nTEST(TimePointTest, Constructor)\n{\n auto now = std::chrono::system_clock::now();\n auto diff = std::chrono::microseconds(1);\n\n TimePoint::Rep now_rep = now.time_since_epoch().count();\n TimePoint::Rep diff_rep = diff.count();\n\n TimePoint tp1;\n TimePoint tp2(now);\n TimePoint tp3(now, diff);\n TimePoint tp4(now_rep);\n TimePoint tp5(now_rep, diff_rep);\n TimePoint tp6(1970, 1, 1, 0, 0, 0, 0, 0);\n\n TimePoint tp7 = tp1;\n TimePoint tp8 = std::move(TimePoint(1970, 1, 1, 0, 0, 0, 0, 0, 0));\n\n ASSERT_EQ(0, tp8.getMicrosecTimeSinceEpoch());\n ASSERT_EQ(tp1, tp7);\n ASSERT_EQ(tp2, tp3);\n ASSERT_EQ(tp4, tp5);\n}\n\nTEST(TimePointTest, Swap)\n{\n TimePoint tp1 = TimePoint::now();\n auto g1 = tp1.getTimeSinceEpoch();\n auto l1 = tp1.getLocalTimeSinceEpoch();\n\n std::this_thread::sleep_for(std::chrono::microseconds(1));\n\n TimePoint tp2 = TimePoint::now();\n auto g2 = tp2.getTimeSinceEpoch();\n auto l2 = tp2.getLocalTimeSinceEpoch();\n\n ASSERT_NE(g1, g2);\n ASSERT_NE(l1, l2);\n\n std::swap(tp1, tp2);\n ASSERT_EQ(g1, tp2.getTimeSinceEpoch());\n ASSERT_EQ(l1, tp2.getLocalTimeSinceEpoch());\n ASSERT_EQ(g2, tp1.getTimeSinceEpoch());\n ASSERT_EQ(l2, tp1.getLocalTimeSinceEpoch());\n}\n\nTEST(TimePointTest, Operators)\n{\n using namespace std::chrono;\n\n TimePoint tp1;\n TimePoint tp2(1970, 1, 1, 0, 0, 0, 0, 0);\n ASSERT_EQ(tp1, tp2);\n\n ASSERT_EQ(TimePoint::SystemDuration(0), tp1.getTimeSinceEpoch());\n ASSERT_EQ(TimePoint::SystemDuration(0), tp2.getTimeSinceEpoch());\n\n tp1 += TimePoint::SystemDuration(1);\n tp2 += TimePoint::SystemDuration(1);\n ASSERT_EQ(tp1, tp2);\n\n ASSERT_EQ(TimePoint::SystemDuration(1), tp1.getTimeSinceEpoch());\n ASSERT_EQ(TimePoint::SystemDuration(1), tp2.getTimeSinceEpoch());\n\n tp1 = tp1 - TimePoint::SystemDuration(1);\n tp2 = tp2 - TimePoint::SystemDuration(1);\n\n ASSERT_EQ(TimePoint::SystemDuration(0), tp1.getTimeSinceEpoch());\n ASSERT_EQ(TimePoint::SystemDuration(0), tp2.getTimeSinceEpoch());\n\n tp1 = TimePoint::SystemDuration(0);\n tp2 = TimePoint::SystemDuration(1);\n\n ASSERT_LT(tp1, tp2);\n ASSERT_LE(tp1, tp2);\n ASSERT_GT(tp2, tp1);\n ASSERT_GE(tp2, tp1);\n ASSERT_NE(tp1, tp2);\n}\n\nTEST(TimePointTest, DateTime)\n{\n TimePoint tp1(2017, 4, 5, 3, 28, 27, 100, 99);\n ASSERT_EQ(2017, tp1.year());\n ASSERT_EQ( 4, tp1.month());\n ASSERT_EQ( 5, tp1.day());\n ASSERT_EQ( 3, tp1.hours());\n ASSERT_EQ( 28, tp1.minutes());\n ASSERT_EQ( 27, tp1.seconds());\n ASSERT_EQ( 100, tp1.millisec());\n ASSERT_EQ( 99, tp1.microsec());\n\n TimePoint tp3 = TimePoint::now();\n TimePoint tp4(tp3.year(), tp3.month(), tp3.day(), tp3.hours(), tp3.minutes(), tp3.seconds(), tp3.millisec(), tp3.microsec());\n\n std::cout << \"TP3 Long String: \" << tp3.toLongString() << std::endl;\n std::cout << \"TP4 Long String: \" << tp4.toLongString() << std::endl;\n ASSERT_EQ(tp3, tp4);\n}\n\nTEST(TimePointTest, TimeBeforeEpoch)\n{\n \/\/TimePoint tp2(100, 1, 1, 0, 0, 1, 0, 1);\n \/\/ASSERT_EQ(100, tp2.year());\n \/\/ASSERT_EQ( 1, tp2.month());\n \/\/ASSERT_EQ( 1, tp2.day());\n \/\/ASSERT_EQ( 0, tp2.hours());\n \/\/ASSERT_EQ( 0, tp2.minutes());\n \/\/ASSERT_EQ( 1, tp2.seconds());\n \/\/ASSERT_EQ( 0, tp2.millisec());\n \/\/ASSERT_EQ( 1, tp2.microsec());\n}\n\nFixed nanoseconds error in TestPointTest.DateTime tester.\/**\n * @file TimePointTest.cpp\n * @brief TimePoint class tester.\n * @author zer0\n * @date 2017-04-12\n *\/\n\n#include \n#include \n\n#include \n\nusing namespace libtbag;\nusing namespace libtbag::time;\n\nTEST(TimePointTest, Default)\n{\n TimePoint tp;\n ASSERT_EQ(1970, tp.year());\n ASSERT_EQ( 1, tp.month());\n ASSERT_EQ( 1, tp.day());\n ASSERT_EQ( 0, tp.hours());\n ASSERT_EQ( 0, tp.minutes());\n ASSERT_EQ( 0, tp.seconds());\n ASSERT_EQ( 0, tp.millisec());\n ASSERT_EQ( 0, tp.microsec());\n}\n\nTEST(TimePointTest, Constructor)\n{\n auto now = std::chrono::system_clock::now();\n auto diff = std::chrono::microseconds(1);\n\n TimePoint::Rep now_rep = now.time_since_epoch().count();\n TimePoint::Rep diff_rep = diff.count();\n\n TimePoint tp1;\n TimePoint tp2(now);\n TimePoint tp3(now, diff);\n TimePoint tp4(now_rep);\n TimePoint tp5(now_rep, diff_rep);\n TimePoint tp6(1970, 1, 1, 0, 0, 0, 0, 0);\n\n TimePoint tp7 = tp1;\n TimePoint tp8 = std::move(TimePoint(1970, 1, 1, 0, 0, 0, 0, 0, 0));\n\n ASSERT_EQ(0, tp8.getMicrosecTimeSinceEpoch());\n ASSERT_EQ(tp1, tp7);\n ASSERT_EQ(tp2, tp3);\n ASSERT_EQ(tp4, tp5);\n}\n\nTEST(TimePointTest, Swap)\n{\n TimePoint tp1 = TimePoint::now();\n auto g1 = tp1.getTimeSinceEpoch();\n auto l1 = tp1.getLocalTimeSinceEpoch();\n\n std::this_thread::sleep_for(std::chrono::microseconds(1));\n\n TimePoint tp2 = TimePoint::now();\n auto g2 = tp2.getTimeSinceEpoch();\n auto l2 = tp2.getLocalTimeSinceEpoch();\n\n ASSERT_NE(g1, g2);\n ASSERT_NE(l1, l2);\n\n std::swap(tp1, tp2);\n ASSERT_EQ(g1, tp2.getTimeSinceEpoch());\n ASSERT_EQ(l1, tp2.getLocalTimeSinceEpoch());\n ASSERT_EQ(g2, tp1.getTimeSinceEpoch());\n ASSERT_EQ(l2, tp1.getLocalTimeSinceEpoch());\n}\n\nTEST(TimePointTest, Operators)\n{\n using namespace std::chrono;\n\n TimePoint tp1;\n TimePoint tp2(1970, 1, 1, 0, 0, 0, 0, 0);\n ASSERT_EQ(tp1, tp2);\n\n ASSERT_EQ(TimePoint::SystemDuration(0), tp1.getTimeSinceEpoch());\n ASSERT_EQ(TimePoint::SystemDuration(0), tp2.getTimeSinceEpoch());\n\n tp1 += TimePoint::SystemDuration(1);\n tp2 += TimePoint::SystemDuration(1);\n ASSERT_EQ(tp1, tp2);\n\n ASSERT_EQ(TimePoint::SystemDuration(1), tp1.getTimeSinceEpoch());\n ASSERT_EQ(TimePoint::SystemDuration(1), tp2.getTimeSinceEpoch());\n\n tp1 = tp1 - TimePoint::SystemDuration(1);\n tp2 = tp2 - TimePoint::SystemDuration(1);\n\n ASSERT_EQ(TimePoint::SystemDuration(0), tp1.getTimeSinceEpoch());\n ASSERT_EQ(TimePoint::SystemDuration(0), tp2.getTimeSinceEpoch());\n\n tp1 = TimePoint::SystemDuration(0);\n tp2 = TimePoint::SystemDuration(1);\n\n ASSERT_LT(tp1, tp2);\n ASSERT_LE(tp1, tp2);\n ASSERT_GT(tp2, tp1);\n ASSERT_GE(tp2, tp1);\n ASSERT_NE(tp1, tp2);\n}\n\nTEST(TimePointTest, DateTime)\n{\n TimePoint tp1(2017, 4, 5, 3, 28, 27, 100, 99);\n ASSERT_EQ(2017, tp1.year());\n ASSERT_EQ( 4, tp1.month());\n ASSERT_EQ( 5, tp1.day());\n ASSERT_EQ( 3, tp1.hours());\n ASSERT_EQ( 28, tp1.minutes());\n ASSERT_EQ( 27, tp1.seconds());\n ASSERT_EQ( 100, tp1.millisec());\n ASSERT_EQ( 99, tp1.microsec());\n\n TimePoint tp3 = TimePoint::now();\n TimePoint tp4(tp3.year(), tp3.month(), tp3.day(), tp3.hours(), tp3.minutes(), tp3.seconds(), tp3.millisec(), tp3.microsec(), tp3.nanosec());\n\n std::cout << \"TP3 Long String: \" << tp3.toLongString() << std::endl;\n std::cout << \"TP4 Long String: \" << tp4.toLongString() << std::endl;\n ASSERT_EQ(tp3, tp4);\n}\n\nTEST(TimePointTest, TimeBeforeEpoch)\n{\n \/\/TimePoint tp2(100, 1, 1, 0, 0, 1, 0, 1);\n \/\/ASSERT_EQ(100, tp2.year());\n \/\/ASSERT_EQ( 1, tp2.month());\n \/\/ASSERT_EQ( 1, tp2.day());\n \/\/ASSERT_EQ( 0, tp2.hours());\n \/\/ASSERT_EQ( 0, tp2.minutes());\n \/\/ASSERT_EQ( 1, tp2.seconds());\n \/\/ASSERT_EQ( 0, tp2.millisec());\n \/\/ASSERT_EQ( 1, tp2.microsec());\n}\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: b2dcubicbezier.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: rt $ $Date: 2004-12-13 08:47:52 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _BGFX_CURVE_B2DCUBICBEZIER_HXX\n#include \n#endif\n\n#ifndef _BGFX_VECTOR_B2DVECTOR_HXX\n#include \n#endif\n\n#ifndef _BGFX_POLYGON_B2DPOLYGON_HXX\n#include \n#endif\n\n#ifndef _BGFX_NUMERIC_FTOOLS_HXX\n#include \n#endif\n\n\/\/ #i37443#\n#define FACTOR_FOR_UNSHARPEN (1.6)\n#ifdef DBG_UTIL\nstatic double fMultFactUnsharpen = FACTOR_FOR_UNSHARPEN;\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace basegfx\n{\n namespace\n {\n void ImpSubDiv(\n const B2DPoint& rfPA, \/\/ start point\n const B2DPoint& rfEA, \/\/ edge on A\n const B2DPoint& rfEB, \/\/ edge on B\n const B2DPoint& rfPB, \/\/ end point\n B2DPolygon& rTarget, \/\/ target polygon\n double fAngleBound, \/\/ angle bound in [0.0 .. 2PI]\n bool bAddLastPoint, \/\/ should last point be added?\n bool bAllowUnsharpen, \/\/ #i37443# allow the criteria to get unsharp in recursions\n sal_uInt16 nMaxRecursionDepth) \/\/ endless loop protection\n {\n if(nMaxRecursionDepth)\n {\n \/\/ do angle test\n const B2DVector aLeft(rfEA - rfPA);\n const B2DVector aRight(rfEB - rfPB);\n const double fCurrentAngle(aLeft.angle(aRight));\n\n if(fabs(fCurrentAngle) > (F_PI - fAngleBound))\n {\n \/\/ end recursion\n nMaxRecursionDepth = 0;\n }\n else\n {\n if(bAllowUnsharpen)\n {\n \/\/ #i37443# unsharpen criteria\n#ifdef DBG_UTIL\n fAngleBound *= fMultFactUnsharpen;\n#else\n fAngleBound *= FACTOR_FOR_UNSHARPEN;\n#endif\n }\n }\n }\n\n if(nMaxRecursionDepth)\n {\n \/\/ divide at 0.5\n const B2DPoint aS1L(average(rfPA, rfEA));\n const B2DPoint aS1C(average(rfEA, rfEB));\n const B2DPoint aS1R(average(rfEB, rfPB));\n const B2DPoint aS2L(average(aS1L, aS1C));\n const B2DPoint aS2R(average(aS1C, aS1R));\n const B2DPoint aS3C(average(aS2L, aS2R));\n\n \/\/ left recursion\n ImpSubDiv(rfPA, aS1L, aS2L, aS3C, rTarget, fAngleBound,\n bAddLastPoint, bAllowUnsharpen, nMaxRecursionDepth - 1);\n\n \/\/ right recursion\n ImpSubDiv(aS3C, aS2R, aS1R, rfPB, rTarget, fAngleBound,\n bAddLastPoint, bAllowUnsharpen, nMaxRecursionDepth - 1);\n }\n else\n {\n \/\/ add points\n rTarget.append(rfPA);\n\n if(bAddLastPoint)\n {\n rTarget.append(rfPB);\n }\n }\n }\n\n void ImpSubDivStart(\n const B2DPoint& rfPA, \/\/ start point\n const B2DPoint& rfEA, \/\/ edge on A\n const B2DPoint& rfEB, \/\/ edge on B\n const B2DPoint& rfPB, \/\/ end point\n B2DPolygon& rTarget, \/\/ target polygon\n const double& rfAngleBound, \/\/ angle bound in [0.0 .. 2PI]\n bool bAddLastPoint, \/\/ should last point be added?\n bool bAllowUnsharpen) \/\/ #i37443# allow the criteria to get unsharp in recursions\n {\n sal_uInt16 nMaxRecursionDepth(8);\n const B2DVector aLeft(rfEA - rfPA);\n const B2DVector aRight(rfEB - rfPB);\n bool bLeftEqualZero(aLeft.equalZero());\n bool bRightEqualZero(aRight.equalZero());\n bool bAllParallel(false);\n\n if(bLeftEqualZero && bRightEqualZero)\n {\n nMaxRecursionDepth = 0;\n }\n else\n {\n const B2DVector aBase(rfPB - rfPA);\n const bool bBaseEqualZero(aLeft.equalZero());\n\n if(!bBaseEqualZero)\n {\n const bool bLeftParallel(bLeftEqualZero ? true : areParallel(aLeft, aBase));\n const bool bRightParallel(bRightEqualZero ? true : areParallel(aRight, aBase));\n\n if(bLeftParallel && bRightParallel)\n {\n bAllParallel = true;\n\n if(!bLeftEqualZero)\n {\n double fFactor;\n\n if(fabs(aBase.getX()) > fabs(aBase.getY()))\n {\n fFactor = aLeft.getX() \/ aBase.getX();\n }\n else\n {\n fFactor = aLeft.getY() \/ aBase.getY();\n }\n\n if(fFactor >= 0.0 && fFactor <= 1.0)\n {\n bLeftEqualZero = true;\n }\n }\n\n if(!bRightEqualZero)\n {\n double fFactor;\n\n if(fabs(aBase.getX()) > fabs(aBase.getY()))\n {\n fFactor = aRight.getX() \/ -aBase.getX();\n }\n else\n {\n fFactor = aRight.getY() \/ -aBase.getY();\n }\n\n if(fFactor >= 0.0 && fFactor <= 1.0)\n {\n bRightEqualZero = true;\n }\n }\n\n if(bLeftEqualZero && bRightEqualZero)\n {\n nMaxRecursionDepth = 0;\n }\n }\n }\n }\n\n if(nMaxRecursionDepth)\n {\n \/\/ divide at 0.5 ad test both edges for angle criteria\n const B2DPoint aS1L(average(rfPA, rfEA));\n const B2DPoint aS1C(average(rfEA, rfEB));\n const B2DPoint aS1R(average(rfEB, rfPB));\n const B2DPoint aS2L(average(aS1L, aS1C));\n const B2DPoint aS2R(average(aS1C, aS1R));\n const B2DPoint aS3C(average(aS2L, aS2R));\n\n \/\/ test left\n bool bAngleIsSmallerLeft(bAllParallel && bLeftEqualZero);\n if(!bAngleIsSmallerLeft)\n {\n const B2DVector aLeftLeft(aS1L - rfPA);\n const B2DVector aRightLeft(aS2L - aS3C);\n const double fCurrentAngleLeft(aLeftLeft.angle(aRightLeft));\n bAngleIsSmallerLeft = (fabs(fCurrentAngleLeft) > (F_PI - rfAngleBound));\n }\n\n \/\/ test right\n bool bAngleIsSmallerRight(bAllParallel && bRightEqualZero);\n if(!bAngleIsSmallerRight)\n {\n const B2DVector aLeftRight(aS2R - aS3C);\n const B2DVector aRightRight(aS1R - rfPB);\n const double fCurrentAngleRight(aLeftRight.angle(aRightRight));\n bAngleIsSmallerRight = (fabs(fCurrentAngleRight) > (F_PI - rfAngleBound));\n }\n\n if(bAngleIsSmallerLeft && bAngleIsSmallerRight)\n {\n \/\/ no recursion necessary at all\n nMaxRecursionDepth = 0;\n }\n else\n {\n \/\/ left\n if(bAngleIsSmallerLeft)\n {\n rTarget.append(rfPA);\n if(bAddLastPoint)\n {\n rTarget.append(aS3C);\n }\n }\n else\n {\n ImpSubDiv(rfPA, aS1L, aS2L, aS3C, rTarget, rfAngleBound,\n bAddLastPoint, bAllowUnsharpen, nMaxRecursionDepth);\n }\n\n \/\/ right\n if(bAngleIsSmallerRight)\n {\n rTarget.append(aS3C);\n if(bAddLastPoint)\n {\n rTarget.append(rfPB);\n }\n }\n else\n {\n ImpSubDiv(aS3C, aS2R, aS1R, rfPB, rTarget, rfAngleBound,\n bAddLastPoint, bAllowUnsharpen, nMaxRecursionDepth);\n }\n }\n }\n\n if(!nMaxRecursionDepth)\n {\n rTarget.append(rfPA);\n if(bAddLastPoint)\n {\n rTarget.append(rfPB);\n }\n }\n }\n } \/\/ end of anonymous namespace\n} \/\/ end of namespace basegfx\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace basegfx\n{\n B2DCubicBezier::B2DCubicBezier(const B2DCubicBezier& rBezier)\n : maStartPoint(rBezier.maStartPoint),\n maEndPoint(rBezier.maEndPoint),\n maControlPointA(rBezier.maControlPointA),\n maControlPointB(rBezier.maControlPointB)\n {\n }\n\n B2DCubicBezier::B2DCubicBezier()\n {\n }\n\n B2DCubicBezier::B2DCubicBezier(const B2DPoint& rStart, const B2DPoint& rEnd)\n : maStartPoint(rStart),\n maEndPoint(rEnd),\n maControlPointA(rStart),\n maControlPointB(rEnd)\n {\n }\n\n B2DCubicBezier::B2DCubicBezier(const B2DPoint& rStart, const B2DPoint& rControlPointA,\n const B2DPoint& rControlPointB, const B2DPoint& rEnd)\n : maStartPoint(rStart),\n maEndPoint(rEnd),\n maControlPointA(rControlPointA),\n maControlPointB(rControlPointB)\n {\n }\n\n B2DCubicBezier::~B2DCubicBezier()\n {\n }\n\n \/\/ assignment operator\n B2DCubicBezier& B2DCubicBezier::operator=(const B2DCubicBezier& rBezier)\n {\n maStartPoint = rBezier.maStartPoint;\n maEndPoint = rBezier.maEndPoint;\n maControlPointA = rBezier.maControlPointA;\n maControlPointB = rBezier.maControlPointB;\n\n return *this;\n }\n\n \/\/ compare operators\n bool B2DCubicBezier::operator==(const B2DCubicBezier& rBezier) const\n {\n return (\n maStartPoint == rBezier.maStartPoint\n && maEndPoint == rBezier.maEndPoint\n && maControlPointA == rBezier.maControlPointA\n && maControlPointB == rBezier.maControlPointB\n );\n }\n\n bool B2DCubicBezier::operator!=(const B2DCubicBezier& rBezier) const\n {\n return (\n maStartPoint != rBezier.maStartPoint\n || maEndPoint != rBezier.maEndPoint\n || maControlPointA != rBezier.maControlPointA\n || maControlPointB != rBezier.maControlPointB\n );\n }\n\n \/\/ test if vectors are used\n bool B2DCubicBezier::isBezier() const\n {\n if(maControlPointA != maStartPoint || maControlPointB != maEndPoint)\n {\n return true;\n }\n\n return false;\n }\n\n void B2DCubicBezier::testAndSolveTrivialBezier()\n {\n \/\/ TODO\n }\n\n double B2DCubicBezier::getEdgeLength() const\n {\n const B2DVector aEdge(maEndPoint - maStartPoint);\n return aEdge.getLength();\n }\n\n double B2DCubicBezier::getControlPolygonLength() const\n {\n const B2DVector aVectorA(maControlPointA - maStartPoint);\n const B2DVector aVectorB(maEndPoint - maControlPointB);\n const B2DVector aTop(maControlPointB - maControlPointA);\n return (aVectorA.getLength() + aVectorB.getLength() + aTop.getLength());\n }\n\n void B2DCubicBezier::adaptiveSubdivideByAngle(B2DPolygon& rTarget, double fAngleBound,\n bool bAddLastPoint, bool bAllowUnsharpen) const\n {\n \/\/ use support method #i37443# and allow unsharpen the criteria\n ImpSubDivStart(maStartPoint, maControlPointA, maControlPointB, maEndPoint,\n rTarget, fAngleBound * F_PI180, bAddLastPoint, bAllowUnsharpen);\n }\n\n \/\/ #i37443# adaptive subdivide by nCount subdivisions\n void B2DCubicBezier::adaptiveSubdivideByCount(B2DPolygon& rTarget, sal_uInt32 nCount, bool bAddLastPoint) const\n {\n rTarget.append(maStartPoint);\n\n if(nCount)\n {\n for(sal_uInt32 a(0L); a < nCount; a++)\n {\n const double fPos(double(a + 1L) \/ double(nCount + 1L));\n const B2DPoint aS1L(interpolate(maStartPoint, maControlPointA, fPos));\n const B2DPoint aS1C(interpolate(maControlPointA, maControlPointB, fPos));\n const B2DPoint aS1R(interpolate(maControlPointB, maEndPoint, fPos));\n const B2DPoint aS2L(interpolate(aS1L, aS1C, fPos));\n const B2DPoint aS2R(interpolate(aS1C, aS1R, fPos));\n const B2DPoint aS3C(interpolate(aS2L, aS2R, fPos));\n rTarget.append(aS3C);\n }\n }\n\n if(bAddLastPoint)\n {\n rTarget.append(maEndPoint);\n }\n }\n} \/\/ end of namespace basegfx\n\n\/\/ eof\nINTEGRATION: CWS ooo19126 (1.9.26); FILE MERGED 2005\/09\/05 17:38:33 rt 1.9.26.1: #i54170# Change license header: remove SISSL\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: b2dcubicbezier.cxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: rt $ $Date: 2005-09-07 20:40:27 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _BGFX_CURVE_B2DCUBICBEZIER_HXX\n#include \n#endif\n\n#ifndef _BGFX_VECTOR_B2DVECTOR_HXX\n#include \n#endif\n\n#ifndef _BGFX_POLYGON_B2DPOLYGON_HXX\n#include \n#endif\n\n#ifndef _BGFX_NUMERIC_FTOOLS_HXX\n#include \n#endif\n\n\/\/ #i37443#\n#define FACTOR_FOR_UNSHARPEN (1.6)\n#ifdef DBG_UTIL\nstatic double fMultFactUnsharpen = FACTOR_FOR_UNSHARPEN;\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace basegfx\n{\n namespace\n {\n void ImpSubDiv(\n const B2DPoint& rfPA, \/\/ start point\n const B2DPoint& rfEA, \/\/ edge on A\n const B2DPoint& rfEB, \/\/ edge on B\n const B2DPoint& rfPB, \/\/ end point\n B2DPolygon& rTarget, \/\/ target polygon\n double fAngleBound, \/\/ angle bound in [0.0 .. 2PI]\n bool bAddLastPoint, \/\/ should last point be added?\n bool bAllowUnsharpen, \/\/ #i37443# allow the criteria to get unsharp in recursions\n sal_uInt16 nMaxRecursionDepth) \/\/ endless loop protection\n {\n if(nMaxRecursionDepth)\n {\n \/\/ do angle test\n const B2DVector aLeft(rfEA - rfPA);\n const B2DVector aRight(rfEB - rfPB);\n const double fCurrentAngle(aLeft.angle(aRight));\n\n if(fabs(fCurrentAngle) > (F_PI - fAngleBound))\n {\n \/\/ end recursion\n nMaxRecursionDepth = 0;\n }\n else\n {\n if(bAllowUnsharpen)\n {\n \/\/ #i37443# unsharpen criteria\n#ifdef DBG_UTIL\n fAngleBound *= fMultFactUnsharpen;\n#else\n fAngleBound *= FACTOR_FOR_UNSHARPEN;\n#endif\n }\n }\n }\n\n if(nMaxRecursionDepth)\n {\n \/\/ divide at 0.5\n const B2DPoint aS1L(average(rfPA, rfEA));\n const B2DPoint aS1C(average(rfEA, rfEB));\n const B2DPoint aS1R(average(rfEB, rfPB));\n const B2DPoint aS2L(average(aS1L, aS1C));\n const B2DPoint aS2R(average(aS1C, aS1R));\n const B2DPoint aS3C(average(aS2L, aS2R));\n\n \/\/ left recursion\n ImpSubDiv(rfPA, aS1L, aS2L, aS3C, rTarget, fAngleBound,\n bAddLastPoint, bAllowUnsharpen, nMaxRecursionDepth - 1);\n\n \/\/ right recursion\n ImpSubDiv(aS3C, aS2R, aS1R, rfPB, rTarget, fAngleBound,\n bAddLastPoint, bAllowUnsharpen, nMaxRecursionDepth - 1);\n }\n else\n {\n \/\/ add points\n rTarget.append(rfPA);\n\n if(bAddLastPoint)\n {\n rTarget.append(rfPB);\n }\n }\n }\n\n void ImpSubDivStart(\n const B2DPoint& rfPA, \/\/ start point\n const B2DPoint& rfEA, \/\/ edge on A\n const B2DPoint& rfEB, \/\/ edge on B\n const B2DPoint& rfPB, \/\/ end point\n B2DPolygon& rTarget, \/\/ target polygon\n const double& rfAngleBound, \/\/ angle bound in [0.0 .. 2PI]\n bool bAddLastPoint, \/\/ should last point be added?\n bool bAllowUnsharpen) \/\/ #i37443# allow the criteria to get unsharp in recursions\n {\n sal_uInt16 nMaxRecursionDepth(8);\n const B2DVector aLeft(rfEA - rfPA);\n const B2DVector aRight(rfEB - rfPB);\n bool bLeftEqualZero(aLeft.equalZero());\n bool bRightEqualZero(aRight.equalZero());\n bool bAllParallel(false);\n\n if(bLeftEqualZero && bRightEqualZero)\n {\n nMaxRecursionDepth = 0;\n }\n else\n {\n const B2DVector aBase(rfPB - rfPA);\n const bool bBaseEqualZero(aLeft.equalZero());\n\n if(!bBaseEqualZero)\n {\n const bool bLeftParallel(bLeftEqualZero ? true : areParallel(aLeft, aBase));\n const bool bRightParallel(bRightEqualZero ? true : areParallel(aRight, aBase));\n\n if(bLeftParallel && bRightParallel)\n {\n bAllParallel = true;\n\n if(!bLeftEqualZero)\n {\n double fFactor;\n\n if(fabs(aBase.getX()) > fabs(aBase.getY()))\n {\n fFactor = aLeft.getX() \/ aBase.getX();\n }\n else\n {\n fFactor = aLeft.getY() \/ aBase.getY();\n }\n\n if(fFactor >= 0.0 && fFactor <= 1.0)\n {\n bLeftEqualZero = true;\n }\n }\n\n if(!bRightEqualZero)\n {\n double fFactor;\n\n if(fabs(aBase.getX()) > fabs(aBase.getY()))\n {\n fFactor = aRight.getX() \/ -aBase.getX();\n }\n else\n {\n fFactor = aRight.getY() \/ -aBase.getY();\n }\n\n if(fFactor >= 0.0 && fFactor <= 1.0)\n {\n bRightEqualZero = true;\n }\n }\n\n if(bLeftEqualZero && bRightEqualZero)\n {\n nMaxRecursionDepth = 0;\n }\n }\n }\n }\n\n if(nMaxRecursionDepth)\n {\n \/\/ divide at 0.5 ad test both edges for angle criteria\n const B2DPoint aS1L(average(rfPA, rfEA));\n const B2DPoint aS1C(average(rfEA, rfEB));\n const B2DPoint aS1R(average(rfEB, rfPB));\n const B2DPoint aS2L(average(aS1L, aS1C));\n const B2DPoint aS2R(average(aS1C, aS1R));\n const B2DPoint aS3C(average(aS2L, aS2R));\n\n \/\/ test left\n bool bAngleIsSmallerLeft(bAllParallel && bLeftEqualZero);\n if(!bAngleIsSmallerLeft)\n {\n const B2DVector aLeftLeft(aS1L - rfPA);\n const B2DVector aRightLeft(aS2L - aS3C);\n const double fCurrentAngleLeft(aLeftLeft.angle(aRightLeft));\n bAngleIsSmallerLeft = (fabs(fCurrentAngleLeft) > (F_PI - rfAngleBound));\n }\n\n \/\/ test right\n bool bAngleIsSmallerRight(bAllParallel && bRightEqualZero);\n if(!bAngleIsSmallerRight)\n {\n const B2DVector aLeftRight(aS2R - aS3C);\n const B2DVector aRightRight(aS1R - rfPB);\n const double fCurrentAngleRight(aLeftRight.angle(aRightRight));\n bAngleIsSmallerRight = (fabs(fCurrentAngleRight) > (F_PI - rfAngleBound));\n }\n\n if(bAngleIsSmallerLeft && bAngleIsSmallerRight)\n {\n \/\/ no recursion necessary at all\n nMaxRecursionDepth = 0;\n }\n else\n {\n \/\/ left\n if(bAngleIsSmallerLeft)\n {\n rTarget.append(rfPA);\n if(bAddLastPoint)\n {\n rTarget.append(aS3C);\n }\n }\n else\n {\n ImpSubDiv(rfPA, aS1L, aS2L, aS3C, rTarget, rfAngleBound,\n bAddLastPoint, bAllowUnsharpen, nMaxRecursionDepth);\n }\n\n \/\/ right\n if(bAngleIsSmallerRight)\n {\n rTarget.append(aS3C);\n if(bAddLastPoint)\n {\n rTarget.append(rfPB);\n }\n }\n else\n {\n ImpSubDiv(aS3C, aS2R, aS1R, rfPB, rTarget, rfAngleBound,\n bAddLastPoint, bAllowUnsharpen, nMaxRecursionDepth);\n }\n }\n }\n\n if(!nMaxRecursionDepth)\n {\n rTarget.append(rfPA);\n if(bAddLastPoint)\n {\n rTarget.append(rfPB);\n }\n }\n }\n } \/\/ end of anonymous namespace\n} \/\/ end of namespace basegfx\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace basegfx\n{\n B2DCubicBezier::B2DCubicBezier(const B2DCubicBezier& rBezier)\n : maStartPoint(rBezier.maStartPoint),\n maEndPoint(rBezier.maEndPoint),\n maControlPointA(rBezier.maControlPointA),\n maControlPointB(rBezier.maControlPointB)\n {\n }\n\n B2DCubicBezier::B2DCubicBezier()\n {\n }\n\n B2DCubicBezier::B2DCubicBezier(const B2DPoint& rStart, const B2DPoint& rEnd)\n : maStartPoint(rStart),\n maEndPoint(rEnd),\n maControlPointA(rStart),\n maControlPointB(rEnd)\n {\n }\n\n B2DCubicBezier::B2DCubicBezier(const B2DPoint& rStart, const B2DPoint& rControlPointA,\n const B2DPoint& rControlPointB, const B2DPoint& rEnd)\n : maStartPoint(rStart),\n maEndPoint(rEnd),\n maControlPointA(rControlPointA),\n maControlPointB(rControlPointB)\n {\n }\n\n B2DCubicBezier::~B2DCubicBezier()\n {\n }\n\n \/\/ assignment operator\n B2DCubicBezier& B2DCubicBezier::operator=(const B2DCubicBezier& rBezier)\n {\n maStartPoint = rBezier.maStartPoint;\n maEndPoint = rBezier.maEndPoint;\n maControlPointA = rBezier.maControlPointA;\n maControlPointB = rBezier.maControlPointB;\n\n return *this;\n }\n\n \/\/ compare operators\n bool B2DCubicBezier::operator==(const B2DCubicBezier& rBezier) const\n {\n return (\n maStartPoint == rBezier.maStartPoint\n && maEndPoint == rBezier.maEndPoint\n && maControlPointA == rBezier.maControlPointA\n && maControlPointB == rBezier.maControlPointB\n );\n }\n\n bool B2DCubicBezier::operator!=(const B2DCubicBezier& rBezier) const\n {\n return (\n maStartPoint != rBezier.maStartPoint\n || maEndPoint != rBezier.maEndPoint\n || maControlPointA != rBezier.maControlPointA\n || maControlPointB != rBezier.maControlPointB\n );\n }\n\n \/\/ test if vectors are used\n bool B2DCubicBezier::isBezier() const\n {\n if(maControlPointA != maStartPoint || maControlPointB != maEndPoint)\n {\n return true;\n }\n\n return false;\n }\n\n void B2DCubicBezier::testAndSolveTrivialBezier()\n {\n \/\/ TODO\n }\n\n double B2DCubicBezier::getEdgeLength() const\n {\n const B2DVector aEdge(maEndPoint - maStartPoint);\n return aEdge.getLength();\n }\n\n double B2DCubicBezier::getControlPolygonLength() const\n {\n const B2DVector aVectorA(maControlPointA - maStartPoint);\n const B2DVector aVectorB(maEndPoint - maControlPointB);\n const B2DVector aTop(maControlPointB - maControlPointA);\n return (aVectorA.getLength() + aVectorB.getLength() + aTop.getLength());\n }\n\n void B2DCubicBezier::adaptiveSubdivideByAngle(B2DPolygon& rTarget, double fAngleBound,\n bool bAddLastPoint, bool bAllowUnsharpen) const\n {\n \/\/ use support method #i37443# and allow unsharpen the criteria\n ImpSubDivStart(maStartPoint, maControlPointA, maControlPointB, maEndPoint,\n rTarget, fAngleBound * F_PI180, bAddLastPoint, bAllowUnsharpen);\n }\n\n \/\/ #i37443# adaptive subdivide by nCount subdivisions\n void B2DCubicBezier::adaptiveSubdivideByCount(B2DPolygon& rTarget, sal_uInt32 nCount, bool bAddLastPoint) const\n {\n rTarget.append(maStartPoint);\n\n if(nCount)\n {\n for(sal_uInt32 a(0L); a < nCount; a++)\n {\n const double fPos(double(a + 1L) \/ double(nCount + 1L));\n const B2DPoint aS1L(interpolate(maStartPoint, maControlPointA, fPos));\n const B2DPoint aS1C(interpolate(maControlPointA, maControlPointB, fPos));\n const B2DPoint aS1R(interpolate(maControlPointB, maEndPoint, fPos));\n const B2DPoint aS2L(interpolate(aS1L, aS1C, fPos));\n const B2DPoint aS2R(interpolate(aS1C, aS1R, fPos));\n const B2DPoint aS3C(interpolate(aS2L, aS2R, fPos));\n rTarget.append(aS3C);\n }\n }\n\n if(bAddLastPoint)\n {\n rTarget.append(maEndPoint);\n }\n }\n} \/\/ end of namespace basegfx\n\n\/\/ eof\n<|endoftext|>"} {"text":"Fix flipped sign in BoundingBox::contains().<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2014 Tobias Klauser\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\/\n\n#ifndef __BINSEARCH_CLOSEST_HPP__\n#define __BINSEARCH_CLOSEST_HPP__\n\n#include \n\n\/** Binary search for the closest value in a vector.\n *\n * This function assumes the vector to be sorted. If the value is outside\n * the range of the vector, it is clamped accordingly. If several elements\n * in the vector are equally close, the first one is returned.\n *\n * @param vec\n * The sorted vector to search.\n * @param val\n * Scalar value for which to search the closest element in the vector.\n * @return\n * Index of the element in the vector that is closest to val or -1 if the\n * vector contains no elements.\n *\/\ntemplate\nssize_t binsearch_closest(const std::vector vec, T val)\n{\n\t\/\/ empty vector\n\tif (vec.size() < 1)\n\t return -1;\n\n\t\/\/ clamp value to range of vector\n\tif (val < vec.at(0))\n\t\treturn 0;\n\tif (val > vec.at(vec.size() - 1))\n\t\treturn vec.size() - 1;\n\n\tsize_t imin = 0;\n\tsize_t imax = vec.size() - 1;\n\twhile (imax - imin > 1) {\n\t\t\/\/ determine midpoint, prevent integer overflow\n\t\tsize_t imid = imin + ((imax - imin) \/ 2);\n\t\tif (vec.at(imid) >= val)\n\t\t\timax = imid;\n\t\telse\n\t\t\timin = imid;\n\t}\n\n\tif (imax - imin == 1 && std::abs(vec.at(imax) - val) < std::abs(vec.at(imin) - val))\n\t\timin = imax;\n\n\treturn (ssize_t)imin;\n}\n\n#endif \/* __BINSEARCH_CLOSEST_HPP__ *\/\nbinsearch_closest: Fix spacing\/*\n * Copyright (c) 2014 Tobias Klauser\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\/\n\n#ifndef __BINSEARCH_CLOSEST_HPP__\n#define __BINSEARCH_CLOSEST_HPP__\n\n#include \n\n\/** Binary search for the closest value in a vector.\n *\n * This function assumes the vector to be sorted. If the value is outside\n * the range of the vector, it is clamped accordingly. If several elements\n * in the vector are equally close, the first one is returned.\n *\n * @param vec\n * The sorted vector to search.\n * @param val\n * Scalar value for which to search the closest element in the vector.\n * @return\n * Index of the element in the vector that is closest to val or -1 if the\n * vector contains no elements.\n *\/\ntemplate\nssize_t binsearch_closest(const std::vector vec, T val)\n{\n\t\/\/ empty vector\n\tif (vec.size() < 1)\n\t return -1;\n\n\t\/\/ clamp value to range of vector\n\tif (val < vec.at(0))\n\t\treturn 0;\n\tif (val > vec.at(vec.size() - 1))\n\t\treturn vec.size() - 1;\n\n\tsize_t imin = 0;\n\tsize_t imax = vec.size() - 1;\n\twhile (imax - imin > 1) {\n\t\t\/\/ determine midpoint, prevent integer overflow\n\t\tsize_t imid = imin + ((imax - imin) \/ 2);\n\t\tif (vec.at(imid) >= val)\n\t\t\timax = imid;\n\t\telse\n\t\t\timin = imid;\n\t}\n\n\tif (imax - imin == 1 && std::abs(vec.at(imax) - val) < std::abs(vec.at(imin) - val))\n\t\timin = imax;\n\n\treturn (ssize_t)imin;\n}\n\n#endif \/* __BINSEARCH_CLOSEST_HPP__ *\/\n<|endoftext|>"} {"text":"#include \"time_grid.h\"\n\nTime_grid::Time_grid( Config &conf ) \n{\n check_correctness_of_related_config_fields( conf );\n get_values_from_config( conf );\n init_total_nodes();\n shrink_time_step_size_if_necessary( conf ); \n shrink_time_save_step_if_necessary( conf ); \n set_current_time_and_node();\n}\n\nTime_grid::Time_grid( hid_t h5_time_grid_group )\n{ \n herr_t status;\n status = H5LTget_attribute_double( h5_time_grid_group, \".\/\",\n\t\t\t\t \"total_time\", &total_time ); hdf5_status_check( status );\n status = H5LTget_attribute_double( h5_time_grid_group, \".\/\",\n\t\t\t\t \"current_time\", ¤t_time ); hdf5_status_check( status );\n status = H5LTget_attribute_double( h5_time_grid_group, \".\/\",\n\t\t\t\t \"time_step_size\", &time_step_size ); hdf5_status_check( status );\n status = H5LTget_attribute_double( h5_time_grid_group, \".\/\",\n\t\t\t\t \"time_save_step\", &time_save_step ); hdf5_status_check( status );\n status = H5LTget_attribute_int( h5_time_grid_group, \".\/\",\n\t\t\t\t \"total_nodes\", &total_nodes ); hdf5_status_check( status );\n status = H5LTget_attribute_int( h5_time_grid_group, \".\/\",\n\t\t\t\t \"current_node\", ¤t_node ); hdf5_status_check( status );\n status = H5LTget_attribute_int( h5_time_grid_group, \".\/\",\n\t\t\t\t \"node_to_save\", &node_to_save ); hdf5_status_check( status );\n\n status = H5Gclose(h5_time_grid_group); hdf5_status_check( status );\n}\n\nvoid Time_grid::check_correctness_of_related_config_fields( Config &conf )\n{\n total_time_gt_zero( conf );\n time_step_size_gt_zero_le_total_time( conf );\n time_save_step_ge_time_step_size( conf );\n}\n\nvoid Time_grid::get_values_from_config( Config &conf )\n{\n total_time = conf.time_config_part.total_time;\n time_step_size = conf.time_config_part.time_step_size; \n time_save_step = conf.time_config_part.time_save_step;\n}\n\nvoid Time_grid::init_total_nodes()\n{\n total_nodes = ceil( total_time \/ time_step_size ) + 1; \n}\n\nvoid Time_grid::shrink_time_step_size_if_necessary( Config &conf )\n{\n time_step_size = total_time \/ ( total_nodes - 1 );\n if ( time_step_size != conf.time_config_part.time_step_size ) {\n\tstd::cout.precision(3);\n\tstd::cout << \"Time step was shrinked to \" << time_step_size \n\t\t << \" from \" << conf.time_config_part.time_step_size \n\t\t << \" to fit round number of cells.\" \n\t\t << std::endl;\n }\n}\n\nvoid Time_grid::shrink_time_save_step_if_necessary( Config &conf )\n{\n time_save_step = ( (int)( time_save_step \/ time_step_size ) ) * time_step_size; \n if ( time_save_step != conf.time_config_part.time_save_step ) { \n\tstd::cout.precision(3);\n\tstd::cout << \"Time save step was shrinked to \" << time_save_step \n\t\t << \" from \" << conf.time_config_part.time_save_step \n\t\t << \" to be a multiple of time step.\"\n\t\t << std::endl;\n }\n node_to_save = (int) ( time_save_step \/ time_step_size );\n}\n\nvoid Time_grid::set_current_time_and_node()\n{\n current_time = 0.0;\n current_node = 0;\n}\n\nvoid Time_grid::update_to_next_step()\n{\n current_node++;\n current_time += time_step_size;\n}\n\nvoid Time_grid::print( )\n{\n std::cout << \"### Time grid:\" << std::endl;\n std::cout << \"Total time = \" << total_time << std::endl;\n std::cout << \"Current time = \" << current_time << std::endl;\n std::cout << \"Time step size = \" << time_step_size << std::endl;\n std::cout << \"Time save step = \" << time_save_step << std::endl;\n std::cout << \"Total nodes = \" << total_nodes << std::endl;\n std::cout << \"Current node = \" << current_node << std::endl;\n std::cout << \"Node to save = \" << node_to_save << std::endl;\n return;\n}\n\nvoid Time_grid::write_to_file( hid_t hdf5_file_id )\n{\n hid_t group_id;\n herr_t status;\n int single_element = 1;\n std::string hdf5_groupname = \"\/Time_grid\";\n group_id = H5Gcreate( hdf5_file_id, hdf5_groupname.c_str(),\n\t\t\t H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); hdf5_status_check( group_id );\n\n status = H5LTset_attribute_double( hdf5_file_id, hdf5_groupname.c_str(),\n\t\t\t\t \"total_time\", &total_time, single_element ); hdf5_status_check( status );\n status = H5LTset_attribute_double( hdf5_file_id, hdf5_groupname.c_str(),\n\t\t\t\t \"current_time\", ¤t_time, single_element ); hdf5_status_check( status );\n status = H5LTset_attribute_double( hdf5_file_id, hdf5_groupname.c_str(),\n\t\t\t\t \"time_step_size\", &time_step_size, single_element ); hdf5_status_check( status );\n status = H5LTset_attribute_double( hdf5_file_id, hdf5_groupname.c_str(),\n\t\t\t\t \"time_save_step\", &time_save_step, single_element ); hdf5_status_check( status );\n status = H5LTset_attribute_int( hdf5_file_id, hdf5_groupname.c_str(),\n\t\t\t\t \"total_nodes\", &total_nodes, single_element ); hdf5_status_check( status );\n status = H5LTset_attribute_int( hdf5_file_id, hdf5_groupname.c_str(),\n\t\t\t\t \"current_node\", ¤t_node, single_element ); hdf5_status_check( status );\n status = H5LTset_attribute_int( hdf5_file_id, hdf5_groupname.c_str(),\n\t\t\t\t \"node_to_save\", &node_to_save, single_element ); hdf5_status_check( status );\n\t\n status = H5Gclose(group_id); hdf5_status_check( status );\n return;\n}\n\nvoid Time_grid::hdf5_status_check( herr_t status )\n{\n if( status < 0 ){\n\tstd::cout << \"Something went wrong while writing Time_grid group. Aborting.\"\n\t\t << std::endl;\n\texit( EXIT_FAILURE );\n }\n}\n\nvoid Time_grid::total_time_gt_zero( Config &conf )\n{\n check_and_exit_if_not( \n\tconf.time_config_part.total_time >= 0, \n\t\"total_time < 0\" );\n}\n\nvoid Time_grid::time_step_size_gt_zero_le_total_time( Config &conf )\n{\n check_and_exit_if_not( \n\t( conf.time_config_part.time_step_size > 0 ) && \n\t( conf.time_config_part.time_step_size <= conf.time_config_part.total_time ),\n\t\"time_step_size <= 0 or time_step_size > total_time\" );\n return;\n}\n\nvoid Time_grid::time_save_step_ge_time_step_size( Config &conf )\n{\n check_and_exit_if_not( \n\tconf.time_config_part.time_save_step >= conf.time_config_part.time_step_size,\n\t\"time_save_step < time_step_size\" );\n return;\n}\n\nvoid Time_grid::check_and_exit_if_not( const bool &should_be, const std::string &message )\n{\n if( !should_be ){\n\tstd::cout << \"Error: \" + message << std::endl;\n\texit( EXIT_FAILURE );\n }\n return;\n}\n.\/Time_grid -> .\/TimeGrid in h5#include \"time_grid.h\"\n\nTime_grid::Time_grid( Config &conf ) \n{\n check_correctness_of_related_config_fields( conf );\n get_values_from_config( conf );\n init_total_nodes();\n shrink_time_step_size_if_necessary( conf ); \n shrink_time_save_step_if_necessary( conf ); \n set_current_time_and_node();\n}\n\nTime_grid::Time_grid( hid_t h5_time_grid_group )\n{ \n herr_t status;\n status = H5LTget_attribute_double( h5_time_grid_group, \".\/\",\n\t\t\t\t \"total_time\", &total_time ); hdf5_status_check( status );\n status = H5LTget_attribute_double( h5_time_grid_group, \".\/\",\n\t\t\t\t \"current_time\", ¤t_time ); hdf5_status_check( status );\n status = H5LTget_attribute_double( h5_time_grid_group, \".\/\",\n\t\t\t\t \"time_step_size\", &time_step_size ); hdf5_status_check( status );\n status = H5LTget_attribute_double( h5_time_grid_group, \".\/\",\n\t\t\t\t \"time_save_step\", &time_save_step ); hdf5_status_check( status );\n status = H5LTget_attribute_int( h5_time_grid_group, \".\/\",\n\t\t\t\t \"total_nodes\", &total_nodes ); hdf5_status_check( status );\n status = H5LTget_attribute_int( h5_time_grid_group, \".\/\",\n\t\t\t\t \"current_node\", ¤t_node ); hdf5_status_check( status );\n status = H5LTget_attribute_int( h5_time_grid_group, \".\/\",\n\t\t\t\t \"node_to_save\", &node_to_save ); hdf5_status_check( status );\n\n status = H5Gclose(h5_time_grid_group); hdf5_status_check( status );\n}\n\nvoid Time_grid::check_correctness_of_related_config_fields( Config &conf )\n{\n total_time_gt_zero( conf );\n time_step_size_gt_zero_le_total_time( conf );\n time_save_step_ge_time_step_size( conf );\n}\n\nvoid Time_grid::get_values_from_config( Config &conf )\n{\n total_time = conf.time_config_part.total_time;\n time_step_size = conf.time_config_part.time_step_size; \n time_save_step = conf.time_config_part.time_save_step;\n}\n\nvoid Time_grid::init_total_nodes()\n{\n total_nodes = ceil( total_time \/ time_step_size ) + 1; \n}\n\nvoid Time_grid::shrink_time_step_size_if_necessary( Config &conf )\n{\n time_step_size = total_time \/ ( total_nodes - 1 );\n if ( time_step_size != conf.time_config_part.time_step_size ) {\n\tstd::cout.precision(3);\n\tstd::cout << \"Time step was shrinked to \" << time_step_size \n\t\t << \" from \" << conf.time_config_part.time_step_size \n\t\t << \" to fit round number of cells.\" \n\t\t << std::endl;\n }\n}\n\nvoid Time_grid::shrink_time_save_step_if_necessary( Config &conf )\n{\n time_save_step = ( (int)( time_save_step \/ time_step_size ) ) * time_step_size; \n if ( time_save_step != conf.time_config_part.time_save_step ) { \n\tstd::cout.precision(3);\n\tstd::cout << \"Time save step was shrinked to \" << time_save_step \n\t\t << \" from \" << conf.time_config_part.time_save_step \n\t\t << \" to be a multiple of time step.\"\n\t\t << std::endl;\n }\n node_to_save = (int) ( time_save_step \/ time_step_size );\n}\n\nvoid Time_grid::set_current_time_and_node()\n{\n current_time = 0.0;\n current_node = 0;\n}\n\nvoid Time_grid::update_to_next_step()\n{\n current_node++;\n current_time += time_step_size;\n}\n\nvoid Time_grid::print( )\n{\n std::cout << \"### Time grid:\" << std::endl;\n std::cout << \"Total time = \" << total_time << std::endl;\n std::cout << \"Current time = \" << current_time << std::endl;\n std::cout << \"Time step size = \" << time_step_size << std::endl;\n std::cout << \"Time save step = \" << time_save_step << std::endl;\n std::cout << \"Total nodes = \" << total_nodes << std::endl;\n std::cout << \"Current node = \" << current_node << std::endl;\n std::cout << \"Node to save = \" << node_to_save << std::endl;\n return;\n}\n\nvoid Time_grid::write_to_file( hid_t hdf5_file_id )\n{\n hid_t group_id;\n herr_t status;\n int single_element = 1;\n std::string hdf5_groupname = \"\/TimeGrid\";\n group_id = H5Gcreate( hdf5_file_id, hdf5_groupname.c_str(),\n\t\t\t H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); hdf5_status_check( group_id );\n\n status = H5LTset_attribute_double( hdf5_file_id, hdf5_groupname.c_str(),\n\t\t\t\t \"total_time\", &total_time, single_element ); hdf5_status_check( status );\n status = H5LTset_attribute_double( hdf5_file_id, hdf5_groupname.c_str(),\n\t\t\t\t \"current_time\", ¤t_time, single_element ); hdf5_status_check( status );\n status = H5LTset_attribute_double( hdf5_file_id, hdf5_groupname.c_str(),\n\t\t\t\t \"time_step_size\", &time_step_size, single_element ); hdf5_status_check( status );\n status = H5LTset_attribute_double( hdf5_file_id, hdf5_groupname.c_str(),\n\t\t\t\t \"time_save_step\", &time_save_step, single_element ); hdf5_status_check( status );\n status = H5LTset_attribute_int( hdf5_file_id, hdf5_groupname.c_str(),\n\t\t\t\t \"total_nodes\", &total_nodes, single_element ); hdf5_status_check( status );\n status = H5LTset_attribute_int( hdf5_file_id, hdf5_groupname.c_str(),\n\t\t\t\t \"current_node\", ¤t_node, single_element ); hdf5_status_check( status );\n status = H5LTset_attribute_int( hdf5_file_id, hdf5_groupname.c_str(),\n\t\t\t\t \"node_to_save\", &node_to_save, single_element ); hdf5_status_check( status );\n\t\n status = H5Gclose(group_id); hdf5_status_check( status );\n return;\n}\n\nvoid Time_grid::hdf5_status_check( herr_t status )\n{\n if( status < 0 ){\n\tstd::cout << \"Something went wrong while writing Time_grid group. Aborting.\"\n\t\t << std::endl;\n\texit( EXIT_FAILURE );\n }\n}\n\nvoid Time_grid::total_time_gt_zero( Config &conf )\n{\n check_and_exit_if_not( \n\tconf.time_config_part.total_time >= 0, \n\t\"total_time < 0\" );\n}\n\nvoid Time_grid::time_step_size_gt_zero_le_total_time( Config &conf )\n{\n check_and_exit_if_not( \n\t( conf.time_config_part.time_step_size > 0 ) && \n\t( conf.time_config_part.time_step_size <= conf.time_config_part.total_time ),\n\t\"time_step_size <= 0 or time_step_size > total_time\" );\n return;\n}\n\nvoid Time_grid::time_save_step_ge_time_step_size( Config &conf )\n{\n check_and_exit_if_not( \n\tconf.time_config_part.time_save_step >= conf.time_config_part.time_step_size,\n\t\"time_save_step < time_step_size\" );\n return;\n}\n\nvoid Time_grid::check_and_exit_if_not( const bool &should_be, const std::string &message )\n{\n if( !should_be ){\n\tstd::cout << \"Error: \" + message << std::endl;\n\texit( EXIT_FAILURE );\n }\n return;\n}\n<|endoftext|>"} {"text":"\/\/ vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:\n\/*\nCopyright (c) 2009 Aristid Breitkreuz, Ash Berlin, Ruediger Sonderfeld\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#ifndef FLUSSFPERD_CLASS_DESCRIPTION_HPP\n#define FLUSSFPERD_CLASS_DESCRIPTION_HPP\n\n#ifndef PREPROC_DEBUG\n#include \"class.hpp\"\n#include \"native_object_base.hpp\"\n#endif\n#include \n\n\/* 2-tuple seq *\/\n\n#define FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS2(x, y) \\\n ((x, y)) \\\n FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS\n\n#define FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS(x, y) \\\n ((x, y)) \\\n FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS2\n\n#define FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS_ELIM\n#define FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS2_ELIM\n\n#define FLUSSPFERD_PP_GEN_TUPLE2SEQ(x) \\\n BOOST_PP_CAT(FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS x, _ELIM)\n\n\/* 3-tuple seq *\/\n\n#define FLUSSPFERD_PP_GEN_TUPLE3SEQ_PROCESS2(x, y, z) \\\n ((x, y, z)) \\\n FLUSSPFERD_PP_GEN_TUPLE3SEQ_PROCESS\n\n#define FLUSSPFERD_PP_GEN_TUPLE3SEQ_PROCESS(x, y, z) \\\n ((x, y, z)) \\\n FLUSSPFERD_PP_GEN_TUPLE3SEQ_PROCESS2\n\n#define FLUSSPFERD_PP_GEN_TUPLE3SEQ_PROCESS_ELIM\n#define FLUSSPFERD_PP_GEN_TUPLE3SEQ_PROCESS2_ELIM\n\n#define FLUSSPFERD_PP_GEN_TUPLE3SEQ(x) \\\n BOOST_PP_CAT(FLUSSPFERD_PP_GEN_TUPLE3SEQ_PROCESS x, _ELIM)\n\n\/* -- *\/\n\n#define FLUSSPFERD_CD_PARAM_FOLD(s, state, elem) \\\n BOOST_PP_ARRAY_REPLACE( \\\n state, \\\n BOOST_PP_EXPAND( \\\n BOOST_PP_CAT(FLUSSPFERD_CD_PARAM__, \\\n BOOST_PP_TUPLE_ELEM(2, 0, elem))), \\\n BOOST_PP_TUPLE_ELEM(2, 1, elem)) \\\n \/* *\/\n\n#define FLUSSPFERD_CD_PARAM_INITIAL \\\n (11, ( \\\n ~cpp_name~, \/* name *\/ \\\n ~constructor_name~, \/* constructor name *\/ \\\n 0, \/* constructor arity *\/ \\\n ~full_name~, \/* full name *\/ \\\n ~methods~, \/* methods *\/ \\\n 0, \/* NO methods *\/ \\\n 0, \/* augment constructor (custom func.)*\/ \\\n true, \/* constructible *\/ \\\n false, \/* custom enumerate *\/ \\\n ::flusspferd::native_object_base, \/* base class *\/ \\\n 0 \/* augment prototype (custom func.) *\/ \\\n )) \\\n \/* *\/\n\n#define FLUSSPFERD_CD_PARAM__cpp_name 0\n#define FLUSSPFERD_CD_PARAM__constructor_name 1\n#define FLUSSPFERD_CD_PARAM__constructor_arity 2\n#define FLUSSPFERD_CD_PARAM__full_name 3\n#define FLUSSPFERD_CD_PARAM__methods 4\n#define FLUSSPFERD_CD_PARAM__no_methods 5\n#define FLUSSPFERD_CD_PARAM__augment_constructor 6\n#define FLUSSPFERD_CD_PARAM__constructible 7\n#define FLUSSPFERD_CD_PARAM__custom_enumerate 8\n#define FLUSSPFERD_CD_PARAM__base 9\n#define FLUSSPFERD_CD_PARAM__augment_prototype 10\n\n#define FLUSSPFERD_CD_PARAM(tuple_seq) \\\n BOOST_PP_SEQ_FOLD_LEFT( \\\n FLUSSPFERD_CD_PARAM_FOLD, \\\n FLUSSPFERD_CD_PARAM_INITIAL, \\\n FLUSSPFERD_PP_GEN_TUPLE2SEQ(tuple_seq) \\\n ) \\\n \/* *\/\n\n#define FLUSSPFERD_CLASS_DESCRIPTION_A(array) \\\n BOOST_PP_EXPAND(FLUSSPFERD_CLASS_DESCRIPTION_P BOOST_PP_ARRAY_DATA(array)) \\\n \/* *\/\n\n#define FLUSSPFERD_CLASS_DESCRIPTION_P( \\\n p_cpp_name, \\\n p_constructor_name, \\\n p_constructor_arity, \\\n p_full_name, \\\n p_methods, \\\n p_no_methods, \\\n p_augment_constructor, \\\n p_constructible, \\\n p_custom_enumerate, \\\n p_base, \\\n p_augment_prototype \\\n) \\\n class p_cpp_name : public p_base { \\\n public: \\\n struct class_info : ::flusspferd::class_info { \\\n typedef boost::mpl::bool_< (p_constructible) > constructible; \\\n static char const *constructor_name() { \\\n return (p_constructor_name); \\\n } \\\n typedef ::boost::mpl::size_t< (p_constructor_arity) > constructor_arity; \\\n static char const *full_name() { \\\n return (p_full_name); \\\n } \\\n static ::flusspferd::object create_prototype() { \\\n ::flusspferd::object proto = ::flusspferd::create_object( \\\n ::flusspferd::prototype< p_base >() \\\n ); \\\n BOOST_PP_IF( \\\n p_no_methods, \\\n BOOST_PP_TUPLE_EAT(2), \\\n FLUSSPFERD_CD_METHODS \\\n ) (p_cpp_name, p_methods) \\\n BOOST_PP_EXPR_IF( \\\n p_augment_prototype, \\\n p_cpp_name :: augment_prototype(proto);) \\\n return proto; \\\n } \\\n static void augment_constructor(::flusspferd::object &o) { \\\n (void)o; \\\n BOOST_PP_EXPR_IF( \\\n p_augment_constructor, \\\n p_cpp_name :: augment_constructor(o);) \\\n } \\\n typedef boost::mpl::bool_< (p_custom_enumerate) > custom_enumerate; \\\n }; \\\n BOOST_PP_EXPR_IF( \\\n p_augment_constructor, \\\n static void augment_constructor(::flusspferd::object &o);) \\\n BOOST_PP_EXPR_IF( \\\n p_augment_prototype, \\\n static void augment_prototype(::flusspferd::object &proto);) \\\n private: \\\n \/* *\/\n\n#define FLUSSPFERD_CD_METHODS(p_cpp_name, p_methods) \\\n BOOST_PP_SEQ_FOR_EACH( \\\n FLUSSPFERD_CD_METHOD, \\\n p_cpp_name, \\\n FLUSSPFERD_PP_GEN_TUPLE3SEQ(p_methods)) \\\n \/* *\/\n\n#define FLUSSPFERD_CD_METHOD(r, p_cpp_name, p_method) \\\n BOOST_PP_CAT( \\\n FLUSSPFERD_CD_METHOD__, \\\n BOOST_PP_TUPLE_ELEM(3, 1, p_method) \\\n ) ( \\\n p_cpp_name, \\\n BOOST_PP_TUPLE_ELEM(3, 0, p_method), \\\n BOOST_PP_TUPLE_ELEM(3, 2, p_method) \\\n ) \\\n \/* *\/\n\n#define FLUSSPFERD_CD_METHOD__bind(p_cpp_name, p_method_name, p_bound) \\\n ::flusspferd::create_native_method( \\\n proto, \\\n (p_method_name), \\\n & p_cpp_name :: p_bound); \\\n \/* *\/\n\n#define FLUSSPFERD_CD_METHOD__alias(p_cpp_name, p_method_name, p_alias) \\\n proto.define_property( \\\n (p_method_name), \\\n proto.get_property((p_alias)), \\\n ::flusspferd::dont_enumerate); \\\n \/* *\/\n\n#define FLUSSPFERD_CLASS_DESCRIPTION(tuple_seq) \\\n FLUSSPFERD_CLASS_DESCRIPTION_A(FLUSSPFERD_CD_PARAM(tuple_seq)) \\\n \/* *\/\n\n#define FLUSSPFERD_CLASS_DESCRIPTION_END() \\\n }; \\\n \/* *\/\n\n#endif\nclass_macros: reorder parameters\/\/ vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:\n\/*\nCopyright (c) 2009 Aristid Breitkreuz, Ash Berlin, Ruediger Sonderfeld\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#ifndef FLUSSFPERD_CLASS_DESCRIPTION_HPP\n#define FLUSSFPERD_CLASS_DESCRIPTION_HPP\n\n#ifndef PREPROC_DEBUG\n#include \"class.hpp\"\n#include \"native_object_base.hpp\"\n#endif\n#include \n\n\/* 2-tuple seq *\/\n\n#define FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS2(x, y) \\\n ((x, y)) \\\n FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS\n\n#define FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS(x, y) \\\n ((x, y)) \\\n FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS2\n\n#define FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS_ELIM\n#define FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS2_ELIM\n\n#define FLUSSPFERD_PP_GEN_TUPLE2SEQ(x) \\\n BOOST_PP_CAT(FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS x, _ELIM)\n\n\/* 3-tuple seq *\/\n\n#define FLUSSPFERD_PP_GEN_TUPLE3SEQ_PROCESS2(x, y, z) \\\n ((x, y, z)) \\\n FLUSSPFERD_PP_GEN_TUPLE3SEQ_PROCESS\n\n#define FLUSSPFERD_PP_GEN_TUPLE3SEQ_PROCESS(x, y, z) \\\n ((x, y, z)) \\\n FLUSSPFERD_PP_GEN_TUPLE3SEQ_PROCESS2\n\n#define FLUSSPFERD_PP_GEN_TUPLE3SEQ_PROCESS_ELIM\n#define FLUSSPFERD_PP_GEN_TUPLE3SEQ_PROCESS2_ELIM\n\n#define FLUSSPFERD_PP_GEN_TUPLE3SEQ(x) \\\n BOOST_PP_CAT(FLUSSPFERD_PP_GEN_TUPLE3SEQ_PROCESS x, _ELIM)\n\n\/* -- *\/\n\n#define FLUSSPFERD_CD_PARAM_FOLD(s, state, elem) \\\n BOOST_PP_ARRAY_REPLACE( \\\n state, \\\n BOOST_PP_EXPAND( \\\n BOOST_PP_CAT(FLUSSPFERD_CD_PARAM__, \\\n BOOST_PP_TUPLE_ELEM(2, 0, elem))), \\\n BOOST_PP_TUPLE_ELEM(2, 1, elem)) \\\n \/* *\/\n\n#define FLUSSPFERD_CD_PARAM_INITIAL \\\n (11, ( \\\n ~cpp_name~, \/* name *\/ \\\n ::flusspferd::native_object_base, \/* base class *\/ \\\n ~constructor_name~, \/* constructor name *\/ \\\n 0, \/* constructor arity *\/ \\\n true, \/* constructible *\/ \\\n ~full_name~, \/* full name *\/ \\\n ~methods~, \/* methods *\/ \\\n 0, \/* NO methods *\/ \\\n false, \/* custom enumerate *\/ \\\n 0, \/* augment constructor (custom func.)*\/\\\n 0 \/* augment prototype (custom func.) *\/ \\\n )) \\\n \/* *\/\n\n#define FLUSSPFERD_CD_PARAM__cpp_name 0\n#define FLUSSPFERD_CD_PARAM__base 1\n#define FLUSSPFERD_CD_PARAM__constructor_name 2\n#define FLUSSPFERD_CD_PARAM__constructor_arity 3\n#define FLUSSPFERD_CD_PARAM__constructible 4\n#define FLUSSPFERD_CD_PARAM__full_name 5\n#define FLUSSPFERD_CD_PARAM__methods 6\n#define FLUSSPFERD_CD_PARAM__no_methods 7\n#define FLUSSPFERD_CD_PARAM__custom_enumerate 8\n#define FLUSSPFERD_CD_PARAM__augment_constructor 9\n#define FLUSSPFERD_CD_PARAM__augment_prototype 10\n\n#define FLUSSPFERD_CD_PARAM(tuple_seq) \\\n BOOST_PP_SEQ_FOLD_LEFT( \\\n FLUSSPFERD_CD_PARAM_FOLD, \\\n FLUSSPFERD_CD_PARAM_INITIAL, \\\n FLUSSPFERD_PP_GEN_TUPLE2SEQ(tuple_seq) \\\n ) \\\n \/* *\/\n\n#define FLUSSPFERD_CLASS_DESCRIPTION_A(array) \\\n BOOST_PP_EXPAND(FLUSSPFERD_CLASS_DESCRIPTION_P BOOST_PP_ARRAY_DATA(array)) \\\n \/* *\/\n\n#define FLUSSPFERD_CLASS_DESCRIPTION_P( \\\n p_cpp_name, \\\n p_base, \\\n p_constructor_name, \\\n p_constructor_arity, \\\n p_constructible, \\\n p_full_name, \\\n p_methods, \\\n p_no_methods, \\\n p_custom_enumerate, \\\n p_augment_constructor, \\\n p_augment_prototype \\\n) \\\n class p_cpp_name : public p_base { \\\n public: \\\n struct class_info : ::flusspferd::class_info { \\\n typedef boost::mpl::bool_< (p_constructible) > constructible; \\\n static char const *constructor_name() { \\\n return (p_constructor_name); \\\n } \\\n typedef ::boost::mpl::size_t< (p_constructor_arity) > constructor_arity; \\\n static char const *full_name() { \\\n return (p_full_name); \\\n } \\\n static ::flusspferd::object create_prototype() { \\\n ::flusspferd::object proto = ::flusspferd::create_object( \\\n ::flusspferd::prototype< p_base >() \\\n ); \\\n BOOST_PP_IF( \\\n p_no_methods, \\\n BOOST_PP_TUPLE_EAT(2), \\\n FLUSSPFERD_CD_METHODS \\\n ) (p_cpp_name, p_methods) \\\n BOOST_PP_EXPR_IF( \\\n p_augment_prototype, \\\n p_cpp_name :: augment_prototype(proto);) \\\n return proto; \\\n } \\\n static void augment_constructor(::flusspferd::object &o) { \\\n (void)o; \\\n BOOST_PP_EXPR_IF( \\\n p_augment_constructor, \\\n p_cpp_name :: augment_constructor(o);) \\\n } \\\n typedef boost::mpl::bool_< (p_custom_enumerate) > custom_enumerate; \\\n }; \\\n BOOST_PP_EXPR_IF( \\\n p_augment_constructor, \\\n static void augment_constructor(::flusspferd::object &o);) \\\n BOOST_PP_EXPR_IF( \\\n p_augment_prototype, \\\n static void augment_prototype(::flusspferd::object &proto);) \\\n private: \\\n \/* *\/\n\n#define FLUSSPFERD_CD_METHODS(p_cpp_name, p_methods) \\\n BOOST_PP_SEQ_FOR_EACH( \\\n FLUSSPFERD_CD_METHOD, \\\n p_cpp_name, \\\n FLUSSPFERD_PP_GEN_TUPLE3SEQ(p_methods)) \\\n \/* *\/\n\n#define FLUSSPFERD_CD_METHOD(r, p_cpp_name, p_method) \\\n BOOST_PP_CAT( \\\n FLUSSPFERD_CD_METHOD__, \\\n BOOST_PP_TUPLE_ELEM(3, 1, p_method) \\\n ) ( \\\n p_cpp_name, \\\n BOOST_PP_TUPLE_ELEM(3, 0, p_method), \\\n BOOST_PP_TUPLE_ELEM(3, 2, p_method) \\\n ) \\\n \/* *\/\n\n#define FLUSSPFERD_CD_METHOD__bind(p_cpp_name, p_method_name, p_bound) \\\n ::flusspferd::create_native_method( \\\n proto, \\\n (p_method_name), \\\n & p_cpp_name :: p_bound); \\\n \/* *\/\n\n#define FLUSSPFERD_CD_METHOD__alias(p_cpp_name, p_method_name, p_alias) \\\n proto.define_property( \\\n (p_method_name), \\\n proto.get_property((p_alias)), \\\n ::flusspferd::dont_enumerate); \\\n \/* *\/\n\n#define FLUSSPFERD_CLASS_DESCRIPTION(tuple_seq) \\\n FLUSSPFERD_CLASS_DESCRIPTION_A(FLUSSPFERD_CD_PARAM(tuple_seq)) \\\n \/* *\/\n\n#define FLUSSPFERD_CLASS_DESCRIPTION_END() \\\n }; \\\n \/* *\/\n\n#endif\n<|endoftext|>"} {"text":"\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2015 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n#ifndef MAPNIK_TEXT_LINE_POLICY_HPP\n#define MAPNIK_TEXT_LINE_POLICY_HPP\n\n#include \n#include \n\nnamespace mapnik\n{\n\nstruct text_line_policy\n{\n using params_type = label_placement::placement_params;\n\n text_line_policy(\n vertex_cache & path,\n text_layout_generator const & lg,\n double layout_width,\n params_type const & params)\n : layout_generator_(lg),\n params_(params),\n layout_width_(layout_width),\n minimum_path_length_(lg.get_text_props().minimum_path_length),\n path_(path)\n {\n }\n\n bool check_size() const\n {\n return !(\n path_.length() < minimum_path_length_ * params_.scale_factor ||\n path_.length() < layout_width_);\n }\n\n double get_spacing() const\n {\n return spacing_;\n }\n\n bool next_subpath()\n {\n if (path_.next_subpath())\n {\n spacing_ = init_spacing();\n position_tolerance_ = init_position_tolerance();\n return true;\n }\n return false;\n }\n\n bool align()\n {\n auto const & root_layout = layout_generator_.layouts_->root_layout();\n horizontal_alignment_e halign = root_layout.horizontal_alignment();\n\n \/\/ halign == H_LEFT -> don't move\n if (halign == H_MIDDLE ||\n halign == H_AUTO)\n {\n if (!path_.forward(spacing_ \/ 2.0))\n {\n return false;\n }\n }\n else if (halign == H_RIGHT)\n {\n if (!path_.forward(path_.length()))\n {\n return false;\n }\n }\n else if (halign == H_ADJUST)\n {\n if (!path_.forward(path_.length() \/ 2.0))\n {\n return false;\n }\n }\n\n double move_dx = root_layout.displacement().x;\n if (move_dx != 0.0)\n {\n vertex_cache::state state = path_.save_state();\n if (!path_.move(move_dx))\n {\n path_.restore_state(state);\n }\n }\n return true;\n }\n\n bool move(double distance)\n {\n return path_.move(distance);\n }\n\n bool forward(bool success)\n {\n return path_.forward(spacing_);\n }\n\n double position_tolerance() const\n {\n return position_tolerance_;\n }\n\n text_layout_generator const & layout_generator_;\n params_type const & params_;\n const double layout_width_;\n const double minimum_path_length_;\n vertex_cache & path_;\n double spacing_;\n double position_tolerance_;\n\nprivate:\n double init_spacing() const\n {\n double spacing = layout_generator_.get_text_props().label_spacing;\n int num_labels = 1;\n if (spacing > 0)\n {\n double count_float = path_.length() \/ (spacing * params_.scale_factor + layout_width_);\n const double epsilon = std::numeric_limits::epsilon() * count_float;\n bool round = std::abs(count_float - std::round(count_float)) < epsilon;\n num_labels = round ? std::round(count_float) : std::floor(count_float);\n }\n if (num_labels <= 0)\n {\n num_labels = 1;\n }\n return path_.length() \/ num_labels;\n }\n\n double init_position_tolerance() const\n {\n double tolerance = layout_generator_.get_text_props().label_position_tolerance * params_.scale_factor;\n if (tolerance > 0)\n {\n return tolerance;\n }\n\n auto const & root_layout = layout_generator_.layouts_->root_layout();\n horizontal_alignment_e halign = root_layout.horizontal_alignment();\n if (halign == H_ADJUST)\n {\n \/\/ Let small tolerance by default.\n return 10.0;\n }\n\n return spacing_ \/ 2.0;\n }\n};\n\nstruct text_max_line_angle_policy : text_line_policy\n{\n using params_type = label_placement::placement_params;\n\n text_max_line_angle_policy(\n vertex_cache & path,\n text_layout_generator const & lg,\n double layout_width,\n params_type const & params,\n double max_angle_diff,\n double max_angle_distance)\n : text_line_policy(path, lg, layout_width, params),\n mover_(path, max_angle_diff, max_angle_distance)\n {\n }\n\n bool move(double distance)\n {\n if (!text_line_policy::move(distance))\n {\n return false;\n }\n\n return mover_.move(distance);\n }\n\n max_line_angle_mover mover_;\n};\n\n}\/\/ns mapnik\n\n#endif \/\/ MAPNIK_TEXT_LINE_POLICY_HPP\nScale factor\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2015 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n#ifndef MAPNIK_TEXT_LINE_POLICY_HPP\n#define MAPNIK_TEXT_LINE_POLICY_HPP\n\n#include \n#include \n\nnamespace mapnik\n{\n\nstruct text_line_policy\n{\n using params_type = label_placement::placement_params;\n\n text_line_policy(\n vertex_cache & path,\n text_layout_generator const & lg,\n double layout_width,\n params_type const & params)\n : layout_generator_(lg),\n params_(params),\n layout_width_(layout_width),\n minimum_path_length_(lg.get_text_props().minimum_path_length),\n path_(path)\n {\n }\n\n bool check_size() const\n {\n return !(\n path_.length() < minimum_path_length_ * params_.scale_factor ||\n path_.length() < layout_width_);\n }\n\n double get_spacing() const\n {\n return spacing_;\n }\n\n bool next_subpath()\n {\n if (path_.next_subpath())\n {\n spacing_ = init_spacing();\n position_tolerance_ = init_position_tolerance();\n return true;\n }\n return false;\n }\n\n bool align()\n {\n auto const & root_layout = layout_generator_.layouts_->root_layout();\n horizontal_alignment_e halign = root_layout.horizontal_alignment();\n\n \/\/ halign == H_LEFT -> don't move\n if (halign == H_MIDDLE ||\n halign == H_AUTO)\n {\n if (!path_.forward(spacing_ \/ 2.0))\n {\n return false;\n }\n }\n else if (halign == H_RIGHT)\n {\n if (!path_.forward(path_.length()))\n {\n return false;\n }\n }\n else if (halign == H_ADJUST)\n {\n if (!path_.forward(path_.length() \/ 2.0))\n {\n return false;\n }\n }\n\n double move_dx = root_layout.displacement().x;\n if (move_dx != 0.0)\n {\n vertex_cache::state state = path_.save_state();\n if (!path_.move(move_dx))\n {\n path_.restore_state(state);\n }\n }\n return true;\n }\n\n bool move(double distance)\n {\n return path_.move(distance);\n }\n\n bool forward(bool success)\n {\n return path_.forward(spacing_);\n }\n\n double position_tolerance() const\n {\n return position_tolerance_;\n }\n\n text_layout_generator const & layout_generator_;\n params_type const & params_;\n const double layout_width_;\n const double minimum_path_length_;\n vertex_cache & path_;\n double spacing_;\n double position_tolerance_;\n\nprivate:\n double init_spacing() const\n {\n double spacing = layout_generator_.get_text_props().label_spacing;\n int num_labels = 1;\n if (spacing > 0)\n {\n double count_float = path_.length() \/ (spacing * params_.scale_factor + layout_width_);\n const double epsilon = std::numeric_limits::epsilon() * count_float;\n bool round = std::abs(count_float - std::round(count_float)) < epsilon;\n num_labels = round ? std::round(count_float) : std::floor(count_float);\n }\n if (num_labels <= 0)\n {\n num_labels = 1;\n }\n return path_.length() \/ num_labels;\n }\n\n double init_position_tolerance() const\n {\n double tolerance = layout_generator_.get_text_props().label_position_tolerance * params_.scale_factor;\n if (tolerance > 0)\n {\n return tolerance;\n }\n\n auto const & root_layout = layout_generator_.layouts_->root_layout();\n horizontal_alignment_e halign = root_layout.horizontal_alignment();\n if (halign == H_ADJUST)\n {\n \/\/ Let small tolerance by default.\n return 10.0 * params_.scale_factor;\n }\n\n return spacing_ \/ 2.0;\n }\n};\n\nstruct text_max_line_angle_policy : text_line_policy\n{\n using params_type = label_placement::placement_params;\n\n text_max_line_angle_policy(\n vertex_cache & path,\n text_layout_generator const & lg,\n double layout_width,\n params_type const & params,\n double max_angle_diff,\n double max_angle_distance)\n : text_line_policy(path, lg, layout_width, params),\n mover_(path, max_angle_diff, max_angle_distance)\n {\n }\n\n bool move(double distance)\n {\n if (!text_line_policy::move(distance))\n {\n return false;\n }\n\n return mover_.move(distance);\n }\n\n max_line_angle_mover mover_;\n};\n\n}\/\/ns mapnik\n\n#endif \/\/ MAPNIK_TEXT_LINE_POLICY_HPP\n<|endoftext|>"} {"text":"\/\/ Copyright (C) 2010-2012 Joshua Boyce.\r\n\/\/ See the file COPYING for copying permission.\r\n\r\n#pragma once\r\n\r\n#include \r\n#include \r\n\r\n#include \"hadesmem\/config.hpp\"\r\n\r\nnamespace hadesmem\r\n{\r\n\r\nclass Process;\r\n\r\nclass ProcessEntry;\r\n\r\nnamespace detail\r\n{\r\n\r\nstruct ProcessIteratorImpl;\r\n\r\n}\r\n\r\n\/\/ ModuleIterator satisfies the requirements of an input iterator \r\n\/\/ (C++ Standard, 24.2.1, Input Iterators [input.iterators]).\r\nclass ProcessIterator : public std::iterator\r\n{\r\npublic:\r\n ProcessIterator() HADESMEM_NOEXCEPT;\r\n\r\n explicit ProcessIterator(int dummy);\r\n \r\n reference operator*() const HADESMEM_NOEXCEPT;\r\n \r\n pointer operator->() const HADESMEM_NOEXCEPT;\r\n \r\n ProcessIterator& operator++();\r\n \r\n ProcessIterator operator++(int);\r\n \r\n bool operator==(ProcessIterator const& other) const HADESMEM_NOEXCEPT;\r\n \r\n bool operator!=(ProcessIterator const& other) const HADESMEM_NOEXCEPT;\r\n \r\nprivate:\r\n \/\/ Using a shared_ptr to provide shallow copy semantics, as \r\n \/\/ required by InputIterator.\r\n std::shared_ptr impl_;\r\n};\r\n\r\nclass ProcessList\r\n{\r\npublic:\r\n typedef ProcessIterator iterator;\r\n typedef ProcessIterator const_iterator;\r\n\r\n ProcessList() HADESMEM_NOEXCEPT;\r\n \r\n iterator begin();\r\n \r\n const_iterator begin() const;\r\n \r\n iterator end() HADESMEM_NOEXCEPT;\r\n \r\n const_iterator end() const HADESMEM_NOEXCEPT;\r\n};\r\n\r\n}\r\n* Fix comment.\/\/ Copyright (C) 2010-2012 Joshua Boyce.\r\n\/\/ See the file COPYING for copying permission.\r\n\r\n#pragma once\r\n\r\n#include \r\n#include \r\n\r\n#include \"hadesmem\/config.hpp\"\r\n\r\nnamespace hadesmem\r\n{\r\n\r\nclass Process;\r\n\r\nclass ProcessEntry;\r\n\r\nnamespace detail\r\n{\r\n\r\nstruct ProcessIteratorImpl;\r\n\r\n}\r\n\r\n\/\/ ProcessIterator satisfies the requirements of an input iterator \r\n\/\/ (C++ Standard, 24.2.1, Input Iterators [input.iterators]).\r\nclass ProcessIterator : public std::iterator\r\n{\r\npublic:\r\n ProcessIterator() HADESMEM_NOEXCEPT;\r\n\r\n explicit ProcessIterator(int dummy);\r\n \r\n reference operator*() const HADESMEM_NOEXCEPT;\r\n \r\n pointer operator->() const HADESMEM_NOEXCEPT;\r\n \r\n ProcessIterator& operator++();\r\n \r\n ProcessIterator operator++(int);\r\n \r\n bool operator==(ProcessIterator const& other) const HADESMEM_NOEXCEPT;\r\n \r\n bool operator!=(ProcessIterator const& other) const HADESMEM_NOEXCEPT;\r\n \r\nprivate:\r\n \/\/ Using a shared_ptr to provide shallow copy semantics, as \r\n \/\/ required by InputIterator.\r\n std::shared_ptr impl_;\r\n};\r\n\r\nclass ProcessList\r\n{\r\npublic:\r\n typedef ProcessIterator iterator;\r\n typedef ProcessIterator const_iterator;\r\n\r\n ProcessList() HADESMEM_NOEXCEPT;\r\n \r\n iterator begin();\r\n \r\n const_iterator begin() const;\r\n \r\n iterator end() HADESMEM_NOEXCEPT;\r\n \r\n const_iterator end() const HADESMEM_NOEXCEPT;\r\n};\r\n\r\n}\r\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: xmlstreamio.hxx,v $\n * $Revision: 1.3 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#include \"diagnose.hxx\"\n#include \n#include \n#include \"rtl\/instance.hxx\"\n#include \"rtl\/bootstrap.hxx\"\n\nnamespace xmlsecurity {\n\nstruct UseDiagnose : public rtl::StaticWithInit<\n const bool, UseDiagnose>\n{\n const bool operator () ()\n {\n ::rtl::OUString value;\n sal_Bool res = rtl::Bootstrap::get(\n ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"XMLSECURITY_TRACE\")), value);\n return res == sal_True ? true : false;\n }\n};\n\n\/* the function will print the string when\n - build with debug\n - the bootstrap variable XMLSECURITY_TRACE is set.\n *\/\nvoid xmlsec_trace(const char* pszFormat, ...)\n{\n bool bDebug = false;\n\n#if OSL_DEBUG_LEVEL > 1\n bDebug = true;\n#endif\n if (bDebug || UseDiagnose::get())\n {\n va_list args;\n fprintf(stderr, \"[xmlsecurity] \");\n va_start(args, pszFormat);\n vfprintf(stderr, pszFormat, args);\n va_end(args);\n\n fprintf(stderr,\"\\n\");\n fflush(stderr);\n }\n}\n\n\n\n}\ncmcfixes73: #i110566# silence gcc warnings\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: xmlstreamio.hxx,v $\n * $Revision: 1.3 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#include \"diagnose.hxx\"\n#include \n#include \n#include \"rtl\/instance.hxx\"\n#include \"rtl\/bootstrap.hxx\"\n\nnamespace xmlsecurity {\n\nstruct UseDiagnose : public rtl::StaticWithInit<\n const bool, UseDiagnose>\n{\n bool operator () () const\n {\n ::rtl::OUString value;\n sal_Bool res = rtl::Bootstrap::get(\n ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"XMLSECURITY_TRACE\")), value);\n return res == sal_True ? true : false;\n }\n};\n\n\/* the function will print the string when\n - build with debug\n - the bootstrap variable XMLSECURITY_TRACE is set.\n *\/\nvoid xmlsec_trace(const char* pszFormat, ...)\n{\n bool bDebug = false;\n\n#if OSL_DEBUG_LEVEL > 1\n bDebug = true;\n#endif\n if (bDebug || UseDiagnose::get())\n {\n va_list args;\n fprintf(stderr, \"[xmlsecurity] \");\n va_start(args, pszFormat);\n vfprintf(stderr, pszFormat, args);\n va_end(args);\n\n fprintf(stderr,\"\\n\");\n fflush(stderr);\n }\n}\n\n\n\n}\n<|endoftext|>"} {"text":"\/*\n * boost_date_time.hpp\n *\n * Created on: Sep 2, 2015\n * Author: zmij\n *\/\n\n#ifndef LIB_PG_ASYNC_INCLUDE_TIP_DB_PG_IO_BOOST_DATE_TIME_HPP_\n#define LIB_PG_ASYNC_INCLUDE_TIP_DB_PG_IO_BOOST_DATE_TIME_HPP_\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace tip {\nnamespace db {\nnamespace pg {\nnamespace io {\n\nnamespace grammar {\nnamespace parse {\n\ntemplate < typename InputIterator >\nstruct time_grammar :\n\t\tboost::spirit::qi::grammar< InputIterator, boost::posix_time::time_duration()> {\n\ttypedef boost::posix_time::time_duration value_type;\n\ttime_grammar() : time_grammar::base_type(time)\n\t{\n\t\tnamespace qi = boost::spirit::qi;\n\t\tnamespace phx = boost::phoenix;\n\t\tusing qi::_pass;\n\t\tusing qi::_val;\n\t\tusing qi::_1;\n\t\tusing qi::_2;\n\t\tusing qi::_3;\n\t\tusing qi::_4;\n\t\t_2digits = qi::uint_parser< std::uint32_t, 10, 2, 2 >();\n\t\tfractional_part = -('.' >> qi::long_);\n\n\t\ttime = (_2digits >> ':' >> _2digits >> ':' >> _2digits >> fractional_part )\n\t\t\t[ _pass = (_1 < 24) && (_2 < 60) && (_3 < 60),\n\t\t\t _val = phx::construct< value_type >(_1, _2, _3, _4)];\n\t}\n\tboost::spirit::qi::rule< InputIterator, value_type()> time;\n\tboost::spirit::qi::rule< InputIterator, std::uint32_t() > _2digits;\n\tboost::spirit::qi::rule< InputIterator, std::uint64_t() > fractional_part;\n};\n\ntemplate < typename InputIterator >\nstruct date_grammar :\n\t\tboost::spirit::qi::grammar< InputIterator, boost::gregorian::date()> {\n\ttypedef boost::gregorian::date value_type;\n\tdate_grammar() : date_grammar::base_type(date)\n\t{\n\t\tnamespace qi = boost::spirit::qi;\n\t\tnamespace phx = boost::phoenix;\n\t\tusing qi::_pass;\n\t\tusing qi::_val;\n\t\tusing qi::_1;\n\t\tusing qi::_2;\n\t\tusing qi::_3;\n\t\t_2digits = qi::uint_parser< std::uint32_t, 10, 2, 2 >();\n\t\t_4digits = qi::uint_parser< std::uint32_t, 10, 4, 4 >();\n\t\tdate = (_4digits >> \"-\" >> _2digits >> \"-\" >> _2digits)\n\t\t\t[\n\t\t\t \t _pass = _3 < 32,\n\t\t\t\t phx::try_[\n\t\t\t\t\t_val = phx::construct< value_type > (_1, _2, _3)\n\t\t\t\t].catch_all[\n\t\t\t\t\t_pass = false\n\t\t\t\t]\n\t\t\t];\n\t}\n\tboost::spirit::qi::rule< InputIterator, value_type()> date;\n\tboost::spirit::qi::rule< InputIterator, std::int32_t() > _2digits;\n\tboost::spirit::qi::rule< InputIterator, std::int32_t() > _4digits;\n};\n\ntemplate < typename InputIterator, typename DateTime >\nstruct datetime_grammar;\n\ntemplate < typename InputIterator >\nstruct datetime_grammar< InputIterator, boost::posix_time::ptime > :\n\t\tboost::spirit::qi::grammar< InputIterator, boost::posix_time::ptime()> {\n\ttypedef boost::posix_time::ptime value_type;\n\tdatetime_grammar() : datetime_grammar::base_type(datetime)\n\t{\n\t\tnamespace qi = boost::spirit::qi;\n\t\tnamespace phx = boost::phoenix;\n\t\tusing qi::_val;\n\t\tusing qi::_1;\n\t\tusing qi::_2;\n\n\t\tdatetime = (date >> ' ' >> time)\n\t\t\t[ _val = phx::construct< value_type >( _1, _2) ];\n\t}\n\tboost::spirit::qi::rule< InputIterator, value_type()> datetime;\n\tdate_grammar< InputIterator > date;\n\ttime_grammar< InputIterator > time;\n};\n\n} \/\/ namespace parse\n} \/\/ namespace grammar\n\ntemplate < >\nstruct protocol_parser< boost::posix_time::ptime, TEXT_DATA_FORMAT > :\n\t\tdetail::parser_base< boost::posix_time::ptime > {\n\ttypedef detail::parser_base< boost::posix_time::ptime > base_type;\n\ttypedef typename base_type::value_type value_type;\n\tprotocol_parser(value_type& v) : base_type(v) {}\n\n\tsize_t\n\tsize() const;\n\n\ttemplate < typename InputIterator >\n InputIterator\n operator()(InputIterator begin, InputIterator end)\n\t{\n\t\ttypedef std::iterator_traits< InputIterator > iter_traits;\n\t\ttypedef typename iter_traits::value_type iter_value_type;\n\t\tstatic_assert(std::is_same< iter_value_type, byte >::type::value,\n\t\t\t\t\"Input iterator must be over a char container\");\n\t\tnamespace qi = boost::spirit::qi;\n\t\tnamespace parse = grammar::parse;\n\n\t\tparse::datetime_grammar< InputIterator, value_type > grammar;\n\t\tvalue_type tmp;\n\t\tif (qi::parse(begin, end, grammar, tmp)) {\n\t\t\tstd::swap(tmp, base_type::value);\n\t\t}\n\t\treturn begin;\n\t}\n};\n\nnamespace traits {\n\n\/\/@{\ntemplate < >\nstruct pgcpp_data_mapping< oids::type::timestamp > :\n\t\tdetail::data_mapping_base< oids::type::timestamp, boost::posix_time::ptime > {};\ntemplate < >\nstruct cpppg_data_mapping< boost::posix_time::ptime > :\n\t\tdetail::data_mapping_base< oids::type::timestamp, boost::posix_time::ptime > {};\n\ntemplate <>\nstruct is_nullable< boost::posix_time::ptime > : ::std::true_type {};\n\ntemplate <>\nstruct nullable_traits< boost::posix_time::ptime > {\n\tinline static bool\n\tis_null(boost::posix_time::ptime const& val)\n\t{\n\t\treturn val.is_not_a_date_time();\n\t}\n\tinline static void\n\tset_null(boost::posix_time::ptime& val)\n\t{\n\t\tval = boost::posix_time::ptime{};\n\t}\n};\n\ntemplate <>\nstruct needs_quotes< boost::posix_time::ptime > : ::std::true_type {};\n\/\/@}\n\n} \/\/ namespace traits\n\n} \/\/ namespace io\n} \/\/ namespace pg\n} \/\/ namespace db\n} \/\/ namespace tip\n\n\n#endif \/* LIB_PG_ASYNC_INCLUDE_TIP_DB_PG_IO_BOOST_DATE_TIME_HPP_ *\/\nCheck year's range\/*\n * boost_date_time.hpp\n *\n * Created on: Sep 2, 2015\n * Author: zmij\n *\/\n\n#ifndef LIB_PG_ASYNC_INCLUDE_TIP_DB_PG_IO_BOOST_DATE_TIME_HPP_\n#define LIB_PG_ASYNC_INCLUDE_TIP_DB_PG_IO_BOOST_DATE_TIME_HPP_\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace tip {\nnamespace db {\nnamespace pg {\nnamespace io {\n\nnamespace grammar {\nnamespace parse {\n\ntemplate < typename InputIterator >\nstruct time_grammar :\n\t\tboost::spirit::qi::grammar< InputIterator, boost::posix_time::time_duration()> {\n\ttypedef boost::posix_time::time_duration value_type;\n\ttime_grammar() : time_grammar::base_type(time)\n\t{\n\t\tnamespace qi = boost::spirit::qi;\n\t\tnamespace phx = boost::phoenix;\n\t\tusing qi::_pass;\n\t\tusing qi::_val;\n\t\tusing qi::_1;\n\t\tusing qi::_2;\n\t\tusing qi::_3;\n\t\tusing qi::_4;\n\t\t_2digits = qi::uint_parser< std::uint32_t, 10, 2, 2 >();\n\t\tfractional_part = -('.' >> qi::long_);\n\n\t\ttime = (_2digits >> ':' >> _2digits >> ':' >> _2digits >> fractional_part )\n\t\t\t[ _pass = (_1 < 24) && (_2 < 60) && (_3 < 60),\n\t\t\t _val = phx::construct< value_type >(_1, _2, _3, _4)];\n\t}\n\tboost::spirit::qi::rule< InputIterator, value_type()> time;\n\tboost::spirit::qi::rule< InputIterator, std::uint32_t() > _2digits;\n\tboost::spirit::qi::rule< InputIterator, std::uint64_t() > fractional_part;\n};\n\ntemplate < typename InputIterator >\nstruct date_grammar :\n\t\tboost::spirit::qi::grammar< InputIterator, boost::gregorian::date()> {\n\ttypedef boost::gregorian::date value_type;\n\tdate_grammar() : date_grammar::base_type(date)\n\t{\n\t\tnamespace qi = boost::spirit::qi;\n\t\tnamespace phx = boost::phoenix;\n\t\tusing qi::_pass;\n\t\tusing qi::_val;\n\t\tusing qi::_1;\n\t\tusing qi::_2;\n\t\tusing qi::_3;\n\t\t_2digits = qi::uint_parser< std::uint32_t, 10, 2, 2 >();\n\t\t_4digits = qi::uint_parser< std::uint32_t, 10, 4, 4 >();\n\t\tdate = (_4digits >> \"-\" >> _2digits >> \"-\" >> _2digits)\n\t\t\t[\n\t\t\t \t _pass = (1400 <= _1) && (_1 <= 10000) && (_3 < 32),\n\t\t\t\t phx::try_[\n\t\t\t\t\t_val = phx::construct< value_type > (_1, _2, _3)\n\t\t\t\t].catch_all[\n\t\t\t\t\t_pass = false\n\t\t\t\t]\n\t\t\t];\n\t}\n\tboost::spirit::qi::rule< InputIterator, value_type()> date;\n\tboost::spirit::qi::rule< InputIterator, std::int32_t() > _2digits;\n\tboost::spirit::qi::rule< InputIterator, std::int32_t() > _4digits;\n};\n\ntemplate < typename InputIterator, typename DateTime >\nstruct datetime_grammar;\n\ntemplate < typename InputIterator >\nstruct datetime_grammar< InputIterator, boost::posix_time::ptime > :\n\t\tboost::spirit::qi::grammar< InputIterator, boost::posix_time::ptime()> {\n\ttypedef boost::posix_time::ptime value_type;\n\tdatetime_grammar() : datetime_grammar::base_type(datetime)\n\t{\n\t\tnamespace qi = boost::spirit::qi;\n\t\tnamespace phx = boost::phoenix;\n\t\tusing qi::_val;\n\t\tusing qi::_1;\n\t\tusing qi::_2;\n\n\t\tdatetime = (date >> ' ' >> time)\n\t\t\t[ _val = phx::construct< value_type >( _1, _2) ];\n\t}\n\tboost::spirit::qi::rule< InputIterator, value_type()> datetime;\n\tdate_grammar< InputIterator > date;\n\ttime_grammar< InputIterator > time;\n};\n\n} \/\/ namespace parse\n} \/\/ namespace grammar\n\ntemplate < >\nstruct protocol_parser< boost::posix_time::ptime, TEXT_DATA_FORMAT > :\n\t\tdetail::parser_base< boost::posix_time::ptime > {\n\ttypedef detail::parser_base< boost::posix_time::ptime > base_type;\n\ttypedef typename base_type::value_type value_type;\n\tprotocol_parser(value_type& v) : base_type(v) {}\n\n\tsize_t\n\tsize() const;\n\n\ttemplate < typename InputIterator >\n InputIterator\n operator()(InputIterator begin, InputIterator end)\n\t{\n\t\ttypedef std::iterator_traits< InputIterator > iter_traits;\n\t\ttypedef typename iter_traits::value_type iter_value_type;\n\t\tstatic_assert(std::is_same< iter_value_type, byte >::type::value,\n\t\t\t\t\"Input iterator must be over a char container\");\n\t\tnamespace qi = boost::spirit::qi;\n\t\tnamespace parse = grammar::parse;\n\n\t\tparse::datetime_grammar< InputIterator, value_type > grammar;\n\t\tvalue_type tmp;\n\t\tif (qi::parse(begin, end, grammar, tmp)) {\n\t\t\tstd::swap(tmp, base_type::value);\n\t\t}\n\t\treturn begin;\n\t}\n};\n\nnamespace traits {\n\n\/\/@{\ntemplate < >\nstruct pgcpp_data_mapping< oids::type::timestamp > :\n\t\tdetail::data_mapping_base< oids::type::timestamp, boost::posix_time::ptime > {};\ntemplate < >\nstruct cpppg_data_mapping< boost::posix_time::ptime > :\n\t\tdetail::data_mapping_base< oids::type::timestamp, boost::posix_time::ptime > {};\n\ntemplate <>\nstruct is_nullable< boost::posix_time::ptime > : ::std::true_type {};\n\ntemplate <>\nstruct nullable_traits< boost::posix_time::ptime > {\n\tinline static bool\n\tis_null(boost::posix_time::ptime const& val)\n\t{\n\t\treturn val.is_not_a_date_time();\n\t}\n\tinline static void\n\tset_null(boost::posix_time::ptime& val)\n\t{\n\t\tval = boost::posix_time::ptime{};\n\t}\n};\n\ntemplate <>\nstruct needs_quotes< boost::posix_time::ptime > : ::std::true_type {};\n\/\/@}\n\n} \/\/ namespace traits\n\n} \/\/ namespace io\n} \/\/ namespace pg\n} \/\/ namespace db\n} \/\/ namespace tip\n\n\n#endif \/* LIB_PG_ASYNC_INCLUDE_TIP_DB_PG_IO_BOOST_DATE_TIME_HPP_ *\/\n<|endoftext|>"} {"text":"\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"TableOpenHelper.hpp\"\n#include \"protocol.hpp\"\n\n\/\/Feature toggle\n#define BATCH_UPDATES\n#define DEBUG_UPDATES\n#define DEBUG_READ\n\nconst char* updateWorkerThreadAddr = \"inproc:\/\/updateWorkerThread\";\n\nusing namespace std;\n\n\/**\n * Encapsulates multiple key-value tables in one interface.\n * The tables are addressed by number and \n *\/\nclass KeyValueMultiTable {\npublic:\n typedef uint32_t IndexType;\n\n KeyValueMultiTable(IndexType defaultTablespaceSize = 16) : databases(32) {\n \/\/Initialize the table array with 16 tables.\n \/\/This avoids early re-allocation\n databasesSize = 16;\n \/\/Use malloc here to allow usage of realloc\n \/\/Initialize all pointers to zero\n for (int i = 0; i < databases.size(); i++) {\n databases[i] = NULL;\n }\n }\n\n \/**\n * Close all tables and stop the table open server.\n * \n * This can't be done in the destructor because it needs to be done before\n * the context is deallocated\n *\/\n void cleanup() {\n fprintf(stderr, \"Flushing and closing tables...\\n\");\n \/\/Flush & delete all databases\n for (int i = 0; i < databasesSize; i++) {\n if (databases[i] != NULL) {\n delete databases[i];\n }\n }\n }\n\n leveldb::DB* getTable(IndexType index, TableOpenHelper& openHelper) {\n \/\/Check if the database has already been opened\n if (databases[index] == NULL || index >= databases.size()) {\n openHelper.openTable(index);\n }\n return databases[index];\n }\n\n void closeTable(IndexType index) {\n if (databases[index] != NULL) {\n delete databases[index];\n databases[index] = NULL;\n }\n }\n\n leveldb::DB* getExistingTable(IndexType index) {\n return databases[index];\n }\n\n vector& getDatabases() {\n return databases;\n }\nprivate:\n \/**\n * The databases vector.\n * Any method in this class has read-only access (tables may be closed by this class however)\n * \n * Write acess is serialized using the TableOpenHelper class.\n * \n * Therefore locks and double initialization are avoided.\n *\/\n std::vector databases; \/\/Indexed by table num\n uint32_t databasesSize;\n};\n\n\/**\n * This struct is used to shared common variables across a server thread\n *\/\nstruct KVServer {\n\n KVServer(zctx_t* ctx) : ctx(ctx), tables(), numUpdateThreads(0) {\n\n }\n\n void initializeTableOpenHelper() {\n tableOpenHelper = new TableOpenHelper(ctx);\n }\n \n \/**\n * Cleanup. This must be called before the ZMQ context is destroyed\n *\/\n void cleanup() {\n delete tableOpenHelper;\n tables.cleanup();\n }\n\n ~KVServer() {\n if (numUpdateThreads > 0) {\n delete[] updateWorkerThreads;\n }\n printf(\"Gracefully closed tables, exiting...\\n\");\n }\n KeyValueMultiTable tables;\n \/\/External sockets\n void* reqRepSocket; \/\/ROUTER socket that receives remote req\/rep. READ requests can only use this socket\n void* subSocket; \/\/SUB socket that subscribes to UPDATE requests (For mirroring etc)\n void* pullSocket; \/\/PULL socket for UPDATE load balancinge\n void* responseProxySocket; \/\/Worker threads connect to this PULL socket -- messages need to contain envelopes and area automatically proxied to the main router socket\n \/\/Internal sockets\n void* updateWorkerThreadSocket; \/\/PUSH socket that distributes update requests among worker threads\n TableOpenHelper* tableOpenHelper; \/\/Only for use in the main thread\n \/\/Thread info\n uint16_t numUpdateThreads;\n std::thread** updateWorkerThreads;\n \/\/Other stuff\n zctx_t* ctx;\n};\n\nvoid handleReadRequest(KeyValueMultiTable& tables, zmsg_t* msg, TableOpenHelper& openHelper) {\n#ifdef DEBUG_READ\n printf(\"Starting to handle read request of size %d\\n\", (uint32_t) zmsg_size(msg) - 1);\n fflush(stdout);\n#endif\n \/\/Parse the table id\n zframe_t* tableIdFrame = zmsg_next(msg);\n assert(zframe_size(tableIdFrame) == sizeof (uint32_t));\n uint32_t tableId = *((uint32_t*) zframe_data(tableIdFrame));\n cout << \"RM Resized to size \" << zmsg_size(msg) << endl;\n \/\/The response has doesn't have the table frame, so\n \/\/Get the table to read from\n leveldb::DB* db = tables.getTable(tableId, openHelper);\n \/\/Create the response object\n leveldb::ReadOptions readOptions;\n string value; \/\/Where the value will be placed\n leveldb::Status status;\n \/\/Read each read request\n zframe_t* keyFrame = NULL;\n while ((keyFrame = zmsg_next(msg)) != NULL) {\n \/\/Build a slice of the key (zero-copy)\n string keystr((char*) zframe_data(keyFrame), zframe_size(keyFrame));\n leveldb::Slice key((char*) zframe_data(keyFrame), zframe_size(keyFrame));\n#ifdef DEBUG_READ\n printf(\"Reading key %s from table %d\\n\", key.ToString().c_str(), tableId);\n#endif\n status = db->Get(readOptions, key, &value);\n if (status.IsNotFound()) {\n#ifdef DEBUG_READ\n cout << \"Could not find value for key \" << key.ToString() << \"in table \" << tableId << endl;\n#endif\n \/\/Empty value\n zframe_reset(keyFrame, \"\", 0);\n } else {\n#ifdef DEBUG_READ\n cout << \"Read \" << value << \" (key = \" << key.ToString() << \") --> \" << value << endl;\n#endif\n zframe_reset(keyFrame, value.c_str(), value.length());\n }\n }\n \/\/Now we can remove the table ID frame from the message (doing so before would confuse zmsg_next())\n zmsg_remove(msg, tableIdFrame);\n zframe_destroy(&tableIdFrame);\n#ifdef DEBUG_READ\n cout << \"Final reply msg size: \" << zmsg_size(msg) << endl;\n#endif\n}\n\nvoid handleUpdateRequest(KeyValueMultiTable& tables, zmsg_t* msg, TableOpenHelper& helper) {\n leveldb::Status status;\n leveldb::WriteOptions writeOptions;\n \/\/Parse the table id\n \/\/This function requires that the given message has the table id in its first frame\n zframe_t* tableIdFrame = zmsg_first(msg);\n assert(zframe_size(tableIdFrame) == sizeof (uint32_t));\n uint32_t tableId = *((uint32_t*) zframe_data(tableIdFrame));\n zmsg_remove(msg, tableIdFrame);\n \/\/Get the table\n leveldb::DB* db = tables.getTable(tableId, helper);\n \/\/The entire update is processed in one batch\n#ifdef BATCH_UPDATES\n leveldb::WriteBatch batch;\n while (true) {\n \/\/The next two frames contain \n zframe_t* keyFrame = zmsg_next(msg);\n if (!keyFrame) {\n break;\n }\n zframe_t* valueFrame = zmsg_next(msg);\n assert(valueFrame); \/\/if this fails there is an odd number of data frames --> illegal (see protocol spec)\n\n\n leveldb::Slice keySlice((char*) zframe_data(keyFrame), zframe_size(keyFrame));\n leveldb::Slice valueSlice((char*) zframe_data(valueFrame), zframe_size(valueFrame));\n\n#ifdef DEBUG_UPDATES\n printf(\"Insert '%s' = '%s'\\n\", keySlice.ToString().c_str(), valueSlice.ToString().c_str());\n fflush(stdout);\n#endif\n\n batch.Put(keySlice, valueSlice);\n }\n \/\/Commit the batch\n#ifdef DEBUG_UPDATES\n printf(\"Commit update batch\\n\");\n#endif\n db->Write(writeOptions, &batch);\n#else \/\/No batch updates\n for (int i = 0; i < request.write_requests_size(); i++) {\n const KeyValue& kv = request.write_requests(i);\n status = db->Put(writeOptions, kv.key(), kv.value());\n }\n for (int i = 0; i < request.delete_requests_size(); i++) {\n status = db->Delete(writeOptions, request.delete_requests(i));\n }\n#endif\n \/\/The memory occupied by the message is free'd in the thread loop\n}\n\n\/*\n * Request\/response codes are determined by the first byte\n * Request codes (from client):\n * 1: Read. Response: Serialized ReadResponse\n * 2: Update. Response: 0 --> Acknowledge\n * Response codes (to client):\n * 0: Acknowledge\n *\/\nint handleRequestResponse(zloop_t *loop, zmq_pollitem_t *poller, void *arg) {\n KVServer* server = (KVServer*) arg;\n \/\/Initialize a scoped lock\n zmsg_t *msg = zmsg_recv(server->reqRepSocket);\n if (msg) {\n \/\/The message consists of four frames: Client addr, empty delimiter, msg type (1 byte) and data\n assert(zmsg_size(msg) >= 3); \/\/return addr + empty delimiter + protocol header [+ data frames]\n \/\/Extract the frames\n zframe_t* addrFrame = zmsg_first(msg);\n zframe_t* delimiterFrame = zmsg_next(msg);\n zframe_t* headerFrame = zmsg_next(msg);\n \/\/Check the header -- send error message if invalid\n string errorString;\n char* headerData = (char*) zframe_data(headerFrame);\n if (!checkProtocolVersion(headerData, zframe_size(headerFrame), errorString)) {\n fprintf(stderr, \"Got illegal message from client\\n\");\n return 1;\n }\n RequestType requestType = (RequestType) (uint8_t) headerData[2];\n \/\/ fprintf(stderr, \"Got message of type %d from client\\n\", (int) msgType);\n if (requestType == RequestType::ReadRequest) {\n handleReadRequest(server->tables, msg, *(server->tableOpenHelper));\n zmsg_send(&msg, server->reqRepSocket);\n } else if (requestType == RequestType::PutRequest) {\n \/\/We reuse the header frame and the routing information to send the acknowledge message\n \/\/The rest of the msg (the table id + data) is directly forwarded to one of the handler threads\n \/\/Remove the routing information\n zframe_t* routingFrame = zmsg_unwrap(msg);\n \/\/Remove the header frame\n headerFrame = zmsg_pop(msg);\n zframe_destroy(&headerFrame);\n \/\/Send the message to the update worker (--> processed async)\n zmsg_send(&msg, server->updateWorkerThreadSocket);\n \/\/Send acknowledge message\n msg = zmsg_new();\n zmsg_wrap(msg, routingFrame);\n zmsg_addmem(msg, \"\\x31\\x01\\x20\\x00\", 4); \/\/Send response code 0x00 (ack)\n zmsg_send(&msg, server->reqRepSocket);\n } else {\n fprintf(stderr, \"Unknown message type %d from client\\n\", (int) requestType);\n }\n cout << \"Sending reply to\" << (requestType == RequestType::PutRequest ? \" put request \" : \" read request \") << endl;\n }\n return 0;\n}\n\nvoid initializeDirectoryStructure() {\n mkdir(\"tables\", S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP);\n}\n\n\/**\n * This data structure is used in the update worker thread to share info with\n * the update poll handler\n *\/\nstruct UpdateWorkerInfo {\n KVServer* server;\n void* pullSocket;\n};\n\n\/**\n * The main function for the update worker thread\n *\/\nvoid updateWorkerThreadFunction(zctx_t* ctx, KVServer* serverInfo) {\n void* workPullSocket = zsocket_new(ctx, ZMQ_PULL);\n zsocket_connect(workPullSocket, updateWorkerThreadAddr);\n \/\/Create the table open helper (creates a socket that sends table open requests)\n TableOpenHelper tableOpenHelper(ctx);\n \/\/Create the data structure with all info for the poll handler\n while (true) {\n zmsg_t* msg = zmsg_recv(workPullSocket);\n assert(zmsg_size(msg) >= 1);\n \/\/Process the frame\n handleUpdateRequest(serverInfo->tables, msg, tableOpenHelper);\n \/\/Cleanup\n zmsg_destroy(&msg);\n }\n printf(\"Stopping update processor\\n\");\n zsocket_destroy(ctx, workPullSocket);\n}\n\nvoid initializeUpdateWorkers(zctx_t* ctx, KVServer* serverInfo) {\n \/\/Initialize the push socket\n serverInfo->updateWorkerThreadSocket = zsocket_new(ctx, ZMQ_PUSH);\n zsocket_bind(serverInfo->updateWorkerThreadSocket, updateWorkerThreadAddr);\n \/\/Start the threads\n const int numThreads = 3;\n serverInfo->numUpdateThreads = numThreads;\n serverInfo->updateWorkerThreads = new std::thread*[numThreads];\n for (int i = 0; i < numThreads; i++) {\n serverInfo->updateWorkerThreads[i] = new std::thread(updateWorkerThreadFunction, ctx, serverInfo);\n }\n}\n\n\/**\n * ZDB KeyValueServer\n * Port \n *\/\nint main() {\n const char* reqRepUrl = \"tcp:\/\/*:7100\";\n const char* writeSubscriptionUrl = \"tcp:\/\/*:7101\";\n const char* errorPubUrl = \"tcp:\/\/*:7102\";\n \/\/Ensure the tables directory exists\n initializeDirectoryStructure();\n \/\/Create the ZMQ context\n zctx_t* ctx = zctx_new();\n \/\/Create the object that will be shared between the threadsloop\n KVServer server(ctx);\n \/\/Start the table opener thread (constructor returns after thread has been started. Cleanup on scope exit.)\n bool dbCompressionEnabled = true;\n TableOpenServer tableOpenServer(ctx, server.tables.getDatabases(), dbCompressionEnabled);\n server.initializeTableOpenHelper();\n \/\/Initialize all worker threads\n initializeUpdateWorkers(ctx, &server);\n \/\/Initialize the sockets that run on the main thread\n server.reqRepSocket = zsocket_new(ctx, ZMQ_ROUTER);\n server.responseProxySocket = zsocket_new(ctx, ZMQ_PULL);\n zsocket_bind(server.responseProxySocket, \"inproc:\/\/mainRequestProxy\");\n zsocket_bind(server.reqRepSocket, reqRepUrl);\n \/\/Start the loop\n printf(\"Starting server...\\n\");\n zloop_t *reactor = zloop_new();\n zmq_pollitem_t poller = {server.reqRepSocket, 0, ZMQ_POLLIN};\n zmq_pollitem_t poller = {server.repP, 0, ZMQ_POLLIN};\n zloop_poller(reactor, &poller, handleRequestResponse, &server);\n zloop_start(reactor);\n \/\/Cleanup (called when finished)\n zloop_destroy(&reactor);\n server.cleanup(); \/\/Before the context is destroyed\n zctx_destroy(&ctx);\n \/\/All tables are closed at scope exit.\n}Start to add server info support\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"TableOpenHelper.hpp\"\n#include \"protocol.hpp\"\n\n\/\/Feature toggle\n#define BATCH_UPDATES\n#define DEBUG_UPDATES\n#define DEBUG_READ\n\nconst char* updateWorkerThreadAddr = \"inproc:\/\/updateWorkerThread\";\n\nusing namespace std;\n\n\/**\n * Encapsulates multiple key-value tables in one interface.\n * The tables are addressed by number and \n *\/\nclass KeyValueMultiTable {\npublic:\n typedef uint32_t IndexType;\n\n KeyValueMultiTable(IndexType defaultTablespaceSize = 16) : databases(32) {\n \/\/Initialize the table array with 16 tables.\n \/\/This avoids early re-allocation\n databasesSize = 16;\n \/\/Use malloc here to allow usage of realloc\n \/\/Initialize all pointers to zero\n for (int i = 0; i < databases.size(); i++) {\n databases[i] = NULL;\n }\n }\n\n \/**\n * Close all tables and stop the table open server.\n * \n * This can't be done in the destructor because it needs to be done before\n * the context is deallocated\n *\/\n void cleanup() {\n fprintf(stderr, \"Flushing and closing tables...\\n\");\n \/\/Flush & delete all databases\n for (int i = 0; i < databasesSize; i++) {\n if (databases[i] != NULL) {\n delete databases[i];\n }\n }\n }\n\n leveldb::DB* getTable(IndexType index, TableOpenHelper& openHelper) {\n \/\/Check if the database has already been opened\n if (databases[index] == NULL || index >= databases.size()) {\n openHelper.openTable(index);\n }\n return databases[index];\n }\n\n void closeTable(IndexType index) {\n if (databases[index] != NULL) {\n delete databases[index];\n databases[index] = NULL;\n }\n }\n\n leveldb::DB* getExistingTable(IndexType index) {\n return databases[index];\n }\n\n vector& getDatabases() {\n return databases;\n }\nprivate:\n \/**\n * The databases vector.\n * Any method in this class has read-only access (tables may be closed by this class however)\n * \n * Write acess is serialized using the TableOpenHelper class.\n * \n * Therefore locks and double initialization are avoided.\n *\/\n std::vector databases; \/\/Indexed by table num\n uint32_t databasesSize;\n};\n\n\/**\n * This struct is used to shared common variables across a server thread\n *\/\nstruct KVServer {\n\n KVServer(zctx_t* ctx) : ctx(ctx), tables(), numUpdateThreads(0) {\n\n }\n\n void initializeTableOpenHelper() {\n tableOpenHelper = new TableOpenHelper(ctx);\n }\n \n \/**\n * Cleanup. This must be called before the ZMQ context is destroyed\n *\/\n void cleanup() {\n delete tableOpenHelper;\n tables.cleanup();\n }\n\n ~KVServer() {\n if (numUpdateThreads > 0) {\n delete[] updateWorkerThreads;\n }\n printf(\"Gracefully closed tables, exiting...\\n\");\n }\n KeyValueMultiTable tables;\n \/\/External sockets\n void* reqRepSocket; \/\/ROUTER socket that receives remote req\/rep. READ requests can only use this socket\n void* subSocket; \/\/SUB socket that subscribes to UPDATE requests (For mirroring etc)\n void* pullSocket; \/\/PULL socket for UPDATE load balancinge\n void* responseProxySocket; \/\/Worker threads connect to this PULL socket -- messages need to contain envelopes and area automatically proxied to the main router socket\n \/\/Internal sockets\n void* updateWorkerThreadSocket; \/\/PUSH socket that distributes update requests among worker threads\n TableOpenHelper* tableOpenHelper; \/\/Only for use in the main thread\n \/\/Thread info\n uint16_t numUpdateThreads;\n std::thread** updateWorkerThreads;\n \/\/Other stuff\n zctx_t* ctx;\n};\n\nvoid handleReadRequest(KeyValueMultiTable& tables, zmsg_t* msg, TableOpenHelper& openHelper) {\n#ifdef DEBUG_READ\n printf(\"Starting to handle read request of size %d\\n\", (uint32_t) zmsg_size(msg) - 1);\n fflush(stdout);\n#endif\n \/\/Parse the table id\n zframe_t* tableIdFrame = zmsg_next(msg);\n assert(zframe_size(tableIdFrame) == sizeof (uint32_t));\n uint32_t tableId = *((uint32_t*) zframe_data(tableIdFrame));\n cout << \"RM Resized to size \" << zmsg_size(msg) << endl;\n \/\/The response has doesn't have the table frame, so\n \/\/Get the table to read from\n leveldb::DB* db = tables.getTable(tableId, openHelper);\n \/\/Create the response object\n leveldb::ReadOptions readOptions;\n string value; \/\/Where the value will be placed\n leveldb::Status status;\n \/\/Read each read request\n zframe_t* keyFrame = NULL;\n while ((keyFrame = zmsg_next(msg)) != NULL) {\n \/\/Build a slice of the key (zero-copy)\n string keystr((char*) zframe_data(keyFrame), zframe_size(keyFrame));\n leveldb::Slice key((char*) zframe_data(keyFrame), zframe_size(keyFrame));\n#ifdef DEBUG_READ\n printf(\"Reading key %s from table %d\\n\", key.ToString().c_str(), tableId);\n#endif\n status = db->Get(readOptions, key, &value);\n if (status.IsNotFound()) {\n#ifdef DEBUG_READ\n cout << \"Could not find value for key \" << key.ToString() << \"in table \" << tableId << endl;\n#endif\n \/\/Empty value\n zframe_reset(keyFrame, \"\", 0);\n } else {\n#ifdef DEBUG_READ\n cout << \"Read \" << value << \" (key = \" << key.ToString() << \") --> \" << value << endl;\n#endif\n zframe_reset(keyFrame, value.c_str(), value.length());\n }\n }\n \/\/Now we can remove the table ID frame from the message (doing so before would confuse zmsg_next())\n zmsg_remove(msg, tableIdFrame);\n zframe_destroy(&tableIdFrame);\n#ifdef DEBUG_READ\n cout << \"Final reply msg size: \" << zmsg_size(msg) << endl;\n#endif\n}\n\nvoid handleUpdateRequest(KeyValueMultiTable& tables, zmsg_t* msg, TableOpenHelper& helper) {\n leveldb::Status status;\n leveldb::WriteOptions writeOptions;\n \/\/Parse the table id\n \/\/This function requires that the given message has the table id in its first frame\n zframe_t* tableIdFrame = zmsg_first(msg);\n assert(zframe_size(tableIdFrame) == sizeof (uint32_t));\n uint32_t tableId = *((uint32_t*) zframe_data(tableIdFrame));\n zmsg_remove(msg, tableIdFrame);\n \/\/Get the table\n leveldb::DB* db = tables.getTable(tableId, helper);\n \/\/The entire update is processed in one batch\n#ifdef BATCH_UPDATES\n leveldb::WriteBatch batch;\n while (true) {\n \/\/The next two frames contain \n zframe_t* keyFrame = zmsg_next(msg);\n if (!keyFrame) {\n break;\n }\n zframe_t* valueFrame = zmsg_next(msg);\n assert(valueFrame); \/\/if this fails there is an odd number of data frames --> illegal (see protocol spec)\n\n\n leveldb::Slice keySlice((char*) zframe_data(keyFrame), zframe_size(keyFrame));\n leveldb::Slice valueSlice((char*) zframe_data(valueFrame), zframe_size(valueFrame));\n\n#ifdef DEBUG_UPDATES\n printf(\"Insert '%s' = '%s'\\n\", keySlice.ToString().c_str(), valueSlice.ToString().c_str());\n fflush(stdout);\n#endif\n\n batch.Put(keySlice, valueSlice);\n }\n \/\/Commit the batch\n#ifdef DEBUG_UPDATES\n printf(\"Commit update batch\\n\");\n#endif\n db->Write(writeOptions, &batch);\n#else \/\/No batch updates\n for (int i = 0; i < request.write_requests_size(); i++) {\n const KeyValue& kv = request.write_requests(i);\n status = db->Put(writeOptions, kv.key(), kv.value());\n }\n for (int i = 0; i < request.delete_requests_size(); i++) {\n status = db->Delete(writeOptions, request.delete_requests(i));\n }\n#endif\n \/\/The memory occupied by the message is free'd in the thread loop\n}\n\n\/*\n * Request\/response codes are determined by the first byte\n * Request codes (from client):\n * 1: Read. Response: Serialized ReadResponse\n * 2: Update. Response: 0 --> Acknowledge\n * Response codes (to client):\n * 0: Acknowledge\n *\/\nint handleRequestResponse(zloop_t *loop, zmq_pollitem_t *poller, void *arg) {\n KVServer* server = (KVServer*) arg;\n \/\/Initialize a scoped lock\n zmsg_t *msg = zmsg_recv(server->reqRepSocket);\n if (msg) {\n \/\/The message consists of four frames: Client addr, empty delimiter, msg type (1 byte) and data\n assert(zmsg_size(msg) >= 3); \/\/return addr + empty delimiter + protocol header [+ data frames]\n \/\/Extract the frames\n zframe_t* addrFrame = zmsg_first(msg);\n zframe_t* delimiterFrame = zmsg_next(msg);\n zframe_t* headerFrame = zmsg_next(msg);\n \/\/Check the header -- send error message if invalid\n string errorString;\n char* headerData = (char*) zframe_data(headerFrame);\n if (!checkProtocolVersion(headerData, zframe_size(headerFrame), errorString)) {\n fprintf(stderr, \"Got illegal message from client\\n\");\n return 1;\n }\n RequestType requestType = (RequestType) (uint8_t) headerData[2];\n \/\/ fprintf(stderr, \"Got message of type %d from client\\n\", (int) msgType);\n if (requestType == RequestType::ReadRequest) {\n handleReadRequest(server->tables, msg, *(server->tableOpenHelper));\n zmsg_send(&msg, server->reqRepSocket);\n } else if (requestType == RequestType::PutRequest) {\n \/\/We reuse the header frame and the routing information to send the acknowledge message\n \/\/The rest of the msg (the table id + data) is directly forwarded to one of the handler threads\n \/\/Remove the routing information\n zframe_t* routingFrame = zmsg_unwrap(msg);\n \/\/Remove the header frame\n headerFrame = zmsg_pop(msg);\n zframe_destroy(&headerFrame);\n \/\/Send the message to the update worker (--> processed async)\n zmsg_send(&msg, server->updateWorkerThreadSocket);\n \/\/Send acknowledge message\n msg = zmsg_new();\n zmsg_wrap(msg, routingFrame);\n zmsg_addmem(msg, \"\\x31\\x01\\x20\\x00\", 4); \/\/Send response code 0x00 (ack)\n zmsg_send(&msg, server->reqRepSocket);\n } else if(requestType == RequestType::ServerInfoRequest) {\n const uint64_t serverFlags = SupportOnTheFlyTableOpen | SupportPARTSYNC | SupportFULLSYNC;\n zframe_t* frame = zframe_new(3\/*Metadata*\/+8\/*Flags*\/);\n } else {\n fprintf(stderr, \"Unknown message type %d from client\\n\", (int) requestType);\n }\n cout << \"Sending reply to\" << (requestType == RequestType::PutRequest ? \" put request \" : \" read request \") << endl;\n }\n return 0;\n}\n\nvoid initializeDirectoryStructure() {\n mkdir(\"tables\", S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP);\n}\n\n\/**\n * This data structure is used in the update worker thread to share info with\n * the update poll handler\n *\/\nstruct UpdateWorkerInfo {\n KVServer* server;\n void* pullSocket;\n};\n\n\/**\n * The main function for the update worker thread\n *\/\nvoid updateWorkerThreadFunction(zctx_t* ctx, KVServer* serverInfo) {\n void* workPullSocket = zsocket_new(ctx, ZMQ_PULL);\n zsocket_connect(workPullSocket, updateWorkerThreadAddr);\n \/\/Create the table open helper (creates a socket that sends table open requests)\n TableOpenHelper tableOpenHelper(ctx);\n \/\/Create the data structure with all info for the poll handler\n while (true) {\n zmsg_t* msg = zmsg_recv(workPullSocket);\n assert(zmsg_size(msg) >= 1);\n \/\/Process the frame\n handleUpdateRequest(serverInfo->tables, msg, tableOpenHelper);\n \/\/Cleanup\n zmsg_destroy(&msg);\n }\n printf(\"Stopping update processor\\n\");\n zsocket_destroy(ctx, workPullSocket);\n}\n\nvoid initializeUpdateWorkers(zctx_t* ctx, KVServer* serverInfo) {\n \/\/Initialize the push socket\n serverInfo->updateWorkerThreadSocket = zsocket_new(ctx, ZMQ_PUSH);\n zsocket_bind(serverInfo->updateWorkerThreadSocket, updateWorkerThreadAddr);\n \/\/Start the threads\n const int numThreads = 3;\n serverInfo->numUpdateThreads = numThreads;\n serverInfo->updateWorkerThreads = new std::thread*[numThreads];\n for (int i = 0; i < numThreads; i++) {\n serverInfo->updateWorkerThreads[i] = new std::thread(updateWorkerThreadFunction, ctx, serverInfo);\n }\n}\n\n\/**\n * ZDB KeyValueServer\n * Port \n *\/\nint main() {\n const char* reqRepUrl = \"tcp:\/\/*:7100\";\n const char* writeSubscriptionUrl = \"tcp:\/\/*:7101\";\n const char* errorPubUrl = \"tcp:\/\/*:7102\";\n \/\/Ensure the tables directory exists\n initializeDirectoryStructure();\n \/\/Create the ZMQ context\n zctx_t* ctx = zctx_new();\n \/\/Create the object that will be shared between the threadsloop\n KVServer server(ctx);\n \/\/Start the table opener thread (constructor returns after thread has been started. Cleanup on scope exit.)\n bool dbCompressionEnabled = true;\n TableOpenServer tableOpenServer(ctx, server.tables.getDatabases(), dbCompressionEnabled);\n server.initializeTableOpenHelper();\n \/\/Initialize all worker threads\n initializeUpdateWorkers(ctx, &server);\n \/\/Initialize the sockets that run on the main thread\n server.reqRepSocket = zsocket_new(ctx, ZMQ_ROUTER);\n server.responseProxySocket = zsocket_new(ctx, ZMQ_PULL);\n zsocket_bind(server.responseProxySocket, \"inproc:\/\/mainRequestProxy\");\n zsocket_bind(server.reqRepSocket, reqRepUrl);\n \/\/Start the loop\n printf(\"Starting server...\\n\");\n zloop_t *reactor = zloop_new();\n zmq_pollitem_t poller = {server.reqRepSocket, 0, ZMQ_POLLIN};\n zmq_pollitem_t poller = {server.repP, 0, ZMQ_POLLIN};\n zloop_poller(reactor, &poller, handleRequestResponse, &server);\n zloop_start(reactor);\n \/\/Cleanup (called when finished)\n zloop_destroy(&reactor);\n server.cleanup(); \/\/Before the context is destroyed\n zctx_destroy(&ctx);\n \/\/All tables are closed at scope exit.\n}<|endoftext|>"} {"text":"\n#include \"befakprint.h\"\n\n#include \n\n\/\/ baseclass with stuff, inherit to print\/export\/whatever\n\nbeFakPrint::beFakPrint(int id, sqlite *db) {\n\n\tif (id<1) {\n\t\tprintf(\"illegal id!\\n\");\n\t\treturn;\n\t}\n\n\tdbData = db;\n\tfakturaid = id;\n\ttyp = 0;\t\t\/\/ XXX parametr!\n\n\tswitch (typ) {\n\t\tcase 2:\n\t\t\ttypfaktury = \"Duplikat\";\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\ttypfaktury = \"Kopia\";\n\t\t\tbreak;\n\t\tcase 0:\n\t\tdefault:\n\t\t\ttypfaktury = \"Oryginał\";\n\t\t\tbreak;\n\t}\n\n\t\/\/ readout stuff\n\/\/printf(\"reading stuff for id=%i\\n\",fakturaid);\n\tfdata = new fakturadat(db);\n\tflist = new pozfaklist(db);\n\n\tfdata->id = fakturaid;\n\tfdata->fetch();\n\tflist->fetch(fdata->id);\n\n\t\/\/ XXX duplicated in dialfirma constructor!!! separate!!!\n\tint i, j;\n\tint nRows, nCols;\n\tchar **result;\n\tBString sql;\n\tsql = \"SELECT \";\n\tsql += \"nazwa, adres, kod, miejscowosc, telefon, email\";\n\tsql += \", nip, regon, bank, konto\";\n\tsql += \" FROM konfiguracja WHERE zrobiona = 1\";\n\/\/printf(\"sql:%s\\n\",sql.String());\n\tsqlite_get_table(dbData, sql.String(), &result, &nRows, &nCols, &dbErrMsg);\n\/\/printf (\"got:%ix%i\\n\", nRows, nCols);\n\tif (nRows < 1) {\n\t\t\/\/ XXX brak informacji o własnej firmie, co robić?\n\t} else {\n\/\/\t\tprintf(\"not initial\\n\");\n\t\t\/\/ readout data\n\t\ti = nCols;\n\t\town[0] = result[i++];\n\t\tfor (j=2;j<=10;j++) {\n\t\t\town[j] = result[i++];\n\t\t}\n\t}\n\t\/\/ tabela pomocnicza do podsumowania\n\tflist->execSQL(\"CREATE TEMPORARY TABLE sumawydruk ( wnetto DECIMAL(12,2), vatid INTEGER, wvat DECIMAL(12,2), wbrutto DECIMAL(12,2) )\");\n\n\/\/\tprintf(\"stuff in memory, do sth with it\\n\");\n}\n\nvoid beFakPrint::updateSummary(const BString wnetto, const int vatid, const BString wvat, const BString wbrutto) {\n\tint ret;\n\n\tret = sqlite_exec_printf(dbData, \"INSERT INTO sumawydruk (wnetto,vatid,wvat,wbrutto) VALUES ( %Q, %i, %Q, %Q )\", 0, 0, &dbErrMsg,\n\t\twnetto.String(), vatid, wvat.String(), wbrutto.String() );\n\/\/\t\tprintf(\"result: %i, %s\\n\", ret, dbErrMsg);\n\n}\n\nvoid beFakPrint::makeSummary(void) {\n\tint i, j;\n\tint nRows, nCols;\n\tchar **result;\n\tBString sql;\n\n\t\/\/ suma z rozbiciem na stawki\n\tsql = \"SELECT SUM(s.wnetto), v.nazwa, SUM(s.wvat), SUM(s.wbrutto) FROM sumawydruk AS s, stawka_vat AS v WHERE v.id = s.vatid GROUP BY s.vatid ORDER BY v.nazwa\";\n\/\/printf(\"sql:[%s]\\n\",sql.String());\n\tsqlite_get_table(dbData, sql.String(), &result, &nRows, &nCols, &dbErrMsg);\n\/\/printf (\"got:%ix%i, %s\\n\", nRows, nCols, dbErrMsg);\n\tif (nRows < 1) {\n\t\t\/\/ nothin'?\n\t} else {\n\t\ti = nCols;\n\t\tj = 1;\n\t\tfsummarows = nRows;\n\t\tfsumma = new summary[nRows];\n\t\twhile (j <= nRows) {\n\t\t\tfsumma[j-1].summa[0] = decround(result[i++]);\n\t\t\tfsumma[j-1].summa[1] = result[i++];\n\t\t\tfsumma[j-1].summa[2] = decround(result[i++]);\n\t\t\tfsumma[j-1].summa[3] = decround(result[i++]);\n\t\t\tj++;\n\t\t}\n\t}\n\tsqlite_free_table(result);\n\t\/\/ obliczyc RAZEM\n\tsql = \"SELECT SUM(s.wnetto), v.nazwa, SUM(s.wvat), SUM(s.wbrutto) FROM sumawydruk AS s, stawka_vat AS v WHERE v.id = s.vatid\";\n\/\/printf(\"sql:[%s]\\n\",sql.String());\n\tsqlite_get_table(dbData, sql.String(), &result, &nRows, &nCols, &dbErrMsg);\n\/\/printf (\"got:%ix%i, %s\\n\", nRows, nCols, dbErrMsg);\n\tif (nRows < 1) {\n\t\t\/\/ nothin'?\n\t} else {\n\t\ti = nCols;\n\t\trazem.summa[0] = decround(result[i++]);\n\t\trazem.summa[1] = result[i++];\n\t\trazem.summa[2] = decround(result[i++]);\n\t\trazem.summa[3] = decround(result[i++]);\n\t}\n\tsqlite_free_table(result);\n}\n\nbeFakPrint::~beFakPrint() {\n\/\/printf(\"at the end call destructor from baseclass\\n\");\n\tflist->execSQL(\"DROP TABLE sumawydruk\");\n\tdelete [] fsumma;\n\n\tdelete flist;\n\tdelete fdata;\n}\n\nconst char *setki[] = { \"\", \"sto \", \"dwieście \", \"trzysta \", \"czterysta \", \"pięćset \", \"sześćset \", \"siedemset \", \"osiemset \", \"dziewięćset \" };\nconst char *dziesiatki[] = { \"\", \"\", \"dwadzieścia \", \"trzydzieści \", \"czterdzieści \", \"pięćdziesiąt \", \"sześćdziesiąt\", \"siedemdziesiąt \", \"osiemdziesiąt \", \"dziewięćdziesiąt \" };\nconst char *nascie[] = { \"dziesięć \", \"jedenaście \", \"dwanaście \", \"trzynaście \", \"czternaście \", \"piętnaście \", \"szesnaście \", \"siedemnaście \", \"osiemnaście \", \"dziewiętnaście \" };\nconst char *jednosci[] = { \"\", \"jeden \", \"dwa \", \"trzy \", \"cztery \", \"pięć \", \"sześć \", \"siedem \", \"osiem \", \"dziewięć \" };\n\nconst char *beFakPrint::rozbij_tysiac(int val) {\n\tstatic BString tmp;\n\tint i;\n\tint t = val;\n\n\ttmp = \"\";\n\ti = t \/ 100;\n\ttmp += setki[i];\n\tt = t % 100;\n\ti = t \/ 10;\n\tt = t % 10;\n\tif (i!=1) {\n\t\ttmp += dziesiatki[i];\n\t\ttmp += jednosci[t];\n\t} else {\n\t\ttmp += nascie[t];\n\t}\n\treturn tmp.String();\n}\n\nconst char *beFakPrint::slownie(const char *input) {\n\tstatic BString tmp;\n\n\tint i = 0;\n\tint l = strlen(input);\n\tchar c;\n\n\tint z = 0;\t\t\/\/ zlote\n\tint g = 0;\t\t\/\/ grosze\n\tint w = 0;\t\t\/\/ wykladnik\n\tbool grosze = false;\n\ttmp = \"\";\n\n\twhile (i- initialized fsumma so it may be empty upon destroy\n#include \"befakprint.h\"\n\n#include \n\n\/\/ baseclass with stuff, inherit to print\/export\/whatever\n\nbeFakPrint::beFakPrint(int id, sqlite *db) {\n\n\tif (id<1) {\n\t\tprintf(\"illegal id!\\n\");\n\t\treturn;\n\t}\n\n\tdbData = db;\n\tfakturaid = id;\n\ttyp = 0;\t\t\/\/ XXX parametr!\n\n\tswitch (typ) {\n\t\tcase 2:\n\t\t\ttypfaktury = \"Duplikat\";\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\ttypfaktury = \"Kopia\";\n\t\t\tbreak;\n\t\tcase 0:\n\t\tdefault:\n\t\t\ttypfaktury = \"Oryginał\";\n\t\t\tbreak;\n\t}\n\n\t\/\/ readout stuff\n\/\/printf(\"reading stuff for id=%i\\n\",fakturaid);\n\tfdata = new fakturadat(db);\n\tflist = new pozfaklist(db);\n\n\tfdata->id = fakturaid;\n\tfdata->fetch();\n\tflist->fetch(fdata->id);\n\tfsumma = NULL;\n\n\t\/\/ XXX duplicated in dialfirma constructor!!! separate!!!\n\tint i, j;\n\tint nRows, nCols;\n\tchar **result;\n\tBString sql;\n\tsql = \"SELECT \";\n\tsql += \"nazwa, adres, kod, miejscowosc, telefon, email\";\n\tsql += \", nip, regon, bank, konto\";\n\tsql += \" FROM konfiguracja WHERE zrobiona = 1\";\n\/\/printf(\"sql:%s\\n\",sql.String());\n\tsqlite_get_table(dbData, sql.String(), &result, &nRows, &nCols, &dbErrMsg);\n\/\/printf (\"got:%ix%i\\n\", nRows, nCols);\n\tif (nRows < 1) {\n\t\t\/\/ XXX brak informacji o własnej firmie, co robić?\n\t} else {\n\/\/\t\tprintf(\"not initial\\n\");\n\t\t\/\/ readout data\n\t\ti = nCols;\n\t\town[0] = result[i++];\n\t\tfor (j=2;j<=10;j++) {\n\t\t\town[j] = result[i++];\n\t\t}\n\t}\n\t\/\/ tabela pomocnicza do podsumowania\n\tflist->execSQL(\"CREATE TEMPORARY TABLE sumawydruk ( wnetto DECIMAL(12,2), vatid INTEGER, wvat DECIMAL(12,2), wbrutto DECIMAL(12,2) )\");\n\n\/\/\tprintf(\"stuff in memory, do sth with it\\n\");\n}\n\nvoid beFakPrint::updateSummary(const BString wnetto, const int vatid, const BString wvat, const BString wbrutto) {\n\tint ret;\n\n\tret = sqlite_exec_printf(dbData, \"INSERT INTO sumawydruk (wnetto,vatid,wvat,wbrutto) VALUES ( %Q, %i, %Q, %Q )\", 0, 0, &dbErrMsg,\n\t\twnetto.String(), vatid, wvat.String(), wbrutto.String() );\n\/\/\t\tprintf(\"result: %i, %s\\n\", ret, dbErrMsg);\n\n}\n\nvoid beFakPrint::makeSummary(void) {\n\tint i, j;\n\tint nRows, nCols;\n\tchar **result;\n\tBString sql;\n\n\t\/\/ suma z rozbiciem na stawki\n\tsql = \"SELECT SUM(s.wnetto), v.nazwa, SUM(s.wvat), SUM(s.wbrutto) FROM sumawydruk AS s, stawka_vat AS v WHERE v.id = s.vatid GROUP BY s.vatid ORDER BY v.nazwa\";\n\/\/printf(\"sql:[%s]\\n\",sql.String());\n\tsqlite_get_table(dbData, sql.String(), &result, &nRows, &nCols, &dbErrMsg);\n\/\/printf (\"got:%ix%i, %s\\n\", nRows, nCols, dbErrMsg);\n\tif (nRows < 1) {\n\t\t\/\/ nothin'?\n\t} else {\n\t\ti = nCols;\n\t\tj = 1;\n\t\tfsummarows = nRows;\n\t\tfsumma = new summary[nRows];\n\t\twhile (j <= nRows) {\n\t\t\tfsumma[j-1].summa[0] = decround(result[i++]);\n\t\t\tfsumma[j-1].summa[1] = result[i++];\n\t\t\tfsumma[j-1].summa[2] = decround(result[i++]);\n\t\t\tfsumma[j-1].summa[3] = decround(result[i++]);\n\t\t\tj++;\n\t\t}\n\t}\n\tsqlite_free_table(result);\n\t\/\/ obliczyc RAZEM\n\tsql = \"SELECT SUM(s.wnetto), v.nazwa, SUM(s.wvat), SUM(s.wbrutto) FROM sumawydruk AS s, stawka_vat AS v WHERE v.id = s.vatid\";\n\/\/printf(\"sql:[%s]\\n\",sql.String());\n\tsqlite_get_table(dbData, sql.String(), &result, &nRows, &nCols, &dbErrMsg);\n\/\/printf (\"got:%ix%i, %s\\n\", nRows, nCols, dbErrMsg);\n\tif (nRows < 1) {\n\t\t\/\/ nothin'?\n\t} else {\n\t\ti = nCols;\n\t\trazem.summa[0] = decround(result[i++]);\n\t\trazem.summa[1] = result[i++];\n\t\trazem.summa[2] = decround(result[i++]);\n\t\trazem.summa[3] = decround(result[i++]);\n\t}\n\tsqlite_free_table(result);\n}\n\nbeFakPrint::~beFakPrint() {\n\/\/printf(\"at the end call destructor from baseclass\\n\");\n\tflist->execSQL(\"DROP TABLE sumawydruk\");\n\tdelete [] fsumma;\n\n\tdelete flist;\n\tdelete fdata;\n}\n\nconst char *setki[] = { \"\", \"sto \", \"dwieście \", \"trzysta \", \"czterysta \", \"pięćset \", \"sześćset \", \"siedemset \", \"osiemset \", \"dziewięćset \" };\nconst char *dziesiatki[] = { \"\", \"\", \"dwadzieścia \", \"trzydzieści \", \"czterdzieści \", \"pięćdziesiąt \", \"sześćdziesiąt\", \"siedemdziesiąt \", \"osiemdziesiąt \", \"dziewięćdziesiąt \" };\nconst char *nascie[] = { \"dziesięć \", \"jedenaście \", \"dwanaście \", \"trzynaście \", \"czternaście \", \"piętnaście \", \"szesnaście \", \"siedemnaście \", \"osiemnaście \", \"dziewiętnaście \" };\nconst char *jednosci[] = { \"\", \"jeden \", \"dwa \", \"trzy \", \"cztery \", \"pięć \", \"sześć \", \"siedem \", \"osiem \", \"dziewięć \" };\n\nconst char *beFakPrint::rozbij_tysiac(int val) {\n\tstatic BString tmp;\n\tint i;\n\tint t = val;\n\n\ttmp = \"\";\n\ti = t \/ 100;\n\ttmp += setki[i];\n\tt = t % 100;\n\ti = t \/ 10;\n\tt = t % 10;\n\tif (i!=1) {\n\t\ttmp += dziesiatki[i];\n\t\ttmp += jednosci[t];\n\t} else {\n\t\ttmp += nascie[t];\n\t}\n\treturn tmp.String();\n}\n\nconst char *beFakPrint::slownie(const char *input) {\n\tstatic BString tmp;\n\n\tint i = 0;\n\tint l = strlen(input);\n\tchar c;\n\n\tint z = 0;\t\t\/\/ zlote\n\tint g = 0;\t\t\/\/ grosze\n\tint w = 0;\t\t\/\/ wykladnik\n\tbool grosze = false;\n\ttmp = \"\";\n\n\twhile (i"} {"text":"\/*\n * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n#include \"CppUTest\/TestHarness.h\"\n#include \"CppUTest\/FailableMemoryAllocator.h\"\n#include \"CppUTest\/TestTestingFixture.h\"\n\n\n\/\/ Allocator must be global. Otherwise, it does not exist when memory leak detector\n\/\/ reports memory leaks.\nstatic FailableMemoryAllocator failableMallocAllocator(\"Failable Malloc Allocator\", \"malloc\", \"free\");\nstatic FailableMemoryAllocator failableNewAllocator(\"Failable New Allocator\", \"new\", \"delete\");\nstatic FailableMemoryAllocator failableNewArrayAllocator(\"Failable New [] Allocator\", \"new []\", \"delete []\");\n\n\n#if CPPUTEST_USE_MEM_LEAK_DETECTION\n\nTEST_GROUP(FailableMemoryAllocator)\n{\n void setup()\n {\n failableMallocAllocator.clearFailedAllocations();\n failableNewAllocator.clearFailedAllocations();\n failableNewArrayAllocator.clearFailedAllocations();\n\n setCurrentMallocAllocator(&failableMallocAllocator);\n setCurrentNewAllocator(&failableNewAllocator);\n setCurrentNewArrayAllocator(&failableNewArrayAllocator);\n }\n void teardown()\n {\n setCurrentMallocAllocatorToDefault();\n setCurrentNewAllocatorToDefault();\n setCurrentNewArrayAllocatorToDefault();\n }\n};\n\n#if CPPUTEST_USE_MALLOC_MACROS\nTEST(FailableMemoryAllocator, MallocWorksNormallyIfNotAskedToFail)\n{\n int *memory = (int*)malloc(sizeof(int));\n *memory = 1;\n CHECK(memory != NULL);\n free(memory);\n}\n\nTEST(FailableMemoryAllocator, FailFirstMalloc)\n{\n failableMallocAllocator.failAllocNumber(1);\n POINTERS_EQUAL(NULL, (int*)malloc(sizeof(int)));\n}\n\nTEST(FailableMemoryAllocator, FailSecondAndFourthMalloc)\n{\n failableMallocAllocator.failAllocNumber(2);\n failableMallocAllocator.failAllocNumber(4);\n int *memory1 = (int*)malloc(sizeof(int));\n int *memory2 = (int*)malloc(sizeof(int));\n int *memory3 = (int*)malloc(sizeof(int));\n int *memory4 = (int*)malloc(sizeof(int));\n\n CHECK(NULL != memory1);\n POINTERS_EQUAL(NULL, memory2);\n CHECK(NULL != memory3);\n POINTERS_EQUAL(NULL, memory4);\n\n free(memory1);\n free(memory3);\n}\n\nstatic void _setUpTooManyFailedMallocs()\n{\n FailableMemoryAllocator allocator;\n for (int i = 0; i <= allocator.MAX_NUMBER_OF_FAILED_ALLOCS; i++)\n allocator.failAllocNumber(i + 1);\n}\n\nTEST(FailableMemoryAllocator, SettingUpTooManyFailedAllocsWillFail)\n{\n TestTestingFixture *fixture = new TestTestingFixture;\n fixture->setTestFunction(_setUpTooManyFailedMallocs);\n\n fixture->runAllTests();\n\n LONGS_EQUAL(1, fixture->getFailureCount());\n fixture->assertPrintContains(\"Maximum number of failed memory allocations exceeded\");\n delete fixture;\n}\n#endif\n\nTEST(FailableMemoryAllocator, NewWorksNormallyIfNotAskedToFail)\n{\n int *memory = new int;\n *memory = 1;\n CHECK(memory != NULL);\n delete memory;\n}\n\nTEST(FailableMemoryAllocator, NewArrayWorksNormallyIfNotAskedToFail)\n{\n int *memory = new int[10];\n memory[0] = 1;\n CHECK(memory != NULL);\n delete [] memory;\n}\n\n#if CPPUTEST_USE_STD_CPP_LIB\n\nTEST(FailableMemoryAllocator, FailSecondNewRaisesException)\n{\n failableNewAllocator.failAllocNumber(2);\n int *memory1 = new int;\n\n CHECK_THROWS(std::bad_alloc, new int);\n\n delete memory1;\n}\n\nTEST(FailableMemoryAllocator, FailSecondNewArrayRaisesException)\n{\n failableNewArrayAllocator.failAllocNumber(2);\n int *memory1 = new int[10];\n\n CHECK_THROWS(std::bad_alloc, new int[10]);\n\n delete [] memory1;\n}\n\n#endif\n\n#ifdef __clang__\nIGNORE_TEST(FailableMemoryAllocator, FailSecondAndFourthNewNoThrow)\n{\n \/* Clang misbehaves with -O2 - it will not overload operator new or\n * operator new[] no matter what. Therefore, this test is must be ignored.\n *\/\n}\n#else\n\n#if CPPUTEST_USE_STD_CPP_LIB\n#define STD_NOTHROW (std::nothrow)\n#else\n#define STD_NOTHROW\n#endif\n\nTEST(FailableMemoryAllocator, FailSecondAndFourthNewNoThrow)\n{\n#undef new\n failableNewAllocator.failAllocNumber(2);\n failableNewAllocator.failAllocNumber(4);\n int *memory1 = new STD_NOTHROW int;\n int *memory2 = new STD_NOTHROW int;\n int *memory3 = new STD_NOTHROW int;\n int *memory4 = new STD_NOTHROW int;\n\n CHECK(NULL != memory1);\n POINTERS_EQUAL(NULL, memory2);\n CHECK(NULL != memory3);\n POINTERS_EQUAL(NULL, memory4);\n\n delete memory1;\n delete memory3;\n}\n#endif\n\n#ifdef __clang__\nIGNORE_TEST(FailableMemoryAllocator, FailSecondAndFourthNewArrayNoThrow)\n{\n \/* Clang misbehaves with -O2 - it will not overload operator new or\n * operator new[] no matter what. Therefore, this test is must be ignored.\n *\/\n}\n#else\n\nTEST(FailableMemoryAllocator, FailSecondAndFourthNewArrayNoThrow)\n{\n failableNewArrayAllocator.failAllocNumber(2);\n failableNewArrayAllocator.failAllocNumber(4);\n int *memory1 = new STD_NOTHROW int[10];\n int *memory2 = new STD_NOTHROW int[10];\n int *memory3 = new STD_NOTHROW int[10];\n int *memory4 = new STD_NOTHROW int[10];\n\n CHECK(NULL != memory1);\n POINTERS_EQUAL(NULL, memory2);\n CHECK(NULL != memory3);\n POINTERS_EQUAL(NULL, memory4);\n\n delete [] memory1;\n delete [] memory3;\n}\n#endif\n\n#endif\nCreate TestTestingFixture in stack instead of new-delete\/*\n * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n#include \"CppUTest\/TestHarness.h\"\n#include \"CppUTest\/FailableMemoryAllocator.h\"\n#include \"CppUTest\/TestTestingFixture.h\"\n\n\n\/\/ Allocator must be global. Otherwise, it does not exist when memory leak detector\n\/\/ reports memory leaks.\nstatic FailableMemoryAllocator failableMallocAllocator(\"Failable Malloc Allocator\", \"malloc\", \"free\");\nstatic FailableMemoryAllocator failableNewAllocator(\"Failable New Allocator\", \"new\", \"delete\");\nstatic FailableMemoryAllocator failableNewArrayAllocator(\"Failable New [] Allocator\", \"new []\", \"delete []\");\n\n\n#if CPPUTEST_USE_MEM_LEAK_DETECTION\n\nTEST_GROUP(FailableMemoryAllocator)\n{\n void setup()\n {\n failableMallocAllocator.clearFailedAllocations();\n failableNewAllocator.clearFailedAllocations();\n failableNewArrayAllocator.clearFailedAllocations();\n\n setCurrentMallocAllocator(&failableMallocAllocator);\n setCurrentNewAllocator(&failableNewAllocator);\n setCurrentNewArrayAllocator(&failableNewArrayAllocator);\n }\n void teardown()\n {\n setCurrentMallocAllocatorToDefault();\n setCurrentNewAllocatorToDefault();\n setCurrentNewArrayAllocatorToDefault();\n }\n};\n\n#if CPPUTEST_USE_MALLOC_MACROS\nTEST(FailableMemoryAllocator, MallocWorksNormallyIfNotAskedToFail)\n{\n int *memory = (int*)malloc(sizeof(int));\n *memory = 1;\n CHECK(memory != NULL);\n free(memory);\n}\n\nTEST(FailableMemoryAllocator, FailFirstMalloc)\n{\n failableMallocAllocator.failAllocNumber(1);\n POINTERS_EQUAL(NULL, (int*)malloc(sizeof(int)));\n}\n\nTEST(FailableMemoryAllocator, FailSecondAndFourthMalloc)\n{\n failableMallocAllocator.failAllocNumber(2);\n failableMallocAllocator.failAllocNumber(4);\n int *memory1 = (int*)malloc(sizeof(int));\n int *memory2 = (int*)malloc(sizeof(int));\n int *memory3 = (int*)malloc(sizeof(int));\n int *memory4 = (int*)malloc(sizeof(int));\n\n CHECK(NULL != memory1);\n POINTERS_EQUAL(NULL, memory2);\n CHECK(NULL != memory3);\n POINTERS_EQUAL(NULL, memory4);\n\n free(memory1);\n free(memory3);\n}\n\nstatic void _setUpTooManyFailedMallocs()\n{\n FailableMemoryAllocator allocator;\n for (int i = 0; i <= allocator.MAX_NUMBER_OF_FAILED_ALLOCS; i++)\n allocator.failAllocNumber(i + 1);\n}\n\nTEST(FailableMemoryAllocator, SettingUpTooManyFailedAllocsWillFail)\n{\n TestTestingFixture fixture;\n fixture.setTestFunction(_setUpTooManyFailedMallocs);\n\n fixture.runAllTests();\n\n LONGS_EQUAL(1, fixture.getFailureCount());\n fixture.assertPrintContains(\"Maximum number of failed memory allocations exceeded\");\n}\n#endif\n\nTEST(FailableMemoryAllocator, NewWorksNormallyIfNotAskedToFail)\n{\n int *memory = new int;\n *memory = 1;\n CHECK(memory != NULL);\n delete memory;\n}\n\nTEST(FailableMemoryAllocator, NewArrayWorksNormallyIfNotAskedToFail)\n{\n int *memory = new int[10];\n memory[0] = 1;\n CHECK(memory != NULL);\n delete [] memory;\n}\n\n#if CPPUTEST_USE_STD_CPP_LIB\n\nTEST(FailableMemoryAllocator, FailSecondNewRaisesException)\n{\n failableNewAllocator.failAllocNumber(2);\n int *memory1 = new int;\n\n CHECK_THROWS(std::bad_alloc, new int);\n\n delete memory1;\n}\n\nTEST(FailableMemoryAllocator, FailSecondNewArrayRaisesException)\n{\n failableNewArrayAllocator.failAllocNumber(2);\n int *memory1 = new int[10];\n\n CHECK_THROWS(std::bad_alloc, new int[10]);\n\n delete [] memory1;\n}\n\n#endif\n\n#ifdef __clang__\nIGNORE_TEST(FailableMemoryAllocator, FailSecondAndFourthNewNoThrow)\n{\n \/* Clang misbehaves with -O2 - it will not overload operator new or\n * operator new[] no matter what. Therefore, this test is must be ignored.\n *\/\n}\n#else\n\n#if CPPUTEST_USE_STD_CPP_LIB\n#define STD_NOTHROW (std::nothrow)\n#else\n#define STD_NOTHROW\n#endif\n\nTEST(FailableMemoryAllocator, FailSecondAndFourthNewNoThrow)\n{\n#undef new\n failableNewAllocator.failAllocNumber(2);\n failableNewAllocator.failAllocNumber(4);\n int *memory1 = new STD_NOTHROW int;\n int *memory2 = new STD_NOTHROW int;\n int *memory3 = new STD_NOTHROW int;\n int *memory4 = new STD_NOTHROW int;\n\n CHECK(NULL != memory1);\n POINTERS_EQUAL(NULL, memory2);\n CHECK(NULL != memory3);\n POINTERS_EQUAL(NULL, memory4);\n\n delete memory1;\n delete memory3;\n}\n#endif\n\n#ifdef __clang__\nIGNORE_TEST(FailableMemoryAllocator, FailSecondAndFourthNewArrayNoThrow)\n{\n \/* Clang misbehaves with -O2 - it will not overload operator new or\n * operator new[] no matter what. Therefore, this test is must be ignored.\n *\/\n}\n#else\n\nTEST(FailableMemoryAllocator, FailSecondAndFourthNewArrayNoThrow)\n{\n failableNewArrayAllocator.failAllocNumber(2);\n failableNewArrayAllocator.failAllocNumber(4);\n int *memory1 = new STD_NOTHROW int[10];\n int *memory2 = new STD_NOTHROW int[10];\n int *memory3 = new STD_NOTHROW int[10];\n int *memory4 = new STD_NOTHROW int[10];\n\n CHECK(NULL != memory1);\n POINTERS_EQUAL(NULL, memory2);\n CHECK(NULL != memory3);\n POINTERS_EQUAL(NULL, memory4);\n\n delete [] memory1;\n delete [] memory3;\n}\n#endif\n\n#endif\n<|endoftext|>"} {"text":"#include \"joystickDrive.hpp\"\n\n\/\/static SDL_Joystick *joystick;\n\/*\n\/\/Main now in joystickmain\nint main()\n{\n\tjoystickDrive jD;\n\n\tfor(;;)\n\t{\n\t\t\/\/jD.printLoop();\t\t\n\t\tjD.setMotor();\n\t\tjD.readJoystick();\n\t\tif(jD.shouldQuit())\n\t\t{\n\t\t\treturn(0);\n\t\t}\n\t\tusleep(4e4);\n\t\t\n\t}\n}\n*\/\njoystickDrive::joystickDrive()\n{\n\t\/\/m_motorCtr = new OSMC_driver();\t\n\tm_motorCtr = new OSMC_4wd_driver();\n\n\tquit = false;\n\tleftAnalogX = 0;\n\tleftAnalogY = 0;\n\trightAnalogX = 0;\n\trightAnalogY = 0;\n\tdPadX = 0;\n\tdPadY = 0;\n\tjoystickButtons = 0;\n\n\tjoystick_open();\n\t\n}\n\njoystickDrive::joystickDrive(OSMC_4wd_driver* osmc)\n{\t\t\n\tm_motorCtr = osmc;\t\n\tquit = false;\n\tleftAnalogX = 0;\n\tleftAnalogY = 0;\n\trightAnalogX = 0;\n\trightAnalogY = 0;\n\tdPadX = 0;\n\tdPadY = 0;\n\tjoystickButtons = 0;\n\n\tjoystick_open();\n}\n\njoystickDrive::~joystickDrive()\n{\n\tjoystick_close();\n}\n\n\n\/\/return [0,2 PI], normal math def\ninline double joystickDrive::getHeading()\n{\n\t\/\/double theta = atan2(-1*rightAnalogY, rightAnalogX);\n\tdouble theta = atan2(-1*leftAnalogY, leftAnalogX);\n \n\treturn theta;\n}\n\ninline double scaleThrottle(double t)\n{\n\tconst double slope = (double)100\/(double)255;\n\tstd::cout << \"t: \" << t << \"\\tf(t):\" << (t-50)*slope + 50 << std::endl;\n\treturn( (t-50)*slope + 50 );\n}\n#if 0\nvoid joystickDrive::setMotor()\n{\n\treadJoystick();\n\t\n\tdouble mag = abs(leftAnalogY);\n\n\tdouble realmag = sqrt(leftAnalogX*leftAnalogX + leftAnalogY*leftAnalogY) \/ (double(32768)*sqrt(2)) * 225;\n\n\tif(realmag < 50)\n\t{\n\t\tm_motorCtr.setMotorPWM(MC_MOTOR_FORWARD, 0, MC_MOTOR_FORWARD, 0);\n\t\treturn;\n\t}\n\n\tdouble vel = mag \/ (double(32768)*sqrt(2)) * 110;\n\n\tdouble side = leftAnalogX \/ (double(32768)*sqrt(2)) * double(120) \/ double(5);\n\n\tdouble rvel = -1, lvel = -1;\n\n\trvel = vel + side;\n\t\/\/lvel = vel - 1.5*side + 55;\n\tlvel = vel - side;\n\n\n\t\/\/turbo\n\tif((joystickButtons & 32) == 32)\n\t{\n\t\trvel += 20;\n\t\tlvel += 20;\n\t}\n\t\/\/turbo\n\tif((joystickButtons & 128) == 128)\n\t{\n\t\trvel += 40;\n\t\tlvel += 40;\n\t}\n\n\t\/\/force tight turn\n\tif((joystickButtons & 1) == 1)\n\t{\n\t\tm_motorCtr.setMotorPWM(MC_MOTOR_FORWARD, 0, MC_MOTOR_FORWARD, rvel);\n\t\tstd::cout << \"btn:\" << joystickButtons << \"\\tleft at (\"<< leftAnalogX << \",\" << leftAnalogY << \")\\twould have set left: \" << 0 << \" right: \" << vel << std::endl;\n\t\treturn;\n\t}\n\telse if((joystickButtons & 4) == 4)\n\t{\n\t\tm_motorCtr.setMotorPWM(MC_MOTOR_FORWARD, lvel, MC_MOTOR_FORWARD, 0);\n\t\tstd::cout << \"btn:\" << joystickButtons << \"\\tleft at (\"<< leftAnalogX << \",\" << leftAnalogY << \")\\twould have set left: \" << vel << \" right: \" << 0 << std::endl;\n\t\treturn;\n\t}\n\tdouble r = -1,l=-1;\n\t#if 0\n\tif(!qD.getEncoderVel(r,l))\n\t{\n\t\tstd::cout << \"r: \" << r << \"l: \" << l << std::endl;\n\t}\n\t#endif\n\tstd::cout << \"btn:\" << joystickButtons << \"\\tleft at (\"<< leftAnalogX << \",\" << leftAnalogY << \")\\twould have set left: \" << lvel << \" right: \" << rvel << \" side: \" << side < 255)\/\/dead zone\n\t{\n\t\trvel = 0;\n\t}\n\telse\n\t{\n\t\tif(rvel > 0)\n\t\t{\n\t\t\trvel = (rvel - 50) * 2;\n\t\t}\n\t\telse\n\t\t{\n\t\t\trvel = (rvel + 50) * 2;\n\t\t}\n\t}\n\tif(abs(lvel) < 50 || isnan(lvel) || isinf(lvel) || lvel > 255)\/\/dead zone\n\t{\n\t\tlvel = 0;\n\t}\n\telse\n\t{\n\t\tif(lvel > 0)\n\t\t{\n\t\t\tlvel = (lvel - 50) * 2;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tlvel = (lvel + 50) * 2;\n\t\t}\n\t}\n\t\/\/turbo\n\tif((joystickButtons & 32) == 32)\n\t{\n\t\trvel += (rvel >= 0) ? 30 : -30;\n\t\tlvel += (lvel >= 0) ? 30 : -30;\n\t}\n\t\/\/turbo\n\tif((joystickButtons & 128) == 128)\n\t{\n\t\trvel += (rvel >= 0) ? 30 : -30;\n\t\tlvel += (lvel >= 0) ? 30 : -30;\n\t}\n\t\/\/backward\n\t\/*if((joystickButtons & ) == )\n\t{\n\t\trvel -= (rvel >= 0) ? 30 : -30;\n\t\tlvel -= (lvel >= 0) ? 30 : -30;\n\t}\n\tif ((joystickButtons & ) == )\n\t{\n\t\trvel -= (rvel >= 0) ? 30 : -30;\n\t\tlvel -= (lvel >= 0) ? 30 : -30;\n\t}\n\t*\/\n\t\/\/force tight turn\n\tif((joystickButtons & 1) == 1)\n\t{\n\t\tlvel = 0;\n\t}\n\telse if((joystickButtons & 4) == 4)\n\t{\n\t\trvel = 0;\n\t}\n\n\n\tstd::cout << \"btn:\" << joystickButtons << \"\\tleft at (\"<< leftAnalogX << \",\" << leftAnalogY << \") right at (\" << rightAnalogX << \",\" << rightAnalogY << \")\\twould have set lvel: \" << lvel << \" rvel: \" << rvel << std::endl;\n\n\t\/\/ Find button values\n\tprintLoop();\n\n\t\/\/if(m_motorCtr->setMotorPWM(lvel, rvel,lvel, rvel))\n\tif(m_motorCtr->setMotorPWM(rvel, lvel,rvel, lvel))\n\t{\n\t\tstd::cerr << \"set failed\" << std::endl;\n\t}\n}\n#endif\nvoid joystickDrive::joystick_close(void) {\n\t\/\/ Send an SDL_QUIT event to the joystick event loop\n\tSDL_QuitEvent quitEvent = { SDL_QUIT };\n\tSDL_PushEvent((SDL_Event*) &quitEvent);\n}\n\n\/**\n * Opens the joystick.\n * \n * @return\t\tNULL if success;\n * \t\t\t\tor a message if error.\n *\/\nconst char* joystickDrive::joystick_open(void) {\n\tint err;\n\t\n\t\/\/ Initialize SDL\n\tif ( SDL_Init(SDL_INIT_VIDEO|SDL_INIT_JOYSTICK) < 0 ) {\n\t\treturn SDL_GetError();\n\t}\n\t\n\tjoystick = SDL_JoystickOpen(0);\n\tif (!SDL_JoystickOpened(0)) {\n\t\t\/\/ TODO: would it work to return SDL_GetError() here?\n\t\treturn \"SDL_JoystickOpen failed\";\n\t}\n\t\n\t\/\/ Call joystick_run() in new thread\n\t\/\/err = pthread_create(&joystick_thread, NULL, &joystick_run, NULL);\n\tswitch (err) {\n\t\tcase EAGAIN:\n\t\t\treturn \"insufficient thread resources\";\n\t\tcase EINVAL:\n\t\t\treturn \"invalid thread attributes\";\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\t\n\treturn NULL;\t\/\/ no error\n}\n\nvoid joystickDrive::readJoystick() {\n\tint i;\n\tint done;\n\tSDL_Event event;\n\t\n\t\/*\n\t\/\/ Ignore initial events during startup\n\tfor (i=0;i<20;i++) {\n\t\tSDL_PollEvent(&event);\n\t}\n\t*\/\n\t\/\/ Poll the joystick for events, and update globals\n\tdone = 0;\n\t\twhile ( SDL_PollEvent(&event) ) {\n\t\t\tswitch (event.type) {\n\t\t\t\tcase SDL_JOYAXISMOTION:\n\t\t\t\t\tswitch (event.jaxis.axis) {\n\t\t\t\t\t\tcase 0:\n\t\t\t\t\t\t\tleftAnalogX = event.jaxis.value;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 1:\n\t\t\t\t\t\t\tleftAnalogY = event.jaxis.value;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 2:\n\t\t\t\t\t\t\trightAnalogX = event.jaxis.value;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 3:\n\t\t\t\t\t\t\trightAnalogY = event.jaxis.value;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 4:\n\t\t\t\t\t\t\tdPadX = event.jaxis.value;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 5:\n\t\t\t\t\t\t\tdPadY = event.jaxis.value;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase SDL_JOYBUTTONDOWN:\n\t\t\t\t\tjoystickButtons |= (1 << event.jbutton.button);\n\t\t\t\t\tbreak;\n\t\t\t\tcase SDL_JOYBUTTONUP:\n\t\t\t\t\tjoystickButtons &= ~(1 << event.jbutton.button);\n\t\t\t\t\tbreak;\n\t\t\t\t\/*\n\t\t\t\tcase SDL_KEYDOWN:\n\t\t\t\t\tif ( event.key.keysym.sym != SDLK_ESCAPE ) {\/\/this line doesnt work\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t\/\/ Fall through to signal quit\n\t\t\t\t*\/\n\t\t\t\tcase SDL_QUIT:\n\t\t\t\t\t\/\/done = 1;\n\t\t\t\t\t\/\/exit(-1);\n\t\t\t\t\tquit = true;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n}\n\nbool joystickDrive::shouldQuit()\n{\n\treturn(quit);\n}\n\nbool joystickDrive::manualOverride()\n{\n\treturn check_button(RT_TRIG);\t\n\t\/\/ Checks if the manual override button is pressed\n}\n\nvoid joystickDrive::printLoop()\n\/\/ Helper method for figuring out buttons on joystick\n{\n\tfor(;;)\n\t{\n\t\treadJoystick();\t\n\t\tstd::cout << \"Button value: \" << std::hex << joystickButtons << \"\\n\";\n\t\tbool t = joystickButtons << 8;\n\t\tstd::cout << t << \"\\n\";\t\n\t\tusleep(1e5);bool check_button(BUTTON);\n\t}\n}\n\nbool joystickDrive::check_button(BUTTON b)\n{\n\treadJoystick();\n\treturn (bool)(joystickButtons & 1<start working on backward joystick#include \"joystickDrive.hpp\"\n\n\/\/static SDL_Joystick *joystick;\n\/*\n\/\/Main now in joystickmain\nint main()\n{\n\tjoystickDrive jD;\n\n\tfor(;;)\n\t{\n\t\t\/\/jD.printLoop();\t\t\n\t\tjD.setMotor();\n\t\tjD.readJoystick();\n\t\tif(jD.shouldQuit())\n\t\t{\n\t\t\treturn(0);\n\t\t}\n\t\tusleep(4e4);\n\t\t\n\t}\n}\n*\/\njoystickDrive::joystickDrive()\n{\n\t\/\/m_motorCtr = new OSMC_driver();\t\n\tm_motorCtr = new OSMC_4wd_driver();\n\n\tquit = false;\n\tleftAnalogX = 0;\n\tleftAnalogY = 0;\n\trightAnalogX = 0;\n\trightAnalogY = 0;\n\tdPadX = 0;\n\tdPadY = 0;\n\tjoystickButtons = 0;\n\n\tjoystick_open();\n\t\n}\n\njoystickDrive::joystickDrive(OSMC_4wd_driver* osmc)\n{\t\t\n\tm_motorCtr = osmc;\t\n\tquit = false;\n\tleftAnalogX = 0;\n\tleftAnalogY = 0;\n\trightAnalogX = 0;\n\trightAnalogY = 0;\n\tdPadX = 0;\n\tdPadY = 0;\n\tjoystickButtons = 0;\n\n\tjoystick_open();\n}\n\njoystickDrive::~joystickDrive()\n{\n\tjoystick_close();\n}\n\n\n\/\/return [0,2 PI], normal math def\ninline double joystickDrive::getHeading()\n{\n\t\/\/double theta = atan2(-1*rightAnalogY, rightAnalogX);\n\tdouble theta = atan2(-1*leftAnalogY, leftAnalogX);\n \n\treturn theta;\n}\n\ninline double scaleThrottle(double t)\n{\n\tconst double slope = (double)100\/(double)255;\n\tstd::cout << \"t: \" << t << \"\\tf(t):\" << (t-50)*slope + 50 << std::endl;\n\treturn( (t-50)*slope + 50 );\n}\n#if 0\nvoid joystickDrive::setMotor()\n{\n\treadJoystick();\n\t\n\tdouble mag = abs(leftAnalogY);\n\n\tdouble realmag = sqrt(leftAnalogX*leftAnalogX + leftAnalogY*leftAnalogY) \/ (double(32768)*sqrt(2)) * 225;\n\n\tif(realmag < 50)\n\t{\n\t\tm_motorCtr.setMotorPWM(MC_MOTOR_FORWARD, 0, MC_MOTOR_FORWARD, 0);\n\t\treturn;\n\t}\n\n\tdouble vel = mag \/ (double(32768)*sqrt(2)) * 110;\n\n\tdouble side = leftAnalogX \/ (double(32768)*sqrt(2)) * double(120) \/ double(5);\n\n\tdouble rvel = -1, lvel = -1;\n\n\trvel = vel + side;\n\t\/\/lvel = vel - 1.5*side + 55;\n\tlvel = vel - side;\n\n\n\t\/\/turbo\n\tif((joystickButtons & 32) == 32)\n\t{\n\t\trvel += 20;\n\t\tlvel += 20;\n\t}\n\t\/\/turbo\n\tif((joystickButtons & 128) == 128)\n\t{\n\t\trvel += 40;\n\t\tlvel += 40;\n\t}\n\n\t\/\/force tight turn\n\tif((joystickButtons & 1) == 1)\n\t{\n\t\tm_motorCtr.setMotorPWM(MC_MOTOR_FORWARD, 0, MC_MOTOR_FORWARD, rvel);\n\t\tstd::cout << \"btn:\" << joystickButtons << \"\\tleft at (\"<< leftAnalogX << \",\" << leftAnalogY << \")\\twould have set left: \" << 0 << \" right: \" << vel << std::endl;\n\t\treturn;\n\t}\n\telse if((joystickButtons & 4) == 4)\n\t{\n\t\tm_motorCtr.setMotorPWM(MC_MOTOR_FORWARD, lvel, MC_MOTOR_FORWARD, 0);\n\t\tstd::cout << \"btn:\" << joystickButtons << \"\\tleft at (\"<< leftAnalogX << \",\" << leftAnalogY << \")\\twould have set left: \" << vel << \" right: \" << 0 << std::endl;\n\t\treturn;\n\t}\n\tdouble r = -1,l=-1;\n\t#if 0\n\tif(!qD.getEncoderVel(r,l))\n\t{\n\t\tstd::cout << \"r: \" << r << \"l: \" << l << std::endl;\n\t}\n\t#endif\n\tstd::cout << \"btn:\" << joystickButtons << \"\\tleft at (\"<< leftAnalogX << \",\" << leftAnalogY << \")\\twould have set left: \" << lvel << \" right: \" << rvel << \" side: \" << side < 255)\/\/dead zone\n\t{\n\t\trvel = 0;\n\t}\n\telse\n\t{\n\t\tif(rvel > 0)\n\t\t{\n\t\t\trvel = (rvel - 50) * 2;\n\t\t}\n\t\telse\n\t\t{\n\t\t\trvel = (rvel + 50) * 2;\n\t\t}\n\t}\n\tif(abs(lvel) < 50 || isnan(lvel) || isinf(lvel) || lvel > 255)\/\/dead zone\n\t{\n\t\tlvel = 0;\n\t}\n\telse\n\t{\n\t\tif(lvel > 0)\n\t\t{\n\t\t\tlvel = (lvel - 50) * 2;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tlvel = (lvel + 50) * 2;\n\t\t}\n\t}\n\t\/\/turbo\n\tif((joystickButtons & 32) == 32)\n\t{\n\t\trvel += (rvel >= 0) ? 30 : -30;\n\t\tlvel += (lvel >= 0) ? 30 : -30;\n\t}\n\t\/\/turbo\n\tif((joystickButtons & 128) == 128)\n\t{\n\t\trvel += (rvel >= 0) ? 30 : -30;\n\t\tlvel += (lvel >= 0) ? 30 : -30;\n\t}\n\t\/*\/\/backward\n\tif((joystickButtons & 10) == 10)\n\t{\n\t\trvel -= (rvel >= 0) ? 30 : -30;\n\t\tlvel -= (lvel >= 0) ? 30 : -30;\n\t}\n\tif ((joystickButtons & 40) == 40)\n\t{\n\t\trvel -= (rvel >= 0) ? 30 : -30;\n\t\tlvel -= (lvel >= 0) ? 30 : -30;\n\t}*\/\n\t\/\/force tight turn\n\tif((joystickButtons & 1) == 1)\n\t{\n\t\tlvel = 0;\n\t}\n\telse if((joystickButtons & 4) == 4)\n\t{\n\t\trvel = 0;\n\t}\n\n\n\tstd::cout << \/*\"btn:\" << joystickButtons << *\/\"\\tleft at (\"<< leftAnalogX << \",\" << leftAnalogY << \") right at (\" << rightAnalogX << \",\" << rightAnalogY << \")\\twould have set lvel: \" << lvel << \" rvel: \" << rvel << std::endl;\n\n\t\/\/ Find button values\n\t\/\/printLoop();\n\n\t\/\/if(m_motorCtr->setMotorPWM(lvel, rvel,lvel, rvel))\n\tif(m_motorCtr->setMotorPWM(rvel, lvel,rvel, lvel))\n\t{\n\t\tstd::cerr << \"set failed\" << std::endl;\n\t}\n}\n#endif\nvoid joystickDrive::joystick_close(void) {\n\t\/\/ Send an SDL_QUIT event to the joystick event loop\n\tSDL_QuitEvent quitEvent = { SDL_QUIT };\n\tSDL_PushEvent((SDL_Event*) &quitEvent);\n}\n\n\/**\n * Opens the joystick.\n * \n * @return\t\tNULL if success;\n * \t\t\t\tor a message if error.\n *\/\nconst char* joystickDrive::joystick_open(void) {\n\tint err;\n\t\n\t\/\/ Initialize SDL\n\tif ( SDL_Init(SDL_INIT_VIDEO|SDL_INIT_JOYSTICK) < 0 ) {\n\t\treturn SDL_GetError();\n\t}\n\t\n\tjoystick = SDL_JoystickOpen(0);\n\tif (!SDL_JoystickOpened(0)) {\n\t\t\/\/ TODO: would it work to return SDL_GetError() here?\n\t\treturn \"SDL_JoystickOpen failed\";\n\t}\n\t\n\t\/\/ Call joystick_run() in new thread\n\t\/\/err = pthread_create(&joystick_thread, NULL, &joystick_run, NULL);\n\tswitch (err) {\n\t\tcase EAGAIN:\n\t\t\treturn \"insufficient thread resources\";\n\t\tcase EINVAL:\n\t\t\treturn \"invalid thread attributes\";\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\t\n\treturn NULL;\t\/\/ no error\n}\n\nvoid joystickDrive::readJoystick() {\n\tint i;\n\tint done;\n\tSDL_Event event;\n\t\n\t\/*\n\t\/\/ Ignore initial events during startup\n\tfor (i=0;i<20;i++) {\n\t\tSDL_PollEvent(&event);\n\t}\n\t*\/\n\t\/\/ Poll the joystick for events, and update globals\n\tdone = 0;\n\t\twhile ( SDL_PollEvent(&event) ) {\n\t\t\tswitch (event.type) {\n\t\t\t\tcase SDL_JOYAXISMOTION:\n\t\t\t\t\tswitch (event.jaxis.axis) {\n\t\t\t\t\t\tcase 0:\n\t\t\t\t\t\t\tleftAnalogX = event.jaxis.value;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 1:\n\t\t\t\t\t\t\tleftAnalogY = event.jaxis.value;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 2:\n\t\t\t\t\t\t\trightAnalogX = event.jaxis.value;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 3:\n\t\t\t\t\t\t\trightAnalogY = event.jaxis.value;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 4:\n\t\t\t\t\t\t\tdPadX = event.jaxis.value;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 5:\n\t\t\t\t\t\t\tdPadY = event.jaxis.value;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase SDL_JOYBUTTONDOWN:\n\t\t\t\t\tjoystickButtons |= (1 << event.jbutton.button);\n\t\t\t\t\tbreak;\n\t\t\t\tcase SDL_JOYBUTTONUP:\n\t\t\t\t\tjoystickButtons &= ~(1 << event.jbutton.button);\n\t\t\t\t\tbreak;\n\t\t\t\t\/*\n\t\t\t\tcase SDL_KEYDOWN:\n\t\t\t\t\tif ( event.key.keysym.sym != SDLK_ESCAPE ) {\/\/this line doesnt work\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t\/\/ Fall through to signal quit\n\t\t\t\t*\/\n\t\t\t\tcase SDL_QUIT:\n\t\t\t\t\t\/\/done = 1;\n\t\t\t\t\t\/\/exit(-1);\n\t\t\t\t\tquit = true;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n}\n\nbool joystickDrive::shouldQuit()\n{\n\treturn(quit);\n}\n\nbool joystickDrive::manualOverride()\n{\n\treturn check_button(RT_TRIG);\t\n\t\/\/ Checks if the manual override button is pressed\n}\n\nvoid joystickDrive::printLoop()\n\/\/ Helper method for figuring out buttons on joystick\n{\n\tfor(;;)\n\t{\n\t\treadJoystick();\t\n\t\tstd::cout << \"Button value: \" << std::hex << joystickButtons << \"\\n\";\n\t\tbool t = joystickButtons << 8;\n\t\tstd::cout << t << \"\\n\";\t\n\t\tusleep(1e5);bool check_button(BUTTON);\n\t}\n}\n\nbool joystickDrive::check_button(BUTTON b)\n{\n\treadJoystick();\n\treturn (bool)(joystickButtons & 1<"} {"text":"\n#include \n\n\n#include \"modules\/Network\/NetworkManager.hpp\"\n#include \"modules\/FileReader\/FileReaderManager.hpp\"\n#include \"modules\/ModError\/ModErrorManager.hpp\"\n#include \"modules\/DirListing\/DirListingManager.hpp\"\n#include \"utils\/macros.hpp\"\n#include \"utils\/Path.hpp\"\n\n#include \"ModuleManagerFactory.hpp\"\n\nusing namespace ZHTTPD;\n\nModuleManagerFactory::ModuleManagerFactory()\n{\n this->_builders[\"mod_network\"] = &ModuleManagerFactory::_createNetworkModuleManager;\n this->_available_modules[ZHTTPD::API::CATEGORY::INPUTOUTPUT].push_back(\"mod_network\");\n this->_builders[\"mod_filereader\"] = &ModuleManagerFactory::_createFileReaderModuleManager;\n this->_available_modules[ZHTTPD::API::CATEGORY::PROCESSING].push_back(\"mod_filereader\");\n this->_builders[\"mod_error\"] = &ModuleManagerFactory::_createModErrorModuleManager;\n this->_available_modules[ZHTTPD::API::CATEGORY::PROCESSING].push_back(\"mod_error\");\n this->_builders[\"mod_dirlisting\"] = &ModuleManagerFactory::_createDirListingModuleManager;\n this->_available_modules[ZHTTPD::API::CATEGORY::PROCESSING].push_back(\"mod_dirlisting\");\n}\n\nModuleManagerFactory::~ModuleManagerFactory()\n{\n std::map::iterator it = this->_libraries.begin(),\n end = this->_libraries.end();\n for (; it != end; ++it)\n {\n ZHTTPD_DELETE(it->second);\n }\n}\n\nvoid ModuleManagerFactory::findModules(std::string const& modules_directory)\n{\n assert(modules_directory.size() > 0 && \"modules_directory is not a valid path\");\n Path dir(modules_directory);\n if (!dir.exists())\n throw std::runtime_error(\"The path '\" + modules_directory +\"' does not exist\");\n if (!dir.isDirectory())\n throw std::runtime_error(\"The path '\"+ modules_directory +\"'is not a valid directory\");\n std::list files = dir.getDirectoryContent();\n for (std::list::iterator it = files.begin(), end = files.end(); it != end; ++it)\n {\n if (this->_isDynamicLibrary(*it))\n {\n Library* lib = 0;\n try\n {\n lib = new Library(dir + *it);\n lib_handler_t getInstance = lib->resolve(\"getInstance\");\n ZHTTPD::API::IModuleManager* manager = getInstance();\n std::string const& name = manager->getName();\n \/\/ TODO rendre possible de remplacer les modules par défaut\n \/\/ comme mod_network, mod_error, etc...\n if (this->_builders.find(name) != this->_builders.end())\n {\n throw std::runtime_error(\"Two modules with the name '\" +\n name + \"' have been found\");\n }\n this->_libraries[name] = lib;\n this->_builders[name] = &ModuleManagerFactory::_createFromLibrary;\n this->_available_modules[manager->getCategory()].push_back(name);\n \/\/ZHTTPD_DELETE(manager);\n delete manager;\n }\n catch (std::exception& err)\n {\n LOG_ERROR(\"Cannot load '\" + std::string(dir + *it) + \"': \" + err.what());\n ZHTTPD_DELETE(lib);\n }\n }\n }\n}\n\nAPI::IModuleManager* ModuleManagerFactory::getModuleManager(std::string const& name) const\n{\n std::map::const_iterator it = this->_builders.find(name);\n if (it != this->_builders.end())\n {\n return (this->*(it->second))(name);\n }\n LOG_WARN(\"Module '\" + name + \"' is not in the factory\");\n return 0;\n}\n\nModuleManagerFactory::available_modules_t const& ModuleManagerFactory::getAvailableModules() const\n{\n return this->_available_modules;\n}\n\n\nAPI::IModuleManager* ModuleManagerFactory::_createNetworkModuleManager(std::string const&) const\n{\n return new MOD::NetworkManager();\n}\n\nAPI::IModuleManager* ModuleManagerFactory::_createFileReaderModuleManager(std::string const&) const\n{\n return new MOD::FileReaderManager();\n}\n\nAPI::IModuleManager* ModuleManagerFactory::_createModErrorModuleManager(std::string const&) const\n{\n return new MOD::ModErrorManager();\n}\n\nAPI::IModuleManager* ModuleManagerFactory::_createDirListingModuleManager(std::string const&) const\n{\n return new MOD::DirListingManager();\n}\n\nAPI::IModuleManager* ModuleManagerFactory::_createFromLibrary(std::string const& name) const\n{\n std::map::const_iterator it = this->_libraries.find(name);\n assert(it != this->_libraries.end());\n lib_handler_t getInstance = it->second->resolve(\"getInstance\");\n return getInstance();\n}\n\n#ifdef _WIN32\n# define ZHTTPD_LIB_EXTENSION \"dll\"\n#else\n# define ZHTTPD_LIB_EXTENSION \"so\"\n#endif\n\nbool ModuleManagerFactory::_isDynamicLibrary(std::string const& filename) const\n{\n std::size_t i_dot = filename.find_last_of(\".\");\n if (i_dot != std::string::npos && i_dot < filename.size() - 1)\n return (filename.substr(i_dot + 1) == ZHTTPD_LIB_EXTENSION);\n return false;\n}\n\n#undef ZHTTPD_LIB_EXTENSION\n\n\nAdd security when findModules fails\n#include \n\n\n#include \"modules\/Network\/NetworkManager.hpp\"\n#include \"modules\/FileReader\/FileReaderManager.hpp\"\n#include \"modules\/ModError\/ModErrorManager.hpp\"\n#include \"modules\/DirListing\/DirListingManager.hpp\"\n#include \"utils\/macros.hpp\"\n#include \"utils\/Path.hpp\"\n\n#include \"ModuleManagerFactory.hpp\"\n\nusing namespace ZHTTPD;\n\nModuleManagerFactory::ModuleManagerFactory()\n{\n this->_builders[\"mod_network\"] = &ModuleManagerFactory::_createNetworkModuleManager;\n this->_available_modules[ZHTTPD::API::CATEGORY::INPUTOUTPUT].push_back(\"mod_network\");\n this->_builders[\"mod_filereader\"] = &ModuleManagerFactory::_createFileReaderModuleManager;\n this->_available_modules[ZHTTPD::API::CATEGORY::PROCESSING].push_back(\"mod_filereader\");\n this->_builders[\"mod_error\"] = &ModuleManagerFactory::_createModErrorModuleManager;\n this->_available_modules[ZHTTPD::API::CATEGORY::PROCESSING].push_back(\"mod_error\");\n this->_builders[\"mod_dirlisting\"] = &ModuleManagerFactory::_createDirListingModuleManager;\n this->_available_modules[ZHTTPD::API::CATEGORY::PROCESSING].push_back(\"mod_dirlisting\");\n}\n\nModuleManagerFactory::~ModuleManagerFactory()\n{\n std::map::iterator it = this->_libraries.begin(),\n end = this->_libraries.end();\n for (; it != end; ++it)\n {\n ZHTTPD_DELETE(it->second);\n }\n}\n\nvoid ModuleManagerFactory::findModules(std::string const& modules_directory)\n{\n assert(modules_directory.size() > 0 && \"modules_directory is not a valid path\");\n Path dir(modules_directory);\n if (!dir.exists())\n throw std::runtime_error(\"The path '\" + modules_directory +\"' does not exist\");\n if (!dir.isDirectory())\n throw std::runtime_error(\"The path '\"+ modules_directory +\"'is not a valid directory\");\n std::list files = dir.getDirectoryContent();\n for (std::list::iterator it = files.begin(), end = files.end(); it != end; ++it)\n {\n if (this->_isDynamicLibrary(*it))\n {\n Library* lib = 0;\n ZHTTPD::API::IModuleManager* manager = 0;\n try\n {\n lib = new Library(dir + *it);\n lib_handler_t getInstance = lib->resolve(\"getInstance\");\n manager = getInstance();\n std::string const& name = manager->getName();\n \/\/ TODO rendre possible de remplacer les modules par défaut\n \/\/ comme mod_network, mod_error, etc...\n if (this->_builders.find(name) != this->_builders.end())\n {\n throw std::runtime_error(\"Two modules with the name '\" +\n name + \"' have been found\");\n }\n this->_libraries[name] = lib;\n this->_builders[name] = &ModuleManagerFactory::_createFromLibrary;\n this->_available_modules[manager->getCategory()].push_back(name);\n ZHTTPD_DELETE(manager);\n }\n catch (std::exception& err)\n {\n LOG_ERROR(\"Cannot load '\" + std::string(dir + *it) + \"': \" + err.what());\n ZHTTPD_DELETE(lib);\n ZHTTPD_DELETE(manager);\n }\n }\n }\n}\n\nAPI::IModuleManager* ModuleManagerFactory::getModuleManager(std::string const& name) const\n{\n std::map::const_iterator it = this->_builders.find(name);\n if (it != this->_builders.end())\n {\n return (this->*(it->second))(name);\n }\n LOG_WARN(\"Module '\" + name + \"' is not in the factory\");\n return 0;\n}\n\nModuleManagerFactory::available_modules_t const& ModuleManagerFactory::getAvailableModules() const\n{\n return this->_available_modules;\n}\n\n\nAPI::IModuleManager* ModuleManagerFactory::_createNetworkModuleManager(std::string const&) const\n{\n return new MOD::NetworkManager();\n}\n\nAPI::IModuleManager* ModuleManagerFactory::_createFileReaderModuleManager(std::string const&) const\n{\n return new MOD::FileReaderManager();\n}\n\nAPI::IModuleManager* ModuleManagerFactory::_createModErrorModuleManager(std::string const&) const\n{\n return new MOD::ModErrorManager();\n}\n\nAPI::IModuleManager* ModuleManagerFactory::_createDirListingModuleManager(std::string const&) const\n{\n return new MOD::DirListingManager();\n}\n\nAPI::IModuleManager* ModuleManagerFactory::_createFromLibrary(std::string const& name) const\n{\n std::map::const_iterator it = this->_libraries.find(name);\n assert(it != this->_libraries.end());\n lib_handler_t getInstance = it->second->resolve(\"getInstance\");\n return getInstance();\n}\n\n#ifdef _WIN32\n# define ZHTTPD_LIB_EXTENSION \"dll\"\n#else\n# define ZHTTPD_LIB_EXTENSION \"so\"\n#endif\n\nbool ModuleManagerFactory::_isDynamicLibrary(std::string const& filename) const\n{\n std::size_t i_dot = filename.find_last_of(\".\");\n if (i_dot != std::string::npos && i_dot < filename.size() - 1)\n return (filename.substr(i_dot + 1) == ZHTTPD_LIB_EXTENSION);\n return false;\n}\n\n#undef ZHTTPD_LIB_EXTENSION\n\n\n<|endoftext|>"} {"text":"#include \"APSEthernet.h\"\n\nAPSEthernet::APSEthernet() : socket_(ios_) {\n \/\/Setup the socket to the APS_PROTO port and enable broadcasting for enumerating\n std::error_code ec;\n socket_.open(udp::v4(), ec);\n if (ec) {FILE_LOG(logERROR) << \"Failed to open socket.\";}\n socket_.bind(udp::endpoint(asio::ip::address::from_string(\"192.168.5.1\"), APS_PROTO), ec);\n if (ec) {FILE_LOG(logERROR) << \"Failed to bind to socket.\";}\n\n socket_.set_option(asio::socket_base::broadcast(true));\n\n \/\/io_service will return immediately so post receive task before .run()\n setup_receive();\n\n \/\/Setup the asio service to run on a background thread\n receiveThread_ = std::thread([&](){ ios_.run(); });\n\n};\n\nAPSEthernet::~APSEthernet() {\n \/\/Stop the receive thread\n ios_.stop();\n receiveThread_.join();\n}\n\nvoid APSEthernet::setup_receive(){\n socket_.async_receive_from(\n asio::buffer(receivedData_, 2048), senderEndpoint_,\n [this](std::error_code ec, std::size_t bytesReceived)\n {\n \/\/If there is anything to look at hand it off to the sorter\n if (!ec && bytesReceived > 0)\n {\n vector packetData(receivedData_, receivedData_ + bytesReceived);\n sort_packet(packetData, senderEndpoint_);\n }\n\n \/\/Start the receiver again\n setup_receive();\n });\n}\n\nvoid APSEthernet::sort_packet(const vector & packetData, const udp::endpoint & sender){\n \/\/If we have the endpoint address then add it to the queue\n string senderIP = sender.address().to_string();\n if(msgQueues_.find(senderIP) == msgQueues_.end()){\n \/\/If it isn't in our list of APSs then perhaps we are seeing an enumerate status response\n \/\/If so add the device info to the set\n if (packetData.size() == 84) {\n devInfo_[senderIP].endpoint = sender;\n \/\/Turn the byte array into a packet to extract the MAC address\n \/\/Not strictly necessary as we could just use the broadcast MAC address\n APSEthernetPacket packet = APSEthernetPacket(packetData);\n devInfo_[senderIP].macAddr = packet.header.src;\n FILE_LOG(logDEBUG1) << \"Added device with IP \" << senderIP << \" and MAC addresss \" << devInfo_[senderIP].macAddr.to_string();\n } \n }\n else{\n \/\/Turn the byte array into an APSEthernetPacket\n APSEthernetPacket packet = APSEthernetPacket(packetData);\n \/\/Grab a lock and push the packet into the message queue\n mLock_.lock();\n msgQueues_[senderIP].emplace(packet);\n mLock_.unlock();\n }\n}\n\n\/* PUBLIC methods *\/\n\nAPSEthernet::EthernetError APSEthernet::init(string nic) {\n \/*\n --Nothing doing for now\n TODO: Should eventually bind to particular NIC here?\n *\/ \n reset_maps();\n\n return SUCCESS;\n}\n\nset APSEthernet::enumerate() {\n\t\/*\n\t * Look for all APS units that respond to the broadcast packet\n\t *\/\n\n\tFILE_LOG(logDEBUG1) << \"APSEthernet::enumerate\";\n\n reset_maps();\n\n \/\/Put together the broadcast status request\n APSEthernetPacket broadcastPacket = APSEthernetPacket::create_broadcast_packet();\n udp::endpoint broadCastEndPoint(asio::ip::address_v4::broadcast(), APS_PROTO);\n socket_.send_to(asio::buffer(broadcastPacket.serialize()), broadCastEndPoint);\n\n std::this_thread::sleep_for(std::chrono::milliseconds(1000));\n\n set deviceSerials;\n for (auto kv : devInfo_) {\n FILE_LOG(logINFO) << \"Found device: \" << kv.first;\n deviceSerials.insert(kv.first);\n }\n return deviceSerials;\n}\n\nvoid APSEthernet::reset_maps() {\n devInfo_.clear();\n msgQueues_.clear();\n}\n\nAPSEthernet::EthernetError APSEthernet::connect(string serial) {\n\n mLock_.lock();\n\tmsgQueues_[serial] = queue();\n mLock_.unlock();\n\treturn SUCCESS;\n}\n\nAPSEthernet::EthernetError APSEthernet::disconnect(string serial) {\n mLock_.lock();\n\tmsgQueues_.erase(serial);\n mLock_.unlock();\n\treturn SUCCESS;\n}\n\nAPSEthernet::EthernetError APSEthernet::send(string serial, APSEthernetPacket msg){\n return send(serial, vector(1, msg));\n}\n\nAPSEthernet::EthernetError APSEthernet::send(string serial, vector msg, unsigned ackEvery \/* see header for default *\/) {\n \/\/Fill out the destination MAC address\n FILE_LOG(logDEBUG3) << \"Sending \" << msg.size() << \" packets to \" << serial;\n unsigned ackct, retryct = 0;\n auto iter = packet.begin();\n\n while (iter != msg.end()){\n auto packet = *iter;;\n\n \/\/ insert the target MAC address - not really necessary anymore because UDP does filtering\n packet.header.dest = devInfo_[serial].macAddr;\n packet.header.seqNum = ackct;\n\n ackct++;\n \/\/Apply acknowledge flag if necessary\n bool ackFlag = (ackct % ackEvery == 0) || (std::next(iter) == msg.end());\n if( ackFlag ){\n packet.header.command.ack = 1;\n }\n FILE_LOG(logDEBUG4) << \"Packet command: \" << print_APSCommand(packet.header.command);\n socket_.send_to(asio::buffer(packet.serialize()), devInfo_[serial].endpoint);\n iter++;\n\n \/\/Wait for acknowledge if we need to\n \/\/TODO: how to check response mode\/stat for success?\n if (ackFlag){\n try{\n auto response = receive(serial)[0];\n }\n catch (std::exception& e) {\n if (retryct++ < 3) {\n FILE_LOG(logDEBUG) << \"No acknowledge received, retrying ...\";\n \/\/Reset the acknowledge count\n ackct = 0;\n \/\/Go back to the last acknowledged packet\n iter -= (ackct % ackEvery == 0) ? ackEvery : ackct % ackEvery ;\n }\n else {\n return TIMEOUT;\n }\n }\n }\n }\n\n return SUCCESS;\n}\n\nvector APSEthernet::receive(string serial, size_t numPackets, size_t timeoutMS) {\n \/\/Read the packets coming back in up to the timeout\n \/\/Defaults: receive(string serial, size_t numPackets = 1, size_t timeoutMS = 1000);\n std::chrono::time_point start, end;\n\n start = std::chrono::steady_clock::now();\n size_t elapsedTime = 0;\n\n vector outVec;\n\n while (elapsedTime < timeoutMS){\n if (!msgQueues_[serial].empty()){\n mLock_.lock();\n outVec.push_back(msgQueues_[serial].front());\n msgQueues_[serial].pop();\n mLock_.unlock();\n FILE_LOG(logDEBUG4) << \"Received packet command: \" << print_APSCommand(outVec.back().header.command);\n if (outVec.size() == numPackets){\n FILE_LOG(logDEBUG3) << \"Received \" << numPackets << \" packets from \" << serial;\n return outVec;\n }\n }\n std::this_thread::sleep_for(std::chrono::milliseconds(10));\n end = std::chrono::steady_clock::now();\n elapsedTime = std::chrono::duration_cast(end-start).count();\n }\n\n throw runtime_error(\"Timed out on receive\");\n}\n\nShould actually have tried to compile previous commit.#include \"APSEthernet.h\"\n\nAPSEthernet::APSEthernet() : socket_(ios_) {\n \/\/Setup the socket to the APS_PROTO port and enable broadcasting for enumerating\n std::error_code ec;\n socket_.open(udp::v4(), ec);\n if (ec) {FILE_LOG(logERROR) << \"Failed to open socket.\";}\n socket_.bind(udp::endpoint(asio::ip::address::from_string(\"192.168.5.1\"), APS_PROTO), ec);\n if (ec) {FILE_LOG(logERROR) << \"Failed to bind to socket.\";}\n\n socket_.set_option(asio::socket_base::broadcast(true));\n\n \/\/io_service will return immediately so post receive task before .run()\n setup_receive();\n\n \/\/Setup the asio service to run on a background thread\n receiveThread_ = std::thread([&](){ ios_.run(); });\n\n};\n\nAPSEthernet::~APSEthernet() {\n \/\/Stop the receive thread\n ios_.stop();\n receiveThread_.join();\n}\n\nvoid APSEthernet::setup_receive(){\n socket_.async_receive_from(\n asio::buffer(receivedData_, 2048), senderEndpoint_,\n [this](std::error_code ec, std::size_t bytesReceived)\n {\n \/\/If there is anything to look at hand it off to the sorter\n if (!ec && bytesReceived > 0)\n {\n vector packetData(receivedData_, receivedData_ + bytesReceived);\n sort_packet(packetData, senderEndpoint_);\n }\n\n \/\/Start the receiver again\n setup_receive();\n });\n}\n\nvoid APSEthernet::sort_packet(const vector & packetData, const udp::endpoint & sender){\n \/\/If we have the endpoint address then add it to the queue\n string senderIP = sender.address().to_string();\n if(msgQueues_.find(senderIP) == msgQueues_.end()){\n \/\/If it isn't in our list of APSs then perhaps we are seeing an enumerate status response\n \/\/If so add the device info to the set\n if (packetData.size() == 84) {\n devInfo_[senderIP].endpoint = sender;\n \/\/Turn the byte array into a packet to extract the MAC address\n \/\/Not strictly necessary as we could just use the broadcast MAC address\n APSEthernetPacket packet = APSEthernetPacket(packetData);\n devInfo_[senderIP].macAddr = packet.header.src;\n FILE_LOG(logDEBUG1) << \"Added device with IP \" << senderIP << \" and MAC addresss \" << devInfo_[senderIP].macAddr.to_string();\n } \n }\n else{\n \/\/Turn the byte array into an APSEthernetPacket\n APSEthernetPacket packet = APSEthernetPacket(packetData);\n \/\/Grab a lock and push the packet into the message queue\n mLock_.lock();\n msgQueues_[senderIP].emplace(packet);\n mLock_.unlock();\n }\n}\n\n\/* PUBLIC methods *\/\n\nAPSEthernet::EthernetError APSEthernet::init(string nic) {\n \/*\n --Nothing doing for now\n TODO: Should eventually bind to particular NIC here?\n *\/ \n reset_maps();\n\n return SUCCESS;\n}\n\nset APSEthernet::enumerate() {\n\t\/*\n\t * Look for all APS units that respond to the broadcast packet\n\t *\/\n\n\tFILE_LOG(logDEBUG1) << \"APSEthernet::enumerate\";\n\n reset_maps();\n\n \/\/Put together the broadcast status request\n APSEthernetPacket broadcastPacket = APSEthernetPacket::create_broadcast_packet();\n udp::endpoint broadCastEndPoint(asio::ip::address_v4::broadcast(), APS_PROTO);\n socket_.send_to(asio::buffer(broadcastPacket.serialize()), broadCastEndPoint);\n\n std::this_thread::sleep_for(std::chrono::milliseconds(1000));\n\n set deviceSerials;\n for (auto kv : devInfo_) {\n FILE_LOG(logINFO) << \"Found device: \" << kv.first;\n deviceSerials.insert(kv.first);\n }\n return deviceSerials;\n}\n\nvoid APSEthernet::reset_maps() {\n devInfo_.clear();\n msgQueues_.clear();\n}\n\nAPSEthernet::EthernetError APSEthernet::connect(string serial) {\n\n mLock_.lock();\n\tmsgQueues_[serial] = queue();\n mLock_.unlock();\n\treturn SUCCESS;\n}\n\nAPSEthernet::EthernetError APSEthernet::disconnect(string serial) {\n mLock_.lock();\n\tmsgQueues_.erase(serial);\n mLock_.unlock();\n\treturn SUCCESS;\n}\n\nAPSEthernet::EthernetError APSEthernet::send(string serial, APSEthernetPacket msg){\n return send(serial, vector(1, msg));\n}\n\nAPSEthernet::EthernetError APSEthernet::send(string serial, vector msg, unsigned ackEvery \/* see header for default *\/) {\n \/\/Fill out the destination MAC address\n FILE_LOG(logDEBUG3) << \"Sending \" << msg.size() << \" packets to \" << serial;\n unsigned ackct, retryct = 0;\n auto iter = msg.begin();\n\n while (iter != msg.end()){\n auto packet = *iter;;\n\n \/\/ insert the target MAC address - not really necessary anymore because UDP does filtering\n packet.header.dest = devInfo_[serial].macAddr;\n packet.header.seqNum = ackct;\n\n ackct++;\n \/\/Apply acknowledge flag if necessary\n bool ackFlag = (ackct % ackEvery == 0) || (std::next(iter) == msg.end());\n if( ackFlag ){\n packet.header.command.ack = 1;\n }\n FILE_LOG(logDEBUG4) << \"Packet command: \" << print_APSCommand(packet.header.command);\n socket_.send_to(asio::buffer(packet.serialize()), devInfo_[serial].endpoint);\n iter++;\n\n \/\/Wait for acknowledge if we need to\n \/\/TODO: how to check response mode\/stat for success?\n if (ackFlag){\n try{\n auto response = receive(serial)[0];\n }\n catch (std::exception& e) {\n if (retryct++ < 3) {\n FILE_LOG(logDEBUG) << \"No acknowledge received, retrying ...\";\n \/\/Reset the acknowledge count\n ackct = 0;\n \/\/Go back to the last acknowledged packet\n iter -= (ackct % ackEvery == 0) ? ackEvery : ackct % ackEvery ;\n }\n else {\n return TIMEOUT;\n }\n }\n }\n }\n\n return SUCCESS;\n}\n\nvector APSEthernet::receive(string serial, size_t numPackets, size_t timeoutMS) {\n \/\/Read the packets coming back in up to the timeout\n \/\/Defaults: receive(string serial, size_t numPackets = 1, size_t timeoutMS = 1000);\n std::chrono::time_point start, end;\n\n start = std::chrono::steady_clock::now();\n size_t elapsedTime = 0;\n\n vector outVec;\n\n while (elapsedTime < timeoutMS){\n if (!msgQueues_[serial].empty()){\n mLock_.lock();\n outVec.push_back(msgQueues_[serial].front());\n msgQueues_[serial].pop();\n mLock_.unlock();\n FILE_LOG(logDEBUG4) << \"Received packet command: \" << print_APSCommand(outVec.back().header.command);\n if (outVec.size() == numPackets){\n FILE_LOG(logDEBUG3) << \"Received \" << numPackets << \" packets from \" << serial;\n return outVec;\n }\n }\n std::this_thread::sleep_for(std::chrono::milliseconds(10));\n end = std::chrono::steady_clock::now();\n elapsedTime = std::chrono::duration_cast(end-start).count();\n }\n\n throw runtime_error(\"Timed out on receive\");\n}\n\n<|endoftext|>"} {"text":"#include \"CppUTest\/TestHarness.h\"\n#include \"CppUTestExt\/MockSupport.h\"\n\n#include \"Environment.h\"\n#include \"MockSensor.h\"\n\nstatic const char* dummy_name_01 = \"dummy_01\";\nstatic const char* dummy_name_02 = \"dummy_02\";\n\nTEST_GROUP(Environment)\n{\n Environment* env;\n void setup()\n {\n env = new Environment();\n }\n void teardown()\n {\n mock().clear();\n delete env;\n }\n};\n\nTEST(Environment, AddSensor)\n{\n MockSensor* sensor = new MockSensor(dummy_name_01);\n env->addSensor(dummy_name_01, sensor);\n LONGS_EQUAL(1, env->getNumSensor());\n}\n\nTEST(Environment, AddMultipleSensor)\n{\n MockSensor* sensor_1 = new MockSensor(dummy_name_01);\n MockSensor* sensor_2 = new MockSensor(dummy_name_02);\n env->addSensor(dummy_name_01, sensor_1);\n env->addSensor(dummy_name_02, sensor_2);\n\n LONGS_EQUAL(2, env->getNumSensor());\n\n POINTERS_EQUAL(sensor_1, env->getSensorByName(dummy_name_01));\n POINTERS_EQUAL(sensor_2, env->getSensorByName(dummy_name_02));\n}\n\nTEST(Environment, SingleSensorControl)\n{\n MockSensor* sensor = new MockSensor(dummy_name_01);\n env->addSensor(dummy_name_01, sensor);\n\n mock().expectOneCall(\"Sensor#init()\").onObject(sensor);\n env->init();\n mock().expectOneCall(\"Sensor#start()\").onObject(sensor);\n env->start();\n mock().expectOneCall(\"Sensor#stop()\").onObject(sensor);\n env->stop();\n mock().checkExpectations();\n}\nrefactor Environment Test#include \"CppUTest\/TestHarness.h\"\n#include \"CppUTestExt\/MockSupport.h\"\n\n#include \"Environment.h\"\n#include \"MockSensor.h\"\n\nstatic const char* dummy_name_01 = \"dummy_01\";\nstatic const char* dummy_name_02 = \"dummy_02\";\n\ntypedef std::vector MockSensorList;\n\nTEST_GROUP(Environment)\n{\n Environment* env;\n void setup()\n {\n env = new Environment();\n }\n void teardown()\n {\n mock().clear();\n delete env;\n }\n\n int createSensors(std::string names[], unsigned int size, MockSensorList* sensors)\n {\n if(names == NULL || size < 1)\n return -1;\n\n if(sensors == NULL)\n return -1;\n\n sensors->clear();\n for(unsigned int i = 0; i < size; i++)\n sensors->push_back( new MockSensor(names[i]) );\n return 0;\n }\n\n void addSensorsToEnv(MockSensorList* sensors)\n {\n for(unsigned int i = 0; i < sensors->size(); i++)\n env->addSensor(sensors->at(i)->getName(), sensors->at(i));\n }\n\n void checkSensorsInEnv(std::string names[], MockSensorList* sensors)\n {\n LONGS_EQUAL(sensors->size(), env->getNumSensor());\n\n for(unsigned int i = 0; i < sensors->size(); i++)\n POINTERS_EQUAL(sensors->at(i), env->getSensorByName(names[i]));\n }\n};\n\nTEST(Environment, AddSensor)\n{\n MockSensor* sensor = new MockSensor(dummy_name_01);\n env->addSensor(dummy_name_01, sensor);\n LONGS_EQUAL(1, env->getNumSensor());\n}\n\nTEST(Environment, AddMultipleSensor)\n{\n MockSensorList sensors;\n std::string names[] = {dummy_name_01, dummy_name_02};\n\n createSensors(names, 2, &sensors);\n\n addSensorsToEnv(&sensors);\n\n checkSensorsInEnv(names, &sensors);\n}\n\nTEST(Environment, SingleSensorControl)\n{\n MockSensor* sensor = new MockSensor(dummy_name_01);\n env->addSensor(dummy_name_01, sensor);\n\n mock().expectOneCall(\"Sensor#init()\").onObject(sensor);\n env->init();\n mock().expectOneCall(\"Sensor#start()\").onObject(sensor);\n env->start();\n mock().expectOneCall(\"Sensor#stop()\").onObject(sensor);\n env->stop();\n mock().checkExpectations();\n}\n<|endoftext|>"} {"text":"Quick fix for linux shared build.<|endoftext|>"} {"text":"#include \"FAST\/Data\/Image.hpp\"\n#include \"FAST\/Streamers\/ImageFileStreamer.hpp\"\n#include \"FAST\/Algorithms\/UltrasoundVesselDetection\/UltrasoundVesselDetection.hpp\"\n#include \"FAST\/Algorithms\/UltrasoundVesselDetection\/VesselCrossSection.hpp\"\n#include \"FAST\/Exporters\/ImageExporter.hpp\"\n#include \"FAST\/Algorithms\/ImageCropper\/ImageCropper.hpp\"\n#include \"boost\/filesystem.hpp\"\n\nusing namespace fast;\n\ninline std::string currentDateTime() {\n time_t now = time(0);\n struct tm tstruct;\n char buf[80];\n tstruct = *localtime(&now);\n \/\/ Visit http:\/\/en.cppreference.com\/w\/cpp\/chrono\/c\/strftime\n \/\/ for more information about date\/time format\n strftime(buf, sizeof(buf), \"%Y-%m-%d-%H%M%S\", &tstruct);\n\n return buf;\n}\n\nint main() {\n\tstd::string storageDir = \"\/home\/smistad\/vessel_validation_dataset\/\";\n\tboost::filesystem::create_directories(storageDir);\n\t\/\/ Set up stream\n\tstd::vector recordings = {\n\t\t\t\/*\n\t\"\/home\/smistad\/AssistantTestData\/1\/US-Acq_03_20150608T103739\/Acquisition\/US-Acq_03_20150608T103739_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/1\/US-Acq_04_20150608T103837\/Acquisition\/US-Acq_04_20150608T103837_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/1\/US-Acq_07_20150608T104148\/Acquisition\/US-Acq_07_20150608T104148_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/1\/US-Acq_08_20150608T104238\/Acquisition\/US-Acq_08_20150608T104238_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/0\/US-Acq_03_20150608T102144\/Acquisition\/US-Acq_03_20150608T102144_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/0\/US-Acq_04_20150608T102242\/Acquisition\/US-Acq_04_20150608T102242_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/0\/US-Acq_07_20150608T102703\/Acquisition\/US-Acq_07_20150608T102703_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/0\/US-Acq_08_20150608T102854\/Acquisition\/US-Acq_08_20150608T102854_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/2\/US-Acq_03_20150608T104805\/Acquisition\/US-Acq_03_20150608T104805_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/2\/US-Acq_04_20150608T104910\/Acquisition\/US-Acq_04_20150608T104910_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/2\/US-Acq_07_20150608T105549\/Acquisition\/US-Acq_07_20150608T105549_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/2\/US-Acq_08_20150608T105649\/Acquisition\/US-Acq_08_20150608T105649_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/3\/US-Acq_03_20150608T113646\/Acquisition\/US-Acq_03_20150608T113646_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/3\/US-Acq_04_20150608T113750\/Acquisition\/US-Acq_04_20150608T113750_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/3\/US-Acq_07_20150608T114115\/Acquisition\/US-Acq_07_20150608T114115_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/3\/US-Acq_08_20150608T114217\/Acquisition\/US-Acq_08_20150608T114217_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/4\/US-Acq_03_20150608T112610\/Acquisition\/US-Acq_03_20150608T112610_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/4\/US-Acq_04_20150608T112656\/Acquisition\/US-Acq_04_20150608T112656_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/4\/US-Acq_08_20150608T113129\/Acquisition\/US-Acq_08_20150608T113129_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/4\/US-Acq_09_20150608T113245\/Acquisition\/US-Acq_09_20150608T113245_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/5\/US-Acq_03_20150608T111610\/Acquisition\/US-Acq_03_20150608T111610_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/5\/US-Acq_04_20150608T111701\/Acquisition\/US-Acq_04_20150608T111701_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/5\/US-Acq_07_20150608T111940\/Acquisition\/US-Acq_07_20150608T111940_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/6\/0\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/6\/1\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/6\/2\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/6\/3\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/6\/4\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/7\/0\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/7\/1\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/7\/2\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/7\/3\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/8\/0\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/8\/1\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/8\/2\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/8\/3\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/9\/0\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/9\/1\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/9\/2\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/9\/3\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/10\/0\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/10\/1\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/10\/2\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/10\/3\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/11\/0\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/11\/1\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/11\/2\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/11\/3\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/12\/0\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/12\/1\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/12\/2\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/12\/3\/US-2D_#.mhd\",\n\t*\/\n\t\"\/media\/smistad\/New\\ Volume\/Assistant\\ Recordings\/Leuven\\ 5\\ feb\\ 2016\/2016-02-05-105012\/US-2D_#.mhd\",\n\t\"\/media\/smistad\/New\\ Volume\/Assistant\\ Recordings\/Leuven\\ 5\\ feb\\ 2016\/2016-02-05-105257\/US-2D_#.mhd\",\n\t\"\/media\/smistad\/New\\ Volume\/Assistant\\ Recordings\/Leuven\\ 6\\ feb\\ 2016\/2016-02-06-094808\/US-2D_#.mhd\",\n\t\"\/media\/smistad\/New\\ Volume\/Assistant\\ Recordings\/Leuven\\ 6\\ feb\\ 2016\/2016-02-06-095237\/US-2D_#.mhd\",\n\n\t\"\/media\/smistad\/New\\ Volume\/Assistant\\ Recordings\/Leuven\\ 5\\ feb\\ 2016\/2016-02-05-114458\/US-2D_#.mhd\",\n\t\"\/media\/smistad\/New\\ Volume\/Assistant\\ Recordings\/Leuven\\ 5\\ feb\\ 2016\/2016-02-05-120411\/US-2D_#.mhd\",\n\t\"\/media\/smistad\/New\\ Volume\/Assistant\\ Recordings\/Leuven\\ 5\\ feb\\ 2016\/2016-02-05-120648\/US-2D_#.mhd\",\n\t\"\/media\/smistad\/New\\ Volume\/Assistant\\ Recordings\/Leuven\\ 5\\ feb\\ 2016\/2016-02-05-120843\/US-2D_#.mhd\"\n\t};\n\tfor(int i = 0; i < recordings.size(); ++i) {\n\t\tImageFileStreamer::pointer streamer = ImageFileStreamer::New();\n\t\tstreamer->setStreamingMode(STREAMING_MODE_PROCESS_ALL_FRAMES);\n\t\tstreamer->setStepSize(10);\n\t\tstreamer->setFilenameFormat(recordings[i]);\n\t\tstreamer->update();\n\t\tDynamicData::pointer images = streamer->getOutputData();\n\n\t\t\/\/ Put in subfolders\n\t\tint j = i \/ 4; \/\/ Group 4 sequences into each folder\n\t\tstd::string targetDir = storageDir + boost::lexical_cast(j) + \"\/\";\n\t\tboost::filesystem::create_directories(targetDir);\n\n\t\tUltrasoundVesselDetection::pointer dummy = UltrasoundVesselDetection::New();\n\n\t\t\/\/ Store ROIs as PNGs to disk\n\t\tint counter = 0;\n\t\tUltrasoundVesselDetection::pointer detector = UltrasoundVesselDetection::New();\n\t\twhile(!images->hasReachedEnd()) {\n\t\t\tImage::pointer image = images->getNextFrame(dummy);\n\t\t\tVector3ui imageSize = image->getSize();\n\t\t\tVector3f spacing = image->getSpacing();\n\n\t\t\tdetector->setInputData(image);\n\t\t\tdetector->update();\n\t\t\tstd::vector crossSections = detector->getCrossSections();\n\t\t\tstd::cout << \"Found \" << crossSections.size() << \" cross sections\" << std::endl;\n\n\t\t\t\/\/ For each detected black ellipse\n\t\t\tfor(VesselCrossSection::pointer crossSection : crossSections) {\n\t\t\t\tVesselCrossSectionAccess::pointer access = crossSection->getAccess(ACCESS_READ);\n\t\t\t\tVector2f imageCenter = access->getImageCenterPosition();\n\n\t\t\t\t\/\/ Radius in pixels\n\t\t\t\tconst float majorRadius = access->getMajorRadius();\n\t\t\t\tconst float minorRadius = access->getMinorRadius();\n\t\t\t\tconst int frameSize = std::max((int)round(majorRadius), 50); \/\/ Nr if pixels to include around vessel\n\n\t\t\t\tVector2i offset(\n\t\t\t\t\t\tround(imageCenter.x() - majorRadius) - frameSize,\n\t\t\t\t\t\tround(imageCenter.y() - majorRadius) - frameSize\n\t\t\t\t);\n\t\t\t\tint size2 = 2*majorRadius + 2*frameSize;\n\t\t\t\tVector2i size(\n\t\t\t\t\t\tsize2,\n\t\t\t\t\t\tsize2\n\t\t\t\t);\n\n\t\t\t\tImageCropper::pointer cropper = ImageCropper::New();\n\t\t\t\tcropper->setInputData(image);\n\t\t\t\tcropper->allowOutOfBoundsCropping(true);\n\t\t\t\tcropper->setOffset(offset);\n\t\t\t\tcropper->setSize(size);\n\n\t\t\t\tImageExporter::pointer exporter = ImageExporter::New();\n\t\t\t\tstd::string filename = currentDateTime() + \"-\" + boost::lexical_cast(counter) + \".png\";\n\t\t\t\texporter->setFilename(targetDir + filename);\n\t\t\t\texporter->setInputConnection(cropper->getOutputPort());\n\t\t\t\texporter->update();\n\t\t\t\tcounter++;\n\t\t\t}\n\t\t}\n\t\tstd::cout << \"Finished recording \" << (i+1) << \" of \" << recordings.size() << std::endl;\n\t}\n}\nCarotid artery#include \"FAST\/Data\/Image.hpp\"\n#include \"FAST\/Streamers\/ImageFileStreamer.hpp\"\n#include \"FAST\/Algorithms\/UltrasoundVesselDetection\/UltrasoundVesselDetection.hpp\"\n#include \"FAST\/Algorithms\/UltrasoundVesselDetection\/VesselCrossSection.hpp\"\n#include \"FAST\/Exporters\/ImageExporter.hpp\"\n#include \"FAST\/Algorithms\/ImageCropper\/ImageCropper.hpp\"\n#include \"boost\/filesystem.hpp\"\n\nusing namespace fast;\n\ninline std::string currentDateTime() {\n time_t now = time(0);\n struct tm tstruct;\n char buf[80];\n tstruct = *localtime(&now);\n \/\/ Visit http:\/\/en.cppreference.com\/w\/cpp\/chrono\/c\/strftime\n \/\/ for more information about date\/time format\n strftime(buf, sizeof(buf), \"%Y-%m-%d-%H%M%S\", &tstruct);\n\n return buf;\n}\n\nint main() {\n\tstd::string storageDir = \"\/home\/smistad\/carotis_validation_dataset\/\";\n\tboost::filesystem::create_directories(storageDir);\n\t\/\/ Set up stream\n\tstd::vector recordings = {\n\t\t\t\/*\n\t\"\/home\/smistad\/AssistantTestData\/1\/US-Acq_03_20150608T103739\/Acquisition\/US-Acq_03_20150608T103739_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/1\/US-Acq_04_20150608T103837\/Acquisition\/US-Acq_04_20150608T103837_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/1\/US-Acq_07_20150608T104148\/Acquisition\/US-Acq_07_20150608T104148_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/1\/US-Acq_08_20150608T104238\/Acquisition\/US-Acq_08_20150608T104238_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/0\/US-Acq_03_20150608T102144\/Acquisition\/US-Acq_03_20150608T102144_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/0\/US-Acq_04_20150608T102242\/Acquisition\/US-Acq_04_20150608T102242_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/0\/US-Acq_07_20150608T102703\/Acquisition\/US-Acq_07_20150608T102703_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/0\/US-Acq_08_20150608T102854\/Acquisition\/US-Acq_08_20150608T102854_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/2\/US-Acq_03_20150608T104805\/Acquisition\/US-Acq_03_20150608T104805_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/2\/US-Acq_04_20150608T104910\/Acquisition\/US-Acq_04_20150608T104910_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/2\/US-Acq_07_20150608T105549\/Acquisition\/US-Acq_07_20150608T105549_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/2\/US-Acq_08_20150608T105649\/Acquisition\/US-Acq_08_20150608T105649_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/3\/US-Acq_03_20150608T113646\/Acquisition\/US-Acq_03_20150608T113646_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/3\/US-Acq_04_20150608T113750\/Acquisition\/US-Acq_04_20150608T113750_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/3\/US-Acq_07_20150608T114115\/Acquisition\/US-Acq_07_20150608T114115_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/3\/US-Acq_08_20150608T114217\/Acquisition\/US-Acq_08_20150608T114217_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/4\/US-Acq_03_20150608T112610\/Acquisition\/US-Acq_03_20150608T112610_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/4\/US-Acq_04_20150608T112656\/Acquisition\/US-Acq_04_20150608T112656_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/4\/US-Acq_08_20150608T113129\/Acquisition\/US-Acq_08_20150608T113129_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/4\/US-Acq_09_20150608T113245\/Acquisition\/US-Acq_09_20150608T113245_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/5\/US-Acq_03_20150608T111610\/Acquisition\/US-Acq_03_20150608T111610_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/5\/US-Acq_04_20150608T111701\/Acquisition\/US-Acq_04_20150608T111701_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/5\/US-Acq_07_20150608T111940\/Acquisition\/US-Acq_07_20150608T111940_Image_Transducer_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/6\/0\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/6\/1\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/6\/2\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/6\/3\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/6\/4\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/7\/0\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/7\/1\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/7\/2\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/7\/3\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/8\/0\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/8\/1\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/8\/2\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/8\/3\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/9\/0\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/9\/1\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/9\/2\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/9\/3\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/10\/0\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/10\/1\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/10\/2\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/10\/3\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/11\/0\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/11\/1\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/11\/2\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/11\/3\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/12\/0\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/12\/1\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/12\/2\/US-2D_#.mhd\",\n\t\"\/home\/smistad\/AssistantTestData\/12\/3\/US-2D_#.mhd\",\n\t*\/\n\t\t\t\/*\n\t\"\/media\/smistad\/New\\ Volume\/Assistant\\ Recordings\/Leuven\\ 5\\ feb\\ 2016\/2016-02-05-105012\/US-2D_#.mhd\",\n\t\"\/media\/smistad\/New\\ Volume\/Assistant\\ Recordings\/Leuven\\ 5\\ feb\\ 2016\/2016-02-05-105257\/US-2D_#.mhd\",\n\t\"\/media\/smistad\/New\\ Volume\/Assistant\\ Recordings\/Leuven\\ 6\\ feb\\ 2016\/2016-02-06-094808\/US-2D_#.mhd\",\n\t\"\/media\/smistad\/New\\ Volume\/Assistant\\ Recordings\/Leuven\\ 6\\ feb\\ 2016\/2016-02-06-095237\/US-2D_#.mhd\",\n\n\t\"\/media\/smistad\/New\\ Volume\/Assistant\\ Recordings\/Leuven\\ 5\\ feb\\ 2016\/2016-02-05-114458\/US-2D_#.mhd\",\n\t\"\/media\/smistad\/New\\ Volume\/Assistant\\ Recordings\/Leuven\\ 5\\ feb\\ 2016\/2016-02-05-120411\/US-2D_#.mhd\",\n\t\"\/media\/smistad\/New\\ Volume\/Assistant\\ Recordings\/Leuven\\ 5\\ feb\\ 2016\/2016-02-05-120648\/US-2D_#.mhd\",\n\t\"\/media\/smistad\/New\\ Volume\/Assistant\\ Recordings\/Leuven\\ 5\\ feb\\ 2016\/2016-02-05-120843\/US-2D_#.mhd\"\n\t*\/\n\t\t\t\"\/media\/smistad\/New Volume\/Carotis\/2016-06-02-140622\/US-2D_#.mhd\",\n\t\t\t\"\/media\/smistad\/New Volume\/Carotis\/2016-06-02-140721\/US-2D_#.mhd\",\n\t\t\t\"\/media\/smistad\/New Volume\/Carotis\/2016-06-02-140846\/US-2D_#.mhd\",\n\t\t\t\"\/media\/smistad\/New Volume\/Carotis\/2016-06-02-140923\/US-2D_#.mhd\"\n\t};\n\tfor(int i = 0; i < recordings.size(); ++i) {\n\t\tImageFileStreamer::pointer streamer = ImageFileStreamer::New();\n\t\tstreamer->setStreamingMode(STREAMING_MODE_PROCESS_ALL_FRAMES);\n\t\tstreamer->setStepSize(20);\n\t\tstreamer->setFilenameFormat(recordings[i]);\n\t\tstreamer->update();\n\t\tDynamicData::pointer images = streamer->getOutputData();\n\n\t\t\/\/ Put in subfolders\n\t\tint j = i \/ 4; \/\/ Group 4 sequences into each folder\n\t\tstd::string targetDir = storageDir + boost::lexical_cast(j) + \"\/\";\n\t\tboost::filesystem::create_directories(targetDir);\n\n\t\tUltrasoundVesselDetection::pointer dummy = UltrasoundVesselDetection::New();\n\n\t\t\/\/ Store ROIs as PNGs to disk\n\t\tint counter = 0;\n\t\tUltrasoundVesselDetection::pointer detector = UltrasoundVesselDetection::New();\n\t\twhile(!images->hasReachedEnd()) {\n\t\t\tImage::pointer image = images->getNextFrame(dummy);\n\t\t\tVector3ui imageSize = image->getSize();\n\t\t\tVector3f spacing = image->getSpacing();\n\n\t\t\tdetector->setInputData(image);\n\t\t\tdetector->update();\n\t\t\tstd::vector crossSections = detector->getCrossSections();\n\t\t\tstd::cout << \"Found \" << crossSections.size() << \" cross sections\" << std::endl;\n\n\t\t\t\/\/ For each detected black ellipse\n\t\t\tfor(VesselCrossSection::pointer crossSection : crossSections) {\n\t\t\t\tVesselCrossSectionAccess::pointer access = crossSection->getAccess(ACCESS_READ);\n\t\t\t\tVector2f imageCenter = access->getImageCenterPosition();\n\n\t\t\t\t\/\/ Radius in pixels\n\t\t\t\tconst float majorRadius = access->getMajorRadius();\n\t\t\t\tconst float minorRadius = access->getMinorRadius();\n\t\t\t\tconst int frameSize = std::max((int)round(majorRadius), 50); \/\/ Nr if pixels to include around vessel\n\n\t\t\t\tVector2i offset(\n\t\t\t\t\t\tround(imageCenter.x() - majorRadius) - frameSize,\n\t\t\t\t\t\tround(imageCenter.y() - majorRadius) - frameSize\n\t\t\t\t);\n\t\t\t\tint size2 = 2*majorRadius + 2*frameSize;\n\t\t\t\tVector2i size(\n\t\t\t\t\t\tsize2,\n\t\t\t\t\t\tsize2\n\t\t\t\t);\n\n\t\t\t\tImageCropper::pointer cropper = ImageCropper::New();\n\t\t\t\tcropper->setInputData(image);\n\t\t\t\tcropper->allowOutOfBoundsCropping(true);\n\t\t\t\tcropper->setOffset(offset);\n\t\t\t\tcropper->setSize(size);\n\n\t\t\t\tImageExporter::pointer exporter = ImageExporter::New();\n\t\t\t\tstd::string filename = currentDateTime() + \"-\" + boost::lexical_cast(counter) + \".png\";\n\t\t\t\texporter->setFilename(targetDir + filename);\n\t\t\t\texporter->setInputConnection(cropper->getOutputPort());\n\t\t\t\texporter->update();\n\t\t\t\tcounter++;\n\t\t\t}\n\t\t}\n\t\tstd::cout << \"Finished recording \" << (i+1) << \" of \" << recordings.size() << std::endl;\n\t}\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2013-2014, Filippo Basso \n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder(s) nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \n\nnamespace calibration\n{\n\nbool AutomaticCheckerboardFinder::find(const Checkerboard & checkerboard,\n std::vector & corners) const\n{\n cv::Size pattern_size(checkerboard.cols(), checkerboard.rows());\n corners.clear();\n\n bool pattern_found = cv::findChessboardCorners(gray_, pattern_size, corners);\n\n if (pattern_found)\n cv::cornerSubPix(gray_,\n corners,\n cv::Size(2, 2),\n cv::Size(-1, -1),\n cv::TermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 100, 0.01));\n\n return pattern_found;\n}\n\n} \/* namespace calibration *\/\nAdded cv::CALIB_CB_FAST_CHECK flag to pattern extraction function.\/*\n * Copyright (c) 2013-2014, Filippo Basso \n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder(s) nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \n\nnamespace calibration\n{\n\nbool AutomaticCheckerboardFinder::find(const Checkerboard & checkerboard,\n std::vector & corners) const\n{\n cv::Size pattern_size(checkerboard.cols(), checkerboard.rows());\n corners.clear();\n\n bool pattern_found = cv::findChessboardCorners(gray_, pattern_size, corners, cv::CALIB_CB_FAST_CHECK);\n\n if (pattern_found)\n {\n cv::cornerSubPix(gray_,\n corners,\n cv::Size(2, 2),\n cv::Size(-1, -1),\n cv::TermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 100, 0.01));\n }\n\n return pattern_found;\n}\n\n} \/* namespace calibration *\/\n<|endoftext|>"} {"text":"\/\/ Copyright (C) 2015 - 2016 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc., University of Heidelberg, and The University\n\/\/ of Manchester.\n\/\/ All rights reserved.\n\n#include \n#include \n\/\/#include \n\n#include \"copasi\/utilities\/CUnitDefinition.h\"\n\/\/#include \"copasi\/utilities\/CUnitParser.h\"\n#include \"copasi\/report\/CKeyFactory.h\"\n#include \"copasi\/report\/CCopasiRootContainer.h\"\n\/\/#include \"copasi\/model\/CModel.h\"\n#include \"copasi\/xml\/CCopasiXMLInterface.h\"\n\n\/\/#include \"CCopasiException.h\"\n\n\/\/ SI Name, Symbol, Definition\nstruct SIUnit\n{\n const char * name;\n const char * symbol;\n const char * expression;\n};\n\nSIUnit SIUnits[] =\n{\n \/\/SI base\n {\"meter\", \"m\", \"m\"},\n {\"gram\", \"g\", \"g\"},\n {\"second\", \"s\", \"s\"},\n {\"ampere\", \"A\", \"A\"},\n {\"kelvin\", \"K\", \"K\"},\n {\"mole\", \"mol\", \"mol\"},\n {\"candela\", \"cd\", \"cd\"},\n\n \/\/SI derived\n {\"becquerel\", \"Bq\", \"s^-1\"},\n {\"coulomb\", \"C\", \"s*A\"},\n {\"farad\", \"F\", \"m^-2*kg^-1*s^4*A^2\"},\n {\"gray\", \"Gy\", \"m^2*s^-2\"},\n {\"henry\", \"H\", \"m^2*kg*s^-2*A^-2\"},\n {\"hertz\", \"Hz\", \"s^-1\"},\n {\"joule\", \"J\", \"m^2*kg*s^-2\"},\n {\"katal\", \"kat\", \"s^-1*mol\"},\n {\"liter\", \"l\", \"0.001*m^3\"},\n {\"lumen\", \"lm\", \"cd\"},\n {\"lux\", \"lx\", \"m^-2*cd\"},\n {\"mole\", \"mol\", \"Avogadro*#\"},\n {\"newton\", \"N\", \"m*kg*s^-2\"},\n {\"ohm\", \"\\xCE\\xA9\", \"m^2*kg*s^-3*A^-2\"},\n {\"pascal\", \"Pa\", \"m^-1*kg*s^-2\"},\n {\"siemens\", \"S\", \"m^-2*kg^-1*s^3*A^2\"},\n {\"sievert\", \"Sv\", \"m^2*s^-2\"},\n {\"tesla\", \"T\", \"kg*s^-2*A^-1\"},\n {\"volt\", \"V\", \"m^2*kg*s^-3*A^-1\"},\n {\"watt\", \"W\", \"m^2*kg*s^-3\"},\n {\"weber\", \"Wb\", \"m^2*kg*s^-2*A^-1\"},\n\n {\"dimensionless\", \"1\", \"1\"},\n {\"item\", \"#\", \"#\"},\n {\"minute\", \"min\", \"60*s\"},\n {\"hour\", \"h\", \"3600*s\"},\n {\"day\", \"d\", \"86400*s\"},\n\n \/\/ This must be the last element of the SI unit list! Do not delete!\n {NULL, NULL, NULL}\n};\n\n\/\/ static\n\nCUnit CUnitDefinition::getSIUnit(const std::string & symbol,\n const C_FLOAT64 & avogadro)\n{\n SIUnit * pSIUnit = SIUnits;\n\n while (pSIUnit->name && strcmp(pSIUnit->symbol, symbol.c_str()) != 0)\n ++pSIUnit;\n\n if (!pSIUnit->name)\n fatalError();\n\n std::ostringstream buffer;\n\n if (strcmp(pSIUnit->symbol, \"mol\"))\n {\n buffer << pSIUnit->expression;\n }\n else\n {\n buffer << CCopasiXMLInterface::DBL(avogadro) << \"*#\";\n }\n\n CUnit SIunit = CUnit();\n SIunit.setExpression(buffer.str(), avogadro);\n\n return SIunit;\n}\n\n\/\/ static\nvoid CUnitDefinition::updateSIUnitDefinitions(CUnitDefinitionDB * Units,\n const C_FLOAT64 & avogadro)\n{\n SIUnit * pSIUnit = SIUnits;\n\n while (pSIUnit->name)\n {\n CUnitDefinition * pUnitDef = NULL;\n size_t Index = Units->getIndex(pSIUnit->name);\n\n if (Index != C_INVALID_INDEX)\n {\n pUnitDef = Units->operator [](Index);\n }\n else\n {\n pUnitDef = new CUnitDefinition(pSIUnit->name, Units);\n pUnitDef->setSymbol(pSIUnit->symbol);\n }\n\n std::ostringstream buffer;\n\n if (strcmp(pSIUnit->symbol, \"mol\"))\n {\n buffer << pSIUnit->expression;\n }\n else\n {\n buffer << CCopasiXMLInterface::DBL(avogadro) << \"*#\";\n }\n\n pUnitDef->setExpression(buffer.str(), avogadro);\n\n pSIUnit++;\n }\n}\n\n\/\/ constructors\n\/\/ default\nCUnitDefinition::CUnitDefinition(const std::string & name,\n const CCopasiContainer * pParent):\n CCopasiContainer(name, pParent, \"Unit\"),\n CUnit(),\n CAnnotation(),\n mSymbol(\"symbol\")\n{\n setup();\n}\n\n\/\/ kind\nCUnitDefinition::CUnitDefinition(const CBaseUnit::Kind & kind,\n const CCopasiContainer * pParent):\n CCopasiContainer(CBaseUnit::Name[kind], pParent, \"Unit\"),\n CUnit(kind),\n CAnnotation(),\n mSymbol(CBaseUnit::getSymbol(kind))\n{\n setup();\n}\n\n\/\/ copy\nCUnitDefinition::CUnitDefinition(const CUnitDefinition &src,\n const C_FLOAT64 & avogadro,\n const CCopasiContainer * pParent):\n CCopasiContainer(src, pParent),\n CUnit(src, avogadro),\n CAnnotation(src),\n mSymbol(src.mSymbol)\n{\n setup();\n}\n\nCUnitDefinition::~CUnitDefinition()\n{\n CCopasiRootContainer::getKeyFactory()->remove(mKey);\n\n CCopasiContainer * pParent = getObjectParent();\n\n if (pParent != NULL)\n {\n pParent->remove(this);\n }\n}\n\nvoid CUnitDefinition::setup()\n{\n CCopasiContainer * pParent = getObjectParent();\n\n if (pParent != NULL)\n {\n pParent->add(this, true);\n }\n\n mKey = CCopasiRootContainer::getKeyFactory()->add(\"Unit\", this);\n\n \/\/ The following ought to trigger the exception for\n \/\/ a symbol already in the CUnitDefinitionDB\n std::ostringstream Symbol;\n\n Symbol.str(mSymbol.c_str());\n int i = 1;\n\n while (!setSymbol(Symbol.str()))\n {\n Symbol.str(\"\");\n Symbol << mSymbol << \"_\" << i++;\n }\n}\n\n\/\/ virtual\nconst std::string & CUnitDefinition::getKey() const\n{\n return CAnnotation::getKey();\n}\n\nbool CUnitDefinition::setSymbol(const std::string & symbol)\n{\n CUnitDefinitionDB * pUnitDefinitionDB = dynamic_cast < CUnitDefinitionDB * >(getObjectParent());\n\n if (pUnitDefinitionDB == NULL ||\n pUnitDefinitionDB->changeSymbol(this, symbol))\n {\n mSymbol = symbol;\n\n return true;\n }\n\n CCopasiMessage(CCopasiMessage::ERROR, MCUnitDefinition + 2, symbol.c_str());\n\n return false;\n}\n\nconst std::string & CUnitDefinition::getSymbol() const\n{\n return mSymbol;\n}\n\nCUnitDefinition & CUnitDefinition::operator=(const CUnitDefinition & src)\n{\n \/\/ All CUnitDefinition symbols in a CUnitDefinitionDB should be unique\n \/\/ This should protect that for cases like this:\n \/\/ *aCunitDefDB[i] = someCunitDef;\n\n if ((dynamic_cast < CUnitDefinitionDB *>(getObjectParent()))->containsSymbol(src.getSymbol()))\n CCopasiMessage ex(CCopasiMessage::EXCEPTION, MCUnitDefinition + 2);\n\n *this = src;\n\n return *this;\n}\n\n\/\/static\nbool CUnitDefinition::isBuiltinUnitSymbol(std::string symbol)\n{\n SIUnit * pSIUnit = SIUnits;\n\n while (pSIUnit->symbol && strcmp(pSIUnit->symbol, symbol.c_str()) != 0)\n ++pSIUnit;\n\n return (pSIUnit->symbol != NULL);\n}\n\nbool CUnitDefinition::isReadOnly() const\n{\n SIUnit * pSIUnit = SIUnits;\n\n while (pSIUnit->name && getObjectName() != pSIUnit->name)\n ++pSIUnit;\n\n return (pSIUnit->name != NULL);\n}\nFixed CUnitDefinition::operator= to check if rhs is itself, and make sure BOTH the symbol and the name not already used.\/\/ Copyright (C) 2015 - 2016 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc., University of Heidelberg, and The University\n\/\/ of Manchester.\n\/\/ All rights reserved.\n\n#include \n#include \n\/\/#include \n\n#include \"copasi\/utilities\/CUnitDefinition.h\"\n\/\/#include \"copasi\/utilities\/CUnitParser.h\"\n#include \"copasi\/report\/CKeyFactory.h\"\n#include \"copasi\/report\/CCopasiRootContainer.h\"\n\/\/#include \"copasi\/model\/CModel.h\"\n#include \"copasi\/xml\/CCopasiXMLInterface.h\"\n\n\/\/#include \"CCopasiException.h\"\n\n\/\/ SI Name, Symbol, Definition\nstruct SIUnit\n{\n const char * name;\n const char * symbol;\n const char * expression;\n};\n\nSIUnit SIUnits[] =\n{\n \/\/SI base\n {\"meter\", \"m\", \"m\"},\n {\"gram\", \"g\", \"g\"},\n {\"second\", \"s\", \"s\"},\n {\"ampere\", \"A\", \"A\"},\n {\"kelvin\", \"K\", \"K\"},\n {\"mole\", \"mol\", \"mol\"},\n {\"candela\", \"cd\", \"cd\"},\n\n \/\/SI derived\n {\"becquerel\", \"Bq\", \"s^-1\"},\n {\"coulomb\", \"C\", \"s*A\"},\n {\"farad\", \"F\", \"m^-2*kg^-1*s^4*A^2\"},\n {\"gray\", \"Gy\", \"m^2*s^-2\"},\n {\"henry\", \"H\", \"m^2*kg*s^-2*A^-2\"},\n {\"hertz\", \"Hz\", \"s^-1\"},\n {\"joule\", \"J\", \"m^2*kg*s^-2\"},\n {\"katal\", \"kat\", \"s^-1*mol\"},\n {\"liter\", \"l\", \"0.001*m^3\"},\n {\"lumen\", \"lm\", \"cd\"},\n {\"lux\", \"lx\", \"m^-2*cd\"},\n {\"mole\", \"mol\", \"Avogadro*#\"},\n {\"newton\", \"N\", \"m*kg*s^-2\"},\n {\"ohm\", \"\\xCE\\xA9\", \"m^2*kg*s^-3*A^-2\"},\n {\"pascal\", \"Pa\", \"m^-1*kg*s^-2\"},\n {\"siemens\", \"S\", \"m^-2*kg^-1*s^3*A^2\"},\n {\"sievert\", \"Sv\", \"m^2*s^-2\"},\n {\"tesla\", \"T\", \"kg*s^-2*A^-1\"},\n {\"volt\", \"V\", \"m^2*kg*s^-3*A^-1\"},\n {\"watt\", \"W\", \"m^2*kg*s^-3\"},\n {\"weber\", \"Wb\", \"m^2*kg*s^-2*A^-1\"},\n\n {\"dimensionless\", \"1\", \"1\"},\n {\"item\", \"#\", \"#\"},\n {\"minute\", \"min\", \"60*s\"},\n {\"hour\", \"h\", \"3600*s\"},\n {\"day\", \"d\", \"86400*s\"},\n\n \/\/ This must be the last element of the SI unit list! Do not delete!\n {NULL, NULL, NULL}\n};\n\n\/\/ static\n\nCUnit CUnitDefinition::getSIUnit(const std::string & symbol,\n const C_FLOAT64 & avogadro)\n{\n SIUnit * pSIUnit = SIUnits;\n\n while (pSIUnit->name && strcmp(pSIUnit->symbol, symbol.c_str()) != 0)\n ++pSIUnit;\n\n if (!pSIUnit->name)\n fatalError();\n\n std::ostringstream buffer;\n\n if (strcmp(pSIUnit->symbol, \"mol\"))\n {\n buffer << pSIUnit->expression;\n }\n else\n {\n buffer << CCopasiXMLInterface::DBL(avogadro) << \"*#\";\n }\n\n CUnit SIunit = CUnit();\n SIunit.setExpression(buffer.str(), avogadro);\n\n return SIunit;\n}\n\n\/\/ static\nvoid CUnitDefinition::updateSIUnitDefinitions(CUnitDefinitionDB * Units,\n const C_FLOAT64 & avogadro)\n{\n SIUnit * pSIUnit = SIUnits;\n\n while (pSIUnit->name)\n {\n CUnitDefinition * pUnitDef = NULL;\n size_t Index = Units->getIndex(pSIUnit->name);\n\n if (Index != C_INVALID_INDEX)\n {\n pUnitDef = Units->operator [](Index);\n }\n else\n {\n pUnitDef = new CUnitDefinition(pSIUnit->name, Units);\n pUnitDef->setSymbol(pSIUnit->symbol);\n }\n\n std::ostringstream buffer;\n\n if (strcmp(pSIUnit->symbol, \"mol\"))\n {\n buffer << pSIUnit->expression;\n }\n else\n {\n buffer << CCopasiXMLInterface::DBL(avogadro) << \"*#\";\n }\n\n pUnitDef->setExpression(buffer.str(), avogadro);\n\n pSIUnit++;\n }\n}\n\n\/\/ constructors\n\/\/ default\nCUnitDefinition::CUnitDefinition(const std::string & name,\n const CCopasiContainer * pParent):\n CCopasiContainer(name, pParent, \"Unit\"),\n CUnit(),\n CAnnotation(),\n mSymbol(\"symbol\")\n{\n setup();\n}\n\n\/\/ kind\nCUnitDefinition::CUnitDefinition(const CBaseUnit::Kind & kind,\n const CCopasiContainer * pParent):\n CCopasiContainer(CBaseUnit::Name[kind], pParent, \"Unit\"),\n CUnit(kind),\n CAnnotation(),\n mSymbol(CBaseUnit::getSymbol(kind))\n{\n setup();\n}\n\n\/\/ copy\nCUnitDefinition::CUnitDefinition(const CUnitDefinition &src,\n const C_FLOAT64 & avogadro,\n const CCopasiContainer * pParent):\n CCopasiContainer(src, pParent),\n CUnit(src, avogadro),\n CAnnotation(src),\n mSymbol(src.mSymbol)\n{\n setup();\n}\n\nCUnitDefinition::~CUnitDefinition()\n{\n CCopasiRootContainer::getKeyFactory()->remove(mKey);\n\n CCopasiContainer * pParent = getObjectParent();\n\n if (pParent != NULL)\n {\n pParent->remove(this);\n }\n}\n\nvoid CUnitDefinition::setup()\n{\n CCopasiContainer * pParent = getObjectParent();\n\n if (pParent != NULL)\n {\n pParent->add(this, true);\n }\n\n mKey = CCopasiRootContainer::getKeyFactory()->add(\"Unit\", this);\n\n \/\/ The following ought to trigger the exception for\n \/\/ a symbol already in the CUnitDefinitionDB\n std::ostringstream Symbol;\n\n Symbol.str(mSymbol.c_str());\n int i = 1;\n\n while (!setSymbol(Symbol.str()))\n {\n Symbol.str(\"\");\n Symbol << mSymbol << \"_\" << i++;\n }\n}\n\n\/\/ virtual\nconst std::string & CUnitDefinition::getKey() const\n{\n return CAnnotation::getKey();\n}\n\nbool CUnitDefinition::setSymbol(const std::string & symbol)\n{\n CUnitDefinitionDB * pUnitDefinitionDB = dynamic_cast < CUnitDefinitionDB * >(getObjectParent());\n\n if (pUnitDefinitionDB == NULL ||\n pUnitDefinitionDB->changeSymbol(this, symbol))\n {\n mSymbol = symbol;\n\n return true;\n }\n\n CCopasiMessage(CCopasiMessage::ERROR, MCUnitDefinition + 2, symbol.c_str());\n\n return false;\n}\n\nconst std::string & CUnitDefinition::getSymbol() const\n{\n return mSymbol;\n}\n\nCUnitDefinition & CUnitDefinition::operator=(const CUnitDefinition & src)\n{\n if (this == &src) return *this;\n\n \/\/ All CUnitDefinition symbols in a CUnitDefinitionDB should be unique\n \/\/ This should protect that for cases like this:\n \/\/ *aCunitDefDB[i] = someCunitDef;\n\n CUnitDefinitionDB * pDB =\n dynamic_cast < CUnitDefinitionDB * >(getObjectParent());\n\n if (pDB != NULL &&\n pDB->containsSymbol(src.getSymbol()) &&\n pDB->getIndex(src.getObjectName()) != C_INVALID_INDEX)\n CCopasiMessage ex(CCopasiMessage::EXCEPTION, MCUnitDefinition + 2);\n\n *this = src;\n\n return *this;\n}\n\n\/\/static\nbool CUnitDefinition::isBuiltinUnitSymbol(std::string symbol)\n{\n SIUnit * pSIUnit = SIUnits;\n\n while (pSIUnit->symbol && strcmp(pSIUnit->symbol, symbol.c_str()) != 0)\n ++pSIUnit;\n\n return (pSIUnit->symbol != NULL);\n}\n\nbool CUnitDefinition::isReadOnly() const\n{\n SIUnit * pSIUnit = SIUnits;\n\n while (pSIUnit->name && getObjectName() != pSIUnit->name)\n ++pSIUnit;\n\n return (pSIUnit->name != NULL);\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2021 ASMlover. All rights reserved.\n\/\/\n\/\/ ______ __ ___\n\/\/ \/\\__ _\\ \/\\ \\ \/\\_ \\\n\/\/ \\\/_\/\\ \\\/ __ \\_\\ \\ _____ ___\\\/\/\\ \\ __\n\/\/ \\ \\ \\ \/'__`\\ \/'_` \\\/\\ '__`\\ \/ __`\\\\ \\ \\ \/'__`\\\n\/\/ \\ \\ \\\/\\ \\L\\.\\_\/\\ \\L\\ \\ \\ \\L\\ \\\/\\ \\L\\ \\\\_\\ \\_\/\\ __\/\n\/\/ \\ \\_\\ \\__\/.\\_\\ \\___,_\\ \\ ,__\/\\ \\____\/\/\\____\\ \\____\\\n\/\/ \\\/_\/\\\/__\/\\\/_\/\\\/__,_ \/\\ \\ \\\/ \\\/___\/ \\\/____\/\\\/____\/\n\/\/ \\ \\_\\\n\/\/ \\\/_\/\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list ofconditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in\n\/\/ the documentation and\/or other materialsprovided with the\n\/\/ distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace Tadpole::Core {\n\nTadpoleVM::TadpoleVM() noexcept {\n gcompiler_ = new Compiler::GlobalCompiler();\n stack_.reserve(kDefaultCap);\n\n Builtin::register_builtins(*this);\n GC::GC::get_instance().append_roots(\"TadpoleVM\", this);\n}\n\nTadpoleVM::~TadpoleVM() {\n delete gcompiler_;\n globals_.clear();\n}\n\nvoid TadpoleVM::define_native(const str_t& name, Value::TadpoleCFun&& fn) {\n globals_[name] = Object::NativeObject::create(std::move(fn));\n}\n\nInterpretRet TadpoleVM::interpret(const str_t& source_bytes) {\n Object::FunctionObject* fn = gcompiler_->compile(*this, source_bytes);\n if (fn == nullptr)\n return InterpretRet::ECOMPILE;\n\n \/\/ TODO:\n return InterpretRet::OK;\n}\n\nvoid TadpoleVM::iter_objects(Object::ObjectVisitor&& visitor) {\n \/\/ TODO:\n}\n\n}\n:construction: chore(vm): updated the common functional for vm of tadpole\/\/ Copyright (c) 2021 ASMlover. All rights reserved.\n\/\/\n\/\/ ______ __ ___\n\/\/ \/\\__ _\\ \/\\ \\ \/\\_ \\\n\/\/ \\\/_\/\\ \\\/ __ \\_\\ \\ _____ ___\\\/\/\\ \\ __\n\/\/ \\ \\ \\ \/'__`\\ \/'_` \\\/\\ '__`\\ \/ __`\\\\ \\ \\ \/'__`\\\n\/\/ \\ \\ \\\/\\ \\L\\.\\_\/\\ \\L\\ \\ \\ \\L\\ \\\/\\ \\L\\ \\\\_\\ \\_\/\\ __\/\n\/\/ \\ \\_\\ \\__\/.\\_\\ \\___,_\\ \\ ,__\/\\ \\____\/\/\\____\\ \\____\\\n\/\/ \\\/_\/\\\/__\/\\\/_\/\\\/__,_ \/\\ \\ \\\/ \\\/___\/ \\\/____\/\\\/____\/\n\/\/ \\ \\_\\\n\/\/ \\\/_\/\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list ofconditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in\n\/\/ the documentation and\/or other materialsprovided with the\n\/\/ distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace Tadpole::Core {\n\nTadpoleVM::TadpoleVM() noexcept {\n gcompiler_ = new Compiler::GlobalCompiler();\n stack_.reserve(kDefaultCap);\n\n Builtin::register_builtins(*this);\n GC::GC::get_instance().append_roots(\"TadpoleVM\", this);\n}\n\nTadpoleVM::~TadpoleVM() {\n delete gcompiler_;\n globals_.clear();\n}\n\nvoid TadpoleVM::define_native(const str_t& name, Value::TadpoleCFun&& fn) {\n globals_[name] = Object::NativeObject::create(std::move(fn));\n}\n\nInterpretRet TadpoleVM::interpret(const str_t& source_bytes) {\n Object::FunctionObject* fn = gcompiler_->compile(*this, source_bytes);\n if (fn == nullptr)\n return InterpretRet::ECOMPILE;\n\n \/\/ TODO:\n return InterpretRet::OK;\n}\n\nvoid TadpoleVM::iter_objects(Object::ObjectVisitor&& visitor) {\n \/\/ iterate Tadpole objects roots\n gcompiler_->iter_objects(std::move(visitor));\n for (auto& v : stack_)\n visitor(v.as_object(safe_t()));\n for (auto& f : frames_)\n visitor(f.closure());\n for (auto& g : globals_)\n visitor(g.second.as_object(safe_t()));\n for (auto* u = open_upvalues_; u != nullptr; u = u->next())\n visitor(u);\n}\n\nvoid TadpoleVM::reset() {\n stack_.clear();\n frames_.clear();\n open_upvalues_ = nullptr;\n}\n\nvoid TadpoleVM::runtime_error(const char* format, ...) {\n std::cerr << Common::Colorful::fg::red << \"Traceback (most recent call last):\" << std::endl;\n for (auto it = frames_.rbegin(); it != frames_.rend(); ++it) {\n auto& frame = *it;\n\n sz_t i = frame.frame_chunk()->offset_with(frame.ip()) - 1;\n std::cerr\n << \" [LINE: \" << frame.frame_chunk()->get_line(i) << \"] in \"\n << \"`\" << frame.frame_fn()->name_asstr() << \"()`\"\n << std::endl;\n }\n\n va_list ap;\n va_start(ap, format);\n std::vfprintf(stderr, format, ap);\n va_end(ap);\n std::cerr << Common::Colorful::reset << std::endl;\n\n reset();\n}\n\nvoid TadpoleVM::push(const Value::Value& value) noexcept {\n stack_.push_back(value);\n}\n\nValue::Value TadpoleVM::pop() noexcept {\n Value::Value value = stack_.back();\n stack_.pop_back();\n return value;\n}\n\nconst Value::Value& TadpoleVM::peek(sz_t distance) const noexcept {\n return stack_[stack_.size() - 1 - distance];\n}\n\n}\n<|endoftext|>"} {"text":"\/** \\file extract_normdata_translations.cc\n * \\brief Extract IxTheo and MACS translations from the normdata file and write it to \n * language specific text files\n * \\author Johannes Riedl\n *\/\n\n\/*\n Copyright (C) 2016, Library of the University of Tübingen\n\n This program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Affero General Public License as\n published by the Free Software Foundation, either version 3 of the\n License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with this program. If not, see .\n*\/\n\n\/* The German term is found in Field 150 \n Currently there are two different kinds of translations:\n IxTheo-Translations with the following definitions:\n\n 710: Körperschaft - fremdsprachige Äquivalenz \n 711: Konferenz - fremdsprachige Äquivalenz \n 700: Person - fremdsprachige Äquivalenz \n 730: Titel - fremdsprachige Äquivalenz \n 750: Sachbegriff - fremdsprachige Äquivalenz \n 751: Geografikum - fremdsprachige Äquivalenz \n\n LoC\/Rameau Translations:\n 700: Person - Bevorzugter Name in einem anderen Datenbestand\n 710: Körperschaft - Bevorzugter Name in einem anderen Datenbestand \n 711: Konferenz - Bevorzugte Benennung in einem anderen Datenbestand\n 730: Einheitstitel - Bevorzugter Name in einem anderen Datenbestand\n 750: Sachbegriff - Bevorzugte Benennung in einem anderen Datenbestand\n 751: Geografikum - Bevorzugter Name in einem anderen Datenbestand \n*\/ \n#include \n#include \n#include \n#include \"Compiler.h\"\n#include \"MarcUtil.h\"\n#include \"MediaTypeUtil.h\"\n#include \"StringUtil.h\"\n#include \"Subfields.h\"\n#include \"util.h\"\n\n\n\/\/ Languages to handle\nconst unsigned int NUMBER_OF_LANGUAGES = 2;\nconst std::vector languages_to_create{ \"en\", \"fr\" };\nenum Languages { EN, FR };\n\n\nvoid Usage() {\n std::cerr << \"Usage: \" << ::progname << \" norm_data_marc_input extracted_translations\\n\";\n std::exit(EXIT_FAILURE);\n}\n\n\nvoid AugmentIxTheoTagWithLanguage(const MarcUtil::Record &record, const std::string &tag, std::vector * const translations) {\n auto ixtheo_pos(std::find(translations->begin(), translations->end(), \"IxTheo\"));\n if (ixtheo_pos != translations->end()) {\n std::vector ixtheo_lang_codes;\n record.extractSubfields(tag, \"9\", &ixtheo_lang_codes);\n bool already_found_ixtheo_translation(false);\n for (const auto &lang_code : ixtheo_lang_codes) {\n if (lang_code[0] != 'L')\n continue;\n if (already_found_ixtheo_translation)\n continue;\n if (lang_code.find(\"eng\") != std::string::npos and *ixtheo_pos != \"IxTheo_eng\") {\n *ixtheo_pos += + \"_eng\";\n already_found_ixtheo_translation = true;\n } else if (lang_code.find(\"fra\") != std::string::npos and *ixtheo_pos != \"IxTheo_fra\") {\n *ixtheo_pos += \"_fra\";\n already_found_ixtheo_translation = true;\n } else \n Warning(\"Unsupported language code \\\"\" + lang_code + \"\\\" for PPN \" + record.getFields()[0]);\n }\n }\n}\n\n\nvoid ExtractTranslations(File* const marc_norm_input, \n const std::string german_term_field_spec,\n const std::string translation_field_spec,\n std::map term_to_translation_maps[]) \n{\n std::set german_tags_and_subfield_codes;\n if (unlikely(StringUtil::Split(german_term_field_spec, ':', &german_tags_and_subfield_codes) < 1))\n Error(\"ExtractTranslations: Need at least one translation field\");\n\n std::set translation_tags_and_subfield_codes;\n if (unlikely(StringUtil::Split(translation_field_spec, ':', &translation_tags_and_subfield_codes) < 1))\n Error(\"ExtractTranslations: Need at least one translation field\");\n \n if (unlikely(not(german_tags_and_subfield_codes.size() == translation_tags_and_subfield_codes.size())))\n Error(\"ExtractTranslations: Number of german fields and number of translation fields must be equal\");\n \n unsigned count(0);\n \n while (const MarcUtil::Record record = MarcUtil::Record::XmlFactory(marc_norm_input)) {\n std::map> all_translations;\n \n for (auto it = std::make_pair(german_tags_and_subfield_codes.cbegin(), translation_tags_and_subfield_codes.cbegin());\n it.first != german_tags_and_subfield_codes.cend();\n ++it.first, ++it.second) {\n\n const std::string german_tag((*it.first).substr(0, 3));\n const std::string german_subfields((*it.first).substr(3));\n const std::string translation_tag((*it.second).substr(0, 3));\n const std::string translation_subfields((*it.second).substr(3));\n \n for (auto subfield_iterator = std::make_pair(german_subfields.begin(), translation_subfields.cbegin());\n subfield_iterator.first != german_subfields.cend();\n ++subfield_iterator.first, ++subfield_iterator.second) {\n std::vector german_term_for_one_field;\n record.extractSubfields(german_tag, std::string(1, *subfield_iterator.first), &german_term_for_one_field);\n \n std::vector translations;\n \/\/ Always extract subfield 2 where \"IxTheo\" is located\n record.extractSubfields(translation_tag, std::string(1, *subfield_iterator.second) + \"2\", &translations);\n\n \/\/ For IxTheo-Translations add the language code in the same field\n AugmentIxTheoTagWithLanguage(record, translation_tag, &translations);\n if (not(german_term_for_one_field.empty()))\n all_translations.insert(std::make_pair(StringUtil::Join(german_term_for_one_field, ' '), translations));\n }\n } \n \n for (auto it = all_translations.begin(); it != all_translations.end(); ++it) {\n std::string german_term = it->first;\n\n for (auto translation_vector_it = it->second.begin(); translation_vector_it != it->second.end(); ++translation_vector_it) {\n \n if (*translation_vector_it == \"IxTheo_eng\") {\n term_to_translation_maps[EN].emplace(german_term, *(++translation_vector_it));\n } else if (*translation_vector_it == \"IxTheo_fra\") {\n term_to_translation_maps[FR].emplace(german_term, *(++translation_vector_it));\n } else if (*translation_vector_it == \"lcsh\") {\n term_to_translation_maps[EN].emplace(german_term, *(++translation_vector_it));\n } else if (*translation_vector_it == \"ram\") {\n term_to_translation_maps[FR].emplace(german_term, *(++translation_vector_it));\n }\n }\n }\n ++count;\n }\n}\n\n\nstd::unique_ptr OpenInputFile(const std::string &filename) {\n std::string mode(\"r\");\n if (MediaTypeUtil::GetFileMediaType(filename) == \"application\/lz4\") \n mode += \"u\"; \n std::unique_ptr file(new File(filename, mode));\n if (file->fail())\n Error(\"can't open \\\"\" + filename + \"\\\" for reading!\");\n\n return file;\n}\n\n\nint main(int argc, char **argv) {\n ::progname = argv[0];\n\n if (argc != 3)\n Usage();\n\n const std::string norm_data_marc_input_filename(argv[1]);\n std::unique_ptr norm_data_marc_input(OpenInputFile(norm_data_marc_input_filename));\n\n const std::string extracted_translations_filename(argv[2]);\n if (unlikely(norm_data_marc_input_filename == extracted_translations_filename))\n Error(\"Norm data input file name equals output file name!\");\n\n std::string output_mode(\"w\");\n if (norm_data_marc_input->isCompressingOrUncompressing())\n output_mode += 'c';\n \n \/\/ Create a file for each language\n std::vector output_file_components;\n if (unlikely(StringUtil::Split(extracted_translations_filename, \".\", &output_file_components) < 1)) \n Error(\"extracted_translations_filename \" + extracted_translations_filename + \" is not valid\");\n \n File *lang_files[NUMBER_OF_LANGUAGES];\n unsigned i(0);\n \n \/\/ Derive output components from given input filename\n std::string extension = (output_file_components.size() > 1) ? output_file_components.back() : \"\";\n std::string basename;\n if (not extension.empty())\n output_file_components.pop_back();\n basename = StringUtil::Join(output_file_components, \".\");\n \n \/\/ Assemble output filename\n for (auto lang : languages_to_create) {\n lang = StringUtil::Trim(lang);\n\n std::string lang_file_name_str = \n (extension != \"\") ? basename + \"_\" + lang + \".\" + extension : basename + \"_\" + lang;\n\n lang_files[i] = new File(lang_file_name_str, output_mode);\n if (lang_files[i]->fail())\n Error(\"can't open \\\"\" + lang_file_name_str + \"\\\" for writing!\");\n ++i;\n }\n\n try {\n std::map term_to_translation_maps[NUMBER_OF_LANGUAGES];\n\n ExtractTranslations(norm_data_marc_input.get(), \n \"100a:110a:111a:130a:150a:151a\", \n \"700a:710a:711a:730a:750a:751a\",\n term_to_translation_maps);\n for (auto line : term_to_translation_maps[EN]) {\n \n *(lang_files[EN]) << line.first << \"|\" << line.second << \"\\n\";\n }\n\n for (auto line : term_to_translation_maps[FR]) {\n *(lang_files[FR]) << line.first << \"|\" << line.second << \"\\n\";\n }\n\n } catch (const std::exception &x) {\n Error(\"caught exception: \" + std::string(x.what()));\n }\n}\n\n\nClarifications in naming\/** \\file extract_normdata_translations.cc\n * \\brief Extract IxTheo and MACS translations from the normdata file and write it to \n * language specific text files\n * \\author Johannes Riedl\n *\/\n\n\/*\n Copyright (C) 2016, Library of the University of Tübingen\n\n This program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Affero General Public License as\n published by the Free Software Foundation, either version 3 of the\n License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with this program. If not, see .\n*\/\n\n\/* The German term is found in Field 150 \n Currently there are two different kinds of translations:\n IxTheo-Translations with the following definitions:\n\n 710: Körperschaft - fremdsprachige Äquivalenz \n 711: Konferenz - fremdsprachige Äquivalenz \n 700: Person - fremdsprachige Äquivalenz \n 730: Titel - fremdsprachige Äquivalenz \n 750: Sachbegriff - fremdsprachige Äquivalenz \n 751: Geografikum - fremdsprachige Äquivalenz \n\n LoC\/Rameau Translations:\n 700: Person - Bevorzugter Name in einem anderen Datenbestand\n 710: Körperschaft - Bevorzugter Name in einem anderen Datenbestand \n 711: Konferenz - Bevorzugte Benennung in einem anderen Datenbestand\n 730: Einheitstitel - Bevorzugter Name in einem anderen Datenbestand\n 750: Sachbegriff - Bevorzugte Benennung in einem anderen Datenbestand\n 751: Geografikum - Bevorzugter Name in einem anderen Datenbestand \n*\/ \n#include \n#include \n#include \n#include \"Compiler.h\"\n#include \"MarcUtil.h\"\n#include \"MediaTypeUtil.h\"\n#include \"StringUtil.h\"\n#include \"Subfields.h\"\n#include \"util.h\"\n\n\n\/\/ Languages to handle\nconst unsigned int NUMBER_OF_LANGUAGES = 2;\nconst std::vector languages_to_create{ \"en\", \"fr\" };\nenum Languages { EN, FR };\n\n\nvoid Usage() {\n std::cerr << \"Usage: \" << ::progname << \" norm_data_marc_input extracted_translations\\n\";\n std::exit(EXIT_FAILURE);\n}\n\n\nvoid AugmentIxTheoTagWithLanguage(const MarcUtil::Record &record, const std::string &tag, std::vector * const translations) {\n auto ixtheo_pos(std::find(translations->begin(), translations->end(), \"IxTheo\"));\n if (ixtheo_pos != translations->end()) {\n std::vector ixtheo_lang_codes;\n record.extractSubfields(tag, \"9\", &ixtheo_lang_codes);\n bool already_found_ixtheo_translation(false);\n for (const auto &lang_code : ixtheo_lang_codes) {\n if (lang_code[0] != 'L')\n continue;\n if (already_found_ixtheo_translation)\n continue;\n if (lang_code.find(\"eng\") != std::string::npos and *ixtheo_pos != \"IxTheo_eng\") {\n *ixtheo_pos += + \"_eng\";\n already_found_ixtheo_translation = true;\n } else if (lang_code.find(\"fra\") != std::string::npos and *ixtheo_pos != \"IxTheo_fra\") {\n *ixtheo_pos += \"_fra\";\n already_found_ixtheo_translation = true;\n } else \n Warning(\"Unsupported language code \\\"\" + lang_code + \"\\\" for PPN \" + record.getFields()[0]);\n }\n }\n}\n\n\nvoid ExtractTranslations(File* const marc_norm_input, \n const std::string german_term_field_spec,\n const std::string translation_field_spec,\n std::map term_to_translation_maps[]) \n{\n std::set german_tags_and_subfield_codes;\n if (unlikely(StringUtil::Split(german_term_field_spec, ':', &german_tags_and_subfield_codes) < 1))\n Error(\"ExtractTranslations: Need at least one translation field\");\n\n std::set translation_tags_and_subfield_codes;\n if (unlikely(StringUtil::Split(translation_field_spec, ':', &translation_tags_and_subfield_codes) < 1))\n Error(\"ExtractTranslations: Need at least one translation field\");\n \n if (unlikely(not(german_tags_and_subfield_codes.size() == translation_tags_and_subfield_codes.size())))\n Error(\"ExtractTranslations: Number of German fields and number of translation fields must be equal\");\n \n unsigned count(0);\n \n while (const MarcUtil::Record record = MarcUtil::Record::XmlFactory(marc_norm_input)) {\n std::map> all_translations;\n \n for (const auto german_and_translations_it = std::make_pair(german_tags_and_subfield_codes.cbegin(), translation_tags_and_subfield_codes.cbegin());\n german_and_translations_it.first != german_tags_and_subfield_codes.cend();\n ++german_and_translations_it.first, ++german_and_translations_it.second) {\n\n const std::string german_tag((*german_and_translations_it.first).substr(0, 3));\n const std::string german_subfields((*german_and_translations_it.first).substr(3));\n const std::string translation_tag((*german_and_translations_it.second).substr(0, 3));\n const std::string translation_subfields((*german_and_translations_it.second).substr(3));\n \n for (auto subfield_iterator = std::make_pair(german_subfields.begin(), translation_subfields.cbegin());\n subfield_iterator.first != german_subfields.cend();\n ++subfield_iterator.first, ++subfield_iterator.second) {\n std::vector german_term_for_one_field;\n record.extractSubfields(german_tag, std::string(1, *subfield_iterator.first), &german_term_for_one_field);\n \n std::vector translations;\n \/\/ Always extract subfield 2 where \"IxTheo\" is located\n record.extractSubfields(translation_tag, std::string(1, *subfield_iterator.second) + \"2\", &translations);\n\n \/\/ For IxTheo-Translations add the language code in the same field\n AugmentIxTheoTagWithLanguage(record, translation_tag, &translations);\n if (not(german_term_for_one_field.empty()))\n all_translations.insert(std::make_pair(StringUtil::Join(german_term_for_one_field, ' '), translations));\n }\n } \n \n for (auto all_translations_it = all_translations.begin(); all_translations_it != all_translations.end(); ++all_translations_it) {\n std::string german_term = all_translations_it->first;\n\n for (auto translation_vector_it = all_translations_it->second.begin(); translation_vector_it != all_translations_it->second.end(); ++translation_vector_it) {\n \n if (*translation_vector_it == \"IxTheo_eng\") {\n term_to_translation_maps[EN].emplace(german_term, *(++translation_vector_it));\n } else if (*translation_vector_it == \"IxTheo_fra\") {\n term_to_translation_maps[FR].emplace(german_term, *(++translation_vector_it));\n } else if (*translation_vector_it == \"lcsh\") {\n term_to_translation_maps[EN].emplace(german_term, *(++translation_vector_it));\n } else if (*translation_vector_it == \"ram\") {\n term_to_translation_maps[FR].emplace(german_term, *(++translation_vector_it));\n }\n }\n }\n ++count;\n }\n}\n\n\nstd::unique_ptr OpenInputFile(const std::string &filename) {\n std::string mode(\"r\");\n if (MediaTypeUtil::GetFileMediaType(filename) == \"application\/lz4\") \n mode += \"u\"; \n std::unique_ptr file(new File(filename, mode));\n if (file->fail())\n Error(\"can't open \\\"\" + filename + \"\\\" for reading!\");\n\n return file;\n}\n\n\nint main(int argc, char **argv) {\n ::progname = argv[0];\n\n if (argc != 3)\n Usage();\n\n const std::string norm_data_marc_input_filename(argv[1]);\n std::unique_ptr norm_data_marc_input(OpenInputFile(norm_data_marc_input_filename));\n\n const std::string extracted_translations_filename(argv[2]);\n if (unlikely(norm_data_marc_input_filename == extracted_translations_filename))\n Error(\"Norm data input file name equals output file name!\");\n\n std::string output_mode(\"w\");\n if (norm_data_marc_input->isCompressingOrUncompressing())\n output_mode += 'c';\n \n \/\/ Create a file for each language\n std::vector output_file_components;\n if (unlikely(StringUtil::Split(extracted_translations_filename, \".\", &output_file_components) < 1)) \n Error(\"extracted_translations_filename \" + extracted_translations_filename + \" is not valid\");\n \n File *lang_files[NUMBER_OF_LANGUAGES];\n unsigned i(0);\n \n \/\/ Derive output components from given input filename\n std::string extension = (output_file_components.size() > 1) ? output_file_components.back() : \"\";\n std::string basename;\n if (not extension.empty())\n output_file_components.pop_back();\n basename = StringUtil::Join(output_file_components, \".\");\n \n \/\/ Assemble output filename\n for (auto lang : languages_to_create) {\n lang = StringUtil::Trim(lang);\n\n std::string lang_file_name_str = \n (extension != \"\") ? basename + \"_\" + lang + \".\" + extension : basename + \"_\" + lang;\n\n lang_files[i] = new File(lang_file_name_str, output_mode);\n if (lang_files[i]->fail())\n Error(\"can't open \\\"\" + lang_file_name_str + \"\\\" for writing!\");\n ++i;\n }\n\n try {\n std::map term_to_translation_maps[NUMBER_OF_LANGUAGES];\n\n ExtractTranslations(norm_data_marc_input.get(), \n \"100a:110a:111a:130a:150a:151a\", \n \"700a:710a:711a:730a:750a:751a\",\n term_to_translation_maps);\n for (auto line : term_to_translation_maps[EN]) {\n \n *(lang_files[EN]) << line.first << \"|\" << line.second << \"\\n\";\n }\n\n for (auto line : term_to_translation_maps[FR]) {\n *(lang_files[FR]) << line.first << \"|\" << line.second << \"\\n\";\n }\n\n } catch (const std::exception &x) {\n Error(\"caught exception: \" + std::string(x.what()));\n }\n}\n\n\n<|endoftext|>"} {"text":"\/\/ -*- mode: c++; coding: utf-8 -*-\n\/*! @file coord.hpp\n @brief Coordinate system\n*\/\n#pragma once\n#ifndef COORD_HPP_\n#define COORD_HPP_\n\n#include \n#include \n#include \n#include \n#include \n\n\n\/\/\/\/\/\/\/\/\/1\/\/\/\/\/\/\/\/\/2\/\/\/\/\/\/\/\/\/3\/\/\/\/\/\/\/\/\/4\/\/\/\/\/\/\/\/\/5\/\/\/\/\/\/\/\/\/6\/\/\/\/\/\/\/\/\/7\/\/\/\/\/\/\/\/\/\n\ntemplate \nstd::vector& operator+=(std::vector& lhs, const std::vector& rhs) {\n assert(lhs.size() == rhs.size());\n std::transform(lhs.begin(), lhs.end(), rhs.begin(),\n lhs.begin(), std::plus());\n return lhs;\n}\n\ntemplate \nstd::vector& operator-=(std::vector& lhs, const std::vector& rhs) {\n assert(lhs.size() == rhs.size());\n std::transform(lhs.begin(), lhs.end(), rhs.begin(),\n lhs.begin(), std::minus());\n return lhs;\n}\n\ntemplate \nstd::vector operator+(std::vector lhs, const std::vector& rhs) {\n return lhs += rhs;\n}\n\ntemplate \nstd::vector operator-(std::vector lhs, const std::vector& rhs) {\n return lhs -= rhs;\n}\n\n\/\/\/\/\/\/\/\/\/1\/\/\/\/\/\/\/\/\/2\/\/\/\/\/\/\/\/\/3\/\/\/\/\/\/\/\/\/4\/\/\/\/\/\/\/\/\/5\/\/\/\/\/\/\/\/\/6\/\/\/\/\/\/\/\/\/7\/\/\/\/\/\/\/\/\/\n\nclass Coord {\n public:\n Coord() = delete;\n explicit Coord(const size_t d): dimensions(d) {}\n virtual ~Coord() = default;\n const size_t dimensions;\n const std::vector>& directions() const {return directions_;}\n std::vector> neighbors(const std::vector& v) const {\n std::vector> output = directions_;\n for (auto& d: output) {\n d += v;\n }\n return output;\n }\n std::vector outward(const std::vector& v) const {\n const auto candidates = neighbors(v);\n return *std::max_element(candidates.begin(), candidates.end(),\n [this](const std::vector& lhs, const std::vector& rhs) {\n return distance(lhs) < distance(rhs);\n });\n }\n virtual size_t distance(const std::vector& v) const = 0;\n virtual std::vector> origins() const {\n const size_t n = std::pow(2, dimensions);\n std::vector> output;\n output.reserve(n);\n for (size_t i=0; i bs(i);\n std::vector v(dimensions);\n for (size_t j=0; j(bs[j]);\n }\n output.push_back(v);\n }\n return output;\n }\n protected:\n std::vector> directions_;\n};\n\nclass Neumann: public Coord {\n public:\n Neumann() = delete;\n explicit Neumann(const size_t d): Coord(d) {\n directions_.reserve(2 * dimensions);\n std::vector v(dimensions, 0);\n v.back() += 1;\n do {\n directions_.push_back(v);\n } while (std::next_permutation(v.begin(), v.end()));\n v.assign(dimensions, 0);\n v.front() -= 1;\n do {\n directions_.push_back(v);\n } while (std::next_permutation(v.begin(), v.end()));\n }\n size_t distance(const std::vector& v) const {\n return std::accumulate(v.begin(), v.end(), 0, [](const int lhs, const int rhs) {\n return std::abs(lhs) + std::abs(rhs);\n });\n }\n};\n\n\nclass Moore: public Coord {\n public:\n Moore() = delete;\n explicit Moore(const size_t d): Coord(d) {\n directions_.reserve(std::pow(3, dimensions) - 1);\n for (const int x: {-1, 0, 1}) {\n for (const int y: {-1, 0, 1}) {\n if (dimensions == 2) {\n if (x == 0 && y == 0) continue;\n directions_.push_back({x, y});\n continue;\n }\n for (const int z: {-1, 0, 1}) {\n if (x == 0 && y == 0 && z == 0) continue;\n directions_.push_back({x, y, z});\n }\n }\n }\n }\n size_t distance(const std::vector& v) const {\n return std::abs(*std::max_element(v.begin(), v.end(), [](const int lhs, const int rhs) {\n return std::abs(lhs) < std::abs(rhs);\n }));\n }\n};\n\nclass Hexagonal: public Coord {\n public:\n Hexagonal() = delete;\n explicit Hexagonal(const size_t d): Coord(d) {\n std::vector v{-1, 0, 1};\n if (dimensions == 2) {\n directions_.reserve(6);\n do {\n directions_.push_back({v[0], v[1]});\n } while (std::next_permutation(v.begin(), v.end()));\n }\n else {\n directions_.reserve(12);\n do {\n directions_.push_back({v[0], v[1], 0});\n } while (std::next_permutation(v.begin(), v.end()));\n directions_.push_back({0, 0, -1});\n directions_.push_back({1, 0, -1});\n directions_.push_back({1, -1, -1});\n directions_.push_back({0, 0, 1});\n directions_.push_back({-1, 0, 1});\n directions_.push_back({-1, 1, 1});\n }\n }\n size_t distance(const std::vector& v) const {\n std::vector absv;\n absv.reserve(v.size() * 2);\n for (auto x: v) {\n absv.push_back(std::abs(x));\n }\n absv.push_back(std::abs(v[0] + v[1]));\n if (v.size() == 3) {\n absv.push_back(std::abs(v[0] + v[2]));\n }\n return *std::max_element(absv.begin(), absv.end());\n }\n\n std::vector> origins() const {\n std::vector> output = Neumann(dimensions).origins();\n if (dimensions == 3) {\n output.resize(3);\n output.push_back({1, 0, -1});\n }\n return output;\n }\n};\n\n\n\n#endif \/* COORD_HPP_ *\/\nInitialize max_dimensions in Coord::Ctor()\/\/ -*- mode: c++; coding: utf-8 -*-\n\/*! @file coord.hpp\n @brief Coordinate system\n*\/\n#pragma once\n#ifndef COORD_HPP_\n#define COORD_HPP_\n\n#include \n#include \n#include \n#include \n#include \n\n\n\/\/\/\/\/\/\/\/\/1\/\/\/\/\/\/\/\/\/2\/\/\/\/\/\/\/\/\/3\/\/\/\/\/\/\/\/\/4\/\/\/\/\/\/\/\/\/5\/\/\/\/\/\/\/\/\/6\/\/\/\/\/\/\/\/\/7\/\/\/\/\/\/\/\/\/\n\ntemplate \nstd::vector& operator+=(std::vector& lhs, const std::vector& rhs) {\n assert(lhs.size() == rhs.size());\n std::transform(lhs.begin(), lhs.end(), rhs.begin(),\n lhs.begin(), std::plus());\n return lhs;\n}\n\ntemplate \nstd::vector& operator-=(std::vector& lhs, const std::vector& rhs) {\n assert(lhs.size() == rhs.size());\n std::transform(lhs.begin(), lhs.end(), rhs.begin(),\n lhs.begin(), std::minus());\n return lhs;\n}\n\ntemplate \nstd::vector operator+(std::vector lhs, const std::vector& rhs) {\n return lhs += rhs;\n}\n\ntemplate \nstd::vector operator-(std::vector lhs, const std::vector& rhs) {\n return lhs -= rhs;\n}\n\n\/\/\/\/\/\/\/\/\/1\/\/\/\/\/\/\/\/\/2\/\/\/\/\/\/\/\/\/3\/\/\/\/\/\/\/\/\/4\/\/\/\/\/\/\/\/\/5\/\/\/\/\/\/\/\/\/6\/\/\/\/\/\/\/\/\/7\/\/\/\/\/\/\/\/\/\n\nclass Coord {\n public:\n Coord() = delete;\n Coord(const size_t d): dimensions(d) {}\n virtual ~Coord() = default;\n const size_t dimensions;\n const std::vector>& directions() const {return directions_;}\n size_t max_neighbors() const {return max_neighbors_;}\n std::vector> neighbors(const std::vector& v) const {\n std::vector> output = directions_;\n for (auto& d: output) {\n d += v;\n }\n return output;\n }\n std::vector outward(const std::vector& v) const {\n const auto candidates = neighbors(v);\n return *std::max_element(candidates.begin(), candidates.end(),\n [this](const std::vector& lhs, const std::vector& rhs) {\n return distance(lhs) < distance(rhs);\n });\n }\n virtual size_t distance(const std::vector& v) const = 0;\n virtual std::vector> origins() const {\n const size_t n = std::pow(2, dimensions);\n std::vector> output;\n output.reserve(n);\n for (size_t i=0; i bs(i);\n std::vector v(dimensions);\n for (size_t j=0; j(bs[j]);\n }\n output.push_back(v);\n }\n return output;\n }\n protected:\n std::vector> directions_;\n size_t max_neighbors_;\n};\n\nclass Neumann: public Coord {\n public:\n Neumann() = delete;\n explicit Neumann(const size_t d): Coord(d) {\n max_neighbors_ = 2 * d;\n directions_.reserve(max_neighbors_);\n std::vector v(dimensions, 0);\n v.back() += 1;\n do {\n directions_.push_back(v);\n } while (std::next_permutation(v.begin(), v.end()));\n v.assign(dimensions, 0);\n v.front() -= 1;\n do {\n directions_.push_back(v);\n } while (std::next_permutation(v.begin(), v.end()));\n }\n size_t distance(const std::vector& v) const {\n return std::accumulate(v.begin(), v.end(), 0, [](const int lhs, const int rhs) {\n return std::abs(lhs) + std::abs(rhs);\n });\n }\n};\n\n\/\/! Neumann + diagonal cells\nclass Moore: public Coord {\n public:\n Moore() = delete;\n explicit Moore(const size_t d): Coord(d) {\n max_neighbors_ = std::pow(3, dimensions) - 1;\n directions_.reserve(max_neighbors_);\n for (const int x: {-1, 0, 1}) {\n for (const int y: {-1, 0, 1}) {\n if (dimensions == 2) {\n if (x == 0 && y == 0) continue;\n directions_.push_back({x, y});\n continue;\n }\n for (const int z: {-1, 0, 1}) {\n if (x == 0 && y == 0 && z == 0) continue;\n directions_.push_back({x, y, z});\n }\n }\n }\n }\n size_t distance(const std::vector& v) const {\n return std::abs(*std::max_element(v.begin(), v.end(), [](const int lhs, const int rhs) {\n return std::abs(lhs) < std::abs(rhs);\n }));\n }\n};\n\nclass Hexagonal: public Coord {\n public:\n Hexagonal() = delete;\n explicit Hexagonal(const size_t d): Coord(d) {\n max_neighbors_ = 6 * (d - 1);\n std::vector v{-1, 0, 1};\n directions_.reserve(max_neighbors_);\n if (dimensions == 2) {\n do {\n directions_.push_back({v[0], v[1]});\n } while (std::next_permutation(v.begin(), v.end()));\n }\n else {\n do {\n directions_.push_back({v[0], v[1], 0});\n } while (std::next_permutation(v.begin(), v.end()));\n directions_.push_back({0, 0, -1});\n directions_.push_back({1, 0, -1});\n directions_.push_back({1, -1, -1});\n directions_.push_back({0, 0, 1});\n directions_.push_back({-1, 0, 1});\n directions_.push_back({-1, 1, 1});\n }\n }\n size_t distance(const std::vector& v) const {\n std::vector absv;\n absv.reserve(v.size() * 2);\n for (auto x: v) {\n absv.push_back(std::abs(x));\n }\n absv.push_back(std::abs(v[0] + v[1]));\n if (v.size() == 3) {\n absv.push_back(std::abs(v[0] + v[2]));\n }\n return *std::max_element(absv.begin(), absv.end());\n }\n\n std::vector> origins() const {\n std::vector> output = Neumann(dimensions).origins();\n if (dimensions == 3) {\n output.resize(3);\n output.push_back({1, 0, -1});\n }\n return output;\n }\n};\n\n\n\n#endif \/* COORD_HPP_ *\/\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2015-present, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree. An additional grant\n * of patent rights can be found in the PATENTS file in the same directory.\n *\/\n\n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n\nnamespace facebook {\nnamespace jni {\n\nnamespace {\nclass JRuntimeException : public JavaClass {\n public:\n static auto constexpr kJavaDescriptor = \"Ljava\/lang\/RuntimeException;\";\n\n static local_ref create(const char* str) {\n return newInstance(make_jstring(str));\n }\n\n static local_ref create() {\n return newInstance();\n }\n};\n\nclass JIOException : public JavaClass {\n public:\n static auto constexpr kJavaDescriptor = \"Ljava\/io\/IOException;\";\n\n static local_ref create(const char* str) {\n return newInstance(make_jstring(str));\n }\n};\n\nclass JOutOfMemoryError : public JavaClass {\n public:\n static auto constexpr kJavaDescriptor = \"Ljava\/lang\/OutOfMemoryError;\";\n\n static local_ref create(const char* str) {\n return newInstance(make_jstring(str));\n }\n};\n\nclass JArrayIndexOutOfBoundsException : public JavaClass {\n public:\n static auto constexpr kJavaDescriptor = \"Ljava\/lang\/ArrayIndexOutOfBoundsException;\";\n\n static local_ref create(const char* str) {\n return newInstance(make_jstring(str));\n }\n};\n\nclass JUnknownCppException : public JavaClass {\n public:\n static auto constexpr kJavaDescriptor = \"Lcom\/facebook\/jni\/UnknownCppException;\";\n\n static local_ref create() {\n return newInstance();\n }\n\n static local_ref create(const char* str) {\n return newInstance(make_jstring(str));\n }\n};\n\nclass JCppSystemErrorException : public JavaClass {\n public:\n static auto constexpr kJavaDescriptor = \"Lcom\/facebook\/jni\/CppSystemErrorException;\";\n\n static local_ref create(const std::system_error& e) {\n return newInstance(make_jstring(e.what()), e.code().value());\n }\n};\n\n\/\/ Exception throwing & translating functions \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Functions that throw Java exceptions\n\nvoid setJavaExceptionAndAbortOnFailure(alias_ref throwable) {\n auto env = Environment::current();\n if (throwable) {\n env->Throw(throwable.get());\n }\n if (env->ExceptionCheck() != JNI_TRUE) {\n std::abort();\n }\n}\n\n}\n\n\/\/ Functions that throw C++ exceptions\n\n\/\/ TODO(T6618159) Take a stack dump here to save context if it results in a crash when propagated\nvoid throwPendingJniExceptionAsCppException() {\n JNIEnv* env = Environment::current();\n if (env->ExceptionCheck() == JNI_FALSE) {\n return;\n }\n\n auto throwable = adopt_local(env->ExceptionOccurred());\n if (!throwable) {\n throw std::runtime_error(\"Unable to get pending JNI exception.\");\n }\n env->ExceptionClear();\n\n throw JniException(throwable);\n}\n\nvoid throwCppExceptionIf(bool condition) {\n if (!condition) {\n return;\n }\n\n auto env = Environment::current();\n if (env->ExceptionCheck() == JNI_TRUE) {\n throwPendingJniExceptionAsCppException();\n return;\n }\n\n throw JniException();\n}\n\nvoid throwNewJavaException(jthrowable throwable) {\n throw JniException(wrap_alias(throwable));\n}\n\nvoid throwNewJavaException(const char* throwableName, const char* msg) {\n \/\/ If anything of the fbjni calls fail, an exception of a suitable\n \/\/ form will be thrown, which is what we want.\n auto throwableClass = findClassLocal(throwableName);\n auto throwable = throwableClass->newObject(\n throwableClass->getConstructor(),\n make_jstring(msg).release());\n throwNewJavaException(throwable.get());\n}\n\n\/\/ Translate C++ to Java Exception\n\nnamespace {\n\n\/\/ The implementation std::rethrow_if_nested uses a dynamic_cast to determine\n\/\/ if the exception is a nested_exception. If the exception is from a library\n\/\/ built with -fno-rtti, then that will crash. This avoids that.\nvoid rethrow_if_nested() {\n try {\n throw;\n } catch (const std::nested_exception& e) {\n e.rethrow_nested();\n } catch (...) {\n }\n}\n\n\/\/ For each exception in the chain of the currently handled exception, func\n\/\/ will be called with that exception as the currently handled exception (in\n\/\/ reverse order, i.e. innermost first).\nvoid denest(std::function func) {\n try {\n throw;\n } catch (const std::exception& e) {\n try {\n rethrow_if_nested();\n } catch (...) {\n denest(func);\n }\n func();\n } catch (...) {\n func();\n }\n}\n}\n\nvoid translatePendingCppExceptionToJavaException() noexcept {\n local_ref previous;\n auto func = [&previous] () {\n local_ref current;\n try {\n throw;\n } catch(const JniException& ex) {\n current = ex.getThrowable();\n } catch(const std::ios_base::failure& ex) {\n current = JIOException::create(ex.what());\n } catch(const std::bad_alloc& ex) {\n current = JOutOfMemoryError::create(ex.what());\n } catch(const std::out_of_range& ex) {\n current = JArrayIndexOutOfBoundsException::create(ex.what());\n } catch(const std::system_error& ex) {\n current = JCppSystemErrorException::create(ex);\n } catch(const std::runtime_error& ex) {\n current = JRuntimeException::create(ex.what());\n } catch(const std::exception& ex) {\n current = JCppException::create(ex.what());\n } catch(const char* msg) {\n current = JUnknownCppException::create(msg);\n } catch(...) {\nLines authored by mhorowitz\/*\n * Copyright (c) 2015-present, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree. An additional grant\n * of patent rights can be found in the PATENTS file in the same directory.\n *\/\n\n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n\nnamespace facebook {\nnamespace jni {\n\nnamespace {\nclass JRuntimeException : public JavaClass {\n public:\n static auto constexpr kJavaDescriptor = \"Ljava\/lang\/RuntimeException;\";\n\n static local_ref create(const char* str) {\n return newInstance(make_jstring(str));\n }\n\n static local_ref create() {\n return newInstance();\n }\n};\n\nclass JIOException : public JavaClass {\n public:\n static auto constexpr kJavaDescriptor = \"Ljava\/io\/IOException;\";\n\n static local_ref create(const char* str) {\n return newInstance(make_jstring(str));\n }\n};\n\nclass JOutOfMemoryError : public JavaClass {\n public:\n static auto constexpr kJavaDescriptor = \"Ljava\/lang\/OutOfMemoryError;\";\n\n static local_ref create(const char* str) {\n return newInstance(make_jstring(str));\n }\n};\n\nclass JArrayIndexOutOfBoundsException : public JavaClass {\n public:\n static auto constexpr kJavaDescriptor = \"Ljava\/lang\/ArrayIndexOutOfBoundsException;\";\n\n static local_ref create(const char* str) {\n return newInstance(make_jstring(str));\n }\n};\n\nclass JUnknownCppException : public JavaClass {\n public:\n static auto constexpr kJavaDescriptor = \"Lcom\/facebook\/jni\/UnknownCppException;\";\n\n static local_ref create() {\n return newInstance();\n }\n\n static local_ref create(const char* str) {\n return newInstance(make_jstring(str));\n }\n};\n\nclass JCppSystemErrorException : public JavaClass {\n public:\n static auto constexpr kJavaDescriptor = \"Lcom\/facebook\/jni\/CppSystemErrorException;\";\n\n static local_ref create(const std::system_error& e) {\n return newInstance(make_jstring(e.what()), e.code().value());\n }\n};\n\n\/\/ Exception throwing & translating functions \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Functions that throw Java exceptions\n\nvoid setJavaExceptionAndAbortOnFailure(alias_ref throwable) {\n auto env = Environment::current();\n if (throwable) {\n env->Throw(throwable.get());\n }\n if (env->ExceptionCheck() != JNI_TRUE) {\n std::abort();\n }\n}\n\n}\n\n\/\/ Functions that throw C++ exceptions\n\n\/\/ TODO(T6618159) Take a stack dump here to save context if it results in a crash when propagated\nvoid throwPendingJniExceptionAsCppException() {\n JNIEnv* env = Environment::current();\n if (env->ExceptionCheck() == JNI_FALSE) {\n return;\n }\n\n auto throwable = adopt_local(env->ExceptionOccurred());\n if (!throwable) {\n throw std::runtime_error(\"Unable to get pending JNI exception.\");\n }\n env->ExceptionClear();\n\n throw JniException(throwable);\n}\n\nvoid throwCppExceptionIf(bool condition) {\n if (!condition) {\n return;\n }\n\n auto env = Environment::current();\n if (env->ExceptionCheck() == JNI_TRUE) {\n throwPendingJniExceptionAsCppException();\n return;\n }\n\n throw JniException();\n}\n\nvoid throwNewJavaException(jthrowable throwable) {\n throw JniException(wrap_alias(throwable));\n}\n\nvoid throwNewJavaException(const char* throwableName, const char* msg) {\n \/\/ If anything of the fbjni calls fail, an exception of a suitable\n \/\/ form will be thrown, which is what we want.\n auto throwableClass = findClassLocal(throwableName);\n auto throwable = throwableClass->newObject(\n throwableClass->getConstructor(),\n make_jstring(msg).release());\n throwNewJavaException(throwable.get());\n}\n\n\/\/ Translate C++ to Java Exception\n\nnamespace {\n\n\/\/ The implementation std::rethrow_if_nested uses a dynamic_cast to determine\n\/\/ if the exception is a nested_exception. If the exception is from a library\n\/\/ built with -fno-rtti, then that will crash. This avoids that.\nvoid rethrow_if_nested() {\n try {\n throw;\n } catch (const std::nested_exception& e) {\n e.rethrow_nested();\n } catch (...) {\n }\n}\n\n\/\/ For each exception in the chain of the currently handled exception, func\n\/\/ will be called with that exception as the currently handled exception (in\n\/\/ reverse order, i.e. innermost first).\nvoid denest(std::function func) {\n try {\n throw;\n } catch (const std::exception& e) {\n try {\n rethrow_if_nested();\n } catch (...) {\n denest(func);\n }\n func();\n } catch (...) {\n func();\n }\n}\n}\n\nvoid translatePendingCppExceptionToJavaException() noexcept {\n local_ref previous;\n auto func = [&previous] () {\n local_ref current;\n try {\n throw;\n } catch(const JniException& ex) {\n current = ex.getThrowable();\n } catch(const std::ios_base::failure& ex) {\n current = JIOException::create(ex.what());\n } catch(const std::bad_alloc& ex) {\n current = JOutOfMemoryError::create(ex.what());\n } catch(const std::out_of_range& ex) {\n current = JArrayIndexOutOfBoundsException::create(ex.what());\n } catch(const std::system_error& ex) {\n current = JCppSystemErrorException::create(ex);\n } catch(const std::runtime_error& ex) {\n current = JRuntimeException::create(ex.what());\n } catch(const std::exception& ex) {\n current = JCppException::create(ex.what());\n } catch(const char* msg) {\n current = JUnknownCppException::create(msg);\n } catch(...) {\n current = JUnknownCppException::create();\n }\n if (previous) {\n current->initCause(previous);\n<|endoftext|>"} {"text":"\/\/ $Id$\n# ifndef CPPAD_LOCAL_OPTIMIZE_RECORD_CSUM_HPP\n# define CPPAD_LOCAL_OPTIMIZE_RECORD_CSUM_HPP\n\/* --------------------------------------------------------------------------\nCppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-16 Bradley M. Bell\n\nCppAD is distributed under multiple licenses. This distribution is under\nthe terms of the\n Eclipse Public License Version 1.0.\n\nA copy of this license is included in the COPYING file of this distribution.\nPlease visit http:\/\/www.coin-or.org\/CppAD\/ for information on other licenses.\n-------------------------------------------------------------------------- *\/\n\/*!\n\\file record_csum.hpp\nRecording a cummulative cummulative summation.\n*\/\n\/\/ BEGIN_CPPAD_LOCAL_OPTIMIZE_NAMESPACE\nnamespace CppAD { namespace local { namespace optimize {\n\/*!\nRecording a cummulative cummulative summation.\n\n\n\\param tape\nis a vector that maps a variable index, in the old operation sequence,\nto the corresponding struct_old_variable information.\nNote that the old variable index must be greater than or equal zero and\nless than tape.size().\n\n\\param current\nis the index in the old operation sequence for\nthe variable corresponding to the result for the current operator.\nIt follows that current < tape.size() and NumRes( tape[current].op ) > 0.\nSuppose i <= current, j < NumArg( tape[i] ), and k = tape[i].arg[j],\nIt is assumed that tape[i].arg[j] is connected to the dependent variables\nand tape[k].new_var has been set to the corresponding variable.\nNote that tape[i].arg[j] < i <= current and\ntape[k].new_var <= k < current.\n\n\\param npar\nis the number of parameters corresponding to the old operation sequence.\n\n\\param par\nis a vector of length npar containing the parameters\nthe old operation sequence; i.e.,\ngiven a parameter index i < npar, the corresponding parameter value is par[i].\n\n\n\\param rec\nis the object that will record the operations.\n\n\\param work\nIs temporary work space. On input and output,\nwork.op_stack, work.add_stack, and work.sub_stack, are all empty.\nThese stacks are passed in so that they are created once\nand then be reused with calls to record_csum.\n\n\\param var2op\nmapping from old variable index to old operator index\n(only used for error checking)\n\n\\param op_info\nmapping from old index to operator information\n(only used for error checking)\n\n\\par Assumptions\ntape[i].new_var is not yet defined for any node i that is csum_connected\nto the current node; i.e., tape[i].new_var = tape.size() for all such nodes.\nFor example; suppose j is an argument in the old operation sequence for the\ncurrent operator, i = tape[current].arg[j], and\ntape[arg[j]].connect_type == csum_connected. It follows that\ntape[i].new_var == tape.size().\n\n\\par Restriction:\ntape[current].op\nmust be one of AddpvOp, AddvvOp, SubpvOp, SubvpOp, SubvvOp.\ntape[current].connect_type must be yes_connected.\ntape[j].connect_type == csum_connected for some index\nj that is a variable argument for the current operation.\n*\/\n\ntemplate \nstruct_size_pair record_csum(\n\tconst CppAD::vector& tape ,\n\tsize_t current ,\n\tsize_t npar ,\n\tconst Base* par ,\n\trecorder* rec ,\n\t\/\/ local information passed so stacks need not be allocated for every call\n\tstruct_csum_stacks& work ,\n\tconst vector& var2op ,\n\tconst vector& op_info )\n{\n\t\/\/ check assumption about work space\n\tCPPAD_ASSERT_UNKNOWN( work.op_stack.empty() );\n\tCPPAD_ASSERT_UNKNOWN( work.add_stack.empty() );\n\tCPPAD_ASSERT_UNKNOWN( work.sub_stack.empty() );\n\t\/\/\n\tCPPAD_ASSERT_UNKNOWN( tape[current].connect_type == yes_connected );\n# ifndef NDEBUG\n\t{\tsize_t i_op = var2op[current];\n\t\tCPPAD_ASSERT_UNKNOWN( ! op_info[i_op].csum_connected );\n\t}\n# endif\n\n\tsize_t i;\n\tOpCode op;\n\tconst addr_t* arg;\n\tbool add;\n\tstruct struct_csum_variable var;\n\t\/\/\n\t\/\/ information corresponding to the root node in the cummulative summation\n\tvar.op = tape[current].op; \/\/ this operator\n\tvar.arg = tape[current].arg; \/\/ arguments for this operator\n\tvar.add = true; \/\/ was parrent operator positive or negative\n\t\/\/\n\t\/\/ initialize stack as containing this one operator\n\twork.op_stack.push( var );\n\t\/\/\n\t\/\/ initialize sum of parameter values as zero\n\tBase sum_par(0);\n\t\/\/\n# ifndef NDEBUG\n\tbool ok = false;\n\tif( var.op == SubvpOp )\n\t\tok = tape[ tape[current].arg[0] ].connect_type == csum_connected;\n\tif( var.op == AddpvOp || var.op == SubpvOp )\n\t\tok = tape[ tape[current].arg[1] ].connect_type == csum_connected;\n\tif( var.op == AddvvOp || var.op == SubvvOp )\n\t{\tok = tape[ tape[current].arg[0] ].connect_type == csum_connected;\n\t\tok |= tape[ tape[current].arg[1] ].connect_type == csum_connected;\n\t}\n\tCPPAD_ASSERT_UNKNOWN( ok );\n# endif\n\t\/\/\n\t\/\/ while there are operators left on the stack\n\twhile( ! work.op_stack.empty() )\n\t{\t\/\/ get this summation operator\n\t\tvar = work.op_stack.top();\n\t\twork.op_stack.pop();\n\t\top = var.op;\n\t\targ = var.arg;\n\t\tadd = var.add;\n\t\t\/\/\n\t\t\/\/ process first argument to this operator\n\t\tswitch(op)\n\t\t{\t\/\/ cases where first argument is a parameter\n\t\t\tcase AddpvOp:\n\t\t\tcase SubpvOp:\n\t\t\tCPPAD_ASSERT_UNKNOWN( size_t(arg[0]) < npar );\n\t\t\t\/\/ first argument has same sign as parent node\n\t\t\tif( add )\n\t\t\t\tsum_par += par[arg[0]];\n\t\t\telse\tsum_par -= par[arg[0]];\n\t\t\tbreak;\n\n\t\t\t\/\/ cases where first argument is a variable\n\t\t\tcase AddvvOp:\n\t\t\tcase SubvpOp:\n\t\t\tcase SubvvOp:\n\t\t\t\/\/\n\t\t\t\/\/ check if the first argument is csum_connected\n# ifndef NDEBUG\n\t\t\t{\tbool flag1 = tape[arg[0]].connect_type == csum_connected;\n\t\t\t\tbool flag2 = op_info[ var2op[ arg[0] ] ].csum_connected;\n\t\t\t\tCPPAD_ASSERT_UNKNOWN( flag1 == flag2 );\n\t\t\t}\n# endif\n\t\t\tif( tape[arg[0]].connect_type == csum_connected )\n\t\t\t{\tCPPAD_ASSERT_UNKNOWN(\n\t\t\t\t\tsize_t(tape[arg[0]].new_var) == tape.size()\n\t\t\t\t);\n\t\t\t\t\/\/ push the operator corresponding to the first argument\n\t\t\t\tvar.op = tape[arg[0]].op;\n\t\t\t\tvar.arg = tape[arg[0]].arg;\n\t\t\t\t\/\/ first argument has same sign as parent node\n\t\t\t\tvar.add = add;\n\t\t\t\twork.op_stack.push( var );\n\t\t\t}\n\t\t\telse\n\t\t\t{\t\/\/ there are no nodes below this one\n\t\t\t\tCPPAD_ASSERT_UNKNOWN( size_t(arg[0]) < current );\n\t\t\t\tCPPAD_ASSERT_UNKNOWN( tape[arg[0]].new_var <= arg[0] );\n\t\t\t\tif( add )\n\t\t\t\t\twork.add_stack.push(arg[0]);\n\t\t\t\telse\twork.sub_stack.push(arg[0]);\n\t\t\t}\n\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\tCPPAD_ASSERT_UNKNOWN(false);\n\t\t}\n\t\t\/\/ process second argument to this operator\n\t\tswitch(op)\n\t\t{\t\/\/ cases where second argument is a parameter\n\t\t\tcase SubvpOp:\n\t\t\tCPPAD_ASSERT_UNKNOWN( size_t(arg[1]) < npar );\n\t\t\t\/\/ second argument has opposite sign of parent node\n\t\t\tif( add )\n\t\t\t\tsum_par -= par[arg[1]];\n\t\t\telse\tsum_par += par[arg[1]];\n\t\t\tbreak;\n\n\t\t\t\/\/ cases where second argument is a variable and has opposite sign\n\t\t\tcase SubvvOp:\n\t\t\tcase SubpvOp:\n\t\t\tadd = ! add;\n\n\t\t\t\/\/ cases where second argument is a variable and has same sign\n\t\t\tcase AddvvOp:\n\t\t\tcase AddpvOp:\n\t\t\t\/\/ check if the second argument is csum_connected\n# ifndef NDEBUG\n\t\t\t{\tbool flag1 = tape[arg[1]].connect_type == csum_connected;\n\t\t\t\tbool flag2 = op_info[ var2op[ arg[1] ] ].csum_connected;\n\t\t\t\tCPPAD_ASSERT_UNKNOWN( flag1 == flag2 );\n\t\t\t}\n# endif\n\t\t\tif( tape[arg[1]].connect_type == csum_connected )\n\t\t\t{\tCPPAD_ASSERT_UNKNOWN(\n\t\t\t\t\tsize_t(tape[arg[1]].new_var) == tape.size()\n\t\t\t\t);\n\t\t\t\t\/\/ push the operator corresoponding to the second arugment\n\t\t\t\tvar.op = tape[arg[1]].op;\n\t\t\t\tvar.arg = tape[arg[1]].arg;\n\t\t\t\tvar.add = add;\n\t\t\t\twork.op_stack.push( var );\n\t\t\t}\n\t\t\telse\n\t\t\t{\t\/\/ there are no nodes below this one\n\t\t\t\tCPPAD_ASSERT_UNKNOWN( size_t(arg[1]) < current );\n\t\t\t\tCPPAD_ASSERT_UNKNOWN( tape[arg[1]].new_var <= arg[1] );\n\t\t\t\tif( add )\n\t\t\t\t\twork.add_stack.push(arg[1]);\n\t\t\t\telse\twork.sub_stack.push(arg[1]);\n\t\t\t}\n\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\tCPPAD_ASSERT_UNKNOWN(false);\n\t\t}\n\t}\n\t\/\/ number of variables to add in this cummulative sum operator\n\tsize_t n_add = work.add_stack.size();\n\t\/\/ number of variables to subtract in this cummulative sum operator\n\tsize_t n_sub = work.sub_stack.size();\n\t\/\/\n\trec->PutArg(n_add); \/\/ arg[0]\n\trec->PutArg(n_sub); \/\/ arg[1]\n\tsize_t new_arg = rec->PutPar(sum_par);\n\trec->PutArg(new_arg); \/\/ arg[2]\n\t\/\/ addition arguments\n\tfor(i = 0; i < n_add; i++)\n\t{\tCPPAD_ASSERT_UNKNOWN( ! work.add_stack.empty() );\n\t\tsize_t old_arg = work.add_stack.top();\n\t\tnew_arg = tape[old_arg].new_var;\n\t\tCPPAD_ASSERT_UNKNOWN( new_arg < current );\n\t\trec->PutArg(new_arg); \/\/ arg[3+i]\n\t\twork.add_stack.pop();\n\t}\n\t\/\/ subtraction arguments\n\tfor(i = 0; i < n_sub; i++)\n\t{\tCPPAD_ASSERT_UNKNOWN( ! work.sub_stack.empty() );\n\t\tsize_t old_arg = work.sub_stack.top();\n\t\tnew_arg = tape[old_arg].new_var;\n\t\tCPPAD_ASSERT_UNKNOWN( new_arg < current );\n\t\trec->PutArg(new_arg); \/\/ arg[3 + arg[0] + i]\n\t\twork.sub_stack.pop();\n\t}\n\t\/\/ number of additions plus number of subtractions\n\trec->PutArg(n_add + n_sub); \/\/ arg[3 + arg[0] + arg[1]]\n\t\/\/\n\t\/\/ return value\n\tstruct_size_pair ret;\n\tret.i_op = rec->num_op_rec();\n\tret.i_var = rec->PutOp(CSumOp);\n\t\/\/\n\treturn ret;\n}\n\n} } } \/\/ END_CPPAD_LOCAL_OPTIMIZE_NAMESPACE\n\n\n# endif\noptimize branch: record_csum.hpp: remove use of tape csum_connected field.\/\/ $Id$\n# ifndef CPPAD_LOCAL_OPTIMIZE_RECORD_CSUM_HPP\n# define CPPAD_LOCAL_OPTIMIZE_RECORD_CSUM_HPP\n\/* --------------------------------------------------------------------------\nCppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-16 Bradley M. Bell\n\nCppAD is distributed under multiple licenses. This distribution is under\nthe terms of the\n Eclipse Public License Version 1.0.\n\nA copy of this license is included in the COPYING file of this distribution.\nPlease visit http:\/\/www.coin-or.org\/CppAD\/ for information on other licenses.\n-------------------------------------------------------------------------- *\/\n\/*!\n\\file record_csum.hpp\nRecording a cummulative cummulative summation.\n*\/\n\/\/ BEGIN_CPPAD_LOCAL_OPTIMIZE_NAMESPACE\nnamespace CppAD { namespace local { namespace optimize {\n\/*!\nRecording a cummulative cummulative summation.\n\n\n\\param tape\nis a vector that maps a variable index, in the old operation sequence,\nto the corresponding struct_old_variable information.\nNote that the old variable index must be greater than or equal zero and\nless than tape.size().\n\n\\param current\nis the index in the old operation sequence for\nthe variable corresponding to the result for the current operator.\nIt follows that current < tape.size() and NumRes( tape[current].op ) > 0.\nSuppose i <= current, j < NumArg( tape[i] ), and k = tape[i].arg[j],\nIt is assumed that tape[i].arg[j] is connected to the dependent variables\nand tape[k].new_var has been set to the corresponding variable.\nNote that tape[i].arg[j] < i <= current and\ntape[k].new_var <= k < current.\n\n\\param npar\nis the number of parameters corresponding to the old operation sequence.\n\n\\param par\nis a vector of length npar containing the parameters\nthe old operation sequence; i.e.,\ngiven a parameter index i < npar, the corresponding parameter value is par[i].\n\n\n\\param rec\nis the object that will record the operations.\n\n\\param work\nIs temporary work space. On input and output,\nwork.op_stack, work.add_stack, and work.sub_stack, are all empty.\nThese stacks are passed in so that they are created once\nand then be reused with calls to record_csum.\n\n\\param var2op\nmapping from old variable index to old operator index\n(only used for error checking)\n\n\\param op_info\nmapping from old index to operator information\n(only used for error checking)\n\n\\par Assumptions\ntape[i].new_var is not yet defined for any node i that is csum_connected\nto the current node; i.e., tape[i].new_var = tape.size() for all such nodes.\nFor example; suppose j is an argument in the old operation sequence for the\ncurrent operator, i = tape[current].arg[j], and\ntape[arg[j]].connect_type == csum_connected. It follows that\ntape[i].new_var == tape.size().\n\n\\par Restriction:\ntape[current].op\nmust be one of AddpvOp, AddvvOp, SubpvOp, SubvpOp, SubvvOp.\ntape[current].connect_type must be yes_connected.\ntape[j].connect_type == csum_connected for some index\nj that is a variable argument for the current operation.\n*\/\n\ntemplate \nstruct_size_pair record_csum(\n\tconst CppAD::vector& tape ,\n\tsize_t current ,\n\tsize_t npar ,\n\tconst Base* par ,\n\trecorder* rec ,\n\t\/\/ local information passed so stacks need not be allocated for every call\n\tstruct_csum_stacks& work ,\n\tconst vector& var2op ,\n\tconst vector& op_info )\n{\n\t\/\/ check assumption about work space\n\tCPPAD_ASSERT_UNKNOWN( work.op_stack.empty() );\n\tCPPAD_ASSERT_UNKNOWN( work.add_stack.empty() );\n\tCPPAD_ASSERT_UNKNOWN( work.sub_stack.empty() );\n\t\/\/\n\tsize_t i_op = var2op[current];\n\tCPPAD_ASSERT_UNKNOWN( ! op_info[i_op].csum_connected );\n\t\/\/\n\tsize_t i;\n\tOpCode op;\n\tconst addr_t* arg;\n\tbool add;\n\tstruct struct_csum_variable var;\n\t\/\/\n\t\/\/ information corresponding to the root node in the cummulative summation\n\tvar.op = op_info[i_op].op; \/\/ this operator\n\tvar.arg = op_info[i_op].arg; \/\/ arguments for this operator\n\tvar.add = true; \/\/ was parrent operator positive or negative\n\t\/\/\n\t\/\/ initialize stack as containing this one operator\n\twork.op_stack.push( var );\n\t\/\/\n\t\/\/ initialize sum of parameter values as zero\n\tBase sum_par(0);\n\t\/\/\n# ifndef NDEBUG\n\tbool ok = false;\n\tstruct_op_info info = op_info[i_op];\n\tif( var.op == SubvpOp )\n\t\tok = op_info[ var2op[info.arg[0]] ].csum_connected;\n\tif( var.op == AddpvOp || var.op == SubpvOp )\n\t\tok = op_info[ var2op[info.arg[1]] ].csum_connected;\n\tif( var.op == AddvvOp || var.op == SubvvOp )\n\t{\tok = op_info[ var2op[info.arg[0]] ].csum_connected;\n\t\tok |= op_info[ var2op[info.arg[1]] ].csum_connected;\n\t}\n\tCPPAD_ASSERT_UNKNOWN( ok );\n# endif\n\t\/\/\n\t\/\/ while there are operators left on the stack\n\twhile( ! work.op_stack.empty() )\n\t{\t\/\/ get this summation operator\n\t\tvar = work.op_stack.top();\n\t\twork.op_stack.pop();\n\t\top = var.op;\n\t\targ = var.arg;\n\t\tadd = var.add;\n\t\t\/\/\n\t\t\/\/ process first argument to this operator\n\t\tswitch(op)\n\t\t{\t\/\/ cases where first argument is a parameter\n\t\t\tcase AddpvOp:\n\t\t\tcase SubpvOp:\n\t\t\tCPPAD_ASSERT_UNKNOWN( size_t(arg[0]) < npar );\n\t\t\t\/\/ first argument has same sign as parent node\n\t\t\tif( add )\n\t\t\t\tsum_par += par[arg[0]];\n\t\t\telse\tsum_par -= par[arg[0]];\n\t\t\tbreak;\n\n\t\t\t\/\/ cases where first argument is a variable\n\t\t\tcase AddvvOp:\n\t\t\tcase SubvpOp:\n\t\t\tcase SubvvOp:\n\t\t\t\/\/\n\t\t\t\/\/ check if the first argument is csum_connected\n# ifndef NDEBUG\n\t\t\t{\tbool flag1 = op_info[var2op[arg[0]]].csum_connected;\n\t\t\t\tbool flag2 = op_info[ var2op[ arg[0] ] ].csum_connected;\n\t\t\t\tCPPAD_ASSERT_UNKNOWN( flag1 == flag2 );\n\t\t\t}\n# endif\n\t\t\tif( op_info[var2op[arg[0]]].csum_connected )\n\t\t\t{\tCPPAD_ASSERT_UNKNOWN(\n\t\t\t\t\tsize_t(tape[arg[0]].new_var) == tape.size()\n\t\t\t\t);\n\t\t\t\t\/\/ push the operator corresponding to the first argument\n\t\t\t\tvar.op = op_info[ var2op[arg[0]] ].op;\n\t\t\t\tvar.arg = op_info[ var2op[arg[0]] ].arg;\n\t\t\t\t\/\/ first argument has same sign as parent node\n\t\t\t\tvar.add = add;\n\t\t\t\twork.op_stack.push( var );\n\t\t\t}\n\t\t\telse\n\t\t\t{\t\/\/ there are no nodes below this one\n\t\t\t\tCPPAD_ASSERT_UNKNOWN( size_t(arg[0]) < current );\n\t\t\t\tCPPAD_ASSERT_UNKNOWN( tape[arg[0]].new_var <= arg[0] );\n\t\t\t\tif( add )\n\t\t\t\t\twork.add_stack.push(arg[0]);\n\t\t\t\telse\twork.sub_stack.push(arg[0]);\n\t\t\t}\n\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\tCPPAD_ASSERT_UNKNOWN(false);\n\t\t}\n\t\t\/\/ process second argument to this operator\n\t\tswitch(op)\n\t\t{\t\/\/ cases where second argument is a parameter\n\t\t\tcase SubvpOp:\n\t\t\tCPPAD_ASSERT_UNKNOWN( size_t(arg[1]) < npar );\n\t\t\t\/\/ second argument has opposite sign of parent node\n\t\t\tif( add )\n\t\t\t\tsum_par -= par[arg[1]];\n\t\t\telse\tsum_par += par[arg[1]];\n\t\t\tbreak;\n\n\t\t\t\/\/ cases where second argument is a variable and has opposite sign\n\t\t\tcase SubvvOp:\n\t\t\tcase SubpvOp:\n\t\t\tadd = ! add;\n\n\t\t\t\/\/ cases where second argument is a variable and has same sign\n\t\t\tcase AddvvOp:\n\t\t\tcase AddpvOp:\n\t\t\t\/\/ check if the second argument is csum_connected\n# ifndef NDEBUG\n\t\t\t{\tbool flag1 = op_info[var2op[arg[1]]].csum_connected;\n\t\t\t\tbool flag2 = op_info[ var2op[ arg[1] ] ].csum_connected;\n\t\t\t\tCPPAD_ASSERT_UNKNOWN( flag1 == flag2 );\n\t\t\t}\n# endif\n\t\t\tif( op_info[var2op[arg[1]]].csum_connected )\n\t\t\t{\tCPPAD_ASSERT_UNKNOWN(\n\t\t\t\t\tsize_t(tape[arg[1]].new_var) == tape.size()\n\t\t\t\t);\n\t\t\t\t\/\/ push the operator corresoponding to the second arugment\n\t\t\t\tvar.op = op_info[ var2op[arg[1]] ].op;\n\t\t\t\tvar.arg = op_info[ var2op[arg[1]] ].arg;\n\t\t\t\tvar.add = add;\n\t\t\t\twork.op_stack.push( var );\n\t\t\t}\n\t\t\telse\n\t\t\t{\t\/\/ there are no nodes below this one\n\t\t\t\tCPPAD_ASSERT_UNKNOWN( size_t(arg[1]) < current );\n\t\t\t\tCPPAD_ASSERT_UNKNOWN( tape[arg[1]].new_var <= arg[1] );\n\t\t\t\tif( add )\n\t\t\t\t\twork.add_stack.push(arg[1]);\n\t\t\t\telse\twork.sub_stack.push(arg[1]);\n\t\t\t}\n\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\tCPPAD_ASSERT_UNKNOWN(false);\n\t\t}\n\t}\n\t\/\/ number of variables to add in this cummulative sum operator\n\tsize_t n_add = work.add_stack.size();\n\t\/\/ number of variables to subtract in this cummulative sum operator\n\tsize_t n_sub = work.sub_stack.size();\n\t\/\/\n\trec->PutArg(n_add); \/\/ arg[0]\n\trec->PutArg(n_sub); \/\/ arg[1]\n\tsize_t new_arg = rec->PutPar(sum_par);\n\trec->PutArg(new_arg); \/\/ arg[2]\n\t\/\/ addition arguments\n\tfor(i = 0; i < n_add; i++)\n\t{\tCPPAD_ASSERT_UNKNOWN( ! work.add_stack.empty() );\n\t\tsize_t old_arg = work.add_stack.top();\n\t\tnew_arg = tape[old_arg].new_var;\n\t\tCPPAD_ASSERT_UNKNOWN( new_arg < current );\n\t\trec->PutArg(new_arg); \/\/ arg[3+i]\n\t\twork.add_stack.pop();\n\t}\n\t\/\/ subtraction arguments\n\tfor(i = 0; i < n_sub; i++)\n\t{\tCPPAD_ASSERT_UNKNOWN( ! work.sub_stack.empty() );\n\t\tsize_t old_arg = work.sub_stack.top();\n\t\tnew_arg = tape[old_arg].new_var;\n\t\tCPPAD_ASSERT_UNKNOWN( new_arg < current );\n\t\trec->PutArg(new_arg); \/\/ arg[3 + arg[0] + i]\n\t\twork.sub_stack.pop();\n\t}\n\t\/\/ number of additions plus number of subtractions\n\trec->PutArg(n_add + n_sub); \/\/ arg[3 + arg[0] + arg[1]]\n\t\/\/\n\t\/\/ return value\n\tstruct_size_pair ret;\n\tret.i_op = rec->num_op_rec();\n\tret.i_var = rec->PutOp(CSumOp);\n\t\/\/\n\treturn ret;\n}\n\n} } } \/\/ END_CPPAD_LOCAL_OPTIMIZE_NAMESPACE\n\n\n# endif\n<|endoftext|>"} {"text":"\/*\n * Copyright 2015 - 2018 gtalent2@gmail.com\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#if defined(OX_USE_STDLIB)\n#include \n#include \n#endif\n\n#include \"defines.hpp\"\n#include \"stacktrace.hpp\"\n#include \"trace.hpp\"\n\n#include \"assert.hpp\"\n\nnamespace ox {\n\ntemplate<>\nvoid assertFunc([[maybe_unused]]const char *file, [[maybe_unused]]int line, [[maybe_unused]]bool pass, [[maybe_unused]]const char *msg) {\n#if defined(OX_USE_STDLIB)\n\tif (!pass) {\n\t\tstd::cerr << \"\\033[31;1;1mASSERT FAILURE:\\033[0m (\" << file << ':' << line << \"): \" << msg << std::endl;\n\t\tprintStackTrace(2);\n\t\toxTrace(\"assert\").del(\"\") << \"Failed assert: \" << msg << \" (\" << file << \":\" << line << \")\";\n\t\tstd::abort();\n\t}\n#endif\n}\n\ntemplate<>\nvoid assertFunc(const char *file, int line, Error err, const char *assertMsg) {\n\tif (err) {\n\t\tstd::cerr << \"\\033[31;1;1mASSERT FAILURE:\\033[0m (\" << file << ':' << line << \"): \" << assertMsg << '\\n';\n\t\tif (err.msg) {\n\t\t\tstd::cerr << \"\\tError Message:\\t\" << err.msg << '\\n';\n\t\t}\n\t\tstd::cerr << \"\\tError Code:\\t\" << err << '\\n';\n\t\tif (err.file != nullptr) {\n\t\t\tstd::cerr << \"\\tError Location:\\t\" << reinterpret_cast(err.file) << ':' << err.line << '\\n';\n\t\t}\n\t\tprintStackTrace(2);\n\t\toxTrace(\"panic\").del(\"\") << \"Panic: \" << assertMsg << \" (\" << file << \":\" << line << \")\";\n\t\tstd::abort();\n\t}\n}\n\n#if defined(OX_USE_STDLIB)\nvoid panic(const char *file, int line, const char *panicMsg, Error err) {\n\tstd::cerr << \"\\033[31;1;1mPANIC:\\033[0m (\" << file << ':' << line << \"): \" << panicMsg << '\\n';\n\tif (err.msg) {\n\t\tstd::cerr << \"\\tError Message:\\t\" << err.msg << '\\n';\n\t}\n\tstd::cerr << \"\\tError Code:\\t\" << err << '\\n';\n\tif (err.file != nullptr) {\n\t\tstd::cerr << \"\\tError Location:\\t\" << reinterpret_cast(err.file) << ':' << err.line << '\\n';\n\t}\n\tprintStackTrace(2);\n\toxTrace(\"panic\").del(\"\") << \"Panic: \" << panicMsg << \" (\" << file << \":\" << line << \")\";\n\tstd::abort();\n}\n#endif\n\n}\n[ox\/std] Fix assert for !OX_USE_STDLIB\/*\n * Copyright 2015 - 2018 gtalent2@gmail.com\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#if defined(OX_USE_STDLIB)\n#include \n#include \n#endif\n\n#include \"defines.hpp\"\n#include \"stacktrace.hpp\"\n#include \"trace.hpp\"\n\n#include \"assert.hpp\"\n\nnamespace ox {\n\ntemplate<>\nvoid assertFunc([[maybe_unused]]const char *file, [[maybe_unused]]int line, [[maybe_unused]]bool pass, [[maybe_unused]]const char *msg) {\n#if defined(OX_USE_STDLIB)\n\tif (!pass) {\n\t\tstd::cerr << \"\\033[31;1;1mASSERT FAILURE:\\033[0m (\" << file << ':' << line << \"): \" << msg << std::endl;\n\t\tprintStackTrace(2);\n\t\toxTrace(\"assert\").del(\"\") << \"Failed assert: \" << msg << \" (\" << file << \":\" << line << \")\";\n\t\tstd::abort();\n\t}\n#endif\n}\n\ntemplate<>\nvoid assertFunc(const char *file, int line, Error err, const char *assertMsg) {\n\tif (err) {\n#if defined(OX_USE_STDLIB)\n\t\tstd::cerr << \"\\033[31;1;1mASSERT FAILURE:\\033[0m (\" << file << ':' << line << \"): \" << assertMsg << '\\n';\n\t\tif (err.msg) {\n\t\t\tstd::cerr << \"\\tError Message:\\t\" << err.msg << '\\n';\n\t\t}\n\t\tstd::cerr << \"\\tError Code:\\t\" << err << '\\n';\n\t\tif (err.file != nullptr) {\n\t\t\tstd::cerr << \"\\tError Location:\\t\" << reinterpret_cast(err.file) << ':' << err.line << '\\n';\n\t\t}\n\t\tprintStackTrace(2);\n\t\toxTrace(\"panic\").del(\"\") << \"Panic: \" << assertMsg << \" (\" << file << \":\" << line << \")\";\n\t\tstd::abort();\n#else\n\t\tpanic(file, line, assertMsg);\n#endif\n\t}\n}\n\n#if defined(OX_USE_STDLIB)\nvoid panic(const char *file, int line, const char *panicMsg, Error err) {\n\tstd::cerr << \"\\033[31;1;1mPANIC:\\033[0m (\" << file << ':' << line << \"): \" << panicMsg << '\\n';\n\tif (err.msg) {\n\t\tstd::cerr << \"\\tError Message:\\t\" << err.msg << '\\n';\n\t}\n\tstd::cerr << \"\\tError Code:\\t\" << err << '\\n';\n\tif (err.file != nullptr) {\n\t\tstd::cerr << \"\\tError Location:\\t\" << reinterpret_cast(err.file) << ':' << err.line << '\\n';\n\t}\n\tprintStackTrace(2);\n\toxTrace(\"panic\").del(\"\") << \"Panic: \" << panicMsg << \" (\" << file << \":\" << line << \")\";\n\tstd::abort();\n}\n#endif\n\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) the JPEG XL Project Authors. All rights reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n#include \n\n#include \n\n#include \"lib\/jxl\/base\/compiler_specific.h\"\n#include \"lib\/jxl\/color_management.h\"\n#include \"lib\/jxl\/dec_xyb.h\"\n#include \"lib\/jxl\/enc_color_management.h\"\n#include \"lib\/jxl\/enc_xyb.h\"\n#include \"lib\/jxl\/image.h\"\n#include \"lib\/jxl\/linalg.h\"\n#include \"lib\/jxl\/opsin_params.h\"\n\nnamespace jxl {\nnamespace {\n\nclass OpsinImageTargetTest : public hwy::TestWithParamTarget {};\nHWY_TARGET_INSTANTIATE_TEST_SUITE_P(OpsinImageTargetTest);\n\n\/\/ Convert a single linear sRGB color to xyb, using the exact image conversion\n\/\/ procedure that jpeg xl uses.\nvoid LinearSrgbToOpsin(float rgb_r, float rgb_g, float rgb_b,\n float* JXL_RESTRICT xyb_x, float* JXL_RESTRICT xyb_y,\n float* JXL_RESTRICT xyb_b) {\n Image3F linear(1, 1);\n linear.PlaneRow(0, 0)[0] = rgb_r;\n linear.PlaneRow(1, 0)[0] = rgb_g;\n linear.PlaneRow(2, 0)[0] = rgb_b;\n\n ImageMetadata metadata;\n metadata.SetFloat32Samples();\n metadata.color_encoding = ColorEncoding::LinearSRGB();\n ImageBundle ib(&metadata);\n ib.SetFromImage(std::move(linear), metadata.color_encoding);\n Image3F opsin(1, 1);\n (void)ToXYB(ib, \/*pool=*\/nullptr, &opsin, GetJxlCms());\n\n *xyb_x = opsin.PlaneRow(0, 0)[0];\n *xyb_y = opsin.PlaneRow(1, 0)[0];\n *xyb_b = opsin.PlaneRow(2, 0)[0];\n}\n\n\/\/ Convert a single XYB color to linear sRGB, using the exact image conversion\n\/\/ procedure that jpeg xl uses.\nvoid OpsinToLinearSrgb(float xyb_x, float xyb_y, float xyb_b,\n float* JXL_RESTRICT rgb_r, float* JXL_RESTRICT rgb_g,\n float* JXL_RESTRICT rgb_b) {\n Image3F opsin(1, 1);\n opsin.PlaneRow(0, 0)[0] = xyb_x;\n opsin.PlaneRow(1, 0)[0] = xyb_y;\n opsin.PlaneRow(2, 0)[0] = xyb_b;\n Image3F linear(1, 1);\n OpsinParams opsin_params;\n opsin_params.Init(\/*intensity_target=*\/255.0f);\n OpsinToLinear(opsin, Rect(opsin), nullptr, &linear, opsin_params);\n *rgb_r = linear.PlaneRow(0, 0)[0];\n *rgb_g = linear.PlaneRow(1, 0)[0];\n *rgb_b = linear.PlaneRow(2, 0)[0];\n}\n\nvoid OpsinRoundtripTestRGB(float r, float g, float b) {\n float xyb_x, xyb_y, xyb_b;\n LinearSrgbToOpsin(r, g, b, &xyb_x, &xyb_y, &xyb_b);\n float r2, g2, b2;\n OpsinToLinearSrgb(xyb_x, xyb_y, xyb_b, &r2, &g2, &b2);\n EXPECT_NEAR(r, r2, 1e-3);\n EXPECT_NEAR(g, g2, 1e-3);\n EXPECT_NEAR(b, b2, 1e-3);\n}\n\nTEST(OpsinImageTest, VerifyOpsinAbsorbanceInverseMatrix) {\n float matrix[9]; \/\/ writable copy\n for (int i = 0; i < 9; i++) {\n matrix[i] = GetOpsinAbsorbanceInverseMatrix()[i];\n }\n EXPECT_TRUE(Inv3x3Matrix(matrix));\n for (int i = 0; i < 9; i++) {\n EXPECT_NEAR(matrix[i], kOpsinAbsorbanceMatrix[i], 1e-6);\n }\n}\n\nTEST(OpsinImageTest, OpsinRoundtrip) {\n OpsinRoundtripTestRGB(0, 0, 0);\n OpsinRoundtripTestRGB(1. \/ 255, 1. \/ 255, 1. \/ 255);\n OpsinRoundtripTestRGB(128. \/ 255, 128. \/ 255, 128. \/ 255);\n OpsinRoundtripTestRGB(1, 1, 1);\n\n OpsinRoundtripTestRGB(0, 0, 1. \/ 255);\n OpsinRoundtripTestRGB(0, 0, 128. \/ 255);\n OpsinRoundtripTestRGB(0, 0, 1);\n\n OpsinRoundtripTestRGB(0, 1. \/ 255, 0);\n OpsinRoundtripTestRGB(0, 128. \/ 255, 0);\n OpsinRoundtripTestRGB(0, 1, 0);\n\n OpsinRoundtripTestRGB(1. \/ 255, 0, 0);\n OpsinRoundtripTestRGB(128. \/ 255, 0, 0);\n OpsinRoundtripTestRGB(1, 0, 0);\n}\n\nTEST(OpsinImageTest, VerifyZero) {\n \/\/ Test that black color (zero energy) is 0,0,0 in xyb.\n float x, y, b;\n LinearSrgbToOpsin(0, 0, 0, &x, &y, &b);\n EXPECT_NEAR(0, x, 1e-9);\n EXPECT_NEAR(0, y, 1e-7);\n EXPECT_NEAR(0, b, 1e-7);\n}\n\nTEST(OpsinImageTest, VerifyGray) {\n \/\/ Test that grayscale colors have a fixed y\/b ratio and x==0.\n for (size_t i = 1; i < 255; i++) {\n float x, y, b;\n LinearSrgbToOpsin(i \/ 255., i \/ 255., i \/ 255., &x, &y, &b);\n EXPECT_NEAR(0, x, 1e-6);\n EXPECT_NEAR(kYToBRatio, b \/ y, 3e-5);\n }\n}\n\n} \/\/ namespace\n} \/\/ namespace jxl\nremoving empty test (#1509)\/\/ Copyright (c) the JPEG XL Project Authors. All rights reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n#include \n\n#include \n\n#include \"lib\/jxl\/base\/compiler_specific.h\"\n#include \"lib\/jxl\/color_management.h\"\n#include \"lib\/jxl\/dec_xyb.h\"\n#include \"lib\/jxl\/enc_color_management.h\"\n#include \"lib\/jxl\/enc_xyb.h\"\n#include \"lib\/jxl\/image.h\"\n#include \"lib\/jxl\/linalg.h\"\n#include \"lib\/jxl\/opsin_params.h\"\n\nnamespace jxl {\nnamespace {\n\n\/\/ Convert a single linear sRGB color to xyb, using the exact image conversion\n\/\/ procedure that jpeg xl uses.\nvoid LinearSrgbToOpsin(float rgb_r, float rgb_g, float rgb_b,\n float* JXL_RESTRICT xyb_x, float* JXL_RESTRICT xyb_y,\n float* JXL_RESTRICT xyb_b) {\n Image3F linear(1, 1);\n linear.PlaneRow(0, 0)[0] = rgb_r;\n linear.PlaneRow(1, 0)[0] = rgb_g;\n linear.PlaneRow(2, 0)[0] = rgb_b;\n\n ImageMetadata metadata;\n metadata.SetFloat32Samples();\n metadata.color_encoding = ColorEncoding::LinearSRGB();\n ImageBundle ib(&metadata);\n ib.SetFromImage(std::move(linear), metadata.color_encoding);\n Image3F opsin(1, 1);\n (void)ToXYB(ib, \/*pool=*\/nullptr, &opsin, GetJxlCms());\n\n *xyb_x = opsin.PlaneRow(0, 0)[0];\n *xyb_y = opsin.PlaneRow(1, 0)[0];\n *xyb_b = opsin.PlaneRow(2, 0)[0];\n}\n\n\/\/ Convert a single XYB color to linear sRGB, using the exact image conversion\n\/\/ procedure that jpeg xl uses.\nvoid OpsinToLinearSrgb(float xyb_x, float xyb_y, float xyb_b,\n float* JXL_RESTRICT rgb_r, float* JXL_RESTRICT rgb_g,\n float* JXL_RESTRICT rgb_b) {\n Image3F opsin(1, 1);\n opsin.PlaneRow(0, 0)[0] = xyb_x;\n opsin.PlaneRow(1, 0)[0] = xyb_y;\n opsin.PlaneRow(2, 0)[0] = xyb_b;\n Image3F linear(1, 1);\n OpsinParams opsin_params;\n opsin_params.Init(\/*intensity_target=*\/255.0f);\n OpsinToLinear(opsin, Rect(opsin), nullptr, &linear, opsin_params);\n *rgb_r = linear.PlaneRow(0, 0)[0];\n *rgb_g = linear.PlaneRow(1, 0)[0];\n *rgb_b = linear.PlaneRow(2, 0)[0];\n}\n\nvoid OpsinRoundtripTestRGB(float r, float g, float b) {\n float xyb_x, xyb_y, xyb_b;\n LinearSrgbToOpsin(r, g, b, &xyb_x, &xyb_y, &xyb_b);\n float r2, g2, b2;\n OpsinToLinearSrgb(xyb_x, xyb_y, xyb_b, &r2, &g2, &b2);\n EXPECT_NEAR(r, r2, 1e-3);\n EXPECT_NEAR(g, g2, 1e-3);\n EXPECT_NEAR(b, b2, 1e-3);\n}\n\nTEST(OpsinImageTest, VerifyOpsinAbsorbanceInverseMatrix) {\n float matrix[9]; \/\/ writable copy\n for (int i = 0; i < 9; i++) {\n matrix[i] = GetOpsinAbsorbanceInverseMatrix()[i];\n }\n EXPECT_TRUE(Inv3x3Matrix(matrix));\n for (int i = 0; i < 9; i++) {\n EXPECT_NEAR(matrix[i], kOpsinAbsorbanceMatrix[i], 1e-6);\n }\n}\n\nTEST(OpsinImageTest, OpsinRoundtrip) {\n OpsinRoundtripTestRGB(0, 0, 0);\n OpsinRoundtripTestRGB(1. \/ 255, 1. \/ 255, 1. \/ 255);\n OpsinRoundtripTestRGB(128. \/ 255, 128. \/ 255, 128. \/ 255);\n OpsinRoundtripTestRGB(1, 1, 1);\n\n OpsinRoundtripTestRGB(0, 0, 1. \/ 255);\n OpsinRoundtripTestRGB(0, 0, 128. \/ 255);\n OpsinRoundtripTestRGB(0, 0, 1);\n\n OpsinRoundtripTestRGB(0, 1. \/ 255, 0);\n OpsinRoundtripTestRGB(0, 128. \/ 255, 0);\n OpsinRoundtripTestRGB(0, 1, 0);\n\n OpsinRoundtripTestRGB(1. \/ 255, 0, 0);\n OpsinRoundtripTestRGB(128. \/ 255, 0, 0);\n OpsinRoundtripTestRGB(1, 0, 0);\n}\n\nTEST(OpsinImageTest, VerifyZero) {\n \/\/ Test that black color (zero energy) is 0,0,0 in xyb.\n float x, y, b;\n LinearSrgbToOpsin(0, 0, 0, &x, &y, &b);\n EXPECT_NEAR(0, x, 1e-9);\n EXPECT_NEAR(0, y, 1e-7);\n EXPECT_NEAR(0, b, 1e-7);\n}\n\nTEST(OpsinImageTest, VerifyGray) {\n \/\/ Test that grayscale colors have a fixed y\/b ratio and x==0.\n for (size_t i = 1; i < 255; i++) {\n float x, y, b;\n LinearSrgbToOpsin(i \/ 255., i \/ 255., i \/ 255., &x, &y, &b);\n EXPECT_NEAR(0, x, 1e-6);\n EXPECT_NEAR(kYToBRatio, b \/ y, 3e-5);\n }\n}\n\n} \/\/ namespace\n} \/\/ namespace jxl\n<|endoftext|>"} {"text":"\/*\n * This badge clock was coded by none other than Simon Smith and Cameron Kachur.\n * It does clock things such as tell time and.........................\n * You wish you could make a clock badgerooni like this.\n * Happy clocking and turn down for only dead batteries.\n * Boilermake 2014 - All clock no sleep\n *\/\n\n#define MAX_TERMINAL_LINE_LEN 40\n#define MAX_TERMINAL_WORDS 7\n\n\/\/ 14 is strlen(\"send FFFF -m \")\n\/\/ the max message length able to be sent from the terminal is\n\/\/ total terminal line length MINUS the rest of the message\n#define MAX_TERMINAL_MESSAGE_LEN MAX_TERMINAL_LINE_LEN - 14\n\n#include \n#include \n#include \n\nvoid networkRead(void);\n\nvoid setLEDS(word);\nvoid handlePayload(struct payload *);\n\nvoid displayDemo();\n\n\/\/ Maps commands to integers\nconst byte PING = 0; \/\/ Ping\nconst byte LED = 1; \/\/ LED pattern\nconst byte MESS = 2; \/\/ Message\nconst byte DEMO = 3; \/\/ Demo Pattern\n\n\/\/ Global Variables\nint SROEPin = 3; \/\/ using digital pin 3 for SR !OE\nint SRLatchPin = 8; \/\/ using digital pin 4 for SR latch\nboolean terminalConnect = false; \/\/ indicates if the terminal has connected to the board yet\n\n\/\/ nRF24L01 radio static initializations\nRF24 radio(9,10); \/\/ Setup nRF24L01 on SPI bus using pins 9 & 10 as CE & CSN, respectively\n\nuint16_t this_node_address = (EEPROM.read(0) << 8) | EEPROM.read(1); \/\/ Radio address for this node\nunsigned long startTime = 0;\n\nstruct payload{ \/\/ Payload structure\n byte command;\n byte led_pattern;\n char message[30];\n};\n\n\/\/ This runs once on boot\nvoid setup() {\n Serial.begin(9600);\n\n \/\/ SPI initializations\n SPI.begin();\n SPI.setBitOrder(MSBFIRST); \/\/ nRF requires MSB first\n SPI.setClockDivider(16); \/\/ Set SPI clock to 16 MHz \/ 16 = 1 MHz\n\n \/\/ nRF radio initializations\n radio.begin();\n radio.setDataRate(RF24_1MBPS); \/\/ 1Mbps transfer rate\n radio.setCRCLength(RF24_CRC_16); \/\/ 16-bit CRC\n radio.setChannel(80); \/\/ Channel center frequency = 2.4005 GHz + (Channel# * 1 MHz)\n radio.setRetries(200, 5); \/\/ set the delay and number of retries upon failed transmit\n radio.openReadingPipe(0, this_node_address); \/\/ Open this address\n radio.startListening(); \/\/ Start listening on opened address\n\n \/\/ Shift register pin initializations\n pinMode(SROEPin, OUTPUT);\n pinMode(SRLatchPin, OUTPUT);\n digitalWrite(SROEPin, HIGH);\n digitalWrite(SRLatchPin, LOW);\n\n\n \/\/ make the pretty LEDs happen\n displayDemo();\n\n startTime = millis();\n \/\/ \n digitalWrite(SROEPin, LOW);\n}\n\n\n\/\/ This loops forever\nvoid loop() {\n if (Serial && !terminalConnect) { \n terminalConnect = true;\n sync_time_serial();\n } else if (!Serial && terminalConnect) {\n terminalConnect = false;\n }\n \n \n displayTime();\n}\n\nvoid displayTime() {\n unsigned long time = millis() - startTime; \n int hour = (time \/ 3600000) % 12;\n int minute = (time \/ 60000) % 60;\n int second = (time \/ 1000) % 60;\n \n if (second % 2) { \n setLEDS(ledNum(toLED16(hour)) | ledNum(toLED16(minute \/ 5)));\n } else {\n setLEDS(ledNum(toLED16(hour)));\n }\n delay(1000);\n if (minute % 5 == 0 && second < 1) {\n for (int i = 0; i < 16; i++) {\n setLEDS(ledNum(i));\n delay((int) 1000\/16);\n }\n } \n\n Serial.print(millis());\n Serial.print(\" : \");\n Serial.print(time);\n Serial.print(\" : \");\n Serial.print(hour);\n Serial.print(\" : \");\n Serial.println(minute);\n}\n\n\n\/\/12 hour clock, but 16 LEDs\nint toLED16(int i) {\n int ret = i; \n\n \/\/We have to not use 4 of the 16 for a 12 clock\n if (ret >= 3) ret += 1;\n if (ret >= 5) ret += 1;\n if (ret >= 11) ret += 1;\n if (ret >= 13) ret += 1;\n ret += 9; \n return ret % 16;\n}\n\nvoid sync_time_serial() {\n \n}\n\n\/*\n\/\/ Display LED pattern\n\n\/\/ LED numbering:\n\n 9\n 8 10\n 7 11\n 6 12\n 5 13\n 4 14\n 3 15\n 2 16\n 1\n\nshift register 1-8: AA\nshift register 9-16: BB\n\nsetLEDS data in hex: 0xAABB\nwhere AA in binary = 0b[8][7][6][5][4][3][2][1]\n BB in binary = 0b[16][15][14][13][12][11][10][9]\n\n*\/\nword ledNum(int i) {\n word shit[17];\n shit[0] = 0x0000;\n\n shit[1] = 0x0100;\n shit[2] = 0x0200;\n shit[3] = 0x0400;\n shit[4] = 0x0800;\n shit[5] = 0x1000;\n shit[6] = 0x2000;\n shit[7] = 0x4000;\n shit[8] = 0x8000;\n\n shit[9] = 0x0001;\n shit[10] = 0x0002;\n shit[11] = 0x0004;\n shit[12] = 0x0008;\n shit[13] = 0x0010;\n shit[14] = 0x0020;\n shit[15] = 0x0040;\n shit[16] = 0x0080;\n\n return shit[i];\n}\n\n\/\/ LED display demo\nvoid displayDemo() {\n digitalWrite(SROEPin, LOW);\n for (int i = 0; i < 4; i++) {\n setLEDS(0xAAAA);\n delay(125);\n setLEDS(0x5555);\n delay(125);\n }\n digitalWrite(SROEPin, HIGH);\n}\n\n\/\/ Sends word sized value to both SRs & latches output pins\nvoid setLEDS(word value) {\n byte Hvalue = value >> 8;\n byte Lvalue = value & 0x00FF;\n SPI.transfer(Lvalue);\n SPI.transfer(Hvalue);\n digitalWrite(SRLatchPin, HIGH);\n digitalWrite(SRLatchPin, LOW);\n}\nhmm still tired\/*\n * This badge clock was coded by none other than Simon Smith and Cameron Kachur.\n * It does clock things such as tell time and.........................\n * You wish you could make a clock badgerooni like this.\n * Happy clocking and turn down for only dead batteries.\n * Boilermake 2014 - All clock no sleep\n *\/\n\n#define MAX_TERMINAL_LINE_LEN 40\n#define MAX_TERMINAL_WORDS 7\n\n\/\/ 14 is strlen(\"send FFFF -m \")\n\/\/ the max message length able to be sent from the terminal is\n\/\/ total terminal line length MINUS the rest of the message\n#define MAX_TERMINAL_MESSAGE_LEN MAX_TERMINAL_LINE_LEN - 14\n\n#include \n#include \n#include \n\nvoid networkRead(void);\n\nvoid setLEDS(word);\nvoid handlePayload(struct payload *);\n\nvoid displayDemo();\n\n\/\/ Maps commands to integers\nconst byte PING = 0; \/\/ Ping\nconst byte LED = 1; \/\/ LED pattern\nconst byte MESS = 2; \/\/ Message\nconst byte DEMO = 3; \/\/ Demo Pattern\n\n\/\/ Global Variables\nint SROEPin = 3; \/\/ using digital pin 3 for SR !OE\nint SRLatchPin = 8; \/\/ using digital pin 4 for SR latch\nboolean terminalConnect = false; \/\/ indicates if the terminal has connected to the board yet\n\n\/\/ nRF24L01 radio static initializations\nRF24 radio(9,10); \/\/ Setup nRF24L01 on SPI bus using pins 9 & 10 as CE & CSN, respectively\n\nuint16_t this_node_address = (EEPROM.read(0) << 8) | EEPROM.read(1); \/\/ Radio address for this node\nunsigned long startTime = 0;\n\nstruct payload{ \/\/ Payload structure\n byte command;\n byte led_pattern;\n char message[30];\n};\n\n\/\/ This runs once on boot\nvoid setup() {\n Serial.begin(9600);\n\n \/\/ SPI initializations\n SPI.begin();\n SPI.setBitOrder(MSBFIRST); \/\/ nRF requires MSB first\n SPI.setClockDivider(16); \/\/ Set SPI clock to 16 MHz \/ 16 = 1 MHz\n\n \/\/ nRF radio initializations\n radio.begin();\n radio.setDataRate(RF24_1MBPS); \/\/ 1Mbps transfer rate\n radio.setCRCLength(RF24_CRC_16); \/\/ 16-bit CRC\n radio.setChannel(80); \/\/ Channel center frequency = 2.4005 GHz + (Channel# * 1 MHz)\n radio.setRetries(200, 5); \/\/ set the delay and number of retries upon failed transmit\n radio.openReadingPipe(0, this_node_address); \/\/ Open this address\n radio.startListening(); \/\/ Start listening on opened address\n\n \/\/ Shift register pin initializations\n pinMode(SROEPin, OUTPUT);\n pinMode(SRLatchPin, OUTPUT);\n digitalWrite(SROEPin, HIGH);\n digitalWrite(SRLatchPin, LOW);\n\n\n \/\/ make the pretty LEDs happen\n displayDemo();\n\n startTime = millis();\n \/\/ \n digitalWrite(SROEPin, LOW);\n}\n\n\n\/\/ This loops forever\nvoid loop() {\n if (Serial && !terminalConnect) { \n terminalConnect = true;\n sync_time_serial();\n } else if (!Serial && terminalConnect) {\n terminalConnect = false;\n }\n \n \n displayTime();\n}\n\nvoid displayTime() {\n unsigned long time = millis() - startTime; \n int hour = (time \/ 3600000) % 12;\n int minute = (time \/ 60000) % 60;\n int second = (time \/ 1000) % 60;\n \n if (second % 2) { \n setLEDS(ledNum(toLED16(hour)) | ledNum(toLED16(minute \/ 5)));\n } else {\n setLEDS(ledNum(toLED16(hour)));\n }\n delay(1000);\n if (minute % 5 == 0 && second == 0) {\n for (int i = 0; i < 16; i++) {\n setLEDS(ledNum((i + 9 + hour) % 16 + 1));\n delay((int) 1000\/16);\n }\n } \n\n Serial.print(millis());\n Serial.print(\" : \");\n Serial.print(time);\n Serial.print(\" : \");\n Serial.print(hour);\n Serial.print(\" : \");\n Serial.println(minute);\n}\n\n\n\/\/12 hour clock, but 16 LEDs\nint toLED16(int i) {\n int ret = i; \n\n \/\/We have to not use 4 of the 16 for a 12 clock\n if (ret >= 3) ret += 1;\n if (ret >= 5) ret += 1;\n if (ret >= 11) ret += 1;\n if (ret >= 13) ret += 1;\n ret += 9; \n return ret % 16;\n}\n\n\/\/Wait a bit and see if we get serial time sync\nvoid sync_time_serial() {\n \n}\n\n\/*\n\/\/ Display LED pattern\n\n\/\/ LED numbering:\n\n 9\n 8 10\n 7 11\n 6 12\n 5 13\n 4 14\n 3 15\n 2 16\n 1\n\nshift register 1-8: AA\nshift register 9-16: BB\n\nsetLEDS data in hex: 0xAABB\nwhere AA in binary = 0b[8][7][6][5][4][3][2][1]\n BB in binary = 0b[16][15][14][13][12][11][10][9]\n\n*\/\nword ledNum(int i) {\n word shit[17];\n shit[0] = 0x0000;\n\n shit[1] = 0x0100;\n shit[2] = 0x0200;\n shit[3] = 0x0400;\n shit[4] = 0x0800;\n shit[5] = 0x1000;\n shit[6] = 0x2000;\n shit[7] = 0x4000;\n shit[8] = 0x8000;\n\n shit[9] = 0x0001;\n shit[10] = 0x0002;\n shit[11] = 0x0004;\n shit[12] = 0x0008;\n shit[13] = 0x0010;\n shit[14] = 0x0020;\n shit[15] = 0x0040;\n shit[16] = 0x0080;\n\n return shit[i];\n}\n\n\/\/ LED display demo\nvoid displayDemo() {\n digitalWrite(SROEPin, LOW);\n for (int i = 0; i < 4; i++) {\n setLEDS(0xAAAA);\n delay(125);\n setLEDS(0x5555);\n delay(125);\n }\n digitalWrite(SROEPin, HIGH);\n}\n\n\/\/ Sends word sized value to both SRs & latches output pins\nvoid setLEDS(word value) {\n byte Hvalue = value >> 8;\n byte Lvalue = value & 0x00FF;\n SPI.transfer(Lvalue);\n SPI.transfer(Hvalue);\n digitalWrite(SRLatchPin, HIGH);\n digitalWrite(SRLatchPin, LOW);\n}\n<|endoftext|>"} {"text":"\/*\nCopyright libCellML Contributors\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n#include \"gtest\/gtest.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ generated with test resource locations\n#include \"test_resources.h\"\n\nstatic int countImportedComponents(libcellml::ModelPtr model)\n{\n return -1;\n}\n\nTEST(ResolveImports, parseSineModelFromFile) {\n std::ifstream t(TestResources::getLocation(\n TestResources::CELLML_SINE_MODEL_RESOURCE));\n std::stringstream buffer;\n buffer << t.rdbuf();\n\n libcellml::Parser p(libcellml::Format::XML);\n libcellml::ModelPtr model = p.parseModel(buffer.str());\n\n EXPECT_EQ(0, p.errorCount());\n\n EXPECT_EQ(0, countImportedComponents(model));\n}\n\nTEST(ResolveImports, parseSineImportsModelFromFile) {\n std::ifstream t(TestResources::getLocation(\n TestResources::CELLML_SINE_IMPORTS_MODEL_RESOURCE));\n std::stringstream buffer;\n buffer << t.rdbuf();\n\n libcellml::Parser p(libcellml::Format::XML);\n libcellml::ModelPtr model = p.parseModel(buffer.str());\n EXPECT_EQ(0, p.errorCount());\n\n EXPECT_EQ(3, countImportedComponents(model));\n}\nHierarchically counting imported components.\/*\nCopyright libCellML Contributors\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n#include \"gtest\/gtest.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ generated with test resource locations\n#include \"test_resources.h\"\n\nstatic size_t countImportedChildren(libcellml::ComponentPtr parent)\n{\n size_t numberImportedChildren = 0;\n for (size_t n = 0; n < parent->componentCount(); ++n)\n {\n libcellml::ComponentPtr c = parent->getComponent(n);\n if (c->isImport()) ++numberImportedChildren;\n numberImportedChildren += countImportedChildren(c);\n }\n return numberImportedChildren;\n}\n\nTEST(ResolveImports, parseSineModelFromFile) {\n std::ifstream t(TestResources::getLocation(\n TestResources::CELLML_SINE_MODEL_RESOURCE));\n std::stringstream buffer;\n buffer << t.rdbuf();\n\n libcellml::Parser p(libcellml::Format::XML);\n libcellml::ModelPtr model = p.parseModel(buffer.str());\n\n EXPECT_EQ(0, p.errorCount());\n\n size_t nImportedComponents = 0;\n for (size_t n = 0; n < model->componentCount(); ++n)\n {\n libcellml::ComponentPtr c = model->getComponent(n);\n if (c->isImport()) ++nImportedComponents;\n nImportedComponents += countImportedChildren(c);\n }\n EXPECT_EQ(0, nImportedComponents);\n}\n\nTEST(ResolveImports, parseSineImportsModelFromFile) {\n std::ifstream t(TestResources::getLocation(\n TestResources::CELLML_SINE_IMPORTS_MODEL_RESOURCE));\n std::stringstream buffer;\n buffer << t.rdbuf();\n\n libcellml::Parser p(libcellml::Format::XML);\n libcellml::ModelPtr model = p.parseModel(buffer.str());\n EXPECT_EQ(0, p.errorCount());\n\n size_t nImportedComponents = 0;\n for (size_t n = 0; n < model->componentCount(); ++n)\n {\n libcellml::ComponentPtr c = model->getComponent(n);\n if (c->isImport()) ++nImportedComponents;\n nImportedComponents += countImportedChildren(c);\n }\n EXPECT_EQ(3, nImportedComponents);\n}\n<|endoftext|>"} {"text":"\/\/ Licensed GNU LGPL v3 or later: http:\/\/www.gnu.org\/licenses\/lgpl.html\n#include \"text-editor.hh\"\n#include \"factory.hh\"\n#include \"container.hh\"\n#include \"window.hh\" \/\/ FIXME: unneeded\n\nnamespace Rapicorn {\nnamespace Text {\nusing namespace Rapicorn;\n\ntypedef enum {\n NEXT_CHAR,\n PREV_CHAR,\n WARP_HOME,\n WARP_END,\n} CursorMovement;\n\nParaState::ParaState() :\n align (ALIGN_LEFT), ellipsize (ELLIPSIZE_END),\n line_spacing (1), indent (0),\n font_family (\"Sans\"), font_size (12)\n{}\n\nAttrState::AttrState() :\n font_family (\"\"), font_scale (1.0),\n bold (false), italic (false), underline (false),\n small_caps (false), strike_through (false),\n foreground (0), background (0)\n{}\n\nEditor::Client::~Client ()\n{}\n\nString\nEditor::Client::markup_text () const\n{\n return save_markup();\n}\n\nvoid\nEditor::Client::markup_text (const String &markup)\n{\n load_markup (markup);\n}\n\nstatic String\nescape_xml (const String &input)\n{\n String d;\n for (String::const_iterator it = input.begin(); it != input.end(); it++)\n switch (*it)\n {\n case '\"': d += \""\"; break;\n case '&': d += \"&\"; break;\n case '\\'': d += \"'\"; break;\n case '<': d += \"<\"; break;\n case '>': d += \">\"; break;\n default: d += *it; break;\n }\n return d;\n}\n\n\nvoid\nEditor::Client::plain_text (const String &markup)\n{\n load_markup (escape_xml (markup));\n}\n\nString\nEditor::Client::plain_text () const\n{\n int byte_length = 0;\n const char *t = const_cast (this)->peek_text (&byte_length);\n return String (t, byte_length);\n}\n\nconst PropertyList&\nEditor::Client::client_property_list()\n{\n static Property *properties[] = {\n MakeProperty (Client, markup_text, _(\"Markup Text\"), _(\"The text to display, containing font and style markup.\"), \"rw\"),\n MakeProperty (Client, plain_text, _(\"Plain Text\"), _(\"The text to display, without markup information.\"), \"rw\"),\n MakeProperty (Client, text_mode, _(\"Text Mode\"), _(\"The basic text layout mechanism to use.\"), \"rw\"),\n };\n static const PropertyList property_list (properties);\n return property_list;\n}\n\n\nconst PropertyList&\nEditor::__aida_properties__()\n{\n static Property *properties[] = {\n MakeProperty (Editor, text_mode, _(\"Text Mode\"), _(\"The basic text layout mechanism to use.\"), \"rw\"),\n MakeProperty (Editor, markup_text, _(\"Markup Text\"), _(\"The text to display, containing font and style markup.\"), \"rw\"),\n MakeProperty (Editor, plain_text, _(\"Plain Text\"), _(\"The text to display, without markup information.\"), \"rw\"),\n MakeProperty (Editor, request_chars, _(\"Request Chars\"), _(\"Number of characters to request space for.\"), 0, INT_MAX, 2, \"rw\"),\n MakeProperty (Editor, request_digits, _(\"Request Digits\"), _(\"Number of digits to request space for.\"), 0, INT_MAX, 2, \"rw\"),\n };\n static const PropertyList property_list (properties, ContainerImpl::__aida_properties__());\n return property_list;\n}\n\nclass EditorImpl : public virtual SingleContainerImpl, public virtual Editor, public virtual EventHandler {\n uint request_chars_, request_digits_;\n int cursor_;\n TextMode text_mode_;\n Client *cached_client_;\n size_t client_sig_;\npublic:\n EditorImpl() :\n request_chars_ (0), request_digits_ (0),\n cursor_ (0), text_mode_ (TEXT_MODE_SINGLE_LINE), cached_client_ (NULL), client_sig_ (0)\n {}\nprivate:\n ~EditorImpl()\n {\n if (cached_client_)\n {\n cached_client_->sig_selection_changed() -= client_sig_;\n client_sig_ = 0;\n ReferenceCountable *trash = dynamic_cast (cached_client_);\n cached_client_ = NULL;\n if (trash)\n unref (trash);\n }\n }\n Client*\n get_client()\n {\n \/\/ check if text client changed\n Client *candidate = interface();\n if (cached_client_ == candidate)\n return cached_client_;\n \/\/ adjust to new client\n Client *const old = cached_client_;\n const size_t old_sig = client_sig_;\n ReferenceCountable *base = dynamic_cast (candidate);\n cached_client_ = base ? candidate : NULL;\n if (base)\n {\n ref (base);\n client_sig_ = cached_client_->sig_selection_changed() += Aida::slot (this, &EditorImpl::selection_changed);\n }\n else\n client_sig_ = 0;\n \/\/ cleanup old\n base = dynamic_cast (old);\n if (base)\n {\n old->sig_selection_changed() -= old_sig;\n unref (base);\n }\n \/\/ update new client\n if (cached_client_)\n update_client();\n return cached_client_;\n }\n void\n update_client ()\n {\n Client *client = get_client();\n return_unless (client);\n client->text_mode (text_mode_);\n client->cursor2mark();\n cursor_ = client->mark();\n selection_changed();\n }\n virtual void\n size_request (Requisition &requisition)\n {\n update_client();\n SingleContainerImpl::size_request (requisition);\n uint fallback_chars = 0, fallback_digits = 0;\n if (text_mode_ == TEXT_MODE_SINGLE_LINE)\n {\n requisition.width = 0;\n if (request_chars_ <= 0 && request_digits_ <= 0)\n {\n fallback_chars = 26;\n fallback_digits = 10;\n }\n }\n Client *client = get_client();\n if (client)\n requisition.width += client->text_requisition (fallback_chars + request_chars_, fallback_digits + request_digits_);\n }\n virtual bool\n can_focus () const\n {\n Client *client = cached_client_;\n return client != NULL;\n }\n virtual void\n reset (ResetMode mode = RESET_ALL)\n {}\n virtual bool\n handle_event (const Event &event)\n {\n bool handled = false, ignore = false;\n switch (event.type)\n {\n Client *client;\n bool rs;\n const EventKey *kevent;\n const EventData *devent;\n const EventButton *bevent;\n case KEY_PRESS:\n kevent = dynamic_cast (&event);\n rs = (kevent->key_state & MOD_SHIFT) == 0; \/\/ reset selection\n switch (kevent->key)\n {\n case 'a':\n if (kevent->key_state & MOD_CONTROL)\n {\n select_all();\n handled = true;\n break;\n }\n goto _default;\n case 'v':\n if (kevent->key_state & MOD_CONTROL)\n {\n get_window()->request_clipboard (77, \"text\/plain\"); \/\/ FIXME: should operate on viewport\n handled = true;\n break;\n }\n goto _default;\n case KEY_Home: case KEY_KP_Home: handled = move_cursor (WARP_HOME, rs); break;\n case KEY_End: case KEY_KP_End: handled = move_cursor (WARP_END, rs); break;\n case KEY_Right: case KEY_KP_Right: handled = move_cursor (NEXT_CHAR, rs); break; \/\/ FIXME: CTRL moves words\n case KEY_Left: case KEY_KP_Left: handled = move_cursor (PREV_CHAR, rs); break; \/\/ FIXME: CTRL moves words\n case KEY_BackSpace: handled = delete_backward(); break;\n case KEY_Delete: case KEY_KP_Delete: handled = delete_foreward(); break;\n default: _default:\n if (kevent->key_state & MOD_CONTROL && \/\/ preserve Ctrl + FocusKey for navigation\n key_value_is_focus_dir (kevent->key))\n {\n handled = false;\n ignore = true;\n }\n else\n handled = insert_literally (kevent->utf8input);\n break;\n }\n if (!handled && !ignore && !key_value_is_modifier (kevent->key))\n {\n notify_key_error();\n handled = true;\n }\n break;\n case KEY_CANCELED:\n case KEY_RELEASE:\n break;\n case CONTENT_DATA:\n devent = dynamic_cast (&event);\n if (devent->nonce == 77 && devent->data_type == \"text\/plain\")\n {\n handled = insert_literally (devent->data);\n }\n break;\n case CONTENT_REQUEST:\n devent = dynamic_cast (&event);\n if (devent->nonce == 79)\n {\n printerr (\"CONTENT_REQUEST: target=%s nonce=%u\\n\", devent->data_type, devent->nonce);\n }\n break;\n case BUTTON_PRESS:\n bevent = dynamic_cast (&event);\n client = get_client();\n grab_focus();\n if (client && bevent->button == 1)\n {\n int o = client->mark();\n bool moved = client->mark_to_coord (bevent->x, bevent->y);\n int m = client->mark();\n if (o != m)\n {\n cursor_ = m;\n client->mark2cursor();\n changed();\n }\n (void) moved;\n }\n else if (bevent->button == 2)\n {\n get_window()->request_selection (77, \"text\/plain\"); \/\/ FIXME: should operate on viewport\n }\n handled = true;\n break;\n default: ;\n }\n return handled;\n }\n int\n cursor () const\n {\n return cursor_;\n }\n bool\n move_cursor (CursorMovement cm, const bool reset_selection)\n {\n const bool adjust_selection = !reset_selection;\n Client *client = get_client();\n return_unless (client, false);\n int start, end;\n const bool has_selection = client->get_selection (&start, &end);\n \/\/ special case, cursor left\/right deselects\n if (has_selection && reset_selection && (cm == PREV_CHAR || cm == NEXT_CHAR))\n {\n client->mark (cm == PREV_CHAR ? start : end);\n client->hide_selector();\n client->mark2cursor();\n cursor_ = client->mark();\n changed();\n return true;\n }\n client->mark (cursor_);\n if (!has_selection && adjust_selection)\n client->mark2selector(); \/\/ old cursor starts selection\n int o = client->mark();\n switch (cm)\n {\n case NEXT_CHAR: client->step_mark (+1); break;\n case PREV_CHAR: client->step_mark (-1); break;\n case WARP_HOME: client->mark (0); break;\n case WARP_END: client->mark (-1); break;\n }\n int m = client->mark();\n if (o == m)\n return false;\n if (reset_selection && has_selection)\n client->hide_selector();\n cursor_ = m;\n client->mark2cursor();\n changed();\n return true;\n }\n bool\n insert_literally (const String &utf8text)\n {\n if (utf8text.size() == 1 &&\n (utf8text[0] == '\\b' || \/\/ Backspace\n utf8text[0] == '\\n' || \/\/ Newline\n utf8text[0] == '\\r' || \/\/ Carriage Return\n utf8text[0] == 0x7f || \/\/ Delete\n 0))\n return false; \/\/ ignore literal inputs from \"control\" keys\n Client *client = get_client();\n if (client && !utf8text.empty())\n {\n delete_selection();\n client->mark (cursor_);\n client->mark_insert (utf8text);\n cursor_ = client->mark();\n client->mark2cursor();\n changed();\n return true;\n }\n return false;\n }\n bool\n select_all()\n {\n Client *client = get_client();\n return_unless (client, false);\n client->mark (0);\n client->mark2selector();\n client->mark (-1);\n cursor_ = client->mark();\n client->mark2cursor();\n changed();\n return client->get_selection();\n }\n bool\n delete_selection()\n {\n Client *client = get_client();\n return_unless (client, false);\n int start, end, nutf8;\n const bool has_selection = client->get_selection (&start, &end, &nutf8);\n if (!has_selection)\n return false;\n client->mark (start);\n client->mark_delete (nutf8);\n client->hide_selector();\n cursor_ = client->mark();\n client->mark2cursor();\n changed();\n return true;\n }\n bool\n delete_backward ()\n {\n if (delete_selection())\n return true;\n Client *client = get_client();\n if (client)\n {\n client->mark (cursor_);\n int o = client->mark();\n client->step_mark (-1);\n int m = client->mark();\n if (o == m)\n return false;\n cursor_ = m;\n client->mark2cursor();\n client->mark_delete (1);\n changed();\n return true;\n }\n return false;\n }\n bool\n delete_foreward ()\n {\n Client *client = get_client();\n return_unless (client, false);\n if (delete_selection())\n return true;\n client->mark (cursor_);\n if (client->mark_at_end())\n return false;\n client->mark_delete (1);\n changed();\n return true;\n }\n void\n selection_changed()\n {\n Client *client = get_client();\n int start, end, nutf8;\n const bool has_selection = client->get_selection (&start, &end, &nutf8);\n if (!has_selection || nutf8 < 1)\n get_window()->claim_selection (0, StringVector()); \/\/ give up ownership\n else\n get_window()->claim_selection (79, cstrings_to_vector (\"text\/plain\", NULL)); \/\/ claim new selection\n }\n virtual void\n text (const String &text)\n {\n Client *client = get_client();\n if (client)\n client->markup_text (text);\n }\n virtual String\n text () const\n {\n return cached_client_ ? cached_client_->markup_text() : \"\";\n }\n virtual TextMode text_mode () const { return text_mode_; }\n virtual void text_mode (TextMode text_mode)\n {\n text_mode_ = text_mode;\n Client *client = get_client();\n if (client)\n client->text_mode (text_mode_);\n invalidate_size();\n }\n virtual String markup_text () const { return cached_client_ ? cached_client_->markup_text() : \"\"; }\n virtual void markup_text (const String &markup) { Client *client = get_client(); if (client) client->markup_text (markup); }\n virtual String plain_text () const { return cached_client_ ? cached_client_->plain_text() : \"\"; }\n virtual void plain_text (const String &ptext) { Client *client = get_client(); if (client) client->plain_text (ptext); }\n virtual uint request_chars () const { return request_chars_; }\n virtual void request_chars (uint nc) { request_chars_ = nc; invalidate_size(); }\n virtual uint request_digits () const { return request_digits_; }\n virtual void request_digits (uint nd) { request_digits_ = nd; invalidate_size(); }\n};\nstatic const WidgetFactory editor_factory (\"Rapicorn::Factory::Text::Editor\");\n\n\n} \/\/ Text\n} \/\/ Rapicorn\nUI: provide current text selection as text\/plain\/\/ Licensed GNU LGPL v3 or later: http:\/\/www.gnu.org\/licenses\/lgpl.html\n#include \"text-editor.hh\"\n#include \"factory.hh\"\n#include \"container.hh\"\n#include \"window.hh\" \/\/ FIXME: unneeded\n\nnamespace Rapicorn {\nnamespace Text {\nusing namespace Rapicorn;\n\ntypedef enum {\n NEXT_CHAR,\n PREV_CHAR,\n WARP_HOME,\n WARP_END,\n} CursorMovement;\n\nParaState::ParaState() :\n align (ALIGN_LEFT), ellipsize (ELLIPSIZE_END),\n line_spacing (1), indent (0),\n font_family (\"Sans\"), font_size (12)\n{}\n\nAttrState::AttrState() :\n font_family (\"\"), font_scale (1.0),\n bold (false), italic (false), underline (false),\n small_caps (false), strike_through (false),\n foreground (0), background (0)\n{}\n\nEditor::Client::~Client ()\n{}\n\nString\nEditor::Client::markup_text () const\n{\n return save_markup();\n}\n\nvoid\nEditor::Client::markup_text (const String &markup)\n{\n load_markup (markup);\n}\n\nstatic String\nescape_xml (const String &input)\n{\n String d;\n for (String::const_iterator it = input.begin(); it != input.end(); it++)\n switch (*it)\n {\n case '\"': d += \""\"; break;\n case '&': d += \"&\"; break;\n case '\\'': d += \"'\"; break;\n case '<': d += \"<\"; break;\n case '>': d += \">\"; break;\n default: d += *it; break;\n }\n return d;\n}\n\n\nvoid\nEditor::Client::plain_text (const String &markup)\n{\n load_markup (escape_xml (markup));\n}\n\nString\nEditor::Client::plain_text () const\n{\n int byte_length = 0;\n const char *t = const_cast (this)->peek_text (&byte_length);\n return String (t, byte_length);\n}\n\nconst PropertyList&\nEditor::Client::client_property_list()\n{\n static Property *properties[] = {\n MakeProperty (Client, markup_text, _(\"Markup Text\"), _(\"The text to display, containing font and style markup.\"), \"rw\"),\n MakeProperty (Client, plain_text, _(\"Plain Text\"), _(\"The text to display, without markup information.\"), \"rw\"),\n MakeProperty (Client, text_mode, _(\"Text Mode\"), _(\"The basic text layout mechanism to use.\"), \"rw\"),\n };\n static const PropertyList property_list (properties);\n return property_list;\n}\n\n\nconst PropertyList&\nEditor::__aida_properties__()\n{\n static Property *properties[] = {\n MakeProperty (Editor, text_mode, _(\"Text Mode\"), _(\"The basic text layout mechanism to use.\"), \"rw\"),\n MakeProperty (Editor, markup_text, _(\"Markup Text\"), _(\"The text to display, containing font and style markup.\"), \"rw\"),\n MakeProperty (Editor, plain_text, _(\"Plain Text\"), _(\"The text to display, without markup information.\"), \"rw\"),\n MakeProperty (Editor, request_chars, _(\"Request Chars\"), _(\"Number of characters to request space for.\"), 0, INT_MAX, 2, \"rw\"),\n MakeProperty (Editor, request_digits, _(\"Request Digits\"), _(\"Number of digits to request space for.\"), 0, INT_MAX, 2, \"rw\"),\n };\n static const PropertyList property_list (properties, ContainerImpl::__aida_properties__());\n return property_list;\n}\n\nclass EditorImpl : public virtual SingleContainerImpl, public virtual Editor, public virtual EventHandler {\n uint request_chars_, request_digits_;\n int cursor_;\n TextMode text_mode_;\n Client *cached_client_;\n size_t client_sig_;\npublic:\n EditorImpl() :\n request_chars_ (0), request_digits_ (0),\n cursor_ (0), text_mode_ (TEXT_MODE_SINGLE_LINE), cached_client_ (NULL), client_sig_ (0)\n {}\nprivate:\n ~EditorImpl()\n {\n if (cached_client_)\n {\n cached_client_->sig_selection_changed() -= client_sig_;\n client_sig_ = 0;\n ReferenceCountable *trash = dynamic_cast (cached_client_);\n cached_client_ = NULL;\n if (trash)\n unref (trash);\n }\n }\n Client*\n get_client()\n {\n \/\/ check if text client changed\n Client *candidate = interface();\n if (cached_client_ == candidate)\n return cached_client_;\n \/\/ adjust to new client\n Client *const old = cached_client_;\n const size_t old_sig = client_sig_;\n ReferenceCountable *base = dynamic_cast (candidate);\n cached_client_ = base ? candidate : NULL;\n if (base)\n {\n ref (base);\n client_sig_ = cached_client_->sig_selection_changed() += Aida::slot (this, &EditorImpl::selection_changed);\n }\n else\n client_sig_ = 0;\n \/\/ cleanup old\n base = dynamic_cast (old);\n if (base)\n {\n old->sig_selection_changed() -= old_sig;\n unref (base);\n }\n \/\/ update new client\n if (cached_client_)\n update_client();\n return cached_client_;\n }\n void\n update_client ()\n {\n Client *client = get_client();\n return_unless (client);\n client->text_mode (text_mode_);\n client->cursor2mark();\n cursor_ = client->mark();\n selection_changed();\n }\n virtual void\n size_request (Requisition &requisition)\n {\n update_client();\n SingleContainerImpl::size_request (requisition);\n uint fallback_chars = 0, fallback_digits = 0;\n if (text_mode_ == TEXT_MODE_SINGLE_LINE)\n {\n requisition.width = 0;\n if (request_chars_ <= 0 && request_digits_ <= 0)\n {\n fallback_chars = 26;\n fallback_digits = 10;\n }\n }\n Client *client = get_client();\n if (client)\n requisition.width += client->text_requisition (fallback_chars + request_chars_, fallback_digits + request_digits_);\n }\n virtual bool\n can_focus () const\n {\n Client *client = cached_client_;\n return client != NULL;\n }\n virtual void\n reset (ResetMode mode = RESET_ALL)\n {}\n virtual bool\n handle_event (const Event &event)\n {\n bool handled = false, ignore = false;\n switch (event.type)\n {\n Client *client;\n bool rs;\n const EventKey *kevent;\n const EventData *devent;\n const EventButton *bevent;\n case KEY_PRESS:\n kevent = dynamic_cast (&event);\n rs = (kevent->key_state & MOD_SHIFT) == 0; \/\/ reset selection\n switch (kevent->key)\n {\n case 'a':\n if (kevent->key_state & MOD_CONTROL)\n {\n select_all();\n handled = true;\n break;\n }\n goto _default;\n case 'v':\n if (kevent->key_state & MOD_CONTROL)\n {\n get_window()->request_clipboard (77, \"text\/plain\"); \/\/ FIXME: should operate on viewport\n handled = true;\n break;\n }\n goto _default;\n case KEY_Home: case KEY_KP_Home: handled = move_cursor (WARP_HOME, rs); break;\n case KEY_End: case KEY_KP_End: handled = move_cursor (WARP_END, rs); break;\n case KEY_Right: case KEY_KP_Right: handled = move_cursor (NEXT_CHAR, rs); break; \/\/ FIXME: CTRL moves words\n case KEY_Left: case KEY_KP_Left: handled = move_cursor (PREV_CHAR, rs); break; \/\/ FIXME: CTRL moves words\n case KEY_BackSpace: handled = delete_backward(); break;\n case KEY_Delete: case KEY_KP_Delete: handled = delete_foreward(); break;\n default: _default:\n if (kevent->key_state & MOD_CONTROL && \/\/ preserve Ctrl + FocusKey for navigation\n key_value_is_focus_dir (kevent->key))\n {\n handled = false;\n ignore = true;\n }\n else\n handled = insert_literally (kevent->utf8input);\n break;\n }\n if (!handled && !ignore && !key_value_is_modifier (kevent->key))\n {\n notify_key_error();\n handled = true;\n }\n break;\n case KEY_CANCELED:\n case KEY_RELEASE:\n break;\n case CONTENT_DATA:\n devent = dynamic_cast (&event);\n if (devent->nonce == 77 && devent->data_type == \"text\/plain\")\n {\n handled = insert_literally (devent->data);\n }\n break;\n case CONTENT_REQUEST:\n devent = dynamic_cast (&event);\n client = get_client();\n if (client && devent->data_type == \"text\/plain\")\n {\n int start, end;\n const bool has_selection = client->get_selection (&start, &end);\n if (has_selection && start >= 0 && end > start)\n {\n String text = client->plain_text();\n if (size_t (end) <= text.size())\n {\n text = text.substr (start, end - start);\n if (utf8_validate (text))\n get_window()->provide_selection (devent->nonce, \"text\/plain\", text);\n }\n }\n }\n break;\n case BUTTON_PRESS:\n bevent = dynamic_cast (&event);\n client = get_client();\n grab_focus();\n if (client && bevent->button == 1)\n {\n int o = client->mark();\n bool moved = client->mark_to_coord (bevent->x, bevent->y);\n int m = client->mark();\n if (o != m)\n {\n cursor_ = m;\n client->mark2cursor();\n changed();\n }\n (void) moved;\n }\n else if (bevent->button == 2)\n {\n get_window()->request_selection (77, \"text\/plain\"); \/\/ FIXME: should operate on viewport\n }\n handled = true;\n break;\n default: ;\n }\n return handled;\n }\n int\n cursor () const\n {\n return cursor_;\n }\n bool\n move_cursor (CursorMovement cm, const bool reset_selection)\n {\n const bool adjust_selection = !reset_selection;\n Client *client = get_client();\n return_unless (client, false);\n int start, end;\n const bool has_selection = client->get_selection (&start, &end);\n \/\/ special case, cursor left\/right deselects\n if (has_selection && reset_selection && (cm == PREV_CHAR || cm == NEXT_CHAR))\n {\n client->mark (cm == PREV_CHAR ? start : end);\n client->hide_selector();\n client->mark2cursor();\n cursor_ = client->mark();\n changed();\n return true;\n }\n client->mark (cursor_);\n if (!has_selection && adjust_selection)\n client->mark2selector(); \/\/ old cursor starts selection\n int o = client->mark();\n switch (cm)\n {\n case NEXT_CHAR: client->step_mark (+1); break;\n case PREV_CHAR: client->step_mark (-1); break;\n case WARP_HOME: client->mark (0); break;\n case WARP_END: client->mark (-1); break;\n }\n int m = client->mark();\n if (o == m)\n return false;\n if (reset_selection && has_selection)\n client->hide_selector();\n cursor_ = m;\n client->mark2cursor();\n changed();\n return true;\n }\n bool\n insert_literally (const String &utf8text)\n {\n if (utf8text.size() == 1 &&\n (utf8text[0] == '\\b' || \/\/ Backspace\n utf8text[0] == '\\n' || \/\/ Newline\n utf8text[0] == '\\r' || \/\/ Carriage Return\n utf8text[0] == 0x7f || \/\/ Delete\n 0))\n return false; \/\/ ignore literal inputs from \"control\" keys\n Client *client = get_client();\n if (client && !utf8text.empty())\n {\n delete_selection();\n client->mark (cursor_);\n client->mark_insert (utf8text);\n cursor_ = client->mark();\n client->mark2cursor();\n changed();\n return true;\n }\n return false;\n }\n bool\n select_all()\n {\n Client *client = get_client();\n return_unless (client, false);\n client->mark (0);\n client->mark2selector();\n client->mark (-1);\n cursor_ = client->mark();\n client->mark2cursor();\n changed();\n return client->get_selection();\n }\n bool\n delete_selection()\n {\n Client *client = get_client();\n return_unless (client, false);\n int start, end, nutf8;\n const bool has_selection = client->get_selection (&start, &end, &nutf8);\n if (!has_selection)\n return false;\n client->mark (start);\n client->mark_delete (nutf8);\n client->hide_selector();\n cursor_ = client->mark();\n client->mark2cursor();\n changed();\n return true;\n }\n bool\n delete_backward ()\n {\n if (delete_selection())\n return true;\n Client *client = get_client();\n if (client)\n {\n client->mark (cursor_);\n int o = client->mark();\n client->step_mark (-1);\n int m = client->mark();\n if (o == m)\n return false;\n cursor_ = m;\n client->mark2cursor();\n client->mark_delete (1);\n changed();\n return true;\n }\n return false;\n }\n bool\n delete_foreward ()\n {\n Client *client = get_client();\n return_unless (client, false);\n if (delete_selection())\n return true;\n client->mark (cursor_);\n if (client->mark_at_end())\n return false;\n client->mark_delete (1);\n changed();\n return true;\n }\n void\n selection_changed()\n {\n Client *client = get_client();\n int start, end, nutf8;\n const bool has_selection = client->get_selection (&start, &end, &nutf8);\n if (!has_selection || nutf8 < 1)\n get_window()->claim_selection (StringVector()); \/\/ give up ownership\n else\n get_window()->claim_selection (cstrings_to_vector (\"text\/plain\", NULL)); \/\/ claim new selection\n }\n virtual void\n text (const String &text)\n {\n Client *client = get_client();\n if (client)\n client->markup_text (text);\n }\n virtual String\n text () const\n {\n return cached_client_ ? cached_client_->markup_text() : \"\";\n }\n virtual TextMode text_mode () const { return text_mode_; }\n virtual void text_mode (TextMode text_mode)\n {\n text_mode_ = text_mode;\n Client *client = get_client();\n if (client)\n client->text_mode (text_mode_);\n invalidate_size();\n }\n virtual String markup_text () const { return cached_client_ ? cached_client_->markup_text() : \"\"; }\n virtual void markup_text (const String &markup) { Client *client = get_client(); if (client) client->markup_text (markup); }\n virtual String plain_text () const { return cached_client_ ? cached_client_->plain_text() : \"\"; }\n virtual void plain_text (const String &ptext) { Client *client = get_client(); if (client) client->plain_text (ptext); }\n virtual uint request_chars () const { return request_chars_; }\n virtual void request_chars (uint nc) { request_chars_ = nc; invalidate_size(); }\n virtual uint request_digits () const { return request_digits_; }\n virtual void request_digits (uint nd) { request_digits_ = nd; invalidate_size(); }\n};\nstatic const WidgetFactory editor_factory (\"Rapicorn::Factory::Text::Editor\");\n\n\n} \/\/ Text\n} \/\/ Rapicorn\n<|endoftext|>"} {"text":"Fixed<|endoftext|>"} {"text":"\/******************************************************************************\n * ____ _ _____ *\n * \/ ___| \/ \\ | ___| C++ *\n * | | \/ _ \\ | |_ Actor *\n * | |___ \/ ___ \\| _| Framework *\n * \\____\/_\/ \\_|_| *\n * *\n * Copyright (C) 2011 - 2015 *\n * Dominik Charousset *\n * *\n * Distributed under the terms and conditions of the BSD 3-Clause License or *\n * (at your option) under the terms and conditions of the Boost Software *\n * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *\n * *\n * If you did not receive a copy of the license files, see *\n * http:\/\/opensource.org\/licenses\/BSD-3-Clause and *\n * http:\/\/www.boost.org\/LICENSE_1_0.txt. *\n ******************************************************************************\/\n\n#define CAF_SUITE broker\n#include \"caf\/test\/unit_test.hpp\"\n\n#include \n#include \n\n#include \"caf\/all.hpp\"\n#include \"caf\/io\/all.hpp\"\n\n#include \"caf\/string_algorithms.hpp\"\n\n#include \"caf\/detail\/run_program.hpp\"\n\nusing namespace std;\nusing namespace caf;\nusing namespace caf::io;\n\nusing ping_atom = caf::atom_constant;\nusing pong_atom = caf::atom_constant;\nusing publish_atom = caf::atom_constant;\nusing kickoff_atom = caf::atom_constant;\n\nnamespace {\n\nvoid ping(event_based_actor* self, size_t num_pings) {\n CAF_MESSAGE(\"num_pings: \" << num_pings);\n auto count = std::make_shared(0);\n self->become(\n [=](kickoff_atom, const actor& pong) {\n CAF_MESSAGE(\"received `kickoff_atom`\");\n self->send(pong, ping_atom::value, 1);\n self->become(\n [=](pong_atom, int value)->std::tuple {\n if (++*count >= num_pings) {\n CAF_MESSAGE(\"received \" << num_pings\n << \" pings, call self->quit\");\n self->quit();\n }\n return std::make_tuple(ping_atom::value, value + 1);\n },\n others >> [&] {\n CAF_TEST_ERROR(\"Unexpected message: \"\n << to_string(self->current_message()));\n });\n },\n others >> [&] {\n CAF_TEST_ERROR(\"Unexpected message: \"\n << to_string(self->current_message()));\n }\n );\n}\n\nvoid pong(event_based_actor* self) {\n CAF_MESSAGE(\"pong actor started\");\n self->become(\n [=](ping_atom, int value) -> std::tuple {\n CAF_MESSAGE(\"received `ping_atom`\");\n self->monitor(self->current_sender());\n \/\/ set next behavior\n self->become(\n [](ping_atom, int val) {\n return std::make_tuple(pong_atom::value, val);\n },\n [=](const down_msg& dm) {\n CAF_MESSAGE(\"received down_msg{\" << dm.reason << \"}\");\n self->quit(dm.reason);\n },\n others >> [&] {\n CAF_TEST_ERROR(\"Unexpected message: \"\n << to_string(self->current_message()));\n }\n );\n \/\/ reply to 'ping'\n return std::make_tuple(pong_atom::value, value);\n },\n others >> [&] {\n CAF_TEST_ERROR(\"Unexpected message: \"\n << to_string(self->current_message()));\n }\n );\n}\n\n}\n\nvoid peer_fun(broker* self, connection_handle hdl, const actor& buddy) {\n CAF_MESSAGE(\"peer_fun called\");\n CAF_CHECK(self != nullptr);\n CAF_CHECK(buddy != invalid_actor);\n self->monitor(buddy);\n \/\/ assume exactly one connection\n auto cons = self->connections();\n if (cons.size() != 1) {\n cerr << \"expected 1 connection, found \" << cons.size() << endl;\n throw std::logic_error(\"num_connections() != 1\");\n }\n self->configure_read(\n hdl, receive_policy::exactly(sizeof(atom_value) + sizeof(int)));\n auto write = [=](atom_value type, int value) {\n auto& buf = self->wr_buf(hdl);\n auto first = reinterpret_cast(&type);\n buf.insert(buf.end(), first, first + sizeof(atom_value));\n first = reinterpret_cast(&value);\n buf.insert(buf.end(), first, first + sizeof(int));\n self->flush(hdl);\n\n };\n self->become(\n [=](const connection_closed_msg&) {\n CAF_MESSAGE(\"received connection_closed_msg\");\n self->quit();\n },\n [=](const new_data_msg& msg) {\n CAF_MESSAGE(\"received new_data_msg\");\n atom_value type;\n int value;\n memcpy(&type, msg.buf.data(), sizeof(atom_value));\n memcpy(&value, msg.buf.data() + sizeof(atom_value), sizeof(int));\n self->send(buddy, type, value);\n },\n [=](ping_atom, int value) {\n CAF_MESSAGE(\"received ping{\" << value << \"}\");\n write(ping_atom::value, value);\n },\n [=](pong_atom, int value) {\n CAF_MESSAGE(\"received pong{\" << value << \"}\");\n write(pong_atom::value, value);\n },\n [=](const down_msg& dm) {\n CAF_MESSAGE(\"received down_msg\");\n if (dm.source == buddy) {\n self->quit(dm.reason);\n }\n },\n others >> [&] {\n CAF_TEST_ERROR(\"Unexpected message: \"\n << to_string(self->current_message()));\n }\n );\n}\n\nbehavior peer_acceptor_fun(broker* self, const actor& buddy) {\n CAF_MESSAGE(\"peer_acceptor_fun\");\n return {\n [=](const new_connection_msg& msg) {\n CAF_MESSAGE(\"received `new_connection_msg`\");\n self->fork(peer_fun, msg.handle, buddy);\n self->quit();\n },\n [=](publish_atom) {\n return self->add_tcp_doorman(0, \"127.0.0.1\").second;\n },\n others >> [&] {\n CAF_TEST_ERROR(\"Unexpected message: \"\n << to_string(self->current_message()));\n }\n };\n}\n\nnamespace {\n\nvoid run_server(bool spawn_client, const char* bin_path) {\n scoped_actor self;\n auto serv = io::spawn_io(peer_acceptor_fun, spawn(pong));\n self->sync_send(serv, publish_atom::value).await(\n [&](uint16_t port) {\n CAF_MESSAGE(\"server is running on port \" << port);\n if (spawn_client) {\n auto child = detail::run_program(self, bin_path, \"-n\", \"-s\", \"broker\",\n \"--\", \"-c\", port);\n CAF_MESSAGE(\"block till child process has finished\");\n child.join();\n }\n }\n );\n self->await_all_other_actors_done();\n self->receive(\n [](const std::string& output) {\n cout << endl << endl << \"*** output of client program ***\"\n << endl << output << endl;\n }\n );\n}\n\n}\n\nCAF_TEST(test_broker) {\n auto argv = caf::test::engine::argv();\n auto argc = caf::test::engine::argc();\n if (argv) {\n uint16_t port = 0;\n auto r = message_builder(argv, argv + argc).extract_opts({\n {\"client-port,c\", \"set port for IO client\", port},\n {\"server,s\", \"run in server mode\"}\n });\n if (! r.error.empty() || r.opts.count(\"help\") > 0 || ! r.remainder.empty()) {\n cout << r.error << endl << endl << r.helptext << endl;\n return;\n }\n if (r.opts.count(\"client-port\") > 0) {\n auto p = spawn(ping, 10);\n CAF_MESSAGE(\"spawn_io_client...\");\n auto cl = spawn_io_client(peer_fun, \"localhost\", port, p);\n CAF_MESSAGE(\"spawn_io_client finished\");\n anon_send(p, kickoff_atom::value, cl);\n CAF_MESSAGE(\"`kickoff_atom` has been send\");\n } else {\n \/\/ run in server mode\n run_server(false, argv[0]);\n }\n } else {\n run_server(true, caf::test::engine::path());\n }\n CAF_MESSAGE(\"block on `await_all_actors_done`\");\n await_all_actors_done();\n CAF_MESSAGE(\"`await_all_actors_done` has finished\");\n shutdown();\n}\nFix lambda captures in broker unit test\/******************************************************************************\n * ____ _ _____ *\n * \/ ___| \/ \\ | ___| C++ *\n * | | \/ _ \\ | |_ Actor *\n * | |___ \/ ___ \\| _| Framework *\n * \\____\/_\/ \\_|_| *\n * *\n * Copyright (C) 2011 - 2015 *\n * Dominik Charousset *\n * *\n * Distributed under the terms and conditions of the BSD 3-Clause License or *\n * (at your option) under the terms and conditions of the Boost Software *\n * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *\n * *\n * If you did not receive a copy of the license files, see *\n * http:\/\/opensource.org\/licenses\/BSD-3-Clause and *\n * http:\/\/www.boost.org\/LICENSE_1_0.txt. *\n ******************************************************************************\/\n\n#define CAF_SUITE broker\n#include \"caf\/test\/unit_test.hpp\"\n\n#include \n#include \n\n#include \"caf\/all.hpp\"\n#include \"caf\/io\/all.hpp\"\n\n#include \"caf\/string_algorithms.hpp\"\n\n#include \"caf\/detail\/run_program.hpp\"\n\nusing namespace std;\nusing namespace caf;\nusing namespace caf::io;\n\nnamespace {\n\nusing ping_atom = caf::atom_constant;\nusing pong_atom = caf::atom_constant;\nusing publish_atom = caf::atom_constant;\nusing kickoff_atom = caf::atom_constant;\n\nvoid ping(event_based_actor* self, size_t num_pings) {\n CAF_MESSAGE(\"num_pings: \" << num_pings);\n auto count = std::make_shared(0);\n self->become(\n [=](kickoff_atom, const actor& pong) {\n CAF_MESSAGE(\"received `kickoff_atom`\");\n self->send(pong, ping_atom::value, 1);\n self->become(\n [=](pong_atom, int value)->std::tuple {\n if (++*count >= num_pings) {\n CAF_MESSAGE(\"received \" << num_pings\n << \" pings, call self->quit\");\n self->quit();\n }\n return std::make_tuple(ping_atom::value, value + 1);\n },\n others >> [=] {\n CAF_TEST_ERROR(\"Unexpected message: \"\n << to_string(self->current_message()));\n });\n },\n others >> [=] {\n CAF_TEST_ERROR(\"Unexpected message: \"\n << to_string(self->current_message()));\n }\n );\n}\n\nvoid pong(event_based_actor* self) {\n CAF_MESSAGE(\"pong actor started\");\n self->become(\n [=](ping_atom, int value) -> std::tuple {\n CAF_MESSAGE(\"received `ping_atom`\");\n self->monitor(self->current_sender());\n \/\/ set next behavior\n self->become(\n [](ping_atom, int val) {\n return std::make_tuple(pong_atom::value, val);\n },\n [=](const down_msg& dm) {\n CAF_MESSAGE(\"received down_msg{\" << dm.reason << \"}\");\n self->quit(dm.reason);\n },\n others >> [=] {\n CAF_TEST_ERROR(\"Unexpected message: \"\n << to_string(self->current_message()));\n }\n );\n \/\/ reply to 'ping'\n return std::make_tuple(pong_atom::value, value);\n },\n others >> [=] {\n CAF_TEST_ERROR(\"Unexpected message: \"\n << to_string(self->current_message()));\n }\n );\n}\n\nvoid peer_fun(broker* self, connection_handle hdl, const actor& buddy) {\n CAF_MESSAGE(\"peer_fun called\");\n CAF_CHECK(self != nullptr);\n CAF_CHECK(buddy != invalid_actor);\n self->monitor(buddy);\n \/\/ assume exactly one connection\n auto cons = self->connections();\n if (cons.size() != 1) {\n cerr << \"expected 1 connection, found \" << cons.size() << endl;\n throw std::logic_error(\"num_connections() != 1\");\n }\n self->configure_read(\n hdl, receive_policy::exactly(sizeof(atom_value) + sizeof(int)));\n auto write = [=](atom_value type, int value) {\n auto& buf = self->wr_buf(hdl);\n auto first = reinterpret_cast(&type);\n buf.insert(buf.end(), first, first + sizeof(atom_value));\n first = reinterpret_cast(&value);\n buf.insert(buf.end(), first, first + sizeof(int));\n self->flush(hdl);\n\n };\n self->become(\n [=](const connection_closed_msg&) {\n CAF_MESSAGE(\"received connection_closed_msg\");\n self->quit();\n },\n [=](const new_data_msg& msg) {\n CAF_MESSAGE(\"received new_data_msg\");\n atom_value type;\n int value;\n memcpy(&type, msg.buf.data(), sizeof(atom_value));\n memcpy(&value, msg.buf.data() + sizeof(atom_value), sizeof(int));\n self->send(buddy, type, value);\n },\n [=](ping_atom, int value) {\n CAF_MESSAGE(\"received ping{\" << value << \"}\");\n write(ping_atom::value, value);\n },\n [=](pong_atom, int value) {\n CAF_MESSAGE(\"received pong{\" << value << \"}\");\n write(pong_atom::value, value);\n },\n [=](const down_msg& dm) {\n CAF_MESSAGE(\"received down_msg\");\n if (dm.source == buddy) {\n self->quit(dm.reason);\n }\n },\n others >> [=] {\n CAF_TEST_ERROR(\"Unexpected message: \"\n << to_string(self->current_message()));\n }\n );\n}\n\nbehavior peer_acceptor_fun(broker* self, const actor& buddy) {\n CAF_MESSAGE(\"peer_acceptor_fun\");\n return {\n [=](const new_connection_msg& msg) {\n CAF_MESSAGE(\"received `new_connection_msg`\");\n self->fork(peer_fun, msg.handle, buddy);\n self->quit();\n },\n [=](publish_atom) {\n return self->add_tcp_doorman(0, \"127.0.0.1\").second;\n },\n others >> [&] {\n CAF_TEST_ERROR(\"Unexpected message: \"\n << to_string(self->current_message()));\n }\n };\n}\n\nvoid run_server(bool spawn_client, const char* bin_path) {\n scoped_actor self;\n auto serv = io::spawn_io(peer_acceptor_fun, spawn(pong));\n self->sync_send(serv, publish_atom::value).await(\n [&](uint16_t port) {\n CAF_MESSAGE(\"server is running on port \" << port);\n if (spawn_client) {\n auto child = detail::run_program(self, bin_path, \"-n\", \"-s\", \"broker\",\n \"--\", \"-c\", port);\n CAF_MESSAGE(\"block till child process has finished\");\n child.join();\n }\n }\n );\n self->await_all_other_actors_done();\n self->receive(\n [](const std::string& output) {\n cout << endl << endl << \"*** output of client program ***\"\n << endl << output << endl;\n }\n );\n}\n\n} \/\/ namespace \n\nCAF_TEST(test_broker) {\n auto argv = caf::test::engine::argv();\n auto argc = caf::test::engine::argc();\n if (argv) {\n uint16_t port = 0;\n auto r = message_builder(argv, argv + argc).extract_opts({\n {\"client-port,c\", \"set port for IO client\", port},\n {\"server,s\", \"run in server mode\"}\n });\n if (! r.error.empty() || r.opts.count(\"help\") > 0 || ! r.remainder.empty()) {\n cout << r.error << endl << endl << r.helptext << endl;\n return;\n }\n if (r.opts.count(\"client-port\") > 0) {\n auto p = spawn(ping, 10);\n CAF_MESSAGE(\"spawn_io_client...\");\n auto cl = spawn_io_client(peer_fun, \"localhost\", port, p);\n CAF_MESSAGE(\"spawn_io_client finished\");\n anon_send(p, kickoff_atom::value, cl);\n CAF_MESSAGE(\"`kickoff_atom` has been send\");\n } else {\n \/\/ run in server mode\n run_server(false, argv[0]);\n }\n } else {\n run_server(true, caf::test::engine::path());\n }\n CAF_MESSAGE(\"block on `await_all_actors_done`\");\n await_all_actors_done();\n CAF_MESSAGE(\"`await_all_actors_done` has finished\");\n shutdown();\n}\n<|endoftext|>"} {"text":"helloword<|endoftext|>"} {"text":"Re-organize functions in UIRoot<|endoftext|>"} {"text":"\/*=========================================================================\n \n Program: Visualization Toolkit\n Module: vtkVertexBufferObject.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \n\n#include \"vtkCellArray.h\"\n#include \"vtkDataArray.h\"\n#include \"vtkObject.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkOpenGLExtensionManager.h\"\n#include \"vtkOpenGLRenderWindow.h\"\n#include \"vtkPoints.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkUnsignedCharArray.h\"\n\n#include \"vtkgl.h\" \/\/ Needed for gl data types exposed in API\n#include \"vtkOpenGL.h\"\n\n\/\/#define VTK_PBO_DEBUG\n\/\/#define VTK_PBO_TIMING\n\n#ifdef VTK_PBO_TIMING\n#include \"vtkTimerLog.h\"\n#endif\n\n\/\/ Mapping from Usage values to OpenGL values.\n\nGLenum OpenGLVertexBufferObjectUsage[9]=\n{\n vtkgl::STREAM_DRAW,\n vtkgl::STREAM_READ,\n vtkgl::STREAM_COPY,\n vtkgl::STATIC_DRAW,\n vtkgl::STATIC_READ,\n vtkgl::STATIC_COPY,\n vtkgl::DYNAMIC_DRAW,\n vtkgl::DYNAMIC_READ,\n vtkgl::DYNAMIC_COPY\n};\n\nconst char *VertexBufferObjectUsageAsString[9]=\n{\n \"StreamDraw\",\n \"StreamRead\",\n \"StreamCopy\",\n \"StaticDraw\",\n \"StaticRead\",\n \"StaticCopy\",\n \"DynamicDraw\",\n \"DynamicRead\",\n \"DynamicCopy\"\n};\n\n#ifdef VTK_PBO_DEBUG\n#include \/\/ for debugging with MPI, pthread_self()\n#endif\n\nvtkStandardNewMacro(vtkVertexBufferObject);\n\/\/----------------------------------------------------------------------------\nvtkVertexBufferObject::vtkVertexBufferObject()\n{\n this->Handle = 0;\n this->Context = 0;\n this->BufferTarget = 0;\n this->Size=0;\n this->Count=0;\n\/\/ this->Type=VTK_UNSIGNED_CHAR;\n this->Usage=StaticDraw;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkVertexBufferObject::~vtkVertexBufferObject()\n{\n this->SetContext(0);\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Description:\n\/\/ Returns if the context supports the required extensions.\nbool vtkVertexBufferObject::IsSupported(vtkRenderWindow* win)\n{\n vtkOpenGLRenderWindow* renWin = vtkOpenGLRenderWindow::SafeDownCast(win);\n if (renWin)\n {\n vtkOpenGLExtensionManager* mgr = renWin->GetExtensionManager();\n \n bool vbo=mgr->ExtensionSupported(\"GL_VERSION_1_5\") ||\n mgr->ExtensionSupported(\"GL_ARB_vertex_buffer_object\");\n \n return vbo;\n }\n return false;\n}\n\n\/\/----------------------------------------------------------------------------\nbool vtkVertexBufferObject::LoadRequiredExtensions(\n vtkOpenGLExtensionManager* mgr)\n{\n bool gl15 = mgr->ExtensionSupported(\"GL_VERSION_1_5\")==1;\n\n bool vbo = gl15 || mgr->ExtensionSupported(\"GL_ARB_vertex_buffer_object\");\n \n if(vbo)\n {\n if(gl15)\n {\n mgr->LoadExtension(\"GL_VERSION_1_5\");\n }\n else\n {\n mgr->LoadCorePromotedExtension(\"GL_ARB_vertex_buffer_object\");\n }\n }\n return vbo;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkVertexBufferObject::SetContext(vtkRenderWindow* renWin)\n{\n if (this->Context == renWin)\n {\n return;\n }\n \n this->DestroyBuffer(); \n \n vtkOpenGLRenderWindow* openGLRenWin =\n vtkOpenGLRenderWindow::SafeDownCast(renWin);\n this->Context = openGLRenWin;\n if (openGLRenWin)\n {\n if (!this->LoadRequiredExtensions(openGLRenWin->GetExtensionManager()))\n {\n this->Context = 0;\n vtkErrorMacro(\"Required OpenGL extensions not supported by the context.\");\n }\n }\n \n this->Modified();\n}\n\n\/\/----------------------------------------------------------------------------\nvtkRenderWindow* vtkVertexBufferObject::GetContext()\n{\n return this->Context;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkVertexBufferObject::Bind()\n{\n if (!this->Context)\n {\n vtkErrorMacro(\"No context specified. Cannot Bind.\");\n return;\n }\n \n this->CreateBuffer();\n \n vtkgl::BindBuffer(static_cast(this->BufferTarget), this->Handle);\n\n vtkGraphicErrorMacro(this->Context,\"after BindBuffer\");\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkVertexBufferObject::UnBind()\n{\n if (this->Context && this->Handle && this->BufferTarget)\n {\n vtkgl::BindBuffer(this->BufferTarget, 0);\n vtkGraphicErrorMacro(this->Context,\"after BindBuffer\");\n \/\/this->BufferTarget = 0;\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkVertexBufferObject::CreateBuffer()\n{\n this->Context->MakeCurrent();\n if (!this->Handle)\n {\n cout << \"Creating Buffer...\" << endl;\n GLuint ioBuf;\n vtkgl::GenBuffers(1, &ioBuf);\n vtkGraphicErrorMacro(this->Context, \"after GenBuffers\");\n this->Handle = ioBuf;\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkVertexBufferObject::DestroyBuffer()\n{\n if (this->Context && this->Handle)\n {\n GLuint ioBuf = static_cast(this->Handle);\n vtkgl::DeleteBuffers(1, &ioBuf);\n }\n this->Handle = 0;\n}\n\n\/\/----------------------------------------------------------------------------\nbool vtkVertexBufferObject::SetData(vtkPoints *points)\n{\n std::cout << \"Setting Points\" << endl;\n this->Count = points->GetNumberOfPoints();\n this->Size = this->Count * 3 * sizeof(float);\n this->BufferTarget = vtkgl::ARRAY_BUFFER;\n\n return this->SetData(points->GetVoidPointer(0));\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/bool vtkVertexBufferObject::SetData(vtkCellArray *verts)\n\/\/{\n\/\/ \/\/ The correct way to do this is to use each cells vtkIdTypes, but this\n\/\/ \/\/ returns a tuple (1, index) which I don't have time to understand right\n\/\/ \/\/ now\n\/\/ \/\/vtkIdType *oldarray = input->GetVerts()->GetPointer();\n\/\/ \/\/int *newarray = new int[numPoints];\n\/\/ \/\/std::copy(oldarray, oldarray + numPoints, newarray);\n\/\/ \/\/for (size_t i=0; i < numPoints*2; i+=2)\n\/\/ \/\/ std::cout << \"really\" << oldarray[i] << endl;\n\/\/\n\/\/ this->Size = points->GetNumberOfPoints() * sizeof(unsigned int);\n\/\/ this->BufferTarget = vtkgl::ELEMENT_ARRAY_BUFFER;\n\/\/\n\/\/ \/\/ For now, display every indice\n\/\/ unsigned int *indices = new unsigned int[numPoints];\n\/\/ for (size_t i=0; i < numPoints; i++){\n\/\/ indices[i] = i;\n\/\/ }\n\/\/\n\/\/ this->SetData((void *)indices);\n\/\/}\n\n\/\/----------------------------------------------------------------------------\nbool vtkVertexBufferObject::SetData(std::vector *indices)\n{\n std::cout << \"Setting Indices\" << endl;\n this->Count = indices->size();\n this->Size = this->Count * sizeof(unsigned int);\n this->BufferTarget = vtkgl::ELEMENT_ARRAY_BUFFER;\n\n return this->SetData(reinterpret_cast(indices->data()));\n}\n\n\/\/----------------------------------------------------------------------------\nbool vtkVertexBufferObject::SetData(vtkDataArray *colors)\n{\n std::cout << \"Setting Colors\" << endl;\n \/\/this->Count = colors->GetNumberOfTuples();\n this->Count = colors->GetSize();\n std::cout << \"Type: \" << colors->GetDataTypeAsString() <Size = this->Count * 1 * sizeof(float);\n this->BufferTarget = vtkgl::ARRAY_BUFFER;\n std::cout << \"Setting Data\" << endl;\n\n return this->SetData(reinterpret_cast(colors->GetVoidPointer(0)));\n}\n\n\/\/----------------------------------------------------------------------------\nbool vtkVertexBufferObject::SetData(vtkUnsignedCharArray *colors)\n{\n std::cout << \"Setting Colors\" << endl;\n std::cout << \"Colors == NULL: \" << (colors == NULL) << endl;\n this->Count = colors->GetSize();\n std::cout << \"Type: \" << colors->GetDataTypeAsString() <Size = this->Count * 1 * sizeof(float);\n this->BufferTarget = vtkgl::ARRAY_BUFFER;\n\n std::cout << \"Setting Data\" << endl;\n return this->SetData(reinterpret_cast(colors->GetPointer(0)));\n}\n\n\/\/----------------------------------------------------------------------------\nbool vtkVertexBufferObject::SetData(GLvoid* data)\n{\n if (!this->Context)\n {\n vtkErrorMacro(\"No context specified. Cannot upload data.\");\n return false;\n }\n\n this->CreateBuffer();\n\n\/\/ cout << \" Context: \" << this->Context << endl;\n\/\/ cout << \" Handle: \" << this->Handle << endl;\n\/\/ cout << \" Size: \" << this->Size << endl;\n\/\/ cout << \" Count: \" << this->Count << endl;\n\/\/ cout << \" Usage: \" << VertexBufferObjectUsageAsString[this->Usage] << endl;\n\n GLenum usage = OpenGLVertexBufferObjectUsage[this->Usage];\n\n this->Bind();\n vtkgl::BufferData(this->BufferTarget, this->Size, data, usage);\n this->UnBind();\n\n cout << \"Buffer Created\" << endl;\n return true;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkVertexBufferObject::ReleaseMemory()\n{\n if (this->Context && this->Handle)\n {\n this->Bind();\n vtkgl::BufferData(this->BufferTarget, 0, NULL, OpenGLVertexBufferObjectUsage[this->Usage]);\n this->Size = 0;\n this->Count = 0;\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkVertexBufferObject::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os, indent);\n os << indent << \"Context: \" << this->Context << endl;\n os << indent << \"Handle: \" << this->Handle << endl;\n os << indent << \"Size: \" << this->Size << endl;\n os << indent << \"Count: \" << this->Count << endl;\n os << indent << \"Usage:\" << VertexBufferObjectUsageAsString[this->Usage] << endl;\n}\ncompilation under windows\/*=========================================================================\n \n Program: Visualization Toolkit\n Module: vtkVertexBufferObject.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \n\n#include \"vtkCellArray.h\"\n#include \"vtkDataArray.h\"\n#include \"vtkObject.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkOpenGLExtensionManager.h\"\n#include \"vtkOpenGLRenderWindow.h\"\n#include \"vtkPoints.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkUnsignedCharArray.h\"\n\n#include \"vtkgl.h\" \/\/ Needed for gl data types exposed in API\n#include \"vtkOpenGL.h\"\n\n\/\/#define VTK_PBO_DEBUG\n\/\/#define VTK_PBO_TIMING\n\n#ifdef VTK_PBO_TIMING\n#include \"vtkTimerLog.h\"\n#endif\n\n\/\/ Mapping from Usage values to OpenGL values.\n\nGLenum OpenGLVertexBufferObjectUsage[9]=\n{\n vtkgl::STREAM_DRAW,\n vtkgl::STREAM_READ,\n vtkgl::STREAM_COPY,\n vtkgl::STATIC_DRAW,\n vtkgl::STATIC_READ,\n vtkgl::STATIC_COPY,\n vtkgl::DYNAMIC_DRAW,\n vtkgl::DYNAMIC_READ,\n vtkgl::DYNAMIC_COPY\n};\n\nconst char *VertexBufferObjectUsageAsString[9]=\n{\n \"StreamDraw\",\n \"StreamRead\",\n \"StreamCopy\",\n \"StaticDraw\",\n \"StaticRead\",\n \"StaticCopy\",\n \"DynamicDraw\",\n \"DynamicRead\",\n \"DynamicCopy\"\n};\n\n#ifdef VTK_PBO_DEBUG\n#include \/\/ for debugging with MPI, pthread_self()\n#endif\n\nvtkStandardNewMacro(vtkVertexBufferObject);\n\/\/----------------------------------------------------------------------------\nvtkVertexBufferObject::vtkVertexBufferObject()\n{\n this->Handle = 0;\n this->Context = 0;\n this->BufferTarget = 0;\n this->Size=0;\n this->Count=0;\n\/\/ this->Type=VTK_UNSIGNED_CHAR;\n this->Usage=StaticDraw;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkVertexBufferObject::~vtkVertexBufferObject()\n{\n this->SetContext(0);\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Description:\n\/\/ Returns if the context supports the required extensions.\nbool vtkVertexBufferObject::IsSupported(vtkRenderWindow* win)\n{\n vtkOpenGLRenderWindow* renWin = vtkOpenGLRenderWindow::SafeDownCast(win);\n if (renWin)\n {\n vtkOpenGLExtensionManager* mgr = renWin->GetExtensionManager();\n \n bool vbo=mgr->ExtensionSupported(\"GL_VERSION_1_5\") ||\n mgr->ExtensionSupported(\"GL_ARB_vertex_buffer_object\");\n \n return vbo;\n }\n return false;\n}\n\n\/\/----------------------------------------------------------------------------\nbool vtkVertexBufferObject::LoadRequiredExtensions(\n vtkOpenGLExtensionManager* mgr)\n{\n bool gl15 = mgr->ExtensionSupported(\"GL_VERSION_1_5\")==1;\n\n bool vbo = gl15 || mgr->ExtensionSupported(\"GL_ARB_vertex_buffer_object\");\n \n if(vbo)\n {\n if(gl15)\n {\n mgr->LoadExtension(\"GL_VERSION_1_5\");\n }\n else\n {\n mgr->LoadCorePromotedExtension(\"GL_ARB_vertex_buffer_object\");\n }\n }\n return vbo;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkVertexBufferObject::SetContext(vtkRenderWindow* renWin)\n{\n if (this->Context == renWin)\n {\n return;\n }\n \n this->DestroyBuffer(); \n \n vtkOpenGLRenderWindow* openGLRenWin =\n vtkOpenGLRenderWindow::SafeDownCast(renWin);\n this->Context = openGLRenWin;\n if (openGLRenWin)\n {\n if (!this->LoadRequiredExtensions(openGLRenWin->GetExtensionManager()))\n {\n this->Context = 0;\n vtkErrorMacro(\"Required OpenGL extensions not supported by the context.\");\n }\n }\n \n this->Modified();\n}\n\n\/\/----------------------------------------------------------------------------\nvtkRenderWindow* vtkVertexBufferObject::GetContext()\n{\n return this->Context;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkVertexBufferObject::Bind()\n{\n if (!this->Context)\n {\n vtkErrorMacro(\"No context specified. Cannot Bind.\");\n return;\n }\n \n this->CreateBuffer();\n \n vtkgl::BindBuffer(static_cast(this->BufferTarget), this->Handle);\n\n vtkGraphicErrorMacro(this->Context,\"after BindBuffer\");\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkVertexBufferObject::UnBind()\n{\n if (this->Context && this->Handle && this->BufferTarget)\n {\n vtkgl::BindBuffer(this->BufferTarget, 0);\n vtkGraphicErrorMacro(this->Context,\"after BindBuffer\");\n \/\/this->BufferTarget = 0;\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkVertexBufferObject::CreateBuffer()\n{\n this->Context->MakeCurrent();\n if (!this->Handle)\n {\n cout << \"Creating Buffer...\" << endl;\n GLuint ioBuf;\n vtkgl::GenBuffers(1, &ioBuf);\n vtkGraphicErrorMacro(this->Context, \"after GenBuffers\");\n this->Handle = ioBuf;\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkVertexBufferObject::DestroyBuffer()\n{\n if (this->Context && this->Handle)\n {\n GLuint ioBuf = static_cast(this->Handle);\n vtkgl::DeleteBuffers(1, &ioBuf);\n }\n this->Handle = 0;\n}\n\n\/\/----------------------------------------------------------------------------\nbool vtkVertexBufferObject::SetData(vtkPoints *points)\n{\n std::cout << \"Setting Points\" << endl;\n this->Count = points->GetNumberOfPoints();\n this->Size = this->Count * 3 * sizeof(float);\n this->BufferTarget = vtkgl::ARRAY_BUFFER;\n\n return this->SetData(points->GetVoidPointer(0));\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/bool vtkVertexBufferObject::SetData(vtkCellArray *verts)\n\/\/{\n\/\/ \/\/ The correct way to do this is to use each cells vtkIdTypes, but this\n\/\/ \/\/ returns a tuple (1, index) which I don't have time to understand right\n\/\/ \/\/ now\n\/\/ \/\/vtkIdType *oldarray = input->GetVerts()->GetPointer();\n\/\/ \/\/int *newarray = new int[numPoints];\n\/\/ \/\/std::copy(oldarray, oldarray + numPoints, newarray);\n\/\/ \/\/for (size_t i=0; i < numPoints*2; i+=2)\n\/\/ \/\/ std::cout << \"really\" << oldarray[i] << endl;\n\/\/\n\/\/ this->Size = points->GetNumberOfPoints() * sizeof(unsigned int);\n\/\/ this->BufferTarget = vtkgl::ELEMENT_ARRAY_BUFFER;\n\/\/\n\/\/ \/\/ For now, display every indice\n\/\/ unsigned int *indices = new unsigned int[numPoints];\n\/\/ for (size_t i=0; i < numPoints; i++){\n\/\/ indices[i] = i;\n\/\/ }\n\/\/\n\/\/ this->SetData((void *)indices);\n\/\/}\n\n\/\/----------------------------------------------------------------------------\nbool vtkVertexBufferObject::SetData(std::vector *indices)\n{\n std::cout << \"Setting Indices\" << endl;\n this->Count = indices->size();\n this->Size = this->Count * sizeof(unsigned int);\n this->BufferTarget = vtkgl::ELEMENT_ARRAY_BUFFER;\n\n return this->SetData(reinterpret_cast(&indices[0]));\n}\n\n\/\/----------------------------------------------------------------------------\nbool vtkVertexBufferObject::SetData(vtkDataArray *colors)\n{\n std::cout << \"Setting Colors\" << endl;\n \/\/this->Count = colors->GetNumberOfTuples();\n this->Count = colors->GetSize();\n std::cout << \"Type: \" << colors->GetDataTypeAsString() <Size = this->Count * 1 * sizeof(float);\n this->BufferTarget = vtkgl::ARRAY_BUFFER;\n std::cout << \"Setting Data\" << endl;\n\n return this->SetData(reinterpret_cast(colors->GetVoidPointer(0)));\n}\n\n\/\/----------------------------------------------------------------------------\nbool vtkVertexBufferObject::SetData(vtkUnsignedCharArray *colors)\n{\n std::cout << \"Setting Colors\" << endl;\n std::cout << \"Colors == NULL: \" << (colors == NULL) << endl;\n this->Count = colors->GetSize();\n std::cout << \"Type: \" << colors->GetDataTypeAsString() <Size = this->Count * 1 * sizeof(float);\n this->BufferTarget = vtkgl::ARRAY_BUFFER;\n\n std::cout << \"Setting Data\" << endl;\n return this->SetData(reinterpret_cast(colors->GetPointer(0)));\n}\n\n\/\/----------------------------------------------------------------------------\nbool vtkVertexBufferObject::SetData(GLvoid* data)\n{\n if (!this->Context)\n {\n vtkErrorMacro(\"No context specified. Cannot upload data.\");\n return false;\n }\n\n this->CreateBuffer();\n\n\/\/ cout << \" Context: \" << this->Context << endl;\n\/\/ cout << \" Handle: \" << this->Handle << endl;\n\/\/ cout << \" Size: \" << this->Size << endl;\n\/\/ cout << \" Count: \" << this->Count << endl;\n\/\/ cout << \" Usage: \" << VertexBufferObjectUsageAsString[this->Usage] << endl;\n\n GLenum usage = OpenGLVertexBufferObjectUsage[this->Usage];\n\n this->Bind();\n vtkgl::BufferData(this->BufferTarget, this->Size, data, usage);\n this->UnBind();\n\n cout << \"Buffer Created\" << endl;\n return true;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkVertexBufferObject::ReleaseMemory()\n{\n if (this->Context && this->Handle)\n {\n this->Bind();\n vtkgl::BufferData(this->BufferTarget, 0, NULL, OpenGLVertexBufferObjectUsage[this->Usage]);\n this->Size = 0;\n this->Count = 0;\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkVertexBufferObject::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os, indent);\n os << indent << \"Context: \" << this->Context << endl;\n os << indent << \"Handle: \" << this->Handle << endl;\n os << indent << \"Size: \" << this->Size << endl;\n os << indent << \"Count: \" << this->Count << endl;\n os << indent << \"Usage:\" << VertexBufferObjectUsageAsString[this->Usage] << endl;\n}\n<|endoftext|>"} {"text":"\/\/ Jubatus: Online machine learning framework for distributed environment\n\/\/ Copyright (C) 2016 Preferred Networks and Nippon Telegraph and Telephone Corporation.\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License version 2.1 as published by the Free Software Foundation.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n#ifndef JUBATUS_DUMP_REGRESSION_HPP_\n#define JUBATUS_DUMP_REGRESSION_HPP_\n\n#include \n\n#include \n#include \n\n#include \n\n#include \"types.hpp\"\n#include \"weight_manager.hpp\"\n#include \"local_storage_mixture.hpp\"\n#include \"regression.hpp\"\n\nnamespace jubatus {\nnamespace dump {\n\nstruct linear_regression {\n local_storage_mixture storage;\n\n MSGPACK_DEFINE(storage);\n};\n\nstruct linear_regression_dump {\n explicit linear_regression_dump(const linear_regression& regression)\n : storage(regression.storage) {\n }\n\n local_storage_mixture_dump storage;\n\n template \n void serialize(Ar& ar) {\n ar & JUBA_MEMBER(storage);\n }\n};\n\ntemplate \nstruct regression {\n typedef S storage_type;\n\n storage_type storage;\n weight_manager weights;\n\n MSGPACK_DEFINE(storage, weights);\n};\n\ntemplate \nstruct regression_dump {\n typedef S storage_type;\n typedef D dump_type;\n\n explicit regression_dump(const regression& regression)\n : storage(regression.storage),\n weights(regression.weights) {\n }\n\n dump_type storage;\n weight_manager_dump weights;\n\n template \n void serialize(Ar& ar) {\n ar & JUBA_MEMBER(storage) & JUBA_MEMBER(weights);\n }\n};\n\n} \/\/ namespace dump\n} \/\/ namespace jubatus\n\n#endif \/\/ JUBATUS_DUMP_REGRESSION_HPP_\nremove unused include\/\/ Jubatus: Online machine learning framework for distributed environment\n\/\/ Copyright (C) 2016 Preferred Networks and Nippon Telegraph and Telephone Corporation.\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License version 2.1 as published by the Free Software Foundation.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n#ifndef JUBATUS_DUMP_REGRESSION_HPP_\n#define JUBATUS_DUMP_REGRESSION_HPP_\n\n#include \n\n#include \n#include \n\n#include \n\n#include \"types.hpp\"\n#include \"weight_manager.hpp\"\n#include \"local_storage_mixture.hpp\"\n\nnamespace jubatus {\nnamespace dump {\n\nstruct linear_regression {\n local_storage_mixture storage;\n\n MSGPACK_DEFINE(storage);\n};\n\nstruct linear_regression_dump {\n explicit linear_regression_dump(const linear_regression& regression)\n : storage(regression.storage) {\n }\n\n local_storage_mixture_dump storage;\n\n template \n void serialize(Ar& ar) {\n ar & JUBA_MEMBER(storage);\n }\n};\n\ntemplate \nstruct regression {\n typedef S storage_type;\n\n storage_type storage;\n weight_manager weights;\n\n MSGPACK_DEFINE(storage, weights);\n};\n\ntemplate \nstruct regression_dump {\n typedef S storage_type;\n typedef D dump_type;\n\n explicit regression_dump(const regression& regression)\n : storage(regression.storage),\n weights(regression.weights) {\n }\n\n dump_type storage;\n weight_manager_dump weights;\n\n template \n void serialize(Ar& ar) {\n ar & JUBA_MEMBER(storage) & JUBA_MEMBER(weights);\n }\n};\n\n} \/\/ namespace dump\n} \/\/ namespace jubatus\n\n#endif \/\/ JUBATUS_DUMP_REGRESSION_HPP_\n<|endoftext|>"} {"text":"\/*\n Simple Console\n Copyright (C) 1998 by Jorrit Tyberghein\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public\n License along with this library; if not, write to the Free\n Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n*\/\n\n#include \n#include \n#include \n\n#include \"sysdef.h\"\n#include \"cssys\/system.h\"\n#include \"cssys\/sysdriv.h\"\n#include \"cstools\/simpcons.h\"\n#include \"csinput\/csinput.h\"\n#include \"csutil\/csrect.h\"\n#include \"csutil\/inifile.h\"\n#include \"igraph2d.h\"\n#include \"itxtmgr.h\"\n\n#define SIZE_LINE\t256\n#define SIZE_HISTORY\t32\n\n#define Gfx2D System->piG2D\n\nvoid GfxWrite (int x, int y, int fg, int bg, char *str, ...)\n{\n va_list arg;\n char buf[256];\n\n va_start (arg, str);\n vsprintf (buf, str, arg);\n va_end (arg);\n\n Gfx2D->Write (x, y, fg, bg, buf);\n}\n\ncsSimpleConsole::csSimpleConsole (csIniFile *iConfig, csSimpleCommand* pc) : command_handler(pc)\n{\n config = iConfig;\n LineMessageMax = config->GetInt (\"SimpleConsole\", \"LINEMAX\", 4);\n HistoryMax = config->GetInt (\"SimpleConsole\", \"LINEHISTORY\", SIZE_HISTORY);\n console_transparent_bg = config->GetYesNo (\"SimpleConsole\", \"TRANSPBG\", 1);\n char *buf = config->GetStr (\"SimpleConsole\", \"CONFG\", \"255,255,255\");\n sscanf (buf, \"%d,%d,%d\", &console_fg_r, &console_fg_g, &console_fg_b);\n buf = config->GetStr (\"SimpleConsole\", \"CONBG\", \"0,0,0\");\n sscanf (buf, \"%d,%d,%d\", &console_bg_r, &console_bg_g, &console_bg_b);\n buf = config->GetStr (\"SimpleConsole\", \"CONFONT\", \"auto\");\n if (!strcasecmp (buf, \"auto\"))\n {\n long screen_surface = System->FrameWidth * System->FrameHeight;\n if (screen_surface <= 320*200)\n console_font = csFontTiny;\n else if (screen_surface <= 640*480)\n console_font = csFontCourier;\n else\n console_font = csFontPolice;\n }\n else if (!strcasecmp (buf, \"tiny\"))\n console_font = csFontTiny;\n else if (!strcasecmp (buf, \"courier\"))\n console_font = csFontCourier;\n else if (!strcasecmp (buf, \"police\"))\n console_font = csFontPolice;\n else\n {\n System->Printf (MSG_FATAL_ERROR, \"Bad value for CONFONT in configuration \"\n \"file.\\nUse 'auto', 'tiny', 'courier', or 'police'\\n\");\n fatal_exit (0, false);\n }\n\n int i;\n\n System->piGI->GetTextHeight (i, console_font);\n i += 2;\n LineMax = (System->FrameHeight \/ i) - 2;\n LineSize = (System->FrameWidth \/ 4) + 1;\n\n if (LineMessageMax <= 0)\n LineMessageMax = 1;\n else if (LineMessageMax >= LineMax)\n LineMessageMax = LineMax-1;\n\n CHK (LineMessage = new char * [LineMessageMax]);\n CHK (LinesChanged = new bool [LineMessageMax]);\n for (i = 0; i < LineMessageMax; i++)\n {\n CHK (LineMessage [i] = new char [SIZE_LINE]);\n LineMessage [i][0] = '\\0';\n LinesChanged [i] = true;\n }\n LineMessageNumber = 0;\n\n CHK (Line = new char * [LineMax]);\n for (i = 0; i < LineMax; i++)\n {\n CHK (Line [i] = new char [SIZE_LINE]);\n Line [i][0] = '\\0';\n }\n LineNumber = 0;\n\n CHK (LineCommand = new char [SIZE_LINE]);\n LineCommand [0] = '\\0';\n LineCommandMax = SIZE_LINE - 1;\n LineCommandCount = 0;\n\n CHK (History = new char * [HistoryMax]);\n for (i = 0; i < HistoryMax; i++)\n {\n CHK (History [i] = new char[SIZE_LINE]);\n History [i][0] = '\\0';\n }\n HistoryCount = 0;\n HistoryCurrent = 0;\n\n LineTime = System->Time ();\n ConsoleMode = MESSAGE_MODE;\n CursorState = false;\n CursorTime = System->Time ();\n}\n\ncsSimpleConsole::~csSimpleConsole ()\n{\n int i;\n\n for (i = 0; i < LineMessageMax; i++)\n CHKB (delete [] LineMessage [i]);\n CHK (delete [] LineMessage);\n\n if (Line)\n {\n for (i = 0; i < LineMax; i++)\n CHKB (delete [] Line [i]);\n CHK (delete [] Line);\n }\n\n if (History)\n {\n for (i = 0; i < HistoryMax; i++)\n CHKB (delete [] History [i]);\n CHK (delete [] History);\n }\n\n CHK (delete [] LineCommand);\n CHK (delete [] LinesChanged);\n}\n\nvoid csSimpleConsole::SetTransparent (int t)\n{\n if (t == -1)\n console_transparent_bg = config->GetYesNo (\"SimpleConsole\", \"TRANSPBG\", 1);\n else\n console_transparent_bg = t;\n}\n\nvoid csSimpleConsole::SetMaxLines (int ml)\n{\n int i;\n\n \/\/ First remove the old messages\n for (i = 0; i < LineMessageMax; i++)\n CHKB (delete [] LineMessage[i]);\n CHK (delete [] LineMessage);\n\n CHK (delete [] LinesChanged);\n\n if (ml == -1)\n LineMessageMax = config->GetInt (\"SimpleConsole\", \"LINEMAX\", 4);\n else\n LineMessageMax = ml;\n if (LineMessageMax >= LineMax)\n LineMessageMax = LineMax-1;\n\n \/\/ Allocate new messages.\n CHK (LineMessage = new char * [LineMessageMax]);\n CHK (LinesChanged = new bool [LineMessageMax]);\n for (i = 0; i < LineMessageMax; i++)\n {\n CHK (LineMessage [i] = new char [SIZE_LINE]);\n LineMessage [i][0] = '\\0';\n LinesChanged[i] = true;\n }\n LineMessageNumber = 0;\n}\n\nvoid csSimpleConsole::Show ()\n{\n ConsoleMode = CONSOLE_MODE;\n}\n\nvoid csSimpleConsole::Hide ()\n{\n Gfx2D->ClearAll (0);\n ConsoleMode = MESSAGE_MODE;\n}\n\nvoid csSimpleConsole::PutMessage (bool advance, char *str,...)\n{\n va_list arg;\n char buf[256];\n\n va_start (arg, str);\n vsprintf (buf, str, arg);\n va_end (arg);\n\n if (LineMessageNumber >= LineMessageMax)\n {\n for (int i = 1; i < LineMessageMax; i++)\n {\n strcpy (LineMessage [i - 1], LineMessage [i]);\n LinesChanged [i - 1] = true;\n }\n LineMessageNumber--;\n }\n\n strncpy (LineMessage [LineMessageNumber], buf, SIZE_LINE - 1);\n LinesChanged [LineMessageNumber] = true;\n\n LineTime = System->Time () + 4000;\n if (advance)\n LineMessageNumber++;\n}\n\nvoid csSimpleConsole::PutText (char *str,...)\n{\n va_list arg;\n char buf[256];\n\n va_start (arg, str);\n vsprintf (buf, str, arg);\n va_end (arg);\n\n if(!buf[0])\n return;\n\n int len = strlen (Line[LineNumber]);\n char* dst = Line[LineNumber] + len;\n char const* src = buf;\n for (char c = *src; c != '\\0'; c = *++src)\n {\n if (c == '\\b')\n {\n if (len != 0)\n {\n dst--;\n len--;\n }\n }\n else if (c == '\\n')\n {\n *dst = '\\0';\n PutMessage (true, \"%s\", Line[LineNumber]);\n if (LineNumber + 1 < LineMax)\n LineNumber++;\n else\n {\n for (int i = 1; i < LineMax; i++)\n strcpy (Line[i - 1], Line[i]);\n }\n dst = Line[LineNumber];\n *dst = '\\0';\n len = 0;\n }\n else if (len < SIZE_LINE - 1)\n {\n *dst++ = c;\n len++;\n } \/* endif *\/\n } \/* endfor *\/\n\n if (len != 0)\n {\n *dst = '\\0';\n PutMessage (false, \"%s\", Line[LineNumber]);\n }\n}\n\nvoid csSimpleConsole::ExecuteCommand (char *command)\n{\n PutText (\"cs# %s\\n\", command);\n if (command && command[0] != '\\0')\n {\n if (command_handler == 0 || !command_handler->PerformLine (command))\n PutText (\"Unknown command: %s\\n\", command);\n\n if (HistoryCount > HistoryMax - 2)\n {\n for (int i = 0; i < (HistoryMax - 2); i++)\n strcpy (History[i], History[i + 1]);\n strncpy (History[HistoryMax - 2], command, SIZE_LINE - 1);\n } else\n {\n strncpy (History[HistoryCount], command, SIZE_LINE - 1);\n HistoryCount++;\n }\n }\n}\n\nvoid csSimpleConsole::Clear ()\n{\n LineCommandCount = 0;\n LineMessageNumber = 0;\n LineNumber = 0;\n Line [LineNumber][0] = '\\0';\n\n for (int i = 0; i < LineMessageMax; i++)\n {\n LineMessage [i][0] = '\\0';\n LinesChanged [i] = true;\n }\n}\n\nvoid csSimpleConsole::Print (csRect* area)\n{\n int i;\n long CurrentTime = System->Time ();\n\n Gfx2D->SetFontID (console_font);\n\n#define WRITE(x,y,fc,bc,s,changed)\t\t\t\t\\\n {\t\t\t\t\t\t\t\t\\\n Gfx2D->Write (x, y, fc, bc, s);\t\t\t\t\\\n if ((changed) && area)\t\t\t\t\t\\\n {\t\t\t\t\t\t\t\t\\\n int tw;\t\t\t\t\t\t\t\\\n System->piGI->GetTextWidth (tw, console_font, s);\t\t\\\n area->Union (x, y, x + tw, y + th);\t\t\t\\\n }\t\t\t\t\t\t\t\t\\\n }\n\n#define WRITE2(x,y,fc,bc,s,changed)\t\t\t\t\\\n {\t\t\t\t\t\t\t\t\\\n Gfx2D->Write (x + 1, y + 1, bc, -1, s);\t\t\t\\\n Gfx2D->Write (x, y, fc, -1, s);\t\t\t\t\\\n if ((changed) && area)\t\t\t\t\t\\\n {\t\t\t\t\t\t\t\t\\\n int tw;\t\t\t\t\t\t\t\\\n System->piGI->GetTextWidth (tw, console_font, s);\t\t\\\n area->Union (x, y, x + 1 + tw, y + 1 + th);\t\t\\\n }\t\t\t\t\t\t\t\t\\\n }\n\n \/\/ text height\n int th;\n System->piGI->GetTextHeight (th, console_font);\n th += 2;\n\n bool dblbuff;\n Gfx2D->GetDoubleBufferState (dblbuff);\n\n switch (ConsoleMode)\n {\n case MESSAGE_MODE:\n {\n if (CurrentTime > LineTime)\n {\n \/\/ Scroll all lines up once per four seconds\n for (i = 1; i < LineMessageMax; i++)\n {\n strcpy (LineMessage [i - 1], LineMessage [i]);\n LinesChanged [i - 1] = true;\n }\n if (LineMessageNumber > 0)\n LineMessageNumber--;\n LineMessage [LineMessageMax - 1][0] = '\\0';\n LinesChanged [LineMessageMax - 1] = true;\n LineTime = System->Time () + 4000;\n }\n for (i = 0; i < LineMessageMax; i++)\n {\n WRITE2 (10, 10 + th * i, console_fg, console_bg, LineMessage [i],\n\t dblbuff || LinesChanged [i]);\n\tLinesChanged [i] = false;\n }\n break;\n }\n case CONSOLE_MODE:\n {\n if (CurrentTime > CursorTime)\n {\n CursorState = !CursorState;\n CursorTime = System->Time () + 333;\n }\n\n char buf [256];\n sprintf (buf, CursorState ? \"cs# %s_\" : \"cs# %s\", LineCommand);\n\n int const lastline = strlen (Line[LineNumber]) == 0 ?\n\t LineNumber : LineNumber + 1; \/\/ Account for partial lines.\n\n if (console_transparent_bg)\n {\n for (i = 0; i < lastline; i++)\n WRITE2 (1, th * i, console_fg, console_bg, Line [i], dblbuff);\n WRITE2 (1, th * lastline, console_fg, console_bg, buf, dblbuff);\n }\n else\n {\n Gfx2D->Clear (console_bg);\n if (dblbuff && area)\n area->Union (0, 0, System->FrameWidth - 1, System->FrameHeight - 1);\n for (i = 0; i < lastline; i++)\n WRITE (1, th * i, console_fg, -1, Line [i], false);\n WRITE (1, th * lastline, console_fg, -1, buf, false);\n }\n break;\n }\n }\n}\n\nvoid csSimpleConsole::AddChar (int c)\n{\n switch (c)\n {\n case CSKEY_TAB:\n Hide ();\n break;\n\n case CSKEY_ENTER:\n ExecuteCommand (LineCommand);\n LineCommand[0] = '\\0';\n LineCommandCount = 0;\n HistoryCurrent = HistoryCount;\n break;\n\n case CSKEY_BACKSPACE:\n if (LineCommandCount >= 0)\n LineCommand[--LineCommandCount] = '\\0';\n break;\n\n case CSKEY_DOWN:\n if (HistoryCurrent < HistoryCount)\n HistoryCurrent++;\n strcpy (LineCommand, History[HistoryCurrent]);\n LineCommandCount = strlen (LineCommand);\n break;\n\n case CSKEY_UP:\n if (HistoryCurrent > 0)\n HistoryCurrent--;\n strcpy (LineCommand, History[HistoryCurrent]);\n LineCommandCount = strlen (LineCommand);\n break;\n\n default:\n if (c >= ' ' && c < 256)\n if (LineCommandCount < LineCommandMax)\n {\n LineCommand[LineCommandCount++] = c;\n LineCommand[LineCommandCount] = '\\0';\n }\n break;\n }\n}\n\nvoid csSimpleConsole::SetupColors (ITextureManager* txtmgr)\n{\n txtmgr->FindRGB (console_fg_r, console_fg_g, console_fg_b, console_fg);\n txtmgr->FindRGB (console_bg_r, console_bg_g, console_bg_b, console_bg);\n}\nIf I run Walktest and other apps that use the graphical console in a resolution like 320x240 or 400x300, a lot of console messages won't fit the screen width. This led me to decide that the font selection should be based on having at least 80 columns of text - instead of being based on the area of the screen.\/*\n Simple Console\n Copyright (C) 1998 by Jorrit Tyberghein\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public\n License along with this library; if not, write to the Free\n Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n*\/\n\n#include \n#include \n#include \n\n#include \"sysdef.h\"\n#include \"cssys\/system.h\"\n#include \"cssys\/sysdriv.h\"\n#include \"cstools\/simpcons.h\"\n#include \"csinput\/csinput.h\"\n#include \"csutil\/csrect.h\"\n#include \"csutil\/inifile.h\"\n#include \"igraph2d.h\"\n#include \"itxtmgr.h\"\n\n#define SIZE_LINE\t256\n#define SIZE_HISTORY\t32\n\n#define Gfx2D System->piG2D\n\nvoid GfxWrite (int x, int y, int fg, int bg, char *str, ...)\n{\n va_list arg;\n char buf[256];\n\n va_start (arg, str);\n vsprintf (buf, str, arg);\n va_end (arg);\n\n Gfx2D->Write (x, y, fg, bg, buf);\n}\n\ncsSimpleConsole::csSimpleConsole (csIniFile *iConfig, csSimpleCommand* pc) : command_handler(pc)\n{\n config = iConfig;\n LineMessageMax = config->GetInt (\"SimpleConsole\", \"LINEMAX\", 4);\n HistoryMax = config->GetInt (\"SimpleConsole\", \"LINEHISTORY\", SIZE_HISTORY);\n console_transparent_bg = config->GetYesNo (\"SimpleConsole\", \"TRANSPBG\", 1);\n char *buf = config->GetStr (\"SimpleConsole\", \"CONFG\", \"255,255,255\");\n sscanf (buf, \"%d,%d,%d\", &console_fg_r, &console_fg_g, &console_fg_b);\n buf = config->GetStr (\"SimpleConsole\", \"CONBG\", \"0,0,0\");\n sscanf (buf, \"%d,%d,%d\", &console_bg_r, &console_bg_g, &console_bg_b);\n buf = config->GetStr (\"SimpleConsole\", \"CONFONT\", \"auto\");\n if (!strcasecmp (buf, \"auto\"))\n {\n \/\/ choose a font that allows at least 80 columns of text\n if (System->FrameWidth <= 560)\n console_font = csFontTiny;\n else if (System->FrameWidth <= 640)\n console_font = csFontCourier;\n else\n console_font = csFontPolice;\n }\n else if (!strcasecmp (buf, \"tiny\"))\n console_font = csFontTiny;\n else if (!strcasecmp (buf, \"courier\"))\n console_font = csFontCourier;\n else if (!strcasecmp (buf, \"police\"))\n console_font = csFontPolice;\n else\n {\n System->Printf (MSG_FATAL_ERROR, \"Bad value for CONFONT in configuration \"\n \"file.\\nUse 'auto', 'tiny', 'courier', or 'police'\\n\");\n fatal_exit (0, false);\n }\n\n int i;\n\n System->piGI->GetTextHeight (i, console_font);\n i += 2;\n LineMax = (System->FrameHeight \/ i) - 2;\n LineSize = (System->FrameWidth \/ 4) + 1;\n\n if (LineMessageMax <= 0)\n LineMessageMax = 1;\n else if (LineMessageMax >= LineMax)\n LineMessageMax = LineMax-1;\n\n CHK (LineMessage = new char * [LineMessageMax]);\n CHK (LinesChanged = new bool [LineMessageMax]);\n for (i = 0; i < LineMessageMax; i++)\n {\n CHK (LineMessage [i] = new char [SIZE_LINE]);\n LineMessage [i][0] = '\\0';\n LinesChanged [i] = true;\n }\n LineMessageNumber = 0;\n\n CHK (Line = new char * [LineMax]);\n for (i = 0; i < LineMax; i++)\n {\n CHK (Line [i] = new char [SIZE_LINE]);\n Line [i][0] = '\\0';\n }\n LineNumber = 0;\n\n CHK (LineCommand = new char [SIZE_LINE]);\n LineCommand [0] = '\\0';\n LineCommandMax = SIZE_LINE - 1;\n LineCommandCount = 0;\n\n CHK (History = new char * [HistoryMax]);\n for (i = 0; i < HistoryMax; i++)\n {\n CHK (History [i] = new char[SIZE_LINE]);\n History [i][0] = '\\0';\n }\n HistoryCount = 0;\n HistoryCurrent = 0;\n\n LineTime = System->Time ();\n ConsoleMode = MESSAGE_MODE;\n CursorState = false;\n CursorTime = System->Time ();\n}\n\ncsSimpleConsole::~csSimpleConsole ()\n{\n int i;\n\n for (i = 0; i < LineMessageMax; i++)\n CHKB (delete [] LineMessage [i]);\n CHK (delete [] LineMessage);\n\n if (Line)\n {\n for (i = 0; i < LineMax; i++)\n CHKB (delete [] Line [i]);\n CHK (delete [] Line);\n }\n\n if (History)\n {\n for (i = 0; i < HistoryMax; i++)\n CHKB (delete [] History [i]);\n CHK (delete [] History);\n }\n\n CHK (delete [] LineCommand);\n CHK (delete [] LinesChanged);\n}\n\nvoid csSimpleConsole::SetTransparent (int t)\n{\n if (t == -1)\n console_transparent_bg = config->GetYesNo (\"SimpleConsole\", \"TRANSPBG\", 1);\n else\n console_transparent_bg = t;\n}\n\nvoid csSimpleConsole::SetMaxLines (int ml)\n{\n int i;\n\n \/\/ First remove the old messages\n for (i = 0; i < LineMessageMax; i++)\n CHKB (delete [] LineMessage[i]);\n CHK (delete [] LineMessage);\n\n CHK (delete [] LinesChanged);\n\n if (ml == -1)\n LineMessageMax = config->GetInt (\"SimpleConsole\", \"LINEMAX\", 4);\n else\n LineMessageMax = ml;\n if (LineMessageMax >= LineMax)\n LineMessageMax = LineMax-1;\n\n \/\/ Allocate new messages.\n CHK (LineMessage = new char * [LineMessageMax]);\n CHK (LinesChanged = new bool [LineMessageMax]);\n for (i = 0; i < LineMessageMax; i++)\n {\n CHK (LineMessage [i] = new char [SIZE_LINE]);\n LineMessage [i][0] = '\\0';\n LinesChanged[i] = true;\n }\n LineMessageNumber = 0;\n}\n\nvoid csSimpleConsole::Show ()\n{\n ConsoleMode = CONSOLE_MODE;\n}\n\nvoid csSimpleConsole::Hide ()\n{\n Gfx2D->ClearAll (0);\n ConsoleMode = MESSAGE_MODE;\n}\n\nvoid csSimpleConsole::PutMessage (bool advance, char *str,...)\n{\n va_list arg;\n char buf[256];\n\n va_start (arg, str);\n vsprintf (buf, str, arg);\n va_end (arg);\n\n if (LineMessageNumber >= LineMessageMax)\n {\n for (int i = 1; i < LineMessageMax; i++)\n {\n strcpy (LineMessage [i - 1], LineMessage [i]);\n LinesChanged [i - 1] = true;\n }\n LineMessageNumber--;\n }\n\n strncpy (LineMessage [LineMessageNumber], buf, SIZE_LINE - 1);\n LinesChanged [LineMessageNumber] = true;\n\n LineTime = System->Time () + 4000;\n if (advance)\n LineMessageNumber++;\n}\n\nvoid csSimpleConsole::PutText (char *str,...)\n{\n va_list arg;\n char buf[256];\n\n va_start (arg, str);\n vsprintf (buf, str, arg);\n va_end (arg);\n\n if(!buf[0])\n return;\n\n int len = strlen (Line[LineNumber]);\n char* dst = Line[LineNumber] + len;\n char const* src = buf;\n for (char c = *src; c != '\\0'; c = *++src)\n {\n if (c == '\\b')\n {\n if (len != 0)\n {\n dst--;\n len--;\n }\n }\n else if (c == '\\n')\n {\n *dst = '\\0';\n PutMessage (true, \"%s\", Line[LineNumber]);\n if (LineNumber + 1 < LineMax)\n LineNumber++;\n else\n {\n for (int i = 1; i < LineMax; i++)\n strcpy (Line[i - 1], Line[i]);\n }\n dst = Line[LineNumber];\n *dst = '\\0';\n len = 0;\n }\n else if (len < SIZE_LINE - 1)\n {\n *dst++ = c;\n len++;\n } \/* endif *\/\n } \/* endfor *\/\n\n if (len != 0)\n {\n *dst = '\\0';\n PutMessage (false, \"%s\", Line[LineNumber]);\n }\n}\n\nvoid csSimpleConsole::ExecuteCommand (char *command)\n{\n PutText (\"cs# %s\\n\", command);\n if (command && command[0] != '\\0')\n {\n if (command_handler == 0 || !command_handler->PerformLine (command))\n PutText (\"Unknown command: %s\\n\", command);\n\n if (HistoryCount > HistoryMax - 2)\n {\n for (int i = 0; i < (HistoryMax - 2); i++)\n strcpy (History[i], History[i + 1]);\n strncpy (History[HistoryMax - 2], command, SIZE_LINE - 1);\n } else\n {\n strncpy (History[HistoryCount], command, SIZE_LINE - 1);\n HistoryCount++;\n }\n }\n}\n\nvoid csSimpleConsole::Clear ()\n{\n LineCommandCount = 0;\n LineMessageNumber = 0;\n LineNumber = 0;\n Line [LineNumber][0] = '\\0';\n\n for (int i = 0; i < LineMessageMax; i++)\n {\n LineMessage [i][0] = '\\0';\n LinesChanged [i] = true;\n }\n}\n\nvoid csSimpleConsole::Print (csRect* area)\n{\n int i;\n long CurrentTime = System->Time ();\n\n Gfx2D->SetFontID (console_font);\n\n#define WRITE(x,y,fc,bc,s,changed)\t\t\t\t\\\n {\t\t\t\t\t\t\t\t\\\n Gfx2D->Write (x, y, fc, bc, s);\t\t\t\t\\\n if ((changed) && area)\t\t\t\t\t\\\n {\t\t\t\t\t\t\t\t\\\n int tw;\t\t\t\t\t\t\t\\\n System->piGI->GetTextWidth (tw, console_font, s);\t\t\\\n area->Union (x, y, x + tw, y + th);\t\t\t\\\n }\t\t\t\t\t\t\t\t\\\n }\n\n#define WRITE2(x,y,fc,bc,s,changed)\t\t\t\t\\\n {\t\t\t\t\t\t\t\t\\\n Gfx2D->Write (x + 1, y + 1, bc, -1, s);\t\t\t\\\n Gfx2D->Write (x, y, fc, -1, s);\t\t\t\t\\\n if ((changed) && area)\t\t\t\t\t\\\n {\t\t\t\t\t\t\t\t\\\n int tw;\t\t\t\t\t\t\t\\\n System->piGI->GetTextWidth (tw, console_font, s);\t\t\\\n area->Union (x, y, x + 1 + tw, y + 1 + th);\t\t\\\n }\t\t\t\t\t\t\t\t\\\n }\n\n \/\/ text height\n int th;\n System->piGI->GetTextHeight (th, console_font);\n th += 2;\n\n bool dblbuff;\n Gfx2D->GetDoubleBufferState (dblbuff);\n\n switch (ConsoleMode)\n {\n case MESSAGE_MODE:\n {\n if (CurrentTime > LineTime)\n {\n \/\/ Scroll all lines up once per four seconds\n for (i = 1; i < LineMessageMax; i++)\n {\n strcpy (LineMessage [i - 1], LineMessage [i]);\n LinesChanged [i - 1] = true;\n }\n if (LineMessageNumber > 0)\n LineMessageNumber--;\n LineMessage [LineMessageMax - 1][0] = '\\0';\n LinesChanged [LineMessageMax - 1] = true;\n LineTime = System->Time () + 4000;\n }\n for (i = 0; i < LineMessageMax; i++)\n {\n WRITE2 (10, 10 + th * i, console_fg, console_bg, LineMessage [i],\n\t dblbuff || LinesChanged [i]);\n\tLinesChanged [i] = false;\n }\n break;\n }\n case CONSOLE_MODE:\n {\n if (CurrentTime > CursorTime)\n {\n CursorState = !CursorState;\n CursorTime = System->Time () + 333;\n }\n\n char buf [256];\n sprintf (buf, CursorState ? \"cs# %s_\" : \"cs# %s\", LineCommand);\n\n int const lastline = strlen (Line[LineNumber]) == 0 ?\n\t LineNumber : LineNumber + 1; \/\/ Account for partial lines.\n\n if (console_transparent_bg)\n {\n for (i = 0; i < lastline; i++)\n WRITE2 (1, th * i, console_fg, console_bg, Line [i], dblbuff);\n WRITE2 (1, th * lastline, console_fg, console_bg, buf, dblbuff);\n }\n else\n {\n Gfx2D->Clear (console_bg);\n if (dblbuff && area)\n area->Union (0, 0, System->FrameWidth - 1, System->FrameHeight - 1);\n for (i = 0; i < lastline; i++)\n WRITE (1, th * i, console_fg, -1, Line [i], false);\n WRITE (1, th * lastline, console_fg, -1, buf, false);\n }\n break;\n }\n }\n}\n\nvoid csSimpleConsole::AddChar (int c)\n{\n switch (c)\n {\n case CSKEY_TAB:\n Hide ();\n break;\n\n case CSKEY_ENTER:\n ExecuteCommand (LineCommand);\n LineCommand[0] = '\\0';\n LineCommandCount = 0;\n HistoryCurrent = HistoryCount;\n break;\n\n case CSKEY_BACKSPACE:\n if (LineCommandCount >= 0)\n LineCommand[--LineCommandCount] = '\\0';\n break;\n\n case CSKEY_DOWN:\n if (HistoryCurrent < HistoryCount)\n HistoryCurrent++;\n strcpy (LineCommand, History[HistoryCurrent]);\n LineCommandCount = strlen (LineCommand);\n break;\n\n case CSKEY_UP:\n if (HistoryCurrent > 0)\n HistoryCurrent--;\n strcpy (LineCommand, History[HistoryCurrent]);\n LineCommandCount = strlen (LineCommand);\n break;\n\n default:\n if (c >= ' ' && c < 256)\n if (LineCommandCount < LineCommandMax)\n {\n LineCommand[LineCommandCount++] = c;\n LineCommand[LineCommandCount] = '\\0';\n }\n break;\n }\n}\n\nvoid csSimpleConsole::SetupColors (ITextureManager* txtmgr)\n{\n txtmgr->FindRGB (console_fg_r, console_fg_g, console_fg_b, console_fg);\n txtmgr->FindRGB (console_bg_r, console_bg_g, console_bg_b, console_bg);\n}\n<|endoftext|>"} {"text":"A comment that I will need to act on.<|endoftext|>"} {"text":"\/\/\n\/\/ This file is part of the Marble Desktop Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2008 Patrick Spendrin \n\/\/ Copyright 2008 Simon Schmeisser \n\/\/\n\n\n\/\/ Own\n#include \"MarbleGeometryModel.h\"\n\n\/\/ Qt\n#include \n#include \n#include \n#include \n#include \n\n\/\/ Marble\n#include \"GeoDataDocument.h\" \/\/ In geodata\/data\/\n#include \"GeoDataContainer.h\"\n#include \"GeoDataFeature.h\"\n#include \"GeoDataFolder.h\"\n#include \"GeoDataGeometry.h\"\n#include \"GeoDataMultiGeometry.h\"\n#include \"GeoDataPlacemark.h\"\n#include \"GeoDataObject.h\"\n#include \"GeoDataParser.h\"\n\nusing namespace Marble;\n\nclass MarbleGeometryModel::Private {\n public:\n Private( GeoDataDocument* rootDocument ) : m_rootDocument( rootDocument ) {\n mapFeature( m_rootDocument );\n };\n \n Private() : m_rootDocument( 0 ) {};\n\n void mapGeometry( GeoDataGeometry* geometry ) {\n \/*\n * This function iterates over all geometry objects in a MultiGeometry.\n * This is needed to build up the parent Hash.\n *\/\n if( !geometry ) return;\n \n QVector::iterator iterator;\n GeoDataMultiGeometry* multiGeometry = static_cast( geometry );\n for( iterator = multiGeometry->begin(); \n iterator != multiGeometry->end(); \n ++iterator ) {\n m_parent[ iterator ] = geometry;\n if( iterator->geometryId() == GeoDataMultiGeometryId ) mapGeometry( iterator );\n }\n };\n \n void mapFeature( GeoDataFeature* feature ) {\n if( !feature ) return;\n \n if( feature->featureId() == GeoDataDocumentId || feature->featureId() == GeoDataFolderId ) {\n Q_FOREACH( GeoDataFeature childFeature, static_cast( feature )->features() ) {\n m_parent[ &childFeature ] = feature;\n mapFeature( &childFeature );\n }\n }\n if( feature->featureId() == GeoDataPlacemarkId ) {\n if( dynamic_cast( feature )->geometry() && dynamic_cast( feature )->geometry()->geometryId() == GeoDataMultiGeometryId ) {\n m_parent[ dynamic_cast( feature )->geometry() ] = feature;\n mapGeometry( dynamic_cast( feature )->geometry() );\n }\n }\n };\n \n GeoDataDocument* m_rootDocument;\n QHash m_parent;\n};\n\nMarbleGeometryModel::MarbleGeometryModel( QObject *parent )\n : QAbstractItemModel(), d( new Private() )\n{\n}\n\nMarbleGeometryModel::MarbleGeometryModel( GeoDataDocument *rootDocument, QObject *parent )\n : QAbstractItemModel(), d( new Private( rootDocument ) )\n{\n}\n\nMarbleGeometryModel::~MarbleGeometryModel()\n{\n delete d;\n}\n\nvoid MarbleGeometryModel::setGeoDataRoot( GeoDataDocument* root )\n{\n if( d->m_rootDocument != root ) {\n reset();\n qDebug() << \"resetting the base of the Geometry model\" << root;\n d->m_rootDocument = root;\n d->mapFeature( d->m_rootDocument );\n }\n}\n\nGeoDataDocument* MarbleGeometryModel::geoDataRoot() const\n{\n return d->m_rootDocument;\n}\n\nint MarbleGeometryModel::rowCount( const QModelIndex &parent ) const\n{\n \/* For now we will simply take over the mechanism of TreeModels:\n * each node gives the number of subnodes it has as its rowCount\n *\/\n GeoDataObject *parentItem;\n if( parent.column() > 0 )\n return 0;\n\n if( !parent.isValid() )\n parentItem = d->m_rootDocument;\n else\n parentItem = static_cast( parent.internalPointer() );\n\n if( dynamic_cast( parentItem ) ||\n dynamic_cast( parentItem ) )\n {\n return dynamic_cast( parentItem )->features().size();\n }\n \n if( dynamic_cast( parentItem ) )\n {\n \/* there is only one GeoDataGeometry Object per Placemark; if Styles \n * are added later, add them here *\/\n return 1;\n }\n \n if( dynamic_cast( parentItem ) )\n {\n return dynamic_cast( parentItem )->size();\n }\n return 0;\n}\n\nQVariant MarbleGeometryModel::data( const QModelIndex &index, int role ) const\n{\n GeoDataObject *item;\n if( index.isValid() )\n {\n item = static_cast( index.internalPointer() );\n }\n else \/* the rootIndex is invalid *\/\n {\n item = static_cast( d->m_rootDocument );\n }\n\n \/* for now simply give back the type of the GeoDataObject \n * there might be a need to extend this, but usually we want \n *\/\n if( role == Qt::DisplayRole ) {\n if( dynamic_cast( item ) ) {\n switch( dynamic_cast( item )->featureId() ) {\n case InvalidFeatureId:\n return QVariant( \"InvalidFeature\" );\n case GeoDataDocumentId:\n return QVariant( \"GeoDataDocument\" );\n case GeoDataFolderId:\n return QVariant( \"GeoDataFolder\" );\n case GeoDataPlacemarkId:\n return QVariant( \"GeoDataPlacemark\" );\n case GeoDataNetworkLinkId:\n return QVariant( \"GeoDataNetworkLink\" );\n case GeoDataScreenOverlayId:\n return QVariant( \"GeoDataScreenOverlay\" );\n case GeoDataGroundOverlayId:\n return QVariant( \"GeoDataGroundOverlay\" );\n }\n }\n if( dynamic_cast( item ) ) {\n switch( dynamic_cast( item )->geometryId() ) {\n case InvalidGeometryId:\n return QVariant( \"InvalidGeometry\" );\n case GeoDataMultiGeometryId:\n return QVariant( \"GeoDataMultiGeometry\" );\n case GeoDataLineStringId:\n return QVariant( \"GeoDataLineString\" );\n case GeoDataLinearRingId:\n return QVariant( \"GeoDataLinearRing\" );\n case GeoDataPolygonId:\n return QVariant( \"GeoDataPolygon\" );\n case GeoDataPointId:\n return QVariant( \"GeoDataPoint\" );\n }\n }\n }\n\n if( role == Qt::UserRole + 11 ) \/\/equivalent to MarblePlacemarkModel::ObjectPointerRole\n {\n \/* return the pointer item as a QVariant of (meta-)type\n * Marble::GeoDataObject* *\/\n QVariant v;\n v.setValue( item );\n return v;\n }\n\n return QVariant( \"GeoDataObject\" ); \n \/* TODO the data is hardcoded and very limited right now,\n * the logic what data is returned might be moved to the items\n * themselves later. Use the following code then:\n * return item->data( index.column() ); *\/\n\n}\n\nQModelIndex MarbleGeometryModel::index( int row, int column, const QModelIndex &parent ) const\n{\n if ( !hasIndex( row, column, parent ) )\n return QModelIndex();\n \n GeoDataObject *parentItem;\n \n if ( !parent.isValid() )\n parentItem = d->m_rootDocument;\n else\n parentItem = static_cast( parent.internalPointer() );\n\n GeoDataObject *childItem = 0;\n\n \/* go down into GeoDataContainers *\/\n if( dynamic_cast( parentItem ) || \n dynamic_cast( parentItem ) )\n {\n *childItem = dynamic_cast( \n parentItem )->features().at( row );\n }\n\n if( dynamic_cast( parentItem ) )\n {\n \/* as said above - if you add styles, please check for the row over here *\/\n childItem = dynamic_cast( parentItem )->geometry();\n }\n \n if( dynamic_cast( parentItem ) )\n {\n *childItem = dynamic_cast( parentItem )->at( row );\n }\n\n if ( childItem )\n return createIndex( row, column, childItem );\n else\n return QModelIndex();\n}\n\nQModelIndex MarbleGeometryModel::parent( const QModelIndex &index ) const\n{\n if ( !index.isValid() )\n return QModelIndex();\n\n GeoDataObject *childItem = static_cast( index.internalPointer() );\n GeoDataObject *parentItem = d->m_parent[ childItem ];\n\n if ( parentItem == d->m_rootDocument )\n return QModelIndex();\n\n if( parentItem == 0 ){\n \/* this shouldn't happen *\/\n return QModelIndex();\n }\n\n \/* for now leave that as 0, 0 -> this needs some more thoughts as \n * it is simply wrong *\/\n return createIndex( 0, 0, parentItem );\n}\n\nint MarbleGeometryModel::columnCount( const QModelIndex &node ) const\n{\n if ( node.isValid() )\n return 1;\n \/* TODO when nodes handle their information themselves they will have\n * varying amounts of properties ( or columns ). Right now we only have\n * one information ( type ) per node, so it's hardcoded to \"1\".\n * static_cast( node.internalPointer() )->columnCount(); *\/\n else\n return 1;\n}\n\nvoid MarbleGeometryModel::update()\n{\n QAbstractItemModel::reset();\n}\n\n#include \"MarbleGeometryModel.moc\"\nas we already have the advantage of copying Feature into placemarks and reversed, use it here.\/\/\n\/\/ This file is part of the Marble Desktop Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2008 Patrick Spendrin \n\/\/ Copyright 2008 Simon Schmeisser \n\/\/\n\n\n\/\/ Own\n#include \"MarbleGeometryModel.h\"\n\n\/\/ Qt\n#include \n#include \n#include \n#include \n#include \n\n\/\/ Marble\n#include \"GeoDataDocument.h\" \/\/ In geodata\/data\/\n#include \"GeoDataContainer.h\"\n#include \"GeoDataFeature.h\"\n#include \"GeoDataFolder.h\"\n#include \"GeoDataGeometry.h\"\n#include \"GeoDataMultiGeometry.h\"\n#include \"GeoDataPlacemark.h\"\n#include \"GeoDataObject.h\"\n#include \"GeoDataParser.h\"\n\nusing namespace Marble;\n\nclass MarbleGeometryModel::Private {\n public:\n Private( GeoDataDocument* rootDocument ) : m_rootDocument( rootDocument ) {\n mapFeature( m_rootDocument );\n };\n \n Private() : m_rootDocument( 0 ) {};\n\n void mapGeometry( GeoDataGeometry* geometry ) {\n \/*\n * This function iterates over all geometry objects in a MultiGeometry.\n * This is needed to build up the parent Hash.\n *\/\n if( !geometry ) return;\n \n QVector::iterator iterator;\n GeoDataMultiGeometry* multiGeometry = static_cast( geometry );\n for( iterator = multiGeometry->begin(); \n iterator != multiGeometry->end(); \n ++iterator ) {\n m_parent[ iterator ] = geometry;\n if( iterator->geometryId() == GeoDataMultiGeometryId ) mapGeometry( iterator );\n }\n };\n \n void mapFeature( GeoDataFeature* feature ) {\n if( !feature ) return;\n \n if( feature->featureId() == GeoDataDocumentId || feature->featureId() == GeoDataFolderId ) {\n Q_FOREACH( GeoDataFeature childFeature, static_cast( feature )->features() ) {\n m_parent[ &childFeature ] = feature;\n mapFeature( &childFeature );\n }\n }\n if( feature->featureId() == GeoDataPlacemarkId ) {\n GeoDataPlacemark placemark = *feature;\n if( placemark.geometry() && placemark.geometry()->geometryId() == GeoDataMultiGeometryId ) {\n m_parent[ placemark.geometry() ] = feature;\n mapGeometry( placemark.geometry() );\n }\n }\n };\n \n GeoDataDocument* m_rootDocument;\n QHash m_parent;\n};\n\nMarbleGeometryModel::MarbleGeometryModel( QObject *parent )\n : QAbstractItemModel(), d( new Private() )\n{\n}\n\nMarbleGeometryModel::MarbleGeometryModel( GeoDataDocument *rootDocument, QObject *parent )\n : QAbstractItemModel(), d( new Private( rootDocument ) )\n{\n}\n\nMarbleGeometryModel::~MarbleGeometryModel()\n{\n delete d;\n}\n\nvoid MarbleGeometryModel::setGeoDataRoot( GeoDataDocument* root )\n{\n if( d->m_rootDocument != root ) {\n reset();\n qDebug() << \"resetting the base of the Geometry model\" << root;\n d->m_rootDocument = root;\n d->mapFeature( d->m_rootDocument );\n }\n}\n\nGeoDataDocument* MarbleGeometryModel::geoDataRoot() const\n{\n return d->m_rootDocument;\n}\n\nint MarbleGeometryModel::rowCount( const QModelIndex &parent ) const\n{\n \/* For now we will simply take over the mechanism of TreeModels:\n * each node gives the number of subnodes it has as its rowCount\n *\/\n GeoDataObject *parentItem;\n if( parent.column() > 0 )\n return 0;\n\n if( !parent.isValid() )\n parentItem = d->m_rootDocument;\n else\n parentItem = static_cast( parent.internalPointer() );\n\n if( dynamic_cast( parentItem ) ||\n dynamic_cast( parentItem ) )\n {\n return dynamic_cast( parentItem )->features().size();\n }\n \n if( dynamic_cast( parentItem ) )\n {\n \/* there is only one GeoDataGeometry Object per Placemark; if Styles \n * are added later, add them here *\/\n return 1;\n }\n \n if( dynamic_cast( parentItem ) )\n {\n return dynamic_cast( parentItem )->size();\n }\n return 0;\n}\n\nQVariant MarbleGeometryModel::data( const QModelIndex &index, int role ) const\n{\n GeoDataObject *item;\n if( index.isValid() )\n {\n item = static_cast( index.internalPointer() );\n }\n else \/* the rootIndex is invalid *\/\n {\n item = static_cast( d->m_rootDocument );\n }\n\n \/* for now simply give back the type of the GeoDataObject \n * there might be a need to extend this, but usually we want \n *\/\n if( role == Qt::DisplayRole ) {\n if( dynamic_cast( item ) ) {\n switch( dynamic_cast( item )->featureId() ) {\n case InvalidFeatureId:\n return QVariant( \"InvalidFeature\" );\n case GeoDataDocumentId:\n return QVariant( \"GeoDataDocument\" );\n case GeoDataFolderId:\n return QVariant( \"GeoDataFolder\" );\n case GeoDataPlacemarkId:\n return QVariant( \"GeoDataPlacemark\" );\n case GeoDataNetworkLinkId:\n return QVariant( \"GeoDataNetworkLink\" );\n case GeoDataScreenOverlayId:\n return QVariant( \"GeoDataScreenOverlay\" );\n case GeoDataGroundOverlayId:\n return QVariant( \"GeoDataGroundOverlay\" );\n }\n }\n if( dynamic_cast( item ) ) {\n switch( dynamic_cast( item )->geometryId() ) {\n case InvalidGeometryId:\n return QVariant( \"InvalidGeometry\" );\n case GeoDataMultiGeometryId:\n return QVariant( \"GeoDataMultiGeometry\" );\n case GeoDataLineStringId:\n return QVariant( \"GeoDataLineString\" );\n case GeoDataLinearRingId:\n return QVariant( \"GeoDataLinearRing\" );\n case GeoDataPolygonId:\n return QVariant( \"GeoDataPolygon\" );\n case GeoDataPointId:\n return QVariant( \"GeoDataPoint\" );\n }\n }\n }\n\n if( role == Qt::UserRole + 11 ) \/\/equivalent to MarblePlacemarkModel::ObjectPointerRole\n {\n \/* return the pointer item as a QVariant of (meta-)type\n * Marble::GeoDataObject* *\/\n QVariant v;\n v.setValue( item );\n return v;\n }\n\n return QVariant( \"GeoDataObject\" ); \n \/* TODO the data is hardcoded and very limited right now,\n * the logic what data is returned might be moved to the items\n * themselves later. Use the following code then:\n * return item->data( index.column() ); *\/\n\n}\n\nQModelIndex MarbleGeometryModel::index( int row, int column, const QModelIndex &parent ) const\n{\n if ( !hasIndex( row, column, parent ) )\n return QModelIndex();\n \n GeoDataObject *parentItem;\n \n if ( !parent.isValid() )\n parentItem = d->m_rootDocument;\n else\n parentItem = static_cast( parent.internalPointer() );\n\n GeoDataObject *childItem = 0;\n\n \/* go down into GeoDataContainers *\/\n if( dynamic_cast( parentItem ) || \n dynamic_cast( parentItem ) )\n {\n *childItem = dynamic_cast( \n parentItem )->features().at( row );\n }\n\n if( dynamic_cast( parentItem ) )\n {\n \/* as said above - if you add styles, please check for the row over here *\/\n childItem = dynamic_cast( parentItem )->geometry();\n }\n \n if( dynamic_cast( parentItem ) )\n {\n *childItem = dynamic_cast( parentItem )->at( row );\n }\n\n if ( childItem )\n return createIndex( row, column, childItem );\n else\n return QModelIndex();\n}\n\nQModelIndex MarbleGeometryModel::parent( const QModelIndex &index ) const\n{\n if ( !index.isValid() )\n return QModelIndex();\n\n GeoDataObject *childItem = static_cast( index.internalPointer() );\n GeoDataObject *parentItem = d->m_parent[ childItem ];\n\n if ( parentItem == d->m_rootDocument )\n return QModelIndex();\n\n if( parentItem == 0 ){\n \/* this shouldn't happen *\/\n return QModelIndex();\n }\n\n \/* for now leave that as 0, 0 -> this needs some more thoughts as \n * it is simply wrong *\/\n return createIndex( 0, 0, parentItem );\n}\n\nint MarbleGeometryModel::columnCount( const QModelIndex &node ) const\n{\n if ( node.isValid() )\n return 1;\n \/* TODO when nodes handle their information themselves they will have\n * varying amounts of properties ( or columns ). Right now we only have\n * one information ( type ) per node, so it's hardcoded to \"1\".\n * static_cast( node.internalPointer() )->columnCount(); *\/\n else\n return 1;\n}\n\nvoid MarbleGeometryModel::update()\n{\n QAbstractItemModel::reset();\n}\n\n#include \"MarbleGeometryModel.moc\"\n<|endoftext|>"} {"text":"\/\/\n\/\/ This file is part of the Marble Virtual Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2008 Henry de Valence \n\/\/ Copyright 2010 Dennis Nienhüser \n\n#include \"MarbleRunnerManager.h\"\n\n#include \"MarblePlacemarkModel.h\"\n#include \"MarbleDebug.h\"\n#include \"MarbleModel.h\"\n#include \"Planet.h\"\n#include \"GeoDataPlacemark.h\"\n#include \"PluginManager.h\"\n#include \"RunnerPlugin.h\"\n#include \"RunnerTask.h\"\n#include \"routing\/RouteRequest.h\"\n#include \"routing\/RoutingProfilesModel.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace Marble\n{\n\nclass MarbleModel;\n\nclass MarbleRunnerManagerPrivate\n{\npublic:\n MarbleRunnerManager* q;\n QString m_lastSearchTerm;\n QMutex m_modelMutex;\n MarbleModel * m_marbleModel;\n MarblePlacemarkModel *m_model;\n QVector m_placemarkContainer;\n QVector m_routingResult;\n QList m_reverseGeocodingResults;\n RouteRequest* m_routeRequest;\n PluginManager* m_pluginManager;\n\n MarbleRunnerManagerPrivate( MarbleRunnerManager* parent, PluginManager* pluginManager );\n\n ~MarbleRunnerManagerPrivate();\n\n QList plugins( RunnerPlugin::Capability capability );\n\n QList m_searchTasks;\n QList m_routingTasks;\n\n void cleanupSearchTask( RunnerTask* task );\n\n void cleanupRoutingTask( RunnerTask* task );\n};\n\nMarbleRunnerManagerPrivate::MarbleRunnerManagerPrivate( MarbleRunnerManager* parent, PluginManager* pluginManager ) :\n q( parent ),\n m_marbleModel( 0 ),\n m_model( new MarblePlacemarkModel ),\n m_routeRequest( 0 ),\n m_pluginManager( pluginManager )\n{\n m_model->setPlacemarkContainer( &m_placemarkContainer );\n qRegisterMetaType( \"GeoDataPlacemark\" );\n qRegisterMetaType( \"GeoDataCoordinates\" );\n qRegisterMetaType >( \"QVector\" );\n}\n\nMarbleRunnerManagerPrivate::~MarbleRunnerManagerPrivate()\n{\n delete m_model;\n}\n\nQList MarbleRunnerManagerPrivate::plugins( RunnerPlugin::Capability capability )\n{\n QList result;\n QList plugins = m_pluginManager->runnerPlugins();\n foreach( RunnerPlugin* plugin, plugins ) {\n if ( !plugin->supports( capability ) ) {\n continue;\n }\n\n if ( ( m_marbleModel && m_marbleModel->workOffline() && !plugin->canWorkOffline() ) ) {\n continue;\n }\n\n if ( !plugin->canWork( capability ) ) {\n continue;\n }\n\n if ( m_marbleModel && !plugin->supportsCelestialBody( m_marbleModel->planet()->id() ) )\n {\n continue;\n }\n\n result << plugin;\n }\n\n return result;\n}\n\nvoid MarbleRunnerManagerPrivate::cleanupSearchTask( RunnerTask* task )\n{\n m_searchTasks.removeAll( task );\n\n if ( m_searchTasks.isEmpty() ) {\n emit q->searchFinished( m_lastSearchTerm );\n }\n}\n\nvoid MarbleRunnerManagerPrivate::cleanupRoutingTask( RunnerTask* task )\n{\n m_routingTasks.removeAll( task );\n\n if ( m_routingTasks.isEmpty() && m_routingResult.isEmpty() ) {\n emit q->routeRetrieved( 0 );\n }\n}\n\nMarbleRunnerManager::MarbleRunnerManager( PluginManager* pluginManager, QObject *parent )\n : QObject( parent ), d( new MarbleRunnerManagerPrivate( this, pluginManager ) )\n{\n if ( QThreadPool::globalInstance()->maxThreadCount() < 4 ) {\n QThreadPool::globalInstance()->setMaxThreadCount( 4 );\n }\n}\n\nMarbleRunnerManager::~MarbleRunnerManager()\n{\n delete d;\n}\n\nvoid MarbleRunnerManager::reverseGeocoding( const GeoDataCoordinates &coordinates )\n{\n d->m_reverseGeocodingResults.removeAll( coordinates );\n QList plugins = d->plugins( RunnerPlugin::ReverseGeocoding );\n foreach( RunnerPlugin* plugin, plugins ) {\n MarbleAbstractRunner* runner = plugin->newRunner();\n runner->setParent( this );\n connect( runner, SIGNAL( reverseGeocodingFinished( GeoDataCoordinates, GeoDataPlacemark ) ),\n this, SLOT( addReverseGeocodingResult( GeoDataCoordinates, GeoDataPlacemark ) ) );\n runner->setModel( d->m_marbleModel );\n QThreadPool::globalInstance()->start( new ReverseGeocodingTask( runner, coordinates ) );\n }\n\n if ( plugins.isEmpty() ) {\n emit reverseGeocodingFinished( coordinates, GeoDataPlacemark() );\n }\n}\n\nvoid MarbleRunnerManager::findPlacemarks( const QString &searchTerm )\n{\n if ( searchTerm == d->m_lastSearchTerm ) {\n emit searchFinished( searchTerm );\n emit searchResultChanged( d->m_model );\n return;\n }\n\n d->m_lastSearchTerm = searchTerm;\n\n d->m_searchTasks.clear();\n\n d->m_modelMutex.lock();\n d->m_model->removePlacemarks( \"MarbleRunnerManager\", 0, d->m_placemarkContainer.size() );\n qDeleteAll( d->m_placemarkContainer );\n d->m_placemarkContainer.clear();\n d->m_modelMutex.unlock();\n emit searchResultChanged( d->m_model );\n\n QList plugins = d->plugins( RunnerPlugin::Search );\n foreach( RunnerPlugin* plugin, plugins ) {\n MarbleAbstractRunner* runner = plugin->newRunner();\n runner->setParent( this );\n connect( runner, SIGNAL( searchFinished( QVector ) ),\n this, SLOT( addSearchResult( QVector ) ) );\n runner->setModel( d->m_marbleModel );\n SearchTask* task = new SearchTask( runner, searchTerm );\n connect( task, SIGNAL( finished( RunnerTask* ) ), this, SLOT( cleanupSearchTask( RunnerTask* ) ) );\n d->m_searchTasks << task;\n QThreadPool::globalInstance()->start( task );\n }\n}\n\nvoid MarbleRunnerManager::addSearchResult( QVector result )\n{\n mDebug() << \"Runner reports\" << result.size() << \" search results\";\n if( result.isEmpty() )\n return;\n\n d->m_modelMutex.lock();\n int start = d->m_placemarkContainer.size();\n d->m_placemarkContainer << result;\n d->m_model->addPlacemarks( start, result.size() );\n d->m_modelMutex.unlock();\n emit searchResultChanged( d->m_model );\n emit searchResultChanged( d->m_placemarkContainer );\n}\n\nvoid MarbleRunnerManager::setModel( MarbleModel * model )\n{\n \/\/ TODO: Terminate runners which are making use of the map.\n d->m_marbleModel = model;\n}\n\nvoid MarbleRunnerManager::addReverseGeocodingResult( const GeoDataCoordinates &coordinates, const GeoDataPlacemark &placemark )\n{\n if ( !d->m_reverseGeocodingResults.contains( coordinates ) && !placemark.address().isEmpty() ) {\n d->m_reverseGeocodingResults.push_back( coordinates );\n emit reverseGeocodingFinished( coordinates, placemark );\n }\n}\n\nvoid MarbleRunnerManager::retrieveRoute( RouteRequest *request )\n{\n RoutingProfile profile = request->routingProfile();\n\n d->m_routingTasks.clear();\n d->m_routingResult.clear();\n\n d->m_routeRequest = request;\n QList plugins = d->plugins( RunnerPlugin::Routing );\n bool started = false;\n foreach( RunnerPlugin* plugin, plugins ) {\n if ( !profile.name().isEmpty() && !profile.pluginSettings().contains( plugin->nameId() ) ) {\n continue;\n }\n\n started = true;\n MarbleAbstractRunner* runner = plugin->newRunner();\n runner->setParent( this );\n connect( runner, SIGNAL( routeCalculated( GeoDataDocument* ) ),\n this, SLOT( addRoutingResult( GeoDataDocument* ) ) );\n runner->setModel( d->m_marbleModel );\n RoutingTask* task = new RoutingTask( runner, request );\n d->m_routingTasks << task;\n connect( task, SIGNAL( finished( RunnerTask* ) ), this, SLOT( cleanupRoutingTask( RunnerTask* ) ) );\n QThreadPool::globalInstance()->start( task );\n }\n\n if ( !started ) {\n mDebug() << \"No routing plugins found, cannot retrieve a route\";\n d->cleanupRoutingTask( 0 );\n }\n}\n\nvoid MarbleRunnerManager::addRoutingResult( GeoDataDocument* route )\n{\n if ( route ) {\n d->m_routingResult.push_back( route );\n emit routeRetrieved( route );\n }\n}\n\n}\n\n#include \"MarbleRunnerManager.moc\"\nDon't execute empty search queries.\/\/\n\/\/ This file is part of the Marble Virtual Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2008 Henry de Valence \n\/\/ Copyright 2010 Dennis Nienhüser \n\n#include \"MarbleRunnerManager.h\"\n\n#include \"MarblePlacemarkModel.h\"\n#include \"MarbleDebug.h\"\n#include \"MarbleModel.h\"\n#include \"Planet.h\"\n#include \"GeoDataPlacemark.h\"\n#include \"PluginManager.h\"\n#include \"RunnerPlugin.h\"\n#include \"RunnerTask.h\"\n#include \"routing\/RouteRequest.h\"\n#include \"routing\/RoutingProfilesModel.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace Marble\n{\n\nclass MarbleModel;\n\nclass MarbleRunnerManagerPrivate\n{\npublic:\n MarbleRunnerManager* q;\n QString m_lastSearchTerm;\n QMutex m_modelMutex;\n MarbleModel * m_marbleModel;\n MarblePlacemarkModel *m_model;\n QVector m_placemarkContainer;\n QVector m_routingResult;\n QList m_reverseGeocodingResults;\n RouteRequest* m_routeRequest;\n PluginManager* m_pluginManager;\n\n MarbleRunnerManagerPrivate( MarbleRunnerManager* parent, PluginManager* pluginManager );\n\n ~MarbleRunnerManagerPrivate();\n\n QList plugins( RunnerPlugin::Capability capability );\n\n QList m_searchTasks;\n QList m_routingTasks;\n\n void cleanupSearchTask( RunnerTask* task );\n\n void cleanupRoutingTask( RunnerTask* task );\n};\n\nMarbleRunnerManagerPrivate::MarbleRunnerManagerPrivate( MarbleRunnerManager* parent, PluginManager* pluginManager ) :\n q( parent ),\n m_marbleModel( 0 ),\n m_model( new MarblePlacemarkModel ),\n m_routeRequest( 0 ),\n m_pluginManager( pluginManager )\n{\n m_model->setPlacemarkContainer( &m_placemarkContainer );\n qRegisterMetaType( \"GeoDataPlacemark\" );\n qRegisterMetaType( \"GeoDataCoordinates\" );\n qRegisterMetaType >( \"QVector\" );\n}\n\nMarbleRunnerManagerPrivate::~MarbleRunnerManagerPrivate()\n{\n delete m_model;\n}\n\nQList MarbleRunnerManagerPrivate::plugins( RunnerPlugin::Capability capability )\n{\n QList result;\n QList plugins = m_pluginManager->runnerPlugins();\n foreach( RunnerPlugin* plugin, plugins ) {\n if ( !plugin->supports( capability ) ) {\n continue;\n }\n\n if ( ( m_marbleModel && m_marbleModel->workOffline() && !plugin->canWorkOffline() ) ) {\n continue;\n }\n\n if ( !plugin->canWork( capability ) ) {\n continue;\n }\n\n if ( m_marbleModel && !plugin->supportsCelestialBody( m_marbleModel->planet()->id() ) )\n {\n continue;\n }\n\n result << plugin;\n }\n\n return result;\n}\n\nvoid MarbleRunnerManagerPrivate::cleanupSearchTask( RunnerTask* task )\n{\n m_searchTasks.removeAll( task );\n\n if ( m_searchTasks.isEmpty() ) {\n emit q->searchFinished( m_lastSearchTerm );\n }\n}\n\nvoid MarbleRunnerManagerPrivate::cleanupRoutingTask( RunnerTask* task )\n{\n m_routingTasks.removeAll( task );\n\n if ( m_routingTasks.isEmpty() && m_routingResult.isEmpty() ) {\n emit q->routeRetrieved( 0 );\n }\n}\n\nMarbleRunnerManager::MarbleRunnerManager( PluginManager* pluginManager, QObject *parent )\n : QObject( parent ), d( new MarbleRunnerManagerPrivate( this, pluginManager ) )\n{\n if ( QThreadPool::globalInstance()->maxThreadCount() < 4 ) {\n QThreadPool::globalInstance()->setMaxThreadCount( 4 );\n }\n}\n\nMarbleRunnerManager::~MarbleRunnerManager()\n{\n delete d;\n}\n\nvoid MarbleRunnerManager::reverseGeocoding( const GeoDataCoordinates &coordinates )\n{\n d->m_reverseGeocodingResults.removeAll( coordinates );\n QList plugins = d->plugins( RunnerPlugin::ReverseGeocoding );\n foreach( RunnerPlugin* plugin, plugins ) {\n MarbleAbstractRunner* runner = plugin->newRunner();\n runner->setParent( this );\n connect( runner, SIGNAL( reverseGeocodingFinished( GeoDataCoordinates, GeoDataPlacemark ) ),\n this, SLOT( addReverseGeocodingResult( GeoDataCoordinates, GeoDataPlacemark ) ) );\n runner->setModel( d->m_marbleModel );\n QThreadPool::globalInstance()->start( new ReverseGeocodingTask( runner, coordinates ) );\n }\n\n if ( plugins.isEmpty() ) {\n emit reverseGeocodingFinished( coordinates, GeoDataPlacemark() );\n }\n}\n\nvoid MarbleRunnerManager::findPlacemarks( const QString &searchTerm )\n{\n if ( searchTerm == d->m_lastSearchTerm ) {\n emit searchResultChanged( d->m_model );\n emit searchFinished( searchTerm );\n return;\n }\n\n d->m_lastSearchTerm = searchTerm;\n\n d->m_searchTasks.clear();\n\n d->m_modelMutex.lock();\n d->m_model->removePlacemarks( \"MarbleRunnerManager\", 0, d->m_placemarkContainer.size() );\n qDeleteAll( d->m_placemarkContainer );\n d->m_placemarkContainer.clear();\n d->m_modelMutex.unlock();\n emit searchResultChanged( d->m_model );\n\n if ( searchTerm.trimmed().isEmpty() ) {\n emit searchFinished( searchTerm );\n return;\n }\n\n QList plugins = d->plugins( RunnerPlugin::Search );\n foreach( RunnerPlugin* plugin, plugins ) {\n MarbleAbstractRunner* runner = plugin->newRunner();\n runner->setParent( this );\n connect( runner, SIGNAL( searchFinished( QVector ) ),\n this, SLOT( addSearchResult( QVector ) ) );\n runner->setModel( d->m_marbleModel );\n SearchTask* task = new SearchTask( runner, searchTerm );\n connect( task, SIGNAL( finished( RunnerTask* ) ), this, SLOT( cleanupSearchTask( RunnerTask* ) ) );\n d->m_searchTasks << task;\n QThreadPool::globalInstance()->start( task );\n }\n}\n\nvoid MarbleRunnerManager::addSearchResult( QVector result )\n{\n mDebug() << \"Runner reports\" << result.size() << \" search results\";\n if( result.isEmpty() )\n return;\n\n d->m_modelMutex.lock();\n int start = d->m_placemarkContainer.size();\n d->m_placemarkContainer << result;\n d->m_model->addPlacemarks( start, result.size() );\n d->m_modelMutex.unlock();\n emit searchResultChanged( d->m_model );\n emit searchResultChanged( d->m_placemarkContainer );\n}\n\nvoid MarbleRunnerManager::setModel( MarbleModel * model )\n{\n \/\/ TODO: Terminate runners which are making use of the map.\n d->m_marbleModel = model;\n}\n\nvoid MarbleRunnerManager::addReverseGeocodingResult( const GeoDataCoordinates &coordinates, const GeoDataPlacemark &placemark )\n{\n if ( !d->m_reverseGeocodingResults.contains( coordinates ) && !placemark.address().isEmpty() ) {\n d->m_reverseGeocodingResults.push_back( coordinates );\n emit reverseGeocodingFinished( coordinates, placemark );\n }\n}\n\nvoid MarbleRunnerManager::retrieveRoute( RouteRequest *request )\n{\n RoutingProfile profile = request->routingProfile();\n\n d->m_routingTasks.clear();\n d->m_routingResult.clear();\n\n d->m_routeRequest = request;\n QList plugins = d->plugins( RunnerPlugin::Routing );\n bool started = false;\n foreach( RunnerPlugin* plugin, plugins ) {\n if ( !profile.name().isEmpty() && !profile.pluginSettings().contains( plugin->nameId() ) ) {\n continue;\n }\n\n started = true;\n MarbleAbstractRunner* runner = plugin->newRunner();\n runner->setParent( this );\n connect( runner, SIGNAL( routeCalculated( GeoDataDocument* ) ),\n this, SLOT( addRoutingResult( GeoDataDocument* ) ) );\n runner->setModel( d->m_marbleModel );\n RoutingTask* task = new RoutingTask( runner, request );\n d->m_routingTasks << task;\n connect( task, SIGNAL( finished( RunnerTask* ) ), this, SLOT( cleanupRoutingTask( RunnerTask* ) ) );\n QThreadPool::globalInstance()->start( task );\n }\n\n if ( !started ) {\n mDebug() << \"No routing plugins found, cannot retrieve a route\";\n d->cleanupRoutingTask( 0 );\n }\n}\n\nvoid MarbleRunnerManager::addRoutingResult( GeoDataDocument* route )\n{\n if ( route ) {\n d->m_routingResult.push_back( route );\n emit routeRetrieved( route );\n }\n}\n\n}\n\n#include \"MarbleRunnerManager.moc\"\n<|endoftext|>"} {"text":"#ifndef FILE_MYDEFS\n#define FILE_MYDEFS\n\n\/**************************************************************************\/\n\/* File: mydefs.hh *\/\n\/* Author: Joachim Schoeberl *\/\n\/* Date: 10. Mar. 98 *\/\n\/**************************************************************************\/\n\n\/*\n defines for graphics, testmodes, ...\n*\/\n\n\n\/\/ #define DEBUG\n\n\/\/ Philippose - 31\/01\/2009\n\/\/ Hack for the Windows Version\n\/\/ in Linux, \"PACKAGE_VERSION\" is replaced \n\/\/ in the configure\/make phases, with the \n\/\/ right version number\n#ifdef WIN32\n#define PACKAGE_VERSION \"4.9.13\"\n#endif\n\n\n#ifdef WIN32\n #if NGINTERFACE_EXPORTS || NGLIB_EXPORTS || nglib_EXPORTS\n #define DLL_HEADER __declspec(dllexport)\n #else\n #define DLL_HEADER __declspec(dllimport)\n #endif\n#else\n #define DLL_HEADER \n#endif\n\n\n#define noDEMOVERSION\n#define noDEVELOP\n#define noSTEP\n#define noSOLIDGEOM\n\n#define noDEMOAPP\n#define noMODELLER\n\n#define noSTAT_STREAM\n#define noLOG_STREAM\n\n#endif\nwindows version#ifndef FILE_MYDEFS\n#define FILE_MYDEFS\n\n\/**************************************************************************\/\n\/* File: mydefs.hh *\/\n\/* Author: Joachim Schoeberl *\/\n\/* Date: 10. Mar. 98 *\/\n\/**************************************************************************\/\n\n\/*\n defines for graphics, testmodes, ...\n*\/\n\n\n\/\/ #define DEBUG\n\n\/\/ Philippose - 31\/01\/2009\n\/\/ Hack for the Windows Version\n\/\/ in Linux, \"PACKAGE_VERSION\" is replaced \n\/\/ in the configure\/make phases, with the \n\/\/ right version number\n#ifdef WIN32\n#define PACKAGE_VERSION \"4.9.14\"\n#endif\n\n\n#ifdef WIN32\n #if NGINTERFACE_EXPORTS || NGLIB_EXPORTS || nglib_EXPORTS\n #define DLL_HEADER __declspec(dllexport)\n #else\n #define DLL_HEADER __declspec(dllimport)\n #endif\n#else\n #define DLL_HEADER \n#endif\n\n\n#define noDEMOVERSION\n#define noDEVELOP\n#define noSTEP\n#define noSOLIDGEOM\n\n#define noDEMOAPP\n#define noMODELLER\n\n#define noSTAT_STREAM\n#define noLOG_STREAM\n\n#endif\n<|endoftext|>"} {"text":"instance check - bug fixes and refactoring based on code review.<|endoftext|>"} {"text":"Cleanup in Matrix3x3 tests<|endoftext|>"} {"text":"INTEGRATION: CWS fwk29 (1.66.214); FILE MERGED 2006\/01\/02 15:40:00 cd 1.66.214.1: #i58471# Don't disable fontname box when docshell is not available but we have a valid font list<|endoftext|>"} {"text":"INTEGRATION: CWS pages01_DEV300 (1.70.12); FILE MERGED 2008\/02\/26 10:15:20 fme 1.70.12.7: #i1598# Multiple page view - sync with new notes feature 2008\/02\/21 12:43:52 fme 1.70.12.6: RESYNC: (1.71-1.72); FILE MERGED 2008\/01\/10 09:18:38 fme 1.70.12.5: RESYNC: (1.70-1.71); FILE MERGED 2007\/12\/04 15:39:56 fme 1.70.12.4: #i1598# Multiple Page View - Table row\/column selection 2007\/11\/28 16:02:02 fme 1.70.12.3: #i1598# Multiple Page View - RTL 2007\/11\/19 13:11:02 fme 1.70.12.2: #i1598# Multiple page view 2007\/10\/24 15:00:18 fme 1.70.12.1: #i1598# Multiple Page View<|endoftext|>"} {"text":"\/****************************************************************************\n *\n * Copyright (c) 2013 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file Limits.hpp\n *\n * Limiting \/ constrain helper functions\n *\/\n\n#pragma once\n\n#include \n#include \n\n\/\/this should be defined in stdint.h, but seems to be missing in the ARM toolchain (5.2.0)\n#ifndef UINT64_C\n# if __WORDSIZE == 64\n# define UINT64_C(c)\tc ## UL\n# else\n# define UINT64_C(c)\tc ## ULL\n# endif\n#endif\n\n\nnamespace math\n{\n\ntemplate\ninline const _Tp &min(const _Tp &a, const _Tp &b)\n{\n\treturn (a < b) ? a : b;\n}\n\ntemplate\ninline const _Tp &max(const _Tp &a, const _Tp &b)\n{\n\treturn (a > b) ? a : b;\n}\n\ntemplate\ninline const _Tp &constrain(const _Tp &val, const _Tp &min_val, const _Tp &max_val)\n{\n\treturn (val < min_val) ? min_val : ((val > max_val) ? max_val : val);\n}\n\nfloat __EXPORT radians(float degrees);\n\ndouble __EXPORT radians(double degrees);\n\nfloat __EXPORT degrees(float radians);\n\ndouble __EXPORT degrees(double radians);\n\n}\nmathlib : switch min\/max to constexpr to match std::min\/max\/****************************************************************************\n *\n * Copyright (c) 2013 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file Limits.hpp\n *\n * Limiting \/ constrain helper functions\n *\/\n\n#pragma once\n\n#include \n#include \n\n\/\/this should be defined in stdint.h, but seems to be missing in the ARM toolchain (5.2.0)\n#ifndef UINT64_C\n# if __WORDSIZE == 64\n# define UINT64_C(c)\tc ## UL\n# else\n# define UINT64_C(c)\tc ## ULL\n# endif\n#endif\n\n\nnamespace math\n{\n\ntemplate\ninline constexpr const _Tp &min(const _Tp &a, const _Tp &b)\n{\n\treturn (a < b) ? a : b;\n}\n\ntemplate\ninline constexpr const _Tp &max(const _Tp &a, const _Tp &b)\n{\n\treturn (a > b) ? a : b;\n}\n\ntemplate\ninline constexpr const _Tp &constrain(const _Tp &val, const _Tp &min_val, const _Tp &max_val)\n{\n\treturn (val < min_val) ? min_val : ((val > max_val) ? max_val : val);\n}\n\nfloat __EXPORT radians(float degrees);\n\ndouble __EXPORT radians(double degrees);\n\nfloat __EXPORT degrees(float radians);\n\ndouble __EXPORT degrees(double radians);\n\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n\/*\n * INSTRUCTIONS\n *\n * This module builds a simple cmdline program that tells whether words\/phrases\n * match certain criteria. It uses C++11 constructs, but nothing overly\n * mysterious; reasonable familiarity with STL will probably be enough to\n * make you comfortable. You will be extending and debugging the program.\n *\n * 1. Read and understand the basics of the program. Don't worry too much\n * about style; focus on what work gets done, and how.\n * 2. Extend the program so it can test for palindromes (words\/phrases that are\n * the same written forward and backward, like \"noon\" or \"a toyotas a toyota\").\n * 3. Bonus: can you find a latent bug in VowelHeavy::matches_def?\n * 4. Bonus: can you find a latent bug in FirstConsonant::matches_def?\n * 5. Bonus: can you find a bug with security ramifications in main()?\n * 6. Come up with a list of unit tests for specializations of Test. Think of\n * ones that would catch the bugs you've found, as well as others that might\n * be useful.\n*\/\n\n\n\/\/\/ A Test decides whether a string matches the definition of a\n\/\/\/ an interesting category. For example, a Test might tell you if\n\/\/\/ a string is a noun, a palindrome, longer than 10 letters, etc.\nclass Test {\npublic:\n\tvirtual bool matches_def(const string &) const = 0;\n\tvirtual const char * get_name() const = 0;\n};\n\ntypedef unique_ptr TestHandle;\ntypedef vector Tests;\n\n\nstatic bool is_vowel(char c) {\n\treturn strchr(\"aeiouAEIOU\", c) != nullptr;\n}\n\n\nstatic bool is_consonant(char c) {\n\treturn strchr(\"bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ\", c) != nullptr;\n}\n\n\n\/\/ Does a string have more vowels than consonants?\nclass VowelHeavy: public Test {\npublic:\n\tvirtual bool matches_def(const string & x) const {\n\t\tauto vowel_count = 0u;\n\t\tauto consonant_count = 0u;\n\t\tfor (auto c: x) {\n\t\t\tif (is_vowel(c)) {\n\t\t\t\t++vowel_count;\n\t\t\t} else if (is_consonant(c)) {\n\t\t\t\t++consonant_count;\n\t\t\t}\n\t\t}\n\t\treturn vowel_count \/ (float)consonant_count > 1.0;\n\t}\n\tvirtual const char * get_name() const { return \"vowelheavy\"; }\n};\n\n\n\/\/ Does a string begin with a consonant?\nclass FirstConsonant: public Test {\npublic:\n\tvirtual bool matches_def(const string & x) const {\n\t\treturn !x.empty() && !is_vowel(x[0]);\n\t}\n\tvirtual const char * get_name() const { return \"firstcons\"; }\n};\n\n\n\/\/ Show usage for the program\nstatic void show_help(const Tests & tests) {\n\tcout << \"check \";\n\tint i = 0;\n\tfor (auto & test: tests) {\n\t\tif (i++ > 0) {\n\t\t\tcout << '|';\n\t\t}\n\t\tcout << test->get_name();\n\t}\n\tcout << \" word\" << endl;\n}\n\n\nint main(int argc, char ** argv) {\n\tTests tests;\n\ttests.push_back(TestHandle(new VowelHeavy()));\n\ttests.push_back(TestHandle(new FirstConsonant()));\n\tif (argc < 3) {\n\t\tshow_help(tests);\n\t\treturn 1;\n\t}\n\tauto selected_test = argv[1];\n\tauto word = argv[2];\n\tfor (auto & test: tests) {\n\t\tif (strcmp(selected_test, test->get_name()) == 0) {\n\t\t\tcout << (test->matches_def(word) ? \"yes\" : \"no\") << endl;\n\t\t\treturn 0;\n\t\t}\n\t}\n\tcout << \"Huh?\" << endl;\n\treturn 1;\n}\n\nImprove instructions at top of test.#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n\/*\n * INSTRUCTIONS\n *\n * This module builds a simple cmdline program that tells whether words\/phrases\n * match certain criteria. It uses C++11 constructs, but nothing overly\n * mysterious; reasonable familiarity with STL will probably be enough to\n * make you comfortable. You will be extending and debugging the program.\n *\n * 1. Read and understand the basics of the program. Don't worry too much\n * about style; focus on what work gets done, and how.\n * 2. Extend the program so it can test for palindromes (words\/phrases that are\n * the same written forward and backward, like \"noon\" or \"a toyotas a toyota\").\n * 3. Bonus: can you find a latent bug in VowelHeavy::matches_def?\n * 4. Bonus: can you find a latent bug in FirstConsonant::matches_def?\n * 5. Bonus: can you find a bug with security ramifications in main()?\n * 6. Come up with a list of unit tests for specializations of Test. Think of\n * ones that would catch the bugs you've found, as well as others that might\n * be useful. You don't have to code the tests, just describe them.\n*\/\n\n\n\/\/\/ A Test decides whether a string matches the definition of a\n\/\/\/ an interesting category. For example, a Test might tell you if\n\/\/\/ a string is a noun, a palindrome, longer than 10 letters, etc.\nclass Test {\npublic:\n\tvirtual bool matches_def(const string &) const = 0;\n\tvirtual const char * get_name() const = 0;\n};\n\ntypedef unique_ptr TestHandle;\ntypedef vector Tests;\n\n\nstatic bool is_vowel(char c) {\n\treturn strchr(\"aeiouAEIOU\", c) != nullptr;\n}\n\n\nstatic bool is_consonant(char c) {\n\treturn strchr(\"bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ\", c) != nullptr;\n}\n\n\n\/\/ Does a string have more vowels than consonants?\nclass VowelHeavy: public Test {\npublic:\n\tvirtual bool matches_def(const string & x) const {\n\t\tauto vowel_count = 0u;\n\t\tauto consonant_count = 0u;\n\t\tfor (auto c: x) {\n\t\t\tif (is_vowel(c)) {\n\t\t\t\t++vowel_count;\n\t\t\t} else if (is_consonant(c)) {\n\t\t\t\t++consonant_count;\n\t\t\t}\n\t\t}\n\t\treturn vowel_count \/ (float)consonant_count > 1.0;\n\t}\n\tvirtual const char * get_name() const { return \"vowelheavy\"; }\n};\n\n\n\/\/ Does a string begin with a consonant?\nclass FirstConsonant: public Test {\npublic:\n\tvirtual bool matches_def(const string & x) const {\n\t\treturn !x.empty() && !is_vowel(x[0]);\n\t}\n\tvirtual const char * get_name() const { return \"firstcons\"; }\n};\n\n\n\/\/ Show usage for the program\nstatic void show_help(const Tests & tests) {\n\tcout << \"check \";\n\tint i = 0;\n\tfor (auto & test: tests) {\n\t\tif (i++ > 0) {\n\t\t\tcout << '|';\n\t\t}\n\t\tcout << test->get_name();\n\t}\n\tcout << \" word\" << endl;\n}\n\n\nint main(int argc, char ** argv) {\n\tTests tests;\n\ttests.push_back(TestHandle(new VowelHeavy()));\n\ttests.push_back(TestHandle(new FirstConsonant()));\n\tif (argc < 3) {\n\t\tshow_help(tests);\n\t\treturn 1;\n\t}\n\tauto selected_test = argv[1];\n\tauto word = argv[2];\n\tfor (auto & test: tests) {\n\t\tif (strcmp(selected_test, test->get_name()) == 0) {\n\t\t\tcout << (test->matches_def(word) ? \"yes\" : \"no\") << endl;\n\t\t\treturn 0;\n\t\t}\n\t}\n\tcout << \"Huh?\" << endl;\n\treturn 1;\n}\n\n<|endoftext|>"} {"text":"\/*\n * opencog\/atoms\/reduct\/PlusLink.cc\n *\n * Copyright (C) 2015 Linas Vepstas\n * All Rights Reserved\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License v3 as\n * published by the Plus Software Foundation and including the exceptions\n * at http:\/\/opencog.org\/wiki\/Licenses\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program; if not, write to:\n * Plus Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include \n#include \n#include \n#include \"PlusLink.h\"\n#include \"TimesLink.h\"\n\nusing namespace opencog;\n\nPlusLink::PlusLink(const HandleSeq& oset,\n TruthValuePtr tv,\n AttentionValuePtr av)\n : ArithmeticLink(PLUS_LINK, oset, tv, av)\n{\n\tinit();\n}\n\nPlusLink::PlusLink(Type t, const HandleSeq& oset,\n TruthValuePtr tv,\n AttentionValuePtr av)\n : ArithmeticLink(t, oset, tv, av)\n{\n\tif (not classserver().isA(t, PLUS_LINK))\n\t\tthrow InvalidParamException(TRACE_INFO, \"Expecting a PlusLink\");\n\tinit();\n}\n\nPlusLink::PlusLink(Type t, const Handle& a, const Handle& b,\n TruthValuePtr tv,\n AttentionValuePtr av)\n : ArithmeticLink(t, a, b, tv, av)\n{\n\tif (not classserver().isA(t, PLUS_LINK))\n\t\tthrow InvalidParamException(TRACE_INFO, \"Expecting a PlusLink\");\n\tinit();\n}\n\nPlusLink::PlusLink(Link& l)\n : ArithmeticLink(l)\n{\n\tType tscope = l.getType();\n\tif (not classserver().isA(tscope, PLUS_LINK))\n\t\tthrow InvalidParamException(TRACE_INFO, \"Expecting a PlusLink\");\n\tinit();\n}\n\nstatic double plus(double a, double b) { return a+b; }\n\nvoid PlusLink::init(void)\n{\n\tknild = 0.0;\n\tkonsd = plus;\n}\n\n\/\/ ============================================================\n\n\/\/\/ re-order the contents of a PlusLink into \"lexicographic\" order.\n\/\/\/\n\/\/\/ The goal of the re-ordering is to simplify the reduction code,\n\/\/\/ by placing atoms where they are easily found. For now, this\n\/\/\/ means:\n\/\/\/ first, all of the variables,\n\/\/\/ next, all compound expressions,\n\/\/\/ last, all number nodes (of which there should be only zero or one.)\n\/\/\/ We do not currently sort the variables, but maybe we should...?\n\/\/\/ The FoldLink::reduce() method already returns expressions that are\n\/\/\/ almost in the correct order.\nHandle PlusLink::reorder(void)\n{\n\tHandleSeq vars;\n\tHandleSeq exprs;\n\tHandleSeq numbers;\n\n\tfor (const Handle& h : _outgoing)\n\t{\n\t\tif (h->getType() == VARIABLE_NODE)\n\t\t\tvars.push_back(h);\n\t\telse if (h->getType() == NUMBER_NODE)\n\t\t\tnumbers.push_back(h);\n\t\telse\n\t\t\texprs.push_back(h);\n\t}\n\n\tif (1 < numbers.size())\n\t\tthrow RuntimeException(TRACE_INFO,\n\t\t \"Expecting the plus link to have already been reduced!\");\n\n\tHandleSeq result;\n\tfor (const Handle& h : vars) result.push_back(h);\n\tfor (const Handle& h : exprs) result.push_back(h);\n\tfor (const Handle& h : numbers) result.push_back(h);\n\n\treturn Handle(createPlusLink(result));\n}\n\n\/\/ ============================================================\n\n\/\/\/ Handle normalization of addition into multiplication.\n\/\/\/ aka \"mutiplicattive reduction\"\n\/\/\/\n\/\/\/ There are four cases handled here:\n\/\/\/ x+x ==> 2x\n\/\/\/ x + ax ==> (a+1) x\n\/\/\/ ax + x ==> (a+1) x\n\/\/\/ ax + bx ==> (a + b) x\n\/\/\/\nHandle PlusLink::reduce(void)\n{\n\t\/\/ First, let FoldLink do its stuff.\n\tHandle fold = ArithmeticLink::reduce();\n\n\tif (PLUS_LINK != fold->getType()) return fold;\n\n\tPlusLinkPtr pfold(PlusLinkCast(fold));\n\tif (NULL == pfold)\n\t\tpfold = createPlusLink(*LinkCast(fold));\n\tfold = pfold->reorder();\n\n\t\/\/ Now, look for repeated atoms, two atoms that appear twice\n\t\/\/ in the outgoing set. If they do, then can be mutliplied.\n\tLinkPtr lfold(LinkCast(fold));\n\n\tbool do_reduce = false;\n\tHandle reduct = Handle::UNDEFINED;\n\n\tconst HandleSeq& ofs = lfold->getOutgoingSet();\n\tsize_t fsz = ofs.size();\n\tfor (size_t i = 0; i < fsz; i++)\n\t{\n\t\tconst Handle& fi = ofs[i];\n\t\tfor (size_t j=i+1; j < fsz; j++)\n\t\t{\n\t\t\tconst Handle& fj = ofs[j];\n\n\t\t\t\/\/ Is atom in position i identical to atom in position j?\n\t\t\t\/\/ If so, then replace by 2*i\n\t\t\tif (fi == fj)\n\t\t\t{\n\t\t\t\tHandle two(createNumberNode(\"2\"));\n\t\t\t\treduct = Handle(createTimesLink(fi, two));\n\t\t\t\tdo_reduce = true;\n\t\t\t}\n\n\t\t\t\/\/ If j is (TimesLink x a) and i is identical to x,\n\t\t\t\/\/ then create (TimesLink x (a+1))\n\t\t\t\/\/\n\t\t\t\/\/ If j is (TimesLink x a) and i is (TimesLink x b)\n\t\t\t\/\/ then create (TimesLink x (a+b))\n\t\t\t\/\/\n\t\t\telse if (fj->getType() == TIMES_LINK)\n\t\t\t{\n\t\t\t\tbool do_add = false;\n\t\t\t\tHandleSeq rest;\n\n\t\t\t\tLinkPtr ilp = LinkCast(fi);\n\t\t\t\tLinkPtr jlp = LinkCast(fj);\n\t\t\t\tHandle exx = jlp->getOutgoingAtom(0);\n\n\t\t\t\t\/\/ Handle the (a+1) case described above.\n\t\t\t\tif (fi == exx)\n\t\t\t\t{\n\t\t\t\t\tHandle one(createNumberNode(\"1\"));\n\t\t\t\t\trest.push_back(one);\n\t\t\t\t\tdo_add = true;\n\t\t\t\t}\n\n\t\t\t\t\/\/ Handle the (a+b) case described above.\n\t\t\t\telse if (ilp->getOutgoingAtom(0) == exx)\n\t\t\t\t{\n\t\t\t\t\tconst HandleSeq& ilpo = ilp->getOutgoingSet();\n\t\t\t\t\tsize_t ilpsz = ilpo.size();\n\t\t\t\t\tfor (size_t k=1; kgetOutgoingSet();\n\t\t\t\t\tsize_t jlpsz = jlpo.size();\n\t\t\t\t\tfor (size_t k=1; kreduce());\n\n\t\t\t\t\treduct = Handle(createTimesLink(exx, a_plus));\n\t\t\t\t\tdo_reduce = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (do_reduce)\n\t\t\t{\n\t\t\t\tHandleSeq norm;\n\t\t\t\tnorm.push_back(reduct);\n\n\t\t\t\t\/\/ copy everything else, except for i and j.\n\t\t\t\tfor (size_t k = 0; k< fsz; k++)\n\t\t\t\t{\n\t\t\t\t\tif (k == i or k == j) continue;\n\t\t\t\t\tnorm.push_back(ofs[k]);\n\t\t\t\t}\n\n\t\t\t\tPlusLinkPtr plp = createPlusLink(norm);\n\n\t\t\t\tHandle red(plp->reduce());\n\n\t\t\t\t\/\/ Place the result into the same atomspace we are in.\n\t\t\t\t\/\/ XXX this is bad, buggy, uncomfortable, icky: it pollutes\n\t\t\t\t\/\/ the atomspace with intermediate results. This needs to\n\t\t\t\t\/\/ be fixed somehow. Right now, I don't know how.\n\t\t\t\tif (not _atomTable) return red;\n\n\t\t\t\tAtomSpace* as = _atomTable->getAtomSpace();\n\t\t\t\treturn as->addAtom(red);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn fold;\n}\nBug fix unit test\/*\n * opencog\/atoms\/reduct\/PlusLink.cc\n *\n * Copyright (C) 2015 Linas Vepstas\n * All Rights Reserved\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License v3 as\n * published by the Plus Software Foundation and including the exceptions\n * at http:\/\/opencog.org\/wiki\/Licenses\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program; if not, write to:\n * Plus Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include \n#include \n#include \n#include \"PlusLink.h\"\n#include \"TimesLink.h\"\n\nusing namespace opencog;\n\nPlusLink::PlusLink(const HandleSeq& oset,\n TruthValuePtr tv,\n AttentionValuePtr av)\n : ArithmeticLink(PLUS_LINK, oset, tv, av)\n{\n\tinit();\n}\n\nPlusLink::PlusLink(Type t, const HandleSeq& oset,\n TruthValuePtr tv,\n AttentionValuePtr av)\n : ArithmeticLink(t, oset, tv, av)\n{\n\tif (not classserver().isA(t, PLUS_LINK))\n\t\tthrow InvalidParamException(TRACE_INFO, \"Expecting a PlusLink\");\n\tinit();\n}\n\nPlusLink::PlusLink(Type t, const Handle& a, const Handle& b,\n TruthValuePtr tv,\n AttentionValuePtr av)\n : ArithmeticLink(t, a, b, tv, av)\n{\n\tif (not classserver().isA(t, PLUS_LINK))\n\t\tthrow InvalidParamException(TRACE_INFO, \"Expecting a PlusLink\");\n\tinit();\n}\n\nPlusLink::PlusLink(Link& l)\n : ArithmeticLink(l)\n{\n\tType tscope = l.getType();\n\tif (not classserver().isA(tscope, PLUS_LINK))\n\t\tthrow InvalidParamException(TRACE_INFO, \"Expecting a PlusLink\");\n\tinit();\n}\n\nstatic double plus(double a, double b) { return a+b; }\n\nvoid PlusLink::init(void)\n{\n\tknild = 0.0;\n\tkonsd = plus;\n}\n\n\/\/ ============================================================\n\n\/\/\/ re-order the contents of a PlusLink into \"lexicographic\" order.\n\/\/\/\n\/\/\/ The goal of the re-ordering is to simplify the reduction code,\n\/\/\/ by placing atoms where they are easily found. For now, this\n\/\/\/ means:\n\/\/\/ first, all of the variables,\n\/\/\/ next, all compound expressions,\n\/\/\/ last, all number nodes (of which there should be only zero or one.)\n\/\/\/ We do not currently sort the variables, but maybe we should...?\n\/\/\/ The FoldLink::reduce() method already returns expressions that are\n\/\/\/ almost in the correct order.\nHandle PlusLink::reorder(void)\n{\n\tHandleSeq vars;\n\tHandleSeq exprs;\n\tHandleSeq numbers;\n\n\tfor (const Handle& h : _outgoing)\n\t{\n\t\tif (h->getType() == VARIABLE_NODE)\n\t\t\tvars.push_back(h);\n\t\telse if (h->getType() == NUMBER_NODE)\n\t\t\tnumbers.push_back(h);\n\t\telse\n\t\t\texprs.push_back(h);\n\t}\n\n\tif (1 < numbers.size())\n\t\tthrow RuntimeException(TRACE_INFO,\n\t\t \"Expecting the plus link to have already been reduced!\");\n\n\tHandleSeq result;\n\tfor (const Handle& h : vars) result.push_back(h);\n\tfor (const Handle& h : exprs) result.push_back(h);\n\tfor (const Handle& h : numbers) result.push_back(h);\n\n\treturn Handle(createPlusLink(result));\n}\n\n\/\/ ============================================================\n\n\/\/\/ Handle normalization of addition into multiplication.\n\/\/\/ aka \"mutiplicattive reduction\"\n\/\/\/\n\/\/\/ There are four cases handled here:\n\/\/\/ x+x ==> 2x\n\/\/\/ x + ax ==> (a+1) x\n\/\/\/ ax + x ==> (a+1) x\n\/\/\/ ax + bx ==> (a + b) x\n\/\/\/\nHandle PlusLink::reduce(void)\n{\n\t\/\/ First, let FoldLink do its stuff.\n\tHandle fold = ArithmeticLink::reduce();\n\n\tif (PLUS_LINK != fold->getType()) return fold;\n\n\tPlusLinkPtr pfold(PlusLinkCast(fold));\n\tif (NULL == pfold)\n\t\tpfold = createPlusLink(*LinkCast(fold));\n\tfold = pfold->reorder();\n\n\t\/\/ Now, look for repeated atoms, two atoms that appear twice\n\t\/\/ in the outgoing set. If they do, then can be mutliplied.\n\tLinkPtr lfold(LinkCast(fold));\n\n\tbool do_reduce = false;\n\tHandle reduct = Handle::UNDEFINED;\n\n\tconst HandleSeq& ofs = lfold->getOutgoingSet();\n\tsize_t fsz = ofs.size();\n\tfor (size_t i = 0; i < fsz; i++)\n\t{\n\t\tconst Handle& fi = ofs[i];\n\t\tfor (size_t j=i+1; j < fsz; j++)\n\t\t{\n\t\t\tconst Handle& fj = ofs[j];\n\n\t\t\t\/\/ Is atom in position i identical to atom in position j?\n\t\t\t\/\/ If so, then replace by 2*i\n\t\t\tif (fi == fj)\n\t\t\t{\n\t\t\t\tHandle two(createNumberNode(\"2\"));\n\t\t\t\treduct = Handle(createTimesLink(fi, two));\n\t\t\t\tdo_reduce = true;\n\t\t\t}\n\n\t\t\t\/\/ If j is (TimesLink x a) and i is identical to x,\n\t\t\t\/\/ then create (TimesLink x (a+1))\n\t\t\t\/\/\n\t\t\t\/\/ If j is (TimesLink x a) and i is (TimesLink x b)\n\t\t\t\/\/ then create (TimesLink x (a+b))\n\t\t\t\/\/\n\t\t\telse if (fj->getType() == TIMES_LINK)\n\t\t\t{\n\t\t\t\tbool do_add = false;\n\t\t\t\tHandleSeq rest;\n\n\t\t\t\tLinkPtr ilp = LinkCast(fi);\n\t\t\t\tLinkPtr jlp = LinkCast(fj);\n\t\t\t\tHandle exx = jlp->getOutgoingAtom(0);\n\n\t\t\t\t\/\/ Handle the (a+1) case described above.\n\t\t\t\tif (fi == exx)\n\t\t\t\t{\n\t\t\t\t\tHandle one(createNumberNode(\"1\"));\n\t\t\t\t\trest.push_back(one);\n\t\t\t\t\tdo_add = true;\n\t\t\t\t}\n\n\t\t\t\t\/\/ Handle the (a+b) case described above.\n\t\t\t\telse if (ilp->getOutgoingAtom(0) == exx)\n\t\t\t\t{\n\t\t\t\t\tconst HandleSeq& ilpo = ilp->getOutgoingSet();\n\t\t\t\t\tsize_t ilpsz = ilpo.size();\n\t\t\t\t\tfor (size_t k=1; kgetOutgoingSet();\n\t\t\t\t\tsize_t jlpsz = jlpo.size();\n\t\t\t\t\tfor (size_t k=1; kreduce());\n\n\t\t\t\t\treduct = Handle(createTimesLink(exx, a_plus));\n\t\t\t\t\tdo_reduce = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (do_reduce)\n\t\t\t{\n\t\t\t\tHandleSeq norm;\n\t\t\t\tnorm.push_back(reduct);\n\n\t\t\t\t\/\/ copy everything else, except for i and j.\n\t\t\t\tfor (size_t k = 0; k< fsz; k++)\n\t\t\t\t{\n\t\t\t\t\tif (k == i or k == j) continue;\n\t\t\t\t\tnorm.push_back(ofs[k]);\n\t\t\t\t}\n\n\t\t\t\tPlusLinkPtr plp = createPlusLink(norm);\n\n\t\t\t\tHandle red(plp->reduce());\n\n\t\t\t\t\/\/ Place the result into the same atomspace we are in.\n\t\t\t\t\/\/ XXX this is bad, buggy, uncomfortable, icky: it pollutes\n\t\t\t\t\/\/ the atomspace with intermediate results. This needs to\n\t\t\t\t\/\/ be fixed somehow. Right now, I don't know how.\n\t\t\t\tif (not _atomTable) return red;\n\n\t\t\t\tAtomSpace* as = _atomTable->getAtomSpace();\n\t\t\t\treturn as->addAtom(red);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (not _atomTable) return fold;\n\tAtomSpace* as = _atomTable->getAtomSpace();\n\treturn as->addAtom(fold);\n}\n<|endoftext|>"} {"text":"\/*\n *\n * Copyright 2016 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \"test\/cpp\/util\/cli_credentials.h\"\n\n#include \n\nDEFINE_bool(enable_ssl, false, \"Whether to use ssl\/tls.\");\nDEFINE_bool(use_auth, false, \"Whether to create default google credentials.\");\nDEFINE_string(\n access_token, \"\",\n \"The access token that will be sent to the server to authenticate RPCs.\");\nDEFINE_string(\n ssl_target, \"\",\n \"If not empty, treat the server host name as this for ssl\/tls certificate \"\n \"validation.\");\n\nnamespace grpc {\nnamespace testing {\n\nstd::shared_ptr CliCredentials::GetCredentials()\n const {\n if (!FLAGS_access_token.empty()) {\n if (FLAGS_use_auth) {\n fprintf(stderr,\n \"warning: use_auth is ignored when access_token is provided.\");\n }\n\n return grpc::CompositeChannelCredentials(\n grpc::SslCredentials(grpc::SslCredentialsOptions()),\n grpc::AccessTokenCredentials(FLAGS_access_token));\n }\n\n if (FLAGS_use_auth) {\n return grpc::GoogleDefaultCredentials();\n }\n\n if (FLAGS_enable_ssl) {\n return grpc::SslCredentials(grpc::SslCredentialsOptions());\n }\n\n return grpc::InsecureChannelCredentials();\n}\n\nconst grpc::string CliCredentials::GetCredentialUsage() const {\n return \" --enable_ssl ; Set whether to use tls\\n\"\n \" --use_auth ; Set whether to create default google\"\n \" credentials\\n\"\n \" --access_token ; Set the access token in metadata,\"\n \" overrides --use_auth\\n\"\n \" --ssl_target ; Set server host for tls validation\\n\";\n}\n\nconst grpc::string CliCredentials::GetSslTargetNameOverride() const {\n return FLAGS_enable_ssl ? FLAGS_ssl_target : \"\";\n}\n\n} \/\/ namespace testing\n} \/\/ namespace grpc\nGoogleDefaultCredentials use SSL under the covers; include that case.\/*\n *\n * Copyright 2016 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \"test\/cpp\/util\/cli_credentials.h\"\n\n#include \n\nDEFINE_bool(enable_ssl, false, \"Whether to use ssl\/tls.\");\nDEFINE_bool(use_auth, false, \"Whether to create default google credentials.\");\nDEFINE_string(\n access_token, \"\",\n \"The access token that will be sent to the server to authenticate RPCs.\");\nDEFINE_string(\n ssl_target, \"\",\n \"If not empty, treat the server host name as this for ssl\/tls certificate \"\n \"validation.\");\n\nnamespace grpc {\nnamespace testing {\n\nstd::shared_ptr CliCredentials::GetCredentials()\n const {\n if (!FLAGS_access_token.empty()) {\n if (FLAGS_use_auth) {\n fprintf(stderr,\n \"warning: use_auth is ignored when access_token is provided.\");\n }\n\n return grpc::CompositeChannelCredentials(\n grpc::SslCredentials(grpc::SslCredentialsOptions()),\n grpc::AccessTokenCredentials(FLAGS_access_token));\n }\n\n if (FLAGS_use_auth) {\n return grpc::GoogleDefaultCredentials();\n }\n\n if (FLAGS_enable_ssl) {\n return grpc::SslCredentials(grpc::SslCredentialsOptions());\n }\n\n return grpc::InsecureChannelCredentials();\n}\n\nconst grpc::string CliCredentials::GetCredentialUsage() const {\n return \" --enable_ssl ; Set whether to use tls\\n\"\n \" --use_auth ; Set whether to create default google\"\n \" credentials\\n\"\n \" --access_token ; Set the access token in metadata,\"\n \" overrides --use_auth\\n\"\n \" --ssl_target ; Set server host for tls validation\\n\";\n}\n\nconst grpc::string CliCredentials::GetSslTargetNameOverride() const {\n return (FLAGS_enable_ssl || FLAGS_use_auth) ? FLAGS_ssl_target : \"\";\n}\n\n} \/\/ namespace testing\n} \/\/ namespace grpc\n<|endoftext|>"} {"text":"re-enable cumulative relaxation<|endoftext|>"} {"text":"\/*\n * linked_circular_Queue.hpp\n *\n * Created on: 22-May-2017\n * Author: Anshu\n *\/\n\n#ifndef LINKED_CIRCULAR_QUEUE_HPP_\n#define LINKED_CIRCULAR_QUEUE_HPP_\n\n#include \"link_node.h\"\n\ntemplate\nclass LinkedCircularQueue {\nprivate:\n\tNode* head;\n\tNode* tail;\n\tunsigned int size_t;\n\n\tinline void range_check(void) const;\n\npublic:\n\n\tLinkedCircularQueue(void);\n\n\tLinkedCircularQueue(const LinkedCircularQueue& other);\n\n\tvirtual ~LinkedCircularQueue(void);\n\n\tvoid offer(const T& element);\n\n\tconst T& take(void);\n\n\tinline const T& peek(void) const;\n\n\tinline bool empty(void) const;\n\n\tinline unsigned int size(void) const;\n};\n\ntemplate\nLinkedCircularQueue::LinkedCircularQueue(void) {\n\thead = tail = nullptr;\n\tsize_t = 0;\n}\n\ntemplate\nLinkedCircularQueue::LinkedCircularQueue(\n\t\tconst LinkedCircularQueue& otherQueue) {\n\tNode *node;\n\tif (!otherQueue.empty()) {\n\t\tnode = new Node(otherQueue.head->getData(), nullptr);\n\t\thead = tail = node;\n\t\ttail->setNext(head);\n\n\t\tNode *ptr = otherQueue.head->getNext();\n\t\tfor (; ptr != otherQueue.head; ptr = ptr->getNext()) {\n\t\t\tnode = new Node(ptr->getData(), head);\n\t\t\ttail->setNext(node);\n\t\t\ttail = node;\n\t\t}\n\t}\n\tsize_t = otherQueue.size_t;\n}\n\ntemplate\nLinkedCircularQueue::~LinkedCircularQueue(void) {\n\ttail->setNext(nullptr);\n\tfor (Node *ptr = head; ptr != nullptr;) {\n\t\thead = ptr->getNext();\n\t\tdelete ptr;\n\t\tptr = head;\n\t}\n}\n\ntemplate\ninline unsigned int LinkedCircularQueue::size(void) const {\n\treturn size_t;\n}\n\ntemplate\nvoid LinkedCircularQueue::offer(const T& data) {\n\tNode *node = new Node(data, head);\n\n\tif (size_t == 0) {\n\t\ttail = head = node;\n\t} else {\n\t\ttail->setNext(node);\n\t\ttail = node;\n\t}\n\t++size_t;\n}\n\ntemplate\nconst T& LinkedCircularQueue::take(void) {\n\trange_check();\n\n\tNode *node = head;\n\tT& data = node->getData();\n\tif (size_t == 1) {\n\t\thead = tail = nullptr;\n\t} else {\n\t\thead = node->getNext();\n\t\ttail->setNext(head);\n\t}\n\t--size_t;\n\tdelete node;\n\treturn data;\n}\n\ntemplate\ninline const T& LinkedCircularQueue::peek(void) const {\n\trange_check();\n\treturn head->getData();\n}\n\ntemplate\nbool LinkedCircularQueue::empty(void) const {\n\treturn size_t == 0;\n}\n\ntemplate\ninline void LinkedCircularQueue::range_check(void) const {\n\tif (size_t == 0) {\n\t\tthrow std::logic_error(\"Queue was empty\");\n\t}\n}\n#endif \/* LINKED_CIRCULAR_QUEUE_HPP_ *\/\nAdded circular Queue linked implementation\/*\n * linked_circular_Queue.hpp\n *\n * Created on: 22-May-2017\n * Author: Amit\n *\/\n\n#ifndef LINKED_CIRCULAR_QUEUE_HPP_\n#define LINKED_CIRCULAR_QUEUE_HPP_\n\n#include \"link_node.h\"\n\ntemplate\nclass LinkedCircularQueue {\nprivate:\n\tNode* head;\n\tNode* tail;\n\tunsigned int size_t;\n\n\tinline void range_check(void) const;\n\npublic:\n\n\tLinkedCircularQueue(void);\n\n\tLinkedCircularQueue(const LinkedCircularQueue& other);\n\n\tvirtual ~LinkedCircularQueue(void);\n\n\tvoid offer(const T& element);\n\n\tconst T& take(void);\n\n\tinline const T& peek(void) const;\n\n\tinline bool empty(void) const;\n\n\tinline unsigned int size(void) const;\n};\n\ntemplate\nLinkedCircularQueue::LinkedCircularQueue(void) {\n\thead = tail = nullptr;\n\tsize_t = 0;\n}\n\ntemplate\nLinkedCircularQueue::LinkedCircularQueue(\n\t\tconst LinkedCircularQueue& otherQueue) {\n\tNode *node;\n\tif (!otherQueue.empty()) {\n\t\tnode = new Node(otherQueue.head->getData(), nullptr);\n\t\thead = tail = node;\n\t\ttail->setNext(head);\n\n\t\tNode *ptr = otherQueue.head->getNext();\n\t\tfor (; ptr != otherQueue.head; ptr = ptr->getNext()) {\n\t\t\tnode = new Node(ptr->getData(), head);\n\t\t\ttail->setNext(node);\n\t\t\ttail = node;\n\t\t}\n\t}\n\tsize_t = otherQueue.size_t;\n}\n\ntemplate\nLinkedCircularQueue::~LinkedCircularQueue(void) {\n\ttail->setNext(nullptr);\n\tfor (Node *ptr = head; ptr != nullptr;) {\n\t\thead = ptr->getNext();\n\t\tdelete ptr;\n\t\tptr = head;\n\t}\n}\n\ntemplate\ninline unsigned int LinkedCircularQueue::size(void) const {\n\treturn size_t;\n}\n\ntemplate\nvoid LinkedCircularQueue::offer(const T& data) {\n\tNode *node = new Node(data, head);\n\n\tif (size_t == 0) {\n\t\ttail = head = node;\n\t} else {\n\t\ttail->setNext(node);\n\t\ttail = node;\n\t}\n\t++size_t;\n}\n\ntemplate\nconst T& LinkedCircularQueue::take(void) {\n\trange_check();\n\n\tNode *node = head;\n\tT& data = node->getData();\n\tif (size_t == 1) {\n\t\thead = tail = nullptr;\n\t} else {\n\t\thead = node->getNext();\n\t\ttail->setNext(head);\n\t}\n\t--size_t;\n\tdelete node;\n\treturn data;\n}\n\ntemplate\ninline const T& LinkedCircularQueue::peek(void) const {\n\trange_check();\n\treturn head->getData();\n}\n\ntemplate\nbool LinkedCircularQueue::empty(void) const {\n\treturn size_t == 0;\n}\n\ntemplate\ninline void LinkedCircularQueue::range_check(void) const {\n\tif (size_t == 0) {\n\t\tthrow std::logic_error(\"Queue was empty\");\n\t}\n}\n#endif \/* LINKED_CIRCULAR_QUEUE_HPP_ *\/\n<|endoftext|>"} {"text":"#ifndef __CLITL_HPP__\n#define __CLITL_HPP__\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef UNIX\n#include \n#include \n#include \n#elif WIN32\n#include \n#include \n#endif\n\nnamespace clitl {\n \/* Color class *\/\n enum class color {\n#ifdef UNIX\n DEFAULT = 0,\n BLACK = 0,\n RED = 1,\n GREEN = 2,\n BROWN = 3,\n BLUE = 4,\n MAGENTA = 5,\n CYAN = 6,\n WHITE = 7,\n#elif WIN32\n DEFAULT = 0x7,\n BLACK = 0x0,\n RED = 0x4,\n GREEN = 0x2,\n BROWN = 0x7, \/\/ Worthless\n BLUE = 0x1,\n MAGENTA = 0x7, \/\/ Worthless\n CYAN = 0x9,\n WHITE = 0x7,\n#endif\n };\n\n \/* Basic definitions and containers *\/\n typedef int coord_t;\n \/\/typedef int colornum_t;\n\n template , typename Alloc = std::allocator >\n class basic_cli_object {\n std::pair origin;\n std::pair endpoint;\n std::basic_string str;\n color foreground;\n color background;\n public:\n explicit basic_cli_object(\n const std::pair& origin = std::pair(0, 0),\n const std::pair& endpoint = std::pair(0, 0),\n const std::basic_string& str\n = std::basic_string(),\n const color& foreground = color::WHITE,\n const color& background = color::BLACK)\n : origin(origin), endpoint(endpoint), str(str),\n foreground(foreground), background(background) {}\n\n const basic_cli_object& set_origin(const std::pair& coord)\n {\n origin = coord;\n return *this;\n }\n\n const basic_cli_object& set_endpoint(const std::pair& coord)\n {\n endpoint = coord;\n return *this;\n }\n\n const basic_cli_object& set_string(const std::basic_string& stri)\n {\n str = stri;\n return *this;\n }\n\n const basic_cli_object& set_foreground(const color& foreg)\n {\n foreground = foreg;\n return *this;\n }\n\n const basic_cli_object& set_background(const color& backg)\n {\n background = backg;\n return *this;\n }\n\n const std::pair& get_origin() const\n {\n return origin;\n }\n\n const std::pair& get_endpoint() const\n {\n return endpoint;\n }\n\n const std::basic_string& get_string() const\n {\n return str;\n }\n\n const color& get_foreground() const\n {\n return foreground;\n }\n\n const color& get_background() const\n {\n return background;\n }\n };\n\n template , typename Alloc = std::allocator >\n class rect : public basic_cli_object {\n public:\n explicit rect(\n const std::pair& origin = std::pair(0, 0),\n const std::pair& endpoint = std::pair(0, 0),\n const color& background = color::WHITE)\n : basic_cli_object(origin, endpoint,\n std::basic_string(\" \"), color::DEFAULT, background) {}\n };\n\n template , typename Alloc = std::allocator >\n class coloredstring : public basic_cli_object {\n public:\n explicit coloredstring(\n const std::pair& origin = std::pair(0, 0),\n const std::pair& endpoint = std::pair(0, 0),\n const std::basic_string& str\n = std::basic_string(),\n const color& foreground = clitl::color::WHITE,\n const color& background = clitl::color::BLACK)\n : basic_cli_object(\n origin, endpoint, str, foreground, background) {}\n explicit coloredstring(\n const std::basic_string& str\n = std::basic_string(),\n const color& foreground = clitl::color::WHITE,\n const color& background = clitl::color::BLACK)\n : basic_cli_object(\n std::pair(0, 0), std::pair(0, 0),\n str, foreground, background) {}\n };\n\n \/* Output buffer *\/\n template >\n class basic_outbuf : public std::basic_streambuf {\n protected:\n virtual typename traits::int_type\n overflow(typename traits::int_type c)\n {\n if (std::putchar(c) == EOF) {\n return traits::eof();\n }\n return traits::not_eof(c);\n }\n };\n\n typedef basic_outbuf outbuf;\n typedef basic_outbuf woutbuf;\n\n \/* Output stream *\/\n template >\n class basic_ostream : public std::basic_ostream {\n public:\n#ifdef UNIX\n struct winsize wsize;\n#endif\n#ifdef WIN32\n HANDLE termout_handle;\n CONSOLE_CURSOR_INFO termout_curinfo;\n CONSOLE_SCREEN_BUFFER_INFO termout_sbufinfo;\n CONSOLE_SCREEN_BUFFER_INFO termout_initial_sbufinfo;\n#endif\n explicit basic_ostream(basic_outbuf* sb)\n : std::basic_ostream(sb)\n {\n#ifdef UNIX\n wsize = { 0 };\n#elif WIN32\n termout_handle = GetStdHandle(STD_OUTPUT_HANDLE);\n GetConsoleScreenBufferInfo(termout_handle, &termout_initial_sbufinfo);\n#endif\n }\n\n basic_ostream& movecursor(coord_t xpos, coord_t ypos)\n {\n#ifdef UNIX\n *this << \"\\033[\" << ypos << \";\" << xpos << \"f\";\n#elif WIN32\n COORD pos = { static_cast(xpos) - 1, static_cast(ypos) - 1 };\n SetConsoleCursorPosition(termout_handle, pos);\n#endif\n return *this;\n }\n\n basic_ostream& movecursor(const std::pair& coord)\n {\n movecursor(coord.first, coord.second);\n return *this;\n }\n\n std::pair screensize()\n {\n static coord_t column;\n static coord_t row;\n\n#ifdef UNIX\n column = wsize.ws_col;\n row = wsize.ws_row;\n#elif WIN32\n GetConsoleScreenBufferInfo(termout_handle, &termout_sbufinfo);\n column = static_cast(termout_sbufinfo.dwSize.X);\n row = static_cast(termout_sbufinfo.dwSize.Y);\n#endif\n\n return std::pair(column, row);\n }\n\n basic_ostream& paintmode(color fgd, color bgd)\n {\n#ifdef UNIX\n *this << \"\\033[\"\n << 30 + static_cast(fgd)\n << \";\"\n << 40 + static_cast(bgd)\n << \"m\";\n#elif WIN32\n SetConsoleTextAttribute(this->termout_handle,\n static_cast(static_cast(fgd)\n + 0x10 * static_cast(bgd)));\n#endif\n return *this;\n }\n\n basic_ostream& paintmode(nullptr_t nullp)\n {\n \/\/ Recovery mode\n#ifdef UNIX\n os << \"\\033[0m\";\n#elif WIN32\n SetConsoleTextAttribute(termout_handle, termout_initial_sbufinfo.wAttributes);\n#endif\n return *this;\n }\n\n basic_ostream& operator<<\n (basic_ostream& (*op)(basic_ostream&))\n {\n return (*op)(*this);\n }\n };\n\n typedef basic_ostream ostream;\n typedef basic_ostream wostream;\n\n template \n basic_ostream& alternative_system_screenbuffer(basic_ostream& os)\n {\n#if UNIX\n os << \"\\033[?1049h\"; \/\/ Use alternate screen buffer\n#endif\n return os;\n }\n\n template \n basic_ostream& clear(basic_ostream& os)\n {\n#ifdef UNIX\n os << \"\\033[2J\";\n#elif WIN32\n COORD startpoint = { 0, 0 };\n DWORD dw;\n\n GetConsoleScreenBufferInfo(os.termout_handle, &os.termout_sbufinfo);\n FillConsoleOutputCharacterA(os.termout_handle, ' ',\n os.termout_sbufinfo.dwSize.X * os.termout_sbufinfo.dwSize.Y,\n startpoint, &dw);\n FillConsoleOutputAttribute(os.termout_handle,\n FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE,\n os.termout_sbufinfo.dwSize.X * os.termout_sbufinfo.dwSize.Y,\n startpoint, &dw);\n#endif\n return os;\n }\n\n template \n basic_ostream& hide_cursor(basic_ostream& os)\n {\n#ifdef UNIX\n os << \"\\033[?25l\"; \/\/ Hide cursor\n#elif WIN32\n GetConsoleCursorInfo(os.termout_handle, &os.termout_curinfo);\n os.termout_curinfo.bVisible = 0;\n SetConsoleCursorInfo(os.termout_handle, &os.termout_curinfo);\n#endif\n return os;\n }\n\n template \n basic_ostream& normal_system_screenbuffer(basic_ostream& os)\n {\n#if UNIX\n os << \"\\033[?1049l\"; \/\/ Use normal screen buffer\n#endif\n return os;\n }\n\n template \n basic_ostream& refresh(basic_ostream& os)\n {\n std::fflush(stdout);\n return os;\n }\n\n template \n basic_ostream& show_cursor(basic_ostream& os)\n {\n#if UNIX\n os << \"\\033[?25h\"; \/\/ Show cursor\n#elif WIN32\n CONSOLE_CURSOR_INFO termout_curinfo;\n GetConsoleCursorInfo(os.termout_handle, &termout_curinfo);\n termout_curinfo.bVisible = 1;\n SetConsoleCursorInfo(os.termout_handle, &termout_curinfo);\n#endif\n return os;\n }\n\n template \n basic_ostream& pre_process(basic_ostream& os)\n {\n os << alternative_system_screenbuffer;\n os << hide_cursor;\n os << clear;\n return os;\n }\n\n template \n basic_ostream& post_process(basic_ostream& os)\n {\n os.paintmode(color::WHITE, color::BLACK);\n os << clear;\n os << show_cursor;\n os.movecursor(1, 1);\n os.paintmode(nullptr);\n os << normal_system_screenbuffer;\n return os;\n }\n\n template \n basic_ostream& operator<<\n (basic_ostream& os,\n const coloredstring& cs)\n {\n os.paintmode(cs.get_foreground(), cs.get_background());\n os << cs.get_string().c_str();\n return os;\n }\n\n template \n basic_ostream& operator<<\n (basic_ostream& os, const rect& re)\n {\n for (int i = re.get_origin().first; i <= re.get_endpoint().first; ++i) {\n for (int j = re.get_origin().second; j <= re.get_endpoint().second; ++j) {\n os.movecursor(i, j);\n os << coloredstring(\n re.get_string(), re.get_foreground(), re.get_background());\n }\n }\n return os;\n }\n\n \/* Input buffer *\/\n\n \/* Input stream *\/\n template >\n class basic_istream : public std::basic_istream {\n \n };\n\n typedef basic_istream istream;\n typedef basic_istream wistream;\n}\n\n#endif\nComplete the prototype of ostream#ifndef __CLITL_HPP__\n#define __CLITL_HPP__\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef UNIX\n#include \n#include \n#include \n#elif WIN32\n#include \n#include \n#endif\n\nnamespace clitl {\n \/* Color class *\/\n enum class color {\n#ifdef UNIX\n DEFAULT = 0,\n BLACK = 0,\n RED = 1,\n GREEN = 2,\n BROWN = 3,\n BLUE = 4,\n MAGENTA = 5,\n CYAN = 6,\n WHITE = 7,\n#elif WIN32\n DEFAULT = 0x7,\n BLACK = 0x0,\n RED = 0x4,\n GREEN = 0x2,\n BROWN = 0x7, \/\/ Worthless\n BLUE = 0x1,\n MAGENTA = 0x7, \/\/ Worthless\n CYAN = 0x9,\n WHITE = 0x7,\n#endif\n };\n\n \/* Basic definitions and containers *\/\n typedef int coord_t;\n \/\/typedef int colornum_t;\n\n template , typename Alloc = std::allocator >\n class basic_cli_object {\n std::pair origin;\n std::pair endpoint;\n std::basic_string str;\n color foreground;\n color background;\n public:\n explicit basic_cli_object(\n const std::pair& origin = std::pair(0, 0),\n const std::pair& endpoint = std::pair(0, 0),\n const std::basic_string& str\n = std::basic_string(),\n const color& foreground = color::WHITE,\n const color& background = color::BLACK)\n : origin(origin), endpoint(endpoint), str(str),\n foreground(foreground), background(background) {}\n\n const basic_cli_object& set_origin(const std::pair& coord)\n {\n origin = coord;\n return *this;\n }\n\n const basic_cli_object& set_endpoint(const std::pair& coord)\n {\n endpoint = coord;\n return *this;\n }\n\n const basic_cli_object& set_string(const std::basic_string& stri)\n {\n str = stri;\n return *this;\n }\n\n const basic_cli_object& set_foreground(const color& foreg)\n {\n foreground = foreg;\n return *this;\n }\n\n const basic_cli_object& set_background(const color& backg)\n {\n background = backg;\n return *this;\n }\n\n const std::pair& get_origin() const\n {\n return origin;\n }\n\n const std::pair& get_endpoint() const\n {\n return endpoint;\n }\n\n const std::basic_string& get_string() const\n {\n return str;\n }\n\n const color& get_foreground() const\n {\n return foreground;\n }\n\n const color& get_background() const\n {\n return background;\n }\n };\n\n template , typename Alloc = std::allocator >\n class rect : public basic_cli_object {\n public:\n explicit rect(\n const std::pair& origin = std::pair(0, 0),\n const std::pair& endpoint = std::pair(0, 0),\n const color& background = color::WHITE)\n : basic_cli_object(origin, endpoint,\n std::basic_string(\" \"), color::DEFAULT, background) {}\n };\n\n template , typename Alloc = std::allocator >\n class coloredstring : public basic_cli_object {\n public:\n explicit coloredstring(\n const std::pair& origin = std::pair(0, 0),\n const std::pair& endpoint = std::pair(0, 0),\n const std::basic_string& str\n = std::basic_string(),\n const color& foreground = clitl::color::WHITE,\n const color& background = clitl::color::BLACK)\n : basic_cli_object(\n origin, endpoint, str, foreground, background) {}\n explicit coloredstring(\n const std::basic_string& str\n = std::basic_string(),\n const color& foreground = clitl::color::WHITE,\n const color& background = clitl::color::BLACK)\n : basic_cli_object(\n std::pair(0, 0), std::pair(0, 0),\n str, foreground, background) {}\n };\n\n \/* Output buffer *\/\n template >\n class basic_outbuf : public std::basic_streambuf {\n protected:\n virtual typename traits::int_type\n overflow(typename traits::int_type c)\n {\n if (std::putchar(c) == EOF) {\n return traits::eof();\n }\n return traits::not_eof(c);\n }\n };\n\n typedef basic_outbuf outbuf;\n typedef basic_outbuf woutbuf;\n\n \/* Output stream *\/\n template >\n class basic_ostream : public std::basic_ostream {\n public:\n#ifdef UNIX\n struct winsize wsize;\n#endif\n#ifdef WIN32\n HANDLE termout_handle;\n CONSOLE_CURSOR_INFO termout_curinfo;\n CONSOLE_SCREEN_BUFFER_INFO termout_sbufinfo;\n CONSOLE_SCREEN_BUFFER_INFO termout_initial_sbufinfo;\n#endif\n explicit basic_ostream(basic_outbuf* sb)\n : std::basic_ostream(sb)\n {\n#ifdef UNIX\n wsize = { 0 };\n#elif WIN32\n termout_handle = GetStdHandle(STD_OUTPUT_HANDLE);\n GetConsoleScreenBufferInfo(termout_handle, &termout_initial_sbufinfo);\n#endif\n }\n\n basic_ostream& movecursor(coord_t xpos, coord_t ypos)\n {\n#ifdef UNIX\n *this << \"\\033[\" << ypos << \";\" << xpos << \"f\";\n#elif WIN32\n COORD pos = { static_cast(xpos) - 1, static_cast(ypos) - 1 };\n SetConsoleCursorPosition(termout_handle, pos);\n#endif\n return *this;\n }\n\n basic_ostream& movecursor(const std::pair& coord)\n {\n movecursor(coord.first, coord.second);\n return *this;\n }\n\n std::pair screensize()\n {\n static coord_t column;\n static coord_t row;\n\n#ifdef UNIX\n column = wsize.ws_col;\n row = wsize.ws_row;\n#elif WIN32\n GetConsoleScreenBufferInfo(termout_handle, &termout_sbufinfo);\n column = static_cast(termout_sbufinfo.dwSize.X);\n row = static_cast(termout_sbufinfo.dwSize.Y);\n#endif\n\n return std::pair(column, row);\n }\n\n basic_ostream& paintmode(color fgd, color bgd)\n {\n#ifdef UNIX\n *this << \"\\033[\"\n << 30 + static_cast(fgd)\n << \";\"\n << 40 + static_cast(bgd)\n << \"m\";\n#elif WIN32\n SetConsoleTextAttribute(this->termout_handle,\n static_cast(static_cast(fgd)\n + 0x10 * static_cast(bgd)));\n#endif\n return *this;\n }\n\n basic_ostream& paintmode(nullptr_t nullp)\n {\n \/\/ Recovery mode\n#ifdef UNIX\n os << \"\\033[0m\";\n#elif WIN32\n SetConsoleTextAttribute(termout_handle, termout_initial_sbufinfo.wAttributes);\n#endif\n return *this;\n }\n\n basic_ostream& operator<<\n (basic_ostream& (*op)(basic_ostream&))\n {\n return (*op)(*this);\n }\n };\n\n typedef basic_ostream ostream;\n typedef basic_ostream wostream;\n\n template \n basic_ostream& alternative_system_screenbuffer(basic_ostream& os)\n {\n#if UNIX\n os << \"\\033[?1049h\"; \/\/ Use alternate screen buffer\n#endif\n return os;\n }\n\n template \n basic_ostream& clear(basic_ostream& os)\n {\n#ifdef UNIX\n os << \"\\033[2J\";\n#elif WIN32\n COORD startpoint = { 0, 0 };\n DWORD dw;\n\n GetConsoleScreenBufferInfo(os.termout_handle, &os.termout_sbufinfo);\n FillConsoleOutputCharacterA(os.termout_handle, ' ',\n os.termout_sbufinfo.dwSize.X * os.termout_sbufinfo.dwSize.Y,\n startpoint, &dw);\n FillConsoleOutputAttribute(os.termout_handle,\n FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE,\n os.termout_sbufinfo.dwSize.X * os.termout_sbufinfo.dwSize.Y,\n startpoint, &dw);\n#endif\n return os;\n }\n\n template \n basic_ostream& hide_cursor(basic_ostream& os)\n {\n#ifdef UNIX\n os << \"\\033[?25l\"; \/\/ Hide cursor\n#elif WIN32\n GetConsoleCursorInfo(os.termout_handle, &os.termout_curinfo);\n os.termout_curinfo.bVisible = 0;\n SetConsoleCursorInfo(os.termout_handle, &os.termout_curinfo);\n#endif\n return os;\n }\n\n template \n basic_ostream& normal_system_screenbuffer(basic_ostream& os)\n {\n#if UNIX\n os << \"\\033[?1049l\"; \/\/ Use normal screen buffer\n#endif\n return os;\n }\n\n template \n basic_ostream& refresh(basic_ostream& os)\n {\n std::fflush(stdout);\n return os;\n }\n\n template \n basic_ostream& show_cursor(basic_ostream& os)\n {\n#if UNIX\n os << \"\\033[?25h\"; \/\/ Show cursor\n#elif WIN32\n GetConsoleCursorInfo(os.termout_handle, &os.termout_curinfo);\n os.termout_curinfo.bVisible = 1;\n SetConsoleCursorInfo(os.termout_handle, &os.termout_curinfo);\n#endif\n return os;\n }\n\n template \n basic_ostream& pre_process(basic_ostream& os)\n {\n os << alternative_system_screenbuffer;\n os << hide_cursor;\n os << clear;\n return os;\n }\n\n template \n basic_ostream& post_process(basic_ostream& os)\n {\n os << clear;\n os << show_cursor;\n os.movecursor(1, 1);\n os.paintmode(nullptr);\n os << normal_system_screenbuffer;\n return os;\n }\n\n template \n basic_ostream& operator<<\n (basic_ostream& os,\n const coloredstring& cs)\n {\n os.paintmode(cs.get_foreground(), cs.get_background());\n os << cs.get_string().c_str();\n return os;\n }\n\n template \n basic_ostream& operator<<\n (basic_ostream& os, const rect& re)\n {\n for (int i = re.get_origin().first; i <= re.get_endpoint().first; ++i) {\n for (int j = re.get_origin().second; j <= re.get_endpoint().second; ++j) {\n os.movecursor(i, j);\n os << coloredstring(\n re.get_string(), re.get_foreground(), re.get_background());\n }\n }\n return os;\n }\n\n \/* Input buffer *\/\n\n \/* Input stream *\/\n \/* Keeping it for further update\n\n template >\n class basic_istream : public std::basic_istream {\n \n };\n\n typedef basic_istream istream;\n typedef basic_istream wistream;\n *\/\n}\n\n#endif\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \"reasoning\/kanade_reasoner.h\"\n\nusing namespace std;\n\nnamespace Tracking {\n\n\/\/\/\/\n\/\/\/\/ class KanadeIlp\n\/\/\/\/\n KanadeIlp::~KanadeIlp() {\n env_.end();\n }\n\n size_t KanadeIlp::add_init_hypothesis(size_t idx, double cost) {\n assert(idx < n_tracklets_);\n x_.add(IloBoolVar( obj_(cost) + c_[n_tracklets_ + idx](1) ));\n n_hypotheses_ += 1;\n return n_hypotheses_ - 1;\n }\n\n size_t KanadeIlp::add_term_hypothesis(size_t idx, double cost) {\n assert(idx < n_tracklets_);\n x_.add(IloBoolVar( obj_(cost) + c_[idx](1) ));\n n_hypotheses_ += 1;\n return n_hypotheses_ - 1;\n }\n\n size_t KanadeIlp::add_trans_hypothesis(size_t from_idx, size_t to_idx, double cost) {\n assert(from_idx < n_tracklets_);\n assert(to_idx < n_tracklets_);\n x_.add(IloBoolVar( obj_(cost) + c_[from_idx](1) + c_[n_tracklets_ + to_idx](1) ));\n n_hypotheses_ += 1;\n return n_hypotheses_ - 1;\n }\n\n size_t KanadeIlp::add_div_hypothesis(size_t from_idx, size_t to_idx1, size_t to_idx2, double cost) {\n assert(from_idx < n_tracklets_);\n assert(to_idx1 < n_tracklets_);\n assert(to_idx2 < n_tracklets_);\n x_.add(IloBoolVar( obj_(cost) + c_[from_idx](1) + c_[n_tracklets_ + to_idx1](1) + c_[n_tracklets_ + to_idx2](1) ));\n n_hypotheses_ += 1;\n return n_hypotheses_ - 1;\n }\n\n size_t KanadeIlp::add_fp_hypothesis(size_t idx, double cost) {\n assert(idx < n_tracklets_);\n x_.add(IloBoolVar( obj_(cost) + c_[idx](1) + c_[n_tracklets_ + idx](1)));\n n_hypotheses_ += 1;\n return n_hypotheses_ - 1;\n }\n\n KanadeIlp& KanadeIlp::solve() {\n \/\/ assemble model\n model_.add(obj_);\n model_.add(x_);\n model_.add(c_);\n\n \/\/ solve\n cplex_.extract(model_);\n if( !cplex_.solve() ) {\n throw runtime_error(\"KanadeIlp::solve(): cplex.solve() failed\");\n }\n env_.out() << \"Kanade solution status = \" << cplex_.getStatus() << \"\\n\";\n env_.out() << \"Kanade objective value: \" << cplex_.getObjValue() << \"\\n\"; \n cplex_.getValues(sol_, x_);\n \/\/env_.out() << \"Kanade solution: \" << sol_ << \"\\n\";\n\n return *this;\n }\n\n size_t KanadeIlp::solution_size() {\n size_t size = static_cast(sol_.getSize());\n assert(size == n_hypotheses_);\n return size;\n }\n \n bool KanadeIlp::hypothesis_is_active( size_t idx ) {\n assert(idx < n_hypotheses_);\n return static_cast(sol_[idx]);\n }\n\n\n\n \/\/\/\/\n \/\/\/\/ class Kanade\n \/\/\/\/\n Kanade::~Kanade() {\n if(ilp_ != NULL) {\n delete ilp_;\n ilp_ = NULL;\n }\n }\n \n void Kanade::formulate( const HypothesesGraph& g ) {\n reset();\n\n \/\/ flase positive hypotheses\n size_t count = 0;\n for(HypothesesGraph::NodeIt n(g); n!=lemon::INVALID; ++n) {\n tracklet_idx_map_[n] = count;\n hyp2type_[count] = FP;\n fp2node_[count] = n;\n ++count;\n }\n vector fp_costs(lemon::countNodes( g ), log(misdetection_rate_));\n \n ilp_ = new KanadeIlp( fp_costs.begin(), fp_costs.end());\n\n for(HypothesesGraph::NodeIt n(g); n!=lemon::INVALID; ++n) {\n add_hypotheses(g, n);\n }\n }\n\n void Kanade::infer() {\n}\n\n void Kanade::conclude( HypothesesGraph& \/*g*\/ ) {\n}\n\n void Kanade::reset() {\n if(ilp_ != NULL) {\n delete ilp_;\n ilp_ = NULL;\n }\n }\n\n Kanade& Kanade::add_hypotheses( const HypothesesGraph& g, const HypothesesGraph::Node& n) {\n double COST = 100.2;\n size_t hyp = 0;\n\n \/\/ init hypothesis\n hyp = ilp_->add_init_hypothesis( tracklet_idx_map_[n], COST ); \n hyp2type_[hyp] = INIT;\n\n \/\/ collect and count outgoing arcs\n vector arcs; \n size_t count = 0;\n for(HypothesesGraph::OutArcIt a(g, n); a != lemon::INVALID; ++a) {\n arcs.push_back(a);\n ++count;\n }\n\n if(count == 0) {\n hyp = ilp_->add_term_hypothesis(tracklet_idx_map_[n], COST );\n hyp2type_[hyp] = TERM;\n } else if(count == 1) {\n hyp = ilp_->add_term_hypothesis( tracklet_idx_map_[n], COST );\n hyp2type_[hyp] = TERM;\n \n hyp = ilp_->add_trans_hypothesis( tracklet_idx_map_[n], tracklet_idx_map_[g.target(arcs[0])], COST);\n hyp2type_[hyp] = TRANS;\n trans2arc_[hyp] = arcs[0];\n } else {\n hyp = ilp_->add_term_hypothesis( tracklet_idx_map_[n], COST );\n hyp2type_[hyp] = TERM;\n \n \/\/ translation hypotheses\n for(size_t i = 0; i < count; ++i) {\n\thyp = ilp_->add_trans_hypothesis( tracklet_idx_map_[n], tracklet_idx_map_[g.target(arcs[i])], COST);\n\thyp2type_[hyp] = TRANS;\n\ttrans2arc_[hyp] = arcs[i];\n }\n\n \/\/ division hypotheses\n for(size_t i = 0; i < count - 1; ++i) {\n\tfor(size_t j = i; j < count; ++j) {\n\t hyp = ilp_->add_div_hypothesis( tracklet_idx_map_[n], \n\t\t\t\t tracklet_idx_map_[g.target(arcs[i])],\n\t\t\t\t tracklet_idx_map_[g.target(arcs[j])],\n\t\t\t\t COST);\n\t hyp2type_[hyp] = DIV;\n\t div2arcs_[hyp] = pair(arcs[i], arcs[j]);\n\t}\n }\n }\n\n return *this;\n }\n\n} \/* namespace Tracking *\/ \nimplemented Kanade::conclude()#include \n#include \n#include \n#include \n#include \"reasoning\/kanade_reasoner.h\"\n\nusing namespace std;\n\nnamespace Tracking {\n\n\/\/\/\/\n\/\/\/\/ class KanadeIlp\n\/\/\/\/\n KanadeIlp::~KanadeIlp() {\n env_.end();\n }\n\n size_t KanadeIlp::add_init_hypothesis(size_t idx, double cost) {\n assert(idx < n_tracklets_);\n x_.add(IloBoolVar( obj_(cost) + c_[n_tracklets_ + idx](1) ));\n n_hypotheses_ += 1;\n return n_hypotheses_ - 1;\n }\n\n size_t KanadeIlp::add_term_hypothesis(size_t idx, double cost) {\n assert(idx < n_tracklets_);\n x_.add(IloBoolVar( obj_(cost) + c_[idx](1) ));\n n_hypotheses_ += 1;\n return n_hypotheses_ - 1;\n }\n\n size_t KanadeIlp::add_trans_hypothesis(size_t from_idx, size_t to_idx, double cost) {\n assert(from_idx < n_tracklets_);\n assert(to_idx < n_tracklets_);\n x_.add(IloBoolVar( obj_(cost) + c_[from_idx](1) + c_[n_tracklets_ + to_idx](1) ));\n n_hypotheses_ += 1;\n return n_hypotheses_ - 1;\n }\n\n size_t KanadeIlp::add_div_hypothesis(size_t from_idx, size_t to_idx1, size_t to_idx2, double cost) {\n assert(from_idx < n_tracklets_);\n assert(to_idx1 < n_tracklets_);\n assert(to_idx2 < n_tracklets_);\n x_.add(IloBoolVar( obj_(cost) + c_[from_idx](1) + c_[n_tracklets_ + to_idx1](1) + c_[n_tracklets_ + to_idx2](1) ));\n n_hypotheses_ += 1;\n return n_hypotheses_ - 1;\n }\n\n size_t KanadeIlp::add_fp_hypothesis(size_t idx, double cost) {\n assert(idx < n_tracklets_);\n x_.add(IloBoolVar( obj_(cost) + c_[idx](1) + c_[n_tracklets_ + idx](1)));\n n_hypotheses_ += 1;\n return n_hypotheses_ - 1;\n }\n\n KanadeIlp& KanadeIlp::solve() {\n \/\/ assemble model\n model_.add(obj_);\n model_.add(x_);\n model_.add(c_);\n\n \/\/ solve\n cplex_.extract(model_);\n if( !cplex_.solve() ) {\n throw runtime_error(\"KanadeIlp::solve(): cplex.solve() failed\");\n }\n env_.out() << \"Kanade solution status = \" << cplex_.getStatus() << \"\\n\";\n env_.out() << \"Kanade objective value: \" << cplex_.getObjValue() << \"\\n\"; \n cplex_.getValues(sol_, x_);\n \/\/env_.out() << \"Kanade solution: \" << sol_ << \"\\n\";\n\n return *this;\n }\n\n size_t KanadeIlp::solution_size() {\n size_t size = static_cast(sol_.getSize());\n assert(size == n_hypotheses_);\n return size;\n }\n \n bool KanadeIlp::hypothesis_is_active( size_t idx ) {\n assert(idx < n_hypotheses_);\n return static_cast(sol_[idx]);\n }\n\n\n\n \/\/\/\/\n \/\/\/\/ class Kanade\n \/\/\/\/\n Kanade::~Kanade() {\n if(ilp_ != NULL) {\n delete ilp_;\n ilp_ = NULL;\n }\n }\n \n void Kanade::formulate( const HypothesesGraph& g ) {\n reset();\n\n \/\/ flase positive hypotheses\n size_t count = 0;\n for(HypothesesGraph::NodeIt n(g); n!=lemon::INVALID; ++n) {\n tracklet_idx_map_[n] = count;\n hyp2type_[count] = FP;\n fp2node_[count] = n;\n ++count;\n }\n vector fp_costs(lemon::countNodes( g ), log(misdetection_rate_));\n \n ilp_ = new KanadeIlp( fp_costs.begin(), fp_costs.end());\n\n for(HypothesesGraph::NodeIt n(g); n!=lemon::INVALID; ++n) {\n add_hypotheses(g, n);\n }\n }\n\n void Kanade::infer() {\n ilp_->solve();\n }\n\n void Kanade::conclude( HypothesesGraph& g ) {\n \/\/ add active property to graph and init nodes\/arcs as active\/inactive\n g.add(node_active()).add(arc_active());\n property_map::type& active_nodes = g.get(node_active());\n property_map::type& active_arcs = g.get(arc_active());\n\n for(HypothesesGraph::NodeIt n(g); n!=lemon::INVALID; ++n) {\n active_nodes.set(n, true);\n }\n for(HypothesesGraph::ArcIt a(g); a!=lemon::INVALID; ++a) {\n active_arcs.set(a, false);\n }\n\n\n \/\/ go thru all hyps\n for(size_t hyp = 0; hyp < ilp_->solution_size(); ++hyp) {\n if(ilp_->hypothesis_is_active( hyp )) {\n\t \/\/ mark corresponding nodes\/arcs as active\n\t switch( hyp2type_[hyp] ) {\n\t case TERM:\n\t \/\/ do nothing, because all arcs are inactive by default\n\t break;\n\t case INIT:\n\t \/\/ do nothing, because all arcs are inactive by default\n\t break;\n\t case TRANS:\n\t active_arcs.set(trans2arc_[hyp], true); \n\t break;\n\t case DIV:\n\t active_arcs.set(div2arcs_[hyp].first, true);\n\t active_arcs.set(div2arcs_[hyp].second, true);\n\t break;\n\t case FP:\n\t active_nodes.set(fp2node_[hyp], false);\n\t break;\n\t default:\n\t throw runtime_error(\"Kanade::conclude(): unknown hypothesis type\");\n\t break;\n\t }\n\t}\n }\n }\n\n void Kanade::reset() {\n if(ilp_ != NULL) {\n delete ilp_;\n ilp_ = NULL;\n }\n\n tracklet_idx_map_.clear();\n hyp2type_.clear();\n fp2node_.clear();\n trans2arc_.clear();\n div2arcs_.clear();\n }\n\n Kanade& Kanade::add_hypotheses( const HypothesesGraph& g, const HypothesesGraph::Node& n) {\n double COST = 100.2;\n size_t hyp = 0;\n\n \/\/ init hypothesis\n hyp = ilp_->add_init_hypothesis( tracklet_idx_map_[n], COST ); \n hyp2type_[hyp] = INIT;\n\n \/\/ collect and count outgoing arcs\n vector arcs; \n size_t count = 0;\n for(HypothesesGraph::OutArcIt a(g, n); a != lemon::INVALID; ++a) {\n arcs.push_back(a);\n ++count;\n }\n\n if(count == 0) {\n hyp = ilp_->add_term_hypothesis(tracklet_idx_map_[n], COST );\n hyp2type_[hyp] = TERM;\n } else if(count == 1) {\n hyp = ilp_->add_term_hypothesis( tracklet_idx_map_[n], COST );\n hyp2type_[hyp] = TERM;\n \n hyp = ilp_->add_trans_hypothesis( tracklet_idx_map_[n], tracklet_idx_map_[g.target(arcs[0])], COST);\n hyp2type_[hyp] = TRANS;\n trans2arc_[hyp] = arcs[0];\n } else {\n hyp = ilp_->add_term_hypothesis( tracklet_idx_map_[n], COST );\n hyp2type_[hyp] = TERM;\n \n \/\/ translation hypotheses\n for(size_t i = 0; i < count; ++i) {\n\thyp = ilp_->add_trans_hypothesis( tracklet_idx_map_[n], tracklet_idx_map_[g.target(arcs[i])], COST);\n\thyp2type_[hyp] = TRANS;\n\ttrans2arc_[hyp] = arcs[i];\n }\n\n \/\/ division hypotheses\n for(size_t i = 0; i < count - 1; ++i) {\n\tfor(size_t j = i; j < count; ++j) {\n\t hyp = ilp_->add_div_hypothesis( tracklet_idx_map_[n], \n\t\t\t\t tracklet_idx_map_[g.target(arcs[i])],\n\t\t\t\t tracklet_idx_map_[g.target(arcs[j])],\n\t\t\t\t COST);\n\t hyp2type_[hyp] = DIV;\n\t div2arcs_[hyp] = pair(arcs[i], arcs[j]);\n\t}\n }\n }\n\n return *this;\n }\n\n} \/* namespace Tracking *\/ \n<|endoftext|>"} {"text":"\/\/ Copyright 2015 The Bazel Authors. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#if defined(__FreeBSD__)\n# define HAVE_EXTATTR\n# define HAVE_SYSCTLBYNAME\n#elif defined(__OpenBSD__)\n\/\/ No sys\/extattr.h or sysctlbyname on this platform.\n#else\n# error This BSD is not supported\n#endif\n\n#include \"src\/main\/native\/unix_jni.h\"\n\n#include \n#include \n#include \n#include \n#include \n#if defined(HAVE_EXTATTR)\n# include \n#endif\n#include \n#include \n#include \n#include \n\n#include \n\nnamespace blaze_jni {\n\nusing std::string;\n\n\/\/ See unix_jni.h.\nstring ErrorMessage(int error_number) {\n char buf[1024] = \"\";\n if (strerror_r(error_number, buf, sizeof buf) < 0) {\n snprintf(buf, sizeof buf, \"strerror_r(%d): errno %d\", error_number, errno);\n }\n\n return string(buf);\n}\n\nint portable_fstatat(int dirfd, char *name, portable_stat_struct *statbuf,\n int flags) {\n return fstatat(dirfd, name, statbuf, flags);\n}\n\nint StatSeconds(const portable_stat_struct &statbuf, StatTimes t) {\n switch (t) {\n case STAT_ATIME:\n return statbuf.st_atime;\n case STAT_CTIME:\n return statbuf.st_ctime;\n case STAT_MTIME:\n return statbuf.st_mtime;\n default:\n CHECK(false);\n }\n}\n\nint StatNanoSeconds(const portable_stat_struct &statbuf, StatTimes t) {\n switch (t) {\n case STAT_ATIME:\n return statbuf.st_atimespec.tv_nsec;\n case STAT_CTIME:\n return statbuf.st_ctimespec.tv_nsec;\n case STAT_MTIME:\n return statbuf.st_mtimespec.tv_nsec;\n default:\n CHECK(false);\n }\n}\n\nssize_t portable_getxattr(const char *path, const char *name, void *value,\n size_t size, bool *attr_not_found) {\n#if (HAVE_EXTATTR)\n ssize_t result =\n extattr_get_file(path, EXTATTR_NAMESPACE_SYSTEM, name, value, size);\n *attr_not_found = (errno == ENOATTR);\n return result;\n#else\n *attr_not_found = true;\n return -1;\n#endif\n}\n\nssize_t portable_lgetxattr(const char *path, const char *name, void *value,\n size_t size, bool *attr_not_found) {\n#if (HAVE_EXTATTR)\n ssize_t result =\n extattr_get_link(path, EXTATTR_NAMESPACE_SYSTEM, name, value, size);\n *attr_not_found = (errno == ENOATTR);\n return result;\n#else\n *attr_not_found = true;\n return -1;\n#endif\n}\n\nint portable_sysctlbyname(const char *name_chars, long *mibp, size_t *sizep) {\n#if (HAVE_SYSCTLBYNAME)\n return sysctlbyname(name_chars, mibp, sizep, NULL, 0);\n#else\n errno = ENOSYS;\n return -1;\n#endif\n}\n\nint portable_push_disable_sleep() {\n \/\/ Currently not supported.\n \/\/ https:\/\/wiki.freebsd.org\/SuspendResume\n return -1;\n}\n\nint portable_pop_disable_sleep() {\n \/\/ Currently not supported.\n \/\/ https:\/\/wiki.freebsd.org\/SuspendResume\n return -1;\n}\n\nint portable_suspend_count() {\n \/\/ Currently not implemented.\n return 0;\n}\n\nint portable_memory_pressure_warning_count() {\n \/\/ Currently not implemented.\n return 0;\n}\n\nint portable_memory_pressure_critical_count() {\n \/\/ Currently not implemented.\n return 0;\n}\n\n} \/\/ namespace blaze_jni\nUn-break the build on FreeBSD and OpenBSD.\/\/ Copyright 2015 The Bazel Authors. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#if defined(__FreeBSD__)\n# define HAVE_EXTATTR\n# define HAVE_SYSCTLBYNAME\n#elif defined(__OpenBSD__)\n\/\/ No sys\/extattr.h or sysctlbyname on this platform.\n#else\n# error This BSD is not supported\n#endif\n\n#include \"src\/main\/native\/unix_jni.h\"\n\n#include \n#include \n#include \n#include \n#include \n#if defined(HAVE_EXTATTR)\n# include \n#endif\n#include \n#include \n#include \n#include \n\n#include \n\nnamespace blaze_jni {\n\nusing std::string;\n\n\/\/ See unix_jni.h.\nstring ErrorMessage(int error_number) {\n char buf[1024] = \"\";\n if (strerror_r(error_number, buf, sizeof buf) < 0) {\n snprintf(buf, sizeof buf, \"strerror_r(%d): errno %d\", error_number, errno);\n }\n\n return string(buf);\n}\n\nint portable_fstatat(int dirfd, char *name, portable_stat_struct *statbuf,\n int flags) {\n return fstatat(dirfd, name, statbuf, flags);\n}\n\nint StatSeconds(const portable_stat_struct &statbuf, StatTimes t) {\n switch (t) {\n case STAT_ATIME:\n return statbuf.st_atime;\n case STAT_CTIME:\n return statbuf.st_ctime;\n case STAT_MTIME:\n return statbuf.st_mtime;\n default:\n CHECK(false);\n }\n}\n\nint StatNanoSeconds(const portable_stat_struct &statbuf, StatTimes t) {\n switch (t) {\n case STAT_ATIME:\n return statbuf.st_atimespec.tv_nsec;\n case STAT_CTIME:\n return statbuf.st_ctimespec.tv_nsec;\n case STAT_MTIME:\n return statbuf.st_mtimespec.tv_nsec;\n default:\n CHECK(false);\n }\n}\n\nssize_t portable_getxattr(const char *path, const char *name, void *value,\n size_t size, bool *attr_not_found) {\n#if defined(HAVE_EXTATTR)\n ssize_t result =\n extattr_get_file(path, EXTATTR_NAMESPACE_SYSTEM, name, value, size);\n *attr_not_found = (errno == ENOATTR);\n return result;\n#else\n *attr_not_found = true;\n return -1;\n#endif\n}\n\nssize_t portable_lgetxattr(const char *path, const char *name, void *value,\n size_t size, bool *attr_not_found) {\n#if defined(HAVE_EXTATTR)\n ssize_t result =\n extattr_get_link(path, EXTATTR_NAMESPACE_SYSTEM, name, value, size);\n *attr_not_found = (errno == ENOATTR);\n return result;\n#else\n *attr_not_found = true;\n return -1;\n#endif\n}\n\nint portable_sysctlbyname(const char *name_chars, long *mibp, size_t *sizep) {\n#if defined(HAVE_SYSCTLBYNAME)\n return sysctlbyname(name_chars, mibp, sizep, NULL, 0);\n#else\n errno = ENOSYS;\n return -1;\n#endif\n}\n\nint portable_push_disable_sleep() {\n \/\/ Currently not supported.\n \/\/ https:\/\/wiki.freebsd.org\/SuspendResume\n return -1;\n}\n\nint portable_pop_disable_sleep() {\n \/\/ Currently not supported.\n \/\/ https:\/\/wiki.freebsd.org\/SuspendResume\n return -1;\n}\n\nint portable_suspend_count() {\n \/\/ Currently not implemented.\n return 0;\n}\n\nint portable_memory_pressure_warning_count() {\n \/\/ Currently not implemented.\n return 0;\n}\n\nint portable_memory_pressure_critical_count() {\n \/\/ Currently not implemented.\n return 0;\n}\n\n} \/\/ namespace blaze_jni\n<|endoftext|>"} {"text":"Minor formatting edit.<|endoftext|>"} {"text":"client: fix logger deregistration<|endoftext|>"} {"text":"Using alias instead of typedef<|endoftext|>"} {"text":"fix lazy_entry stream out operator to not leave the stream in hexadecimal mode<|endoftext|>"} {"text":"Set new node id in notify() to enable caching to work properly. Fix by pederb.<|endoftext|>"} {"text":"added header inclusion for exit() in Malloc.hh<|endoftext|>"} {"text":"\n#ifndef __COMMON_HPP__\n#define __COMMON_HPP__\n\n\/\/\/ Disable copy constructor and assignment operator.\n\/\/\/ Put this in your class' private declarations.\n\/\/\/ (from google public C++ coding standards)\n#define DISALLOW_COPY_AND_ASSIGN( Name )\t\\\n Name( const Name & );\t\t\t\t\\\n void operator=( const Name & )\n\n\/\/\/ Sign extension.\n\/\/\/ From Stanford bit-twiddling hacks.\ntemplate \ninline T signextend(const T x)\n{\n struct {T x:B;} s;\n return s.x = x;\n}\n\n\/\/\/ Base 2 log of 32-bit number.\n\/\/\/ Modified from Stanford bit twiddling hacks.\ninline unsigned int log2( unsigned int v ) {\n register unsigned int r; \/\/ result of log2(v) will go here\n register unsigned int shift;\n\n r = (v > 0xFFFF) << 4; v >>= r;\n shift = (v > 0xFF ) << 3; v >>= shift; r |= shift;\n shift = (v > 0xF ) << 2; v >>= shift; r |= shift;\n shift = (v > 0x3 ) << 1; v >>= shift; r |= shift;\n r |= (v >> 1);\n\n return r;\n}\n\n\/\/\/ Read 64-bit timestamp counter.\n#define rdtscll(val) do {\t\t\t\t\t\\\n unsigned int __a,__d;\t\t\t\t\t\\\n asm volatile(\"rdtsc\" : \"=a\" (__a), \"=d\" (__d));\t\t\\\n (val) = ((unsigned long)__a) | (((unsigned long)__d)<<32);\t\\\n } while(0)\n\n#endif\nAdd magic identity function for resolving template function pointers in template functions\n#ifndef __COMMON_HPP__\n#define __COMMON_HPP__\n\n\/\/\/ Disable copy constructor and assignment operator.\n\/\/\/ Put this in your class' private declarations.\n\/\/\/ (from google public C++ coding standards)\n#define DISALLOW_COPY_AND_ASSIGN( Name )\t\\\n Name( const Name & );\t\t\t\t\\\n void operator=( const Name & )\n\n\/\/\/ Sign extension.\n\/\/\/ From Stanford bit-twiddling hacks.\ntemplate \ninline T signextend(const T x)\n{\n struct {T x:B;} s;\n return s.x = x;\n}\n\n\/\/\/ Base 2 log of 32-bit number.\n\/\/\/ Modified from Stanford bit twiddling hacks.\ninline unsigned int log2( unsigned int v ) {\n register unsigned int r; \/\/ result of log2(v) will go here\n register unsigned int shift;\n\n r = (v > 0xFFFF) << 4; v >>= r;\n shift = (v > 0xFF ) << 3; v >>= shift; r |= shift;\n shift = (v > 0xF ) << 2; v >>= shift; r |= shift;\n shift = (v > 0x3 ) << 1; v >>= shift; r |= shift;\n r |= (v >> 1);\n\n return r;\n}\n\n\/\/\/ Read 64-bit timestamp counter.\n#define rdtscll(val) do {\t\t\t\t\t\\\n unsigned int __a,__d;\t\t\t\t\t\\\n asm volatile(\"rdtsc\" : \"=a\" (__a), \"=d\" (__d));\t\t\\\n (val) = ((unsigned long)__a) | (((unsigned long)__d)<<32);\t\\\n } while(0)\n\n\/\/\/ OMGWTFBBQ SoftXMT magic identity function\n\/\/\/ Use this to get a pointer to a template function inside a template function, etc.\ntemplate< typename T >\nT * SoftXMT_magic_identity_function(T * t) {\n return t;\n}\n\n#endif\n<|endoftext|>"} {"text":"\/** \\copyright\n * Copyright (c) 2013, Stuart W Baker\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * \n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * \\file NMRAnetVelocity.hxx\n * This file provides an implementation of velocity in NMRAnet terms.\n *\n * @author Stuart W. Baker\n * @date 2 August 2013\n *\/\n\n#ifndef _NMRAnetVelocity_hxx_\n#define _NMRAnetVelocity_hxx_\n\n#include \n#include \n\n#include \"utils\/macros.h\"\n\nextern \"C\" {\n\/* These come from the ieeehalfprecision.c *\/\nint singles2halfp(void *target, void *source, int numel);\nint halfp2singles(void *target, void *source, int numel);\n}\n\n\/** Conversion factor for MPH. 1 mph = this many m\/s. *\/\n#define MPH_FACTOR 0.44704f\n\n\/** This type represents how velocity is seen on the wire (16 bit float).\n *\/\ntypedef uint16_t float16_t;\n\nnamespace NMRAnet\n{\n\n\/** This class provides a mechanism for working with velocity in different\n * forms. A single precision floating point value is used internally to store\n * velocity, but this class provides the ability to easily work with\n * different velocity formats including DCC 14\/28\/128 speed step formats.\n * NMRAnet velocity is represented as a floating point meters\/sec. The sign\n * represents direction where negative is reverse and positive is forward.\n * Sign is always preserved even when the result is 0. For example,\n * -7.0 + 7.0 = -0.0 and 7.0 - 7.0 = +0.0 Be careful thought, per the C\n * standards, a negative zero (-.0.0) velocity compared to constant 0.0 will\n * compare true. Always use @ref direction() when trying to determine the\n * sign or direction of travel.\n *\/\nclass Velocity\n{\npublic:\n \/** define an enumeration for direction\n *\/\n enum\n {\n FORWARD = 0, \/**< forward direction *\/\n POSITIVE = 0, \/**< forward direction *\/\n REVERSE = 1, \/**< reverse direction *\/\n NEGATIVE = 1, \/**< reverse direction *\/\n };\n\n \/** Default constructor.\n *\/\n Velocity()\n : velocity(0)\n {\n }\n\n \/** Basic constructor.\n * @param value starting value for Velocity.\n *\/\n Velocity(int value)\n : velocity(value)\n {\n }\n\n \/** Basic constructor.\n * @param value starting value for Velocity.\n *\/\n Velocity(unsigned int value)\n : velocity(value)\n {\n }\n\n \/** Basic constructor.\n * @param value starting value for Velocity.\n *\/\n Velocity(float value)\n : velocity(value)\n {\n }\n\n \/** Basic constructor.\n * @param value starting value for Velocity.\n *\/\n Velocity(double value)\n : velocity(value)\n {\n }\n\n \/** Constructor that takes the 16 bit wire format\n * @param value starting value for Velocity as IEEE half precision float.\n *\/\n Velocity(float16_t value)\n : velocity(halfp2singles(&velocity, &value, 1))\n {\n }\n\n \/** Copy constructor. *\/\n Velocity(const Velocity& old_velocity)\n : velocity(old_velocity.velocity)\n {\n }\n\n \/** Destructor does nothing. *\/\n ~Velocity() {}\n\n \/** Return the speed independent of direction.\n * @return speed absolute value of velocity\n *\/\n float speed()\n {\n return fabsf(velocity);\n }\n\n \/** Return the direction independent of speed.\n * @return direction FORWARD or REVERSE\n *\/\n int direction()\n {\n if (std::signbit(velocity))\n {\n return REVERSE;\n }\n return FORWARD;\n }\n \n void set_direction(int direction)\n {\n switch (direction)\n {\n case FORWARD:\n forward();\n break;\n case REVERSE:\n reverse();\n break;\n default:\n DIE(\"Unexpected direction value\");\n }\n }\n\n \/** Set the direction to forward. *\/\n void forward()\n {\n if (std::signbit(velocity))\n {\n velocity = -velocity;\n }\n }\n \n \/** Set the direction to reverse. *\/\n void reverse()\n {\n if (!std::signbit(velocity))\n {\n velocity = -velocity;\n }\n }\n \n \/** Convert the native meters\/sec representation into mile per hour.\n * @return velocity represented as miles per hour\n *\/\n float mph()\n {\n return zero_adjust(velocity \/ MPH_FACTOR, velocity);\n }\n\n \/** Sets the speed value from a given mph value. The sign of the mph value\n * is ignored. *\/\n void set_mph(float mph)\n {\n velocity = std::copysign(mph * MPH_FACTOR, velocity);\n }\n \n \/** Get the speed in DCC 128 speed step format.\n * The mapping from meters\/sec is strait forward. First convert to\n * miles\/hour, then each speed step represents 1 mile\/hour. Saturate at\n * 126 miles\/hour.\n *\n * bit 7: direction\n * bits 6..0: 0 = stopped, 1 = estop, 2 - 127 = speed steps 1 - 126\n * @return DCC encoded speed steps\n *\/\n uint8_t get_dcc_128();\n\n \/** Set the speed from DCC 128 speed step format.\n * The mapping from meters\/sec is strait forward. First convert to\n * miles\/hour, then each speed step represents 1 mile\/hour. Saturate at\n * 126 miles\/hour.\n *\n * @param value bit 7: direction\n * bits 6..0: 0 = stopped, 1 = estop, 2 - 127 = speed steps 1 - 126\n *\/\n void set_dcc_128(uint8_t value);\n \n \/** Get the speed in DCC 28 speed step format.\n * This is a decimation of the 128 speed step mode.\n *\n * bit 7..6: fixed at b'01'\n * bit 5: direction\n * bits 4: speed step least significant bit\n * bits 3..0: speed step significatn bits 4..1\n * @return DCC encoded speed steps\n *\/\n uint8_t get_dcc_28();\n \n \/** Set the speed from DCC 28 speed step format.\n * This is a decimation of the 128 speed step mode.\n *\n * @param value bit 7..6: fixed at b'01'\n * bit 5: direction\n * bits 4: speed step least significant bit\n * bits 3..0: speed step significatn bits 4..1\n *\/\n void set_dcc_28(uint8_t value);\n\n \/** Get the speed in DCC 14 speed step format.\n * This is a decimation of the 128 speed step mode.\n *\n * bit 7..6: fixed at b'01'\n * bit 5: direction\n * bits 4: reserved 0 for headlight\n * bits 3..0: 0 = stopped, 4 - 31 = speed steps 1 - 28 \n * @return DCC encoded speed steps\n *\/\n uint8_t get_dcc_14();\n \n \/** Set the speed from DCC 14 speed step format.\n * This is a decimation of the 128 speed step mode.\n *\n * @param value bit 7..6: fixed at b'01'\n * bit 5: direction\n * bits 4: reserved 0 for headlight\n * bits 3..0: 0 = stopped, 4 - 31 = speed steps 1 - 28 \n *\/\n void set_dcc_14(uint8_t value);\n \n \/** Get a wire version of the velocity.\n * @return IEEE half precision floating point representation of velocity\n *\/\n float16_t get_wire()\n {\n float16_t result;\n singles2halfp(&result, &velocity, 1);\n return result;\n }\n \n \/** Set the value based on the wire version of velocity.\n * @param value IEEE half precision floating point representation of velocity\n *\/\n void set_wire(float16_t value)\n {\n halfp2singles(&velocity, &value, 1);\n }\n\n \/** Overloaded addition operator. *\/\n Velocity operator + (const Velocity& v)\n {\n return Velocity(zero_adjust(velocity + v.velocity,velocity));\n }\n\n \/** Overloaded addition operator. *\/\n Velocity operator + (const float& v)\n {\n return Velocity(zero_adjust(velocity + v,velocity));\n }\n\n \/** Overloaded subtraction operator. *\/\n Velocity operator - (const Velocity& v)\n {\n return Velocity(zero_adjust(velocity - v.velocity,velocity));\n }\n\n \/** Overloaded subtraction operator. *\/\n Velocity operator - (const float& v)\n {\n return Velocity(zero_adjust(velocity - v,velocity));\n }\n\n \/** Overloaded multiplication operator. *\/\n Velocity operator * (const Velocity& v)\n {\n return Velocity(zero_adjust(velocity * v.velocity,velocity));\n }\n\n \/** Overloaded multiplication operator. *\/\n Velocity operator * (const float& v)\n {\n return Velocity(zero_adjust(velocity * v,velocity));\n }\n\n \/** Overloaded division operator. *\/\n Velocity operator \/ (const Velocity& v)\n {\n return Velocity(zero_adjust(velocity \/ v.velocity,velocity));\n }\n\n \/** Overloaded division operator. *\/\n Velocity operator \/ (const float& v)\n {\n return Velocity(zero_adjust(velocity \/ v,velocity));\n }\n\n \/** Overloaded pre-increement operator. *\/\n Velocity& operator ++ ()\n {\n velocity = zero_adjust(velocity + 1,velocity);\n return *this;\n }\n\n \/** Overloaded post-increment operator. *\/\n Velocity operator ++ (int)\n {\n Velocity result(*this);\n velocity = zero_adjust(velocity + 1,velocity);\n return result;\n }\n\n \/** Overloaded pre-decreement operator. *\/\n Velocity& operator -- ()\n {\n velocity = zero_adjust(velocity - 1,velocity);\n return *this;\n }\n\n \/** Overloaded post-decrement operator. *\/\n Velocity operator -- (int)\n {\n Velocity result(*this);\n velocity = zero_adjust(velocity - 1,velocity);\n return result;\n }\n\n \/** Overloaded addition equals operator. *\/\n Velocity& operator += (const Velocity& v)\n {\n velocity = zero_adjust(velocity + v.velocity,velocity);\n return *this;\n }\n\n \/** Overloaded addition equals operator. *\/\n Velocity& operator += (const float& v)\n {\n velocity = zero_adjust(velocity + v,velocity);\n return *this;\n }\n\n \/** Overloaded subtraction equals operator. *\/\n Velocity& operator -= (const Velocity& v)\n {\n velocity = zero_adjust(velocity - v.velocity,velocity);\n return *this;\n }\n\n \/** Overloaded subtraction equals operator. *\/\n Velocity& operator -= (const float& v)\n {\n velocity = zero_adjust(velocity - v,velocity);\n return *this;\n }\n\n \/** Overloaded multiplication equals operator. *\/\n Velocity& operator *= (const Velocity& v)\n {\n velocity = zero_adjust(velocity * v.velocity,velocity);\n return *this;\n }\n\n \/** Overloaded multiplication equals operator. *\/\n Velocity& operator *= (const float& v)\n {\n velocity = zero_adjust(velocity * v,velocity);\n return *this;\n }\n\n \/** Overloaded division equals operator. *\/\n Velocity& operator \/= (const Velocity& v)\n {\n velocity = zero_adjust(velocity \/ v.velocity,velocity);\n return *this;\n }\n\n \/** Overloaded division equals operator. *\/\n Velocity& operator \/= (const float& v)\n {\n velocity = zero_adjust(velocity \/ v,velocity);\n return *this;\n }\n\n \/** Overloaded equals operator. *\/\n Velocity& operator = (const Velocity& v)\n {\n velocity = v.velocity;\n return *this;\n }\n\n \/** Overloaded equals operator. *\/\n Velocity& operator = (const float& v)\n {\n velocity = v;\n return *this;\n }\n\n \/** Overloaded equals equals operator *\/\n bool operator == (const Velocity& v)\n {\n return (v.velocity == velocity);\n }\n \n \/** Overloaded equals equals operator *\/\n bool operator == (const float& v)\n {\n return (v == velocity);\n }\n \n \/** Overloaded not equals operator *\/\n bool operator != (const Velocity& v)\n {\n return (v.velocity != velocity);\n }\n \n \/** Overloaded not equals operator *\/\n bool operator != (const float& v)\n {\n return (v != velocity);\n }\n \nprivate:\n \/** Floating point representation of velocity. *\/\n float velocity;\n \n \/** Adjust for a math result of negative 0.\n * @param value value of math result\n * @param old original value before expression\n *\/\n float zero_adjust(float value, float old)\n {\n if (value == 0)\n {\n return copysign(value, old);\n }\n return value;\n }\n};\n\n\n}; \/* namespace NMRAnet *\/\n\n#endif \/* _NMRAnetVelocity_hxx_ *\/\nmakes mph() return a non-negative value, similar to speed(). Users can always use the direction() function to get the actual direction.\/** \\copyright\n * Copyright (c) 2013, Stuart W Baker\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * \n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * \\file NMRAnetVelocity.hxx\n * This file provides an implementation of velocity in NMRAnet terms.\n *\n * @author Stuart W. Baker\n * @date 2 August 2013\n *\/\n\n#ifndef _NMRAnetVelocity_hxx_\n#define _NMRAnetVelocity_hxx_\n\n#include \n#include \n\n#include \"utils\/macros.h\"\n\nextern \"C\" {\n\/* These come from the ieeehalfprecision.c *\/\nint singles2halfp(void *target, void *source, int numel);\nint halfp2singles(void *target, void *source, int numel);\n}\n\n\/** Conversion factor for MPH. 1 mph = this many m\/s. *\/\n#define MPH_FACTOR 0.44704f\n\n\/** This type represents how velocity is seen on the wire (16 bit float).\n *\/\ntypedef uint16_t float16_t;\n\nnamespace NMRAnet\n{\n\n\/** This class provides a mechanism for working with velocity in different\n * forms. A single precision floating point value is used internally to store\n * velocity, but this class provides the ability to easily work with\n * different velocity formats including DCC 14\/28\/128 speed step formats.\n * NMRAnet velocity is represented as a floating point meters\/sec. The sign\n * represents direction where negative is reverse and positive is forward.\n * Sign is always preserved even when the result is 0. For example,\n * -7.0 + 7.0 = -0.0 and 7.0 - 7.0 = +0.0 Be careful thought, per the C\n * standards, a negative zero (-.0.0) velocity compared to constant 0.0 will\n * compare true. Always use @ref direction() when trying to determine the\n * sign or direction of travel.\n *\/\nclass Velocity\n{\npublic:\n \/** define an enumeration for direction\n *\/\n enum\n {\n FORWARD = 0, \/**< forward direction *\/\n POSITIVE = 0, \/**< forward direction *\/\n REVERSE = 1, \/**< reverse direction *\/\n NEGATIVE = 1, \/**< reverse direction *\/\n };\n\n \/** Default constructor.\n *\/\n Velocity()\n : velocity(0)\n {\n }\n\n \/** Basic constructor.\n * @param value starting value for Velocity.\n *\/\n Velocity(int value)\n : velocity(value)\n {\n }\n\n \/** Basic constructor.\n * @param value starting value for Velocity.\n *\/\n Velocity(unsigned int value)\n : velocity(value)\n {\n }\n\n \/** Basic constructor.\n * @param value starting value for Velocity.\n *\/\n Velocity(float value)\n : velocity(value)\n {\n }\n\n \/** Basic constructor.\n * @param value starting value for Velocity.\n *\/\n Velocity(double value)\n : velocity(value)\n {\n }\n\n \/** Constructor that takes the 16 bit wire format\n * @param value starting value for Velocity as IEEE half precision float.\n *\/\n Velocity(float16_t value)\n : velocity(halfp2singles(&velocity, &value, 1))\n {\n }\n\n \/** Copy constructor. *\/\n Velocity(const Velocity& old_velocity)\n : velocity(old_velocity.velocity)\n {\n }\n\n \/** Destructor does nothing. *\/\n ~Velocity() {}\n\n \/** Return the speed independent of direction.\n * @return speed absolute value of velocity\n *\/\n float speed()\n {\n return fabsf(velocity);\n }\n\n \/** Return the direction independent of speed.\n * @return direction FORWARD or REVERSE\n *\/\n int direction()\n {\n if (std::signbit(velocity))\n {\n return REVERSE;\n }\n return FORWARD;\n }\n \n void set_direction(int direction)\n {\n switch (direction)\n {\n case FORWARD:\n forward();\n break;\n case REVERSE:\n reverse();\n break;\n default:\n DIE(\"Unexpected direction value\");\n }\n }\n\n \/** Set the direction to forward. *\/\n void forward()\n {\n if (std::signbit(velocity))\n {\n velocity = -velocity;\n }\n }\n \n \/** Set the direction to reverse. *\/\n void reverse()\n {\n if (!std::signbit(velocity))\n {\n velocity = -velocity;\n }\n }\n \n \/** Convert the native meters\/sec representation into mile per hour.\n * @return velocity represented as miles per hour. Always non-negative.\n *\/\n float mph()\n {\n return speed() \/ MPH_FACTOR;\n }\n\n \/** Sets the speed value from a given mph value. The sign of the mph value\n * is ignored. *\/\n void set_mph(float mph)\n {\n velocity = std::copysign(mph * MPH_FACTOR, velocity);\n }\n \n \/** Get the speed in DCC 128 speed step format.\n * The mapping from meters\/sec is strait forward. First convert to\n * miles\/hour, then each speed step represents 1 mile\/hour. Saturate at\n * 126 miles\/hour.\n *\n * bit 7: direction\n * bits 6..0: 0 = stopped, 1 = estop, 2 - 127 = speed steps 1 - 126\n * @return DCC encoded speed steps\n *\/\n uint8_t get_dcc_128();\n\n \/** Set the speed from DCC 128 speed step format.\n * The mapping from meters\/sec is strait forward. First convert to\n * miles\/hour, then each speed step represents 1 mile\/hour. Saturate at\n * 126 miles\/hour.\n *\n * @param value bit 7: direction\n * bits 6..0: 0 = stopped, 1 = estop, 2 - 127 = speed steps 1 - 126\n *\/\n void set_dcc_128(uint8_t value);\n \n \/** Get the speed in DCC 28 speed step format.\n * This is a decimation of the 128 speed step mode.\n *\n * bit 7..6: fixed at b'01'\n * bit 5: direction\n * bits 4: speed step least significant bit\n * bits 3..0: speed step significatn bits 4..1\n * @return DCC encoded speed steps\n *\/\n uint8_t get_dcc_28();\n \n \/** Set the speed from DCC 28 speed step format.\n * This is a decimation of the 128 speed step mode.\n *\n * @param value bit 7..6: fixed at b'01'\n * bit 5: direction\n * bits 4: speed step least significant bit\n * bits 3..0: speed step significatn bits 4..1\n *\/\n void set_dcc_28(uint8_t value);\n\n \/** Get the speed in DCC 14 speed step format.\n * This is a decimation of the 128 speed step mode.\n *\n * bit 7..6: fixed at b'01'\n * bit 5: direction\n * bits 4: reserved 0 for headlight\n * bits 3..0: 0 = stopped, 4 - 31 = speed steps 1 - 28 \n * @return DCC encoded speed steps\n *\/\n uint8_t get_dcc_14();\n \n \/** Set the speed from DCC 14 speed step format.\n * This is a decimation of the 128 speed step mode.\n *\n * @param value bit 7..6: fixed at b'01'\n * bit 5: direction\n * bits 4: reserved 0 for headlight\n * bits 3..0: 0 = stopped, 4 - 31 = speed steps 1 - 28 \n *\/\n void set_dcc_14(uint8_t value);\n \n \/** Get a wire version of the velocity.\n * @return IEEE half precision floating point representation of velocity\n *\/\n float16_t get_wire()\n {\n float16_t result;\n singles2halfp(&result, &velocity, 1);\n return result;\n }\n \n \/** Set the value based on the wire version of velocity.\n * @param value IEEE half precision floating point representation of velocity\n *\/\n void set_wire(float16_t value)\n {\n halfp2singles(&velocity, &value, 1);\n }\n\n \/** Overloaded addition operator. *\/\n Velocity operator + (const Velocity& v)\n {\n return Velocity(zero_adjust(velocity + v.velocity,velocity));\n }\n\n \/** Overloaded addition operator. *\/\n Velocity operator + (const float& v)\n {\n return Velocity(zero_adjust(velocity + v,velocity));\n }\n\n \/** Overloaded subtraction operator. *\/\n Velocity operator - (const Velocity& v)\n {\n return Velocity(zero_adjust(velocity - v.velocity,velocity));\n }\n\n \/** Overloaded subtraction operator. *\/\n Velocity operator - (const float& v)\n {\n return Velocity(zero_adjust(velocity - v,velocity));\n }\n\n \/** Overloaded multiplication operator. *\/\n Velocity operator * (const Velocity& v)\n {\n return Velocity(zero_adjust(velocity * v.velocity,velocity));\n }\n\n \/** Overloaded multiplication operator. *\/\n Velocity operator * (const float& v)\n {\n return Velocity(zero_adjust(velocity * v,velocity));\n }\n\n \/** Overloaded division operator. *\/\n Velocity operator \/ (const Velocity& v)\n {\n return Velocity(zero_adjust(velocity \/ v.velocity,velocity));\n }\n\n \/** Overloaded division operator. *\/\n Velocity operator \/ (const float& v)\n {\n return Velocity(zero_adjust(velocity \/ v,velocity));\n }\n\n \/** Overloaded pre-increement operator. *\/\n Velocity& operator ++ ()\n {\n velocity = zero_adjust(velocity + 1,velocity);\n return *this;\n }\n\n \/** Overloaded post-increment operator. *\/\n Velocity operator ++ (int)\n {\n Velocity result(*this);\n velocity = zero_adjust(velocity + 1,velocity);\n return result;\n }\n\n \/** Overloaded pre-decreement operator. *\/\n Velocity& operator -- ()\n {\n velocity = zero_adjust(velocity - 1,velocity);\n return *this;\n }\n\n \/** Overloaded post-decrement operator. *\/\n Velocity operator -- (int)\n {\n Velocity result(*this);\n velocity = zero_adjust(velocity - 1,velocity);\n return result;\n }\n\n \/** Overloaded addition equals operator. *\/\n Velocity& operator += (const Velocity& v)\n {\n velocity = zero_adjust(velocity + v.velocity,velocity);\n return *this;\n }\n\n \/** Overloaded addition equals operator. *\/\n Velocity& operator += (const float& v)\n {\n velocity = zero_adjust(velocity + v,velocity);\n return *this;\n }\n\n \/** Overloaded subtraction equals operator. *\/\n Velocity& operator -= (const Velocity& v)\n {\n velocity = zero_adjust(velocity - v.velocity,velocity);\n return *this;\n }\n\n \/** Overloaded subtraction equals operator. *\/\n Velocity& operator -= (const float& v)\n {\n velocity = zero_adjust(velocity - v,velocity);\n return *this;\n }\n\n \/** Overloaded multiplication equals operator. *\/\n Velocity& operator *= (const Velocity& v)\n {\n velocity = zero_adjust(velocity * v.velocity,velocity);\n return *this;\n }\n\n \/** Overloaded multiplication equals operator. *\/\n Velocity& operator *= (const float& v)\n {\n velocity = zero_adjust(velocity * v,velocity);\n return *this;\n }\n\n \/** Overloaded division equals operator. *\/\n Velocity& operator \/= (const Velocity& v)\n {\n velocity = zero_adjust(velocity \/ v.velocity,velocity);\n return *this;\n }\n\n \/** Overloaded division equals operator. *\/\n Velocity& operator \/= (const float& v)\n {\n velocity = zero_adjust(velocity \/ v,velocity);\n return *this;\n }\n\n \/** Overloaded equals operator. *\/\n Velocity& operator = (const Velocity& v)\n {\n velocity = v.velocity;\n return *this;\n }\n\n \/** Overloaded equals operator. *\/\n Velocity& operator = (const float& v)\n {\n velocity = v;\n return *this;\n }\n\n \/** Overloaded equals equals operator *\/\n bool operator == (const Velocity& v)\n {\n return (v.velocity == velocity);\n }\n \n \/** Overloaded equals equals operator *\/\n bool operator == (const float& v)\n {\n return (v == velocity);\n }\n \n \/** Overloaded not equals operator *\/\n bool operator != (const Velocity& v)\n {\n return (v.velocity != velocity);\n }\n \n \/** Overloaded not equals operator *\/\n bool operator != (const float& v)\n {\n return (v != velocity);\n }\n \nprivate:\n \/** Floating point representation of velocity. *\/\n float velocity;\n \n \/** Adjust for a math result of negative 0.\n * @param value value of math result\n * @param old original value before expression\n *\/\n float zero_adjust(float value, float old)\n {\n if (value == 0)\n {\n return copysign(value, old);\n }\n return value;\n }\n};\n\n\n}; \/* namespace NMRAnet *\/\n\n#endif \/* _NMRAnetVelocity_hxx_ *\/\n<|endoftext|>"} {"text":"\/\/\n\/\/ server.cpp\n\/\/ rdt\n\/\/\n\/\/ Created by Chris Orcutt on 11\/12\/15.\n\/\/ Copyright © 2015 Chris Orcutt. All rights reserved.\n\/\/\n\n#include \"Error.hpp\"\n#include \"GBNServerProtocol.hpp\"\n#include \"Header.hpp\"\n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nvoid * receiveAck(void *);\nvoid sendValidPackets(GBNServerProtocol *);\nvoid resendValidPackets(GBNServerProtocol *);\nvoid sendSynack(GBNServerProtocol *);\n\nint main(int argc, const char ** argv){\n \n\/\/ !! Begin Command Line Argument Parsing !!\n \n if (argc > 10){\n Error::usage();\n }\n \n int port = 45000;\n bool verbose = false;\n bool printSent = false;\n bool printReceived = false;\n int windowSize = 10;\n int timeoutInterval = 2;\n \n for (int index = 0; index < argc; index++){\n\n \/\/indicate port number\n if (strcmp(argv[index], \"--port\") == 0 || strcmp(argv[index], \"-p\") == 0){\n if (index + 1 == argc) {\n Error::usage();\n }\n port = atoi(argv[index + 1]);\n }\n \n \/\/indicate window size\n if (strcmp(argv[index], \"--window\") == 0 || strcmp(argv[index], \"-w\") == 0){\n if (index + 1 == argc) {\n Error::usage();\n }\n windowSize = atoi(argv[index + 1]);\n }\n \n \/\/indicate timeout interval\n if (strcmp(argv[index], \"--timeout\") == 0 || strcmp(argv[index], \"-t\") == 0){\n if (index + 1 == argc) {\n Error::usage();\n }\n timeoutInterval = atoi(argv[index + 1]);\n }\n \n \/\/print all sent data\n if (strcmp(argv[index], \"--print-sent\") == 0 || strcmp(argv[index], \"-ps\") == 0){\n printSent = true;\n }\n \n \/\/print all received data\n if (strcmp(argv[index], \"--print-recv\") == 0 || strcmp(argv[index], \"-pr\") == 0){\n printReceived = true;\n }\n \n \/\/print all data\n if (strcmp(argv[index], \"--print-all\") == 0 || strcmp(argv[index], \"-pa\") == 0){\n printReceived = true;\n printSent = true;\n }\n \n \/\/print server protocol\n if (strcmp(argv[index], \"--verbose\") == 0 || strcmp(argv[index], \"-v\") == 0){\n verbose = true;\n }\n }\n \n\/\/ !! Begin GBN Server Initialization !!\n \n GBNServerProtocol server = GBNServerProtocol(windowSize, timeoutInterval, port);\n server.communicator.printReceieved = printReceived;\n server.communicator.printSent = printSent;\n server.verbose = verbose;\n \n\/\/ !! Begin Handshake !!\n \n if (server.verbose){\n cout << \"Waiting for connection on port \" << server.communicator.socket.port << \".\" << endl;\n }\n \n \/\/waiting for client to request connection\n while (!server.receivedSyn());\n if (server.verbose){\n cout << \"Received: Syn.\" << endl;\n cout << \"Sent: Synack.\" << endl << endl;\n }\n sendSynack(&server);\n \n \/\/wait for synack ack\n pthread_t receiveAckThread;\n if (pthread_create(&receiveAckThread, NULL, receiveAck, &server)) {\n cout << \"Error creating ack thread.\" << endl;\n exit(1);\n }\n \n \/\/resend synack at timeout\n while (server.timeoutTimer.valid){\n if (server.timeoutTimer.elapsedTime() >= server.timeoutInterval){\n if (server.verbose){\n cout << \"Timed out!\" << endl;\n cout << \"Sent: Synack.\" << endl << endl;\n }\n sendSynack(&server);\n }\n }\n \n \/\/join thread when ack received\n if (pthread_join(receiveAckThread, NULL)) {\n cout << \"Error joining ack thread\" << endl;\n exit(1);\n }\n \n\/\/ !! Begin Data Transmission !!\n \n \/\/send data\n while (server.keepAlive && server.currentWindowBase < server.totalChunks ){\n if (server.verbose){\n cout << \"Current window base: \" << server.currentWindowBase << \", Total packets: \" << server.totalChunks << endl << endl;\n }\n server.timeoutTimer.valid = true;\n sendValidPackets(&server);\n \n \/\/wait for ack\n if (pthread_create(&receiveAckThread, NULL, receiveAck, &server)) {\n cout << \"Error creating ack thread\" << endl;\n exit(1);\n }\n \n \/\/resend data at timeout\n while (server.keepAlive && server.timeoutTimer.valid){\n if (server.timeoutTimer.elapsedTime() >= server.timeoutInterval){\n if (server.verbose){\n cout << \"Timed out!\" << endl << \"Resending packets \" << server.currentWindowBase << \" to \" << server.currentWindowBase + server.windowSize - 1 << endl;\n }\n resendValidPackets(&server);\n }\n }\n \n if (!server.keepAlive){\n return 0;\n }\n \n \/\/join thread when ack received\n if (pthread_join(receiveAckThread, NULL)) {\n cout << \"Error joining receive thread\" << endl;\n exit(1);\n }\n }\n \n return 0;\n}\n\n\/\/receives ack in new thread\nvoid * receiveAck(void * aserver){\n GBNServerProtocol * server = (GBNServerProtocol*)aserver;\n while(!server->receivedAck());\n if (server->verbose){\n cout << \"Received: Ack \" << server->receivedAckNum << endl << endl;\n }\n server->currentWindowBase = server->receivedAckNum;\n server->timeoutTimer.stop();\n server->timeoutTimer.valid = false;\n return NULL;\n}\n\n\/\/sends all packets in current window\nvoid resendValidPackets(GBNServerProtocol * server){\n for (int packetNum = server->currentWindowBase; packetNum < server->currentWindowBase + server->windowSize; packetNum++){\n if (packetNum < server->totalChunks){\n if (server->verbose){\n cout << \"Sent: Packet number \" << packetNum << endl;\n }\n server->timeoutTimer.start();\n server->sendData(packetNum);\n }\n }\n if (server->verbose){\n cout << endl;\n }\n}\n\n\/\/TODO: refactorable with resendValidPackets!\nvoid sendValidPackets(GBNServerProtocol * server){\n for (int packetNum = server->currentWindowBase; packetNum < server->currentWindowBase + server->windowSize; packetNum++){\n if (packetNum < server->totalChunks && server->packetState[packetNum] == Unsent){\n if (server->verbose){\n cout << \"Sent: Packet number \" << packetNum << endl;\n }\n server->packetState[packetNum] = Sent;\n server->timeoutTimer.start();\n server->sendData(packetNum);\n }\n }\n if (server->verbose){\n cout << endl;\n }\n}\n\n\/\/sends synack\nvoid sendSynack(GBNServerProtocol * server){\n server->timeoutTimer.start();\n server->sendSynack();\n}\n\n\nUpdate server to recovery from race condition\/\/\n\/\/ server.cpp\n\/\/ rdt\n\/\/\n\/\/ Created by Chris Orcutt on 11\/12\/15.\n\/\/ Copyright © 2015 Chris Orcutt. All rights reserved.\n\/\/\n\n#include \"Error.hpp\"\n#include \"GBNServerProtocol.hpp\"\n#include \"Header.hpp\"\n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nvoid * receiveAck(void *);\nvoid sendValidPackets(GBNServerProtocol *);\nvoid resendValidPackets(GBNServerProtocol *);\nvoid sendSynack(GBNServerProtocol *);\n\nint main(int argc, const char ** argv){\n \n\/\/ !! Begin Command Line Argument Parsing !!\n \n if (argc > 9){\n Error::usage();\n }\n \n int port = 45000;\n bool verbose = false;\n bool printSent = false;\n bool printReceived = false;\n int windowSize = 10;\n int timeoutInterval = 2;\n \n for (int index = 1; index < argc; index++){\n\n \/\/indicate port number\n if (strcmp(argv[index], \"--port\") == 0 || strcmp(argv[index], \"-p\") == 0){\n if (index + 1 == argc) {\n Error::usage();\n }\n port = atoi(argv[index + 1]);\n index++;\n }\n \n \/\/indicate window size\n else if (strcmp(argv[index], \"--window\") == 0 || strcmp(argv[index], \"-w\") == 0){\n if (index + 1 == argc) {\n Error::usage();\n }\n windowSize = atoi(argv[index + 1]);\n index++;\n }\n \n \/\/indicate timeout interval\n else if (strcmp(argv[index], \"--timeout\") == 0 || strcmp(argv[index], \"-t\") == 0){\n if (index + 1 == argc) {\n Error::usage();\n }\n timeoutInterval = atoi(argv[index + 1]);\n index++;\n }\n \n \/\/print all sent data\n else if (strcmp(argv[index], \"--print-sent\") == 0 || strcmp(argv[index], \"-ps\") == 0){\n printSent = true;\n }\n \n \/\/print all received data\n else if (strcmp(argv[index], \"--print-recv\") == 0 || strcmp(argv[index], \"-pr\") == 0){\n printReceived = true;\n }\n \n \/\/print all data\n else if (strcmp(argv[index], \"--print-all\") == 0 || strcmp(argv[index], \"-pa\") == 0){\n printReceived = true;\n printSent = true;\n }\n \n \/\/print server protocol\n else if (strcmp(argv[index], \"--verbose\") == 0 || strcmp(argv[index], \"-v\") == 0){\n verbose = true;\n }else {\n Error::usage();\n Error::exit(-1);\n }\n }\n \n\/\/ !! Begin GBN Server Initialization !!\n \n GBNServerProtocol server = GBNServerProtocol(windowSize, timeoutInterval, port);\n server.communicator.printReceieved = printReceived;\n server.communicator.printSent = printSent;\n server.verbose = verbose;\n \n\/\/ !! Begin Handshake !!\n \n if (server.verbose){\n cout << \"Waiting for connection on port \" << server.communicator.socket.port << \".\" << endl;\n }\n \n \/\/waiting for client to request connection\n while (!server.receivedSyn());\n if (server.verbose){\n cout << \"Received: Syn.\" << endl;\n cout << \"Sent: Synack.\" << endl << endl;\n }\n sendSynack(&server);\n \n \/\/wait for synack ack\n pthread_t receiveSynackThread;\n if (pthread_create(&receiveSynackThread, NULL, receiveAck, &server)) {\n cout << \"Error creating ack thread.\" << endl;\n exit(1);\n }\n \n \/\/resend synack at timeout\n while (server.timeoutTimer.valid){\n if (server.timeoutTimer.elapsedTime() >= server.timeoutInterval){\n if (server.verbose){\n cout << \"Timed out!\" << endl;\n cout << \"Sent: Synack.\" << endl << endl;\n }\n sendSynack(&server);\n }\n }\n \n \/\/join thread when ack received\n if (pthread_join(receiveSynackThread, NULL)) {\n cout << \"Error joining ack thread\" << endl;\n exit(1);\n }\n \n\/\/ !! Begin Data Transmission !!\n \n \/\/send data\n while (server.keepAlive && (server.currentWindowBase < server.totalChunks) ){\n if (server.verbose){\n cout << \"Current window base: \" << server.currentWindowBase << \", Total packets: \" << server.totalChunks << endl;\n }\n server.timeoutTimer.valid = true;\n sendValidPackets(&server);\n \n\n \/\/wait for ack\n pthread_t receiveAckThread;\n if (pthread_create(&receiveAckThread, NULL, receiveAck, &server)) {\n cout << \"Error creating ack thread\" << endl;\n exit(1);\n }\n \n \/\/resend data at timeout\n while (server.keepAlive && server.timeoutTimer.valid){\n if (!server.timeoutTimer.timing){\n server.timeoutTimer.start();\n }\n if (server.timeoutTimer.elapsedTime() >= server.timeoutInterval){\n if (server.verbose){\n cout << \"Timed out!\" << endl << \"Resending packets \" << server.currentWindowBase << \" to \" << server.currentWindowBase + server.windowSize - 1 << endl;\n }\n resendValidPackets(&server);\n }\n }\n \n if (!server.keepAlive){\n return 0;\n }\n \n \/\/join thread when ack received\n if (pthread_join(receiveAckThread, NULL)) {\n cout << \"Error joining receive thread\" << endl;\n exit(1);\n }\n }\n return 0;\n}\n\n\/\/receives ack in new thread\nvoid * receiveAck(void * aserver){\n GBNServerProtocol * server = (GBNServerProtocol*)aserver;\n while(!server->receivedAck());\n if (server->verbose){\n cout << \"Received: Ack \" << server->receivedAckNum << endl;\n }\n server->currentWindowBase = server->receivedAckNum;\n server->timeoutTimer.stop();\n server->timeoutTimer.valid = false;\n return NULL;\n}\n\n\/\/sends all packets in current window\nvoid resendValidPackets(GBNServerProtocol * server){\n for (int packetNum = server->currentWindowBase; packetNum < server->currentWindowBase + server->windowSize; packetNum++){\n if (packetNum < server->totalChunks){\n if (server->verbose){\n cout << \"Sent: Packet number \" << packetNum << endl;\n }\n server->timeoutTimer.start();\n server->sendData(packetNum);\n }\n }\n if (server->verbose){\n cout << endl;\n }\n}\n\n\/\/TODO: refactorable with resendValidPackets!\nvoid sendValidPackets(GBNServerProtocol * server){\n for (int packetNum = server->currentWindowBase; packetNum < server->currentWindowBase + server->windowSize; packetNum++){\n if (packetNum < server->totalChunks && server->packetState[packetNum] == Unsent){\n if (server->verbose){\n cout << \"Sent: Packet number \" << packetNum << endl;\n }\n server->packetState[packetNum] = Sent;\n server->timeoutTimer.start();\n server->sendData(packetNum);\n }\n }\n if (server->verbose){\n cout << endl;\n }\n}\n\n\/\/sends synack\nvoid sendSynack(GBNServerProtocol * server){\n server->timeoutTimer.start();\n server->sendSynack();\n}\n\n\n<|endoftext|>"} {"text":"\/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield \n *\n * This library is open source and may be redistributed and\/or modified under \n * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or \n * (at your option) any later version. The full license is in LICENSE file\n * included with this distribution, and on the openscenegraph.org website.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the \n * OpenSceneGraph Public License for more details.\n*\/\n#include \n#include \n#include \n\n#include \n\n#include \n\n#include \"TriStrip_tri_stripper.h\"\n\nusing namespace osg;\nusing namespace osgUtil;\n\n\/\/ triangle functor.\nstruct TriangleAcumulatorFunctor\n{\n\n triangle_stripper::tri_stripper::indices in_indices;\n const Vec3* _vbase;\n\n TriangleAcumulatorFunctor() : _vbase(0) {}\n \n void setCoords( const Vec3* vbase ) { _vbase = vbase; }\n\n inline void operator() ( const Vec3 &v1, const Vec3 &v2, const Vec3 &v3 )\n {\n int p1 = (int)(&v1-_vbase);\n int p2 = (int)(&v2-_vbase);\n int p3 = (int)(&v3-_vbase);\n if (p1==p2 || p1==p3 || p2==p3) return;\n in_indices.push_back(p1);\n in_indices.push_back(p2);\n in_indices.push_back(p3);\n }\n};\n\nvoid TriStripVisitor::stripify(Geometry& geom)\n{\n\n\n if (geom.getNormalBinding()==osg::Geometry::BIND_PER_PRIMITIVE ||\n geom.getNormalBinding()==osg::Geometry::BIND_PER_PRIMITIVE_SET) return;\n\n if (geom.getColorBinding()==osg::Geometry::BIND_PER_PRIMITIVE ||\n geom.getColorBinding()==osg::Geometry::BIND_PER_PRIMITIVE_SET) return;\n \n if (geom.getSecondaryColorBinding()==osg::Geometry::BIND_PER_PRIMITIVE ||\n geom.getSecondaryColorBinding()==osg::Geometry::BIND_PER_PRIMITIVE_SET) return;\n\n if (geom.getFogCoordBinding()==osg::Geometry::BIND_PER_PRIMITIVE ||\n geom.getFogCoordBinding()==osg::Geometry::BIND_PER_PRIMITIVE_SET) return;\n\n\n\n unsigned int numSurfacePrimitives = 0;\n unsigned int numNonSurfacePrimitives = 0;\n\n Geometry::PrimitiveSetList& primitives = geom.getPrimitiveSetList();\n Geometry::PrimitiveSetList::iterator itr;\n for(itr=primitives.begin();\n itr!=primitives.end();\n ++itr)\n {\n switch((*itr)->getMode())\n {\n case(PrimitiveSet::TRIANGLES):\n case(PrimitiveSet::TRIANGLE_STRIP):\n case(PrimitiveSet::TRIANGLE_FAN):\n case(PrimitiveSet::QUADS):\n case(PrimitiveSet::QUAD_STRIP):\n case(PrimitiveSet::POLYGON):\n ++numSurfacePrimitives;\n break;\n default:\n ++numNonSurfacePrimitives;\n break;\n \n }\n }\n \n if (!numSurfacePrimitives) return;\n \n TriangleFunctor taf;\n\n Geometry::PrimitiveSetList new_primitives;\n new_primitives.reserve(primitives.size());\n\n for(itr=primitives.begin();\n itr!=primitives.end();\n ++itr)\n {\n switch((*itr)->getMode())\n {\n case(PrimitiveSet::TRIANGLES):\n case(PrimitiveSet::TRIANGLE_STRIP):\n case(PrimitiveSet::TRIANGLE_FAN):\n case(PrimitiveSet::QUADS):\n case(PrimitiveSet::QUAD_STRIP):\n case(PrimitiveSet::POLYGON):\n (*itr)->accept(taf);\n break;\n default:\n new_primitives.push_back(*itr);\n break;\n\n }\n }\n \n if (!taf.in_indices.empty())\n {\n int in_numVertices = -1;\n for(triangle_stripper::tri_stripper::indices::iterator itr=taf.in_indices.begin();\n itr!=taf.in_indices.end();\n ++itr)\n {\n if ((int)*itr>in_numVertices) in_numVertices=*itr;\n }\n \/\/ the largest indice is in_numVertices, but indices start at 0\n \/\/ so increment to give to the corrent number of verticies.\n ++in_numVertices; \n\n int in_cacheSize = 16;\n int in_minStripLength = 2;\n\n triangle_stripper::tri_stripper stripifier(taf.in_indices);\n stripifier.SetCacheSize(in_cacheSize);\n stripifier.SetMinStripSize(in_minStripLength);\n\n triangle_stripper::tri_stripper::primitives_vector outPrimitives;\n stripifier.Strip(&outPrimitives);\n\n for(triangle_stripper::tri_stripper::primitives_vector::iterator pitr=outPrimitives.begin();\n pitr!=outPrimitives.end();\n ++pitr)\n {\n osg::DrawElementsUShort* elements = new osg::DrawElementsUShort(pitr->m_Type);\n elements->insert(elements->end(),pitr->m_Indices.begin(),pitr->m_Indices.end());\n new_primitives.push_back(elements);\n }\n\n geom.setPrimitiveSetList(new_primitives);\n }\n}\n\n\nvoid TriStripVisitor::apply(Geode& geode)\n{\n for(unsigned int i = 0; i < geode.getNumDrawables(); ++i )\n {\n osg::Geometry* geom = dynamic_cast(geode.getDrawable(i));\n if (geom) stripify(*geom);\n }\n}\nChanged the template insert(,,) method for a std::copy() implemention as it seems that the Sun Forte compiler can't handle member templates!\/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield \n *\n * This library is open source and may be redistributed and\/or modified under \n * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or \n * (at your option) any later version. The full license is in LICENSE file\n * included with this distribution, and on the openscenegraph.org website.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the \n * OpenSceneGraph Public License for more details.\n*\/\n#include \n#include \n#include \n\n#include \n\n#include \n\n#include \"TriStrip_tri_stripper.h\"\n\nusing namespace osg;\nusing namespace osgUtil;\n\n\/\/ triangle functor.\nstruct TriangleAcumulatorFunctor\n{\n\n triangle_stripper::tri_stripper::indices in_indices;\n const Vec3* _vbase;\n\n TriangleAcumulatorFunctor() : _vbase(0) {}\n \n void setCoords( const Vec3* vbase ) { _vbase = vbase; }\n\n inline void operator() ( const Vec3 &v1, const Vec3 &v2, const Vec3 &v3 )\n {\n int p1 = (int)(&v1-_vbase);\n int p2 = (int)(&v2-_vbase);\n int p3 = (int)(&v3-_vbase);\n if (p1==p2 || p1==p3 || p2==p3) return;\n in_indices.push_back(p1);\n in_indices.push_back(p2);\n in_indices.push_back(p3);\n }\n};\n\nvoid TriStripVisitor::stripify(Geometry& geom)\n{\n\n\n if (geom.getNormalBinding()==osg::Geometry::BIND_PER_PRIMITIVE ||\n geom.getNormalBinding()==osg::Geometry::BIND_PER_PRIMITIVE_SET) return;\n\n if (geom.getColorBinding()==osg::Geometry::BIND_PER_PRIMITIVE ||\n geom.getColorBinding()==osg::Geometry::BIND_PER_PRIMITIVE_SET) return;\n \n if (geom.getSecondaryColorBinding()==osg::Geometry::BIND_PER_PRIMITIVE ||\n geom.getSecondaryColorBinding()==osg::Geometry::BIND_PER_PRIMITIVE_SET) return;\n\n if (geom.getFogCoordBinding()==osg::Geometry::BIND_PER_PRIMITIVE ||\n geom.getFogCoordBinding()==osg::Geometry::BIND_PER_PRIMITIVE_SET) return;\n\n\n\n unsigned int numSurfacePrimitives = 0;\n unsigned int numNonSurfacePrimitives = 0;\n\n Geometry::PrimitiveSetList& primitives = geom.getPrimitiveSetList();\n Geometry::PrimitiveSetList::iterator itr;\n for(itr=primitives.begin();\n itr!=primitives.end();\n ++itr)\n {\n switch((*itr)->getMode())\n {\n case(PrimitiveSet::TRIANGLES):\n case(PrimitiveSet::TRIANGLE_STRIP):\n case(PrimitiveSet::TRIANGLE_FAN):\n case(PrimitiveSet::QUADS):\n case(PrimitiveSet::QUAD_STRIP):\n case(PrimitiveSet::POLYGON):\n ++numSurfacePrimitives;\n break;\n default:\n ++numNonSurfacePrimitives;\n break;\n \n }\n }\n \n if (!numSurfacePrimitives) return;\n \n TriangleFunctor taf;\n\n Geometry::PrimitiveSetList new_primitives;\n new_primitives.reserve(primitives.size());\n\n for(itr=primitives.begin();\n itr!=primitives.end();\n ++itr)\n {\n switch((*itr)->getMode())\n {\n case(PrimitiveSet::TRIANGLES):\n case(PrimitiveSet::TRIANGLE_STRIP):\n case(PrimitiveSet::TRIANGLE_FAN):\n case(PrimitiveSet::QUADS):\n case(PrimitiveSet::QUAD_STRIP):\n case(PrimitiveSet::POLYGON):\n (*itr)->accept(taf);\n break;\n default:\n new_primitives.push_back(*itr);\n break;\n\n }\n }\n \n if (!taf.in_indices.empty())\n {\n int in_numVertices = -1;\n for(triangle_stripper::tri_stripper::indices::iterator itr=taf.in_indices.begin();\n itr!=taf.in_indices.end();\n ++itr)\n {\n if ((int)*itr>in_numVertices) in_numVertices=*itr;\n }\n \/\/ the largest indice is in_numVertices, but indices start at 0\n \/\/ so increment to give to the corrent number of verticies.\n ++in_numVertices; \n\n int in_cacheSize = 16;\n int in_minStripLength = 2;\n\n triangle_stripper::tri_stripper stripifier(taf.in_indices);\n stripifier.SetCacheSize(in_cacheSize);\n stripifier.SetMinStripSize(in_minStripLength);\n\n triangle_stripper::tri_stripper::primitives_vector outPrimitives;\n stripifier.Strip(&outPrimitives);\n\n for(triangle_stripper::tri_stripper::primitives_vector::iterator pitr=outPrimitives.begin();\n pitr!=outPrimitives.end();\n ++pitr)\n {\n osg::DrawElementsUShort* elements = new osg::DrawElementsUShort(pitr->m_Type);\n elements->reserve(pitr->m_Indices.size());\n std::copy(pitr->m_Indices.begin(),pitr->m_Indices.end(),std::back_inserter(*elements));\n \/\/elements->insert(elements->end(),);\n new_primitives.push_back(elements);\n }\n\n geom.setPrimitiveSetList(new_primitives);\n }\n}\n\n\nvoid TriStripVisitor::apply(Geode& geode)\n{\n for(unsigned int i = 0; i < geode.getNumDrawables(); ++i )\n {\n osg::Geometry* geom = dynamic_cast(geode.getDrawable(i));\n if (geom) stripify(*geom);\n }\n}\n<|endoftext|>"} {"text":"#include \n\n#include \"Call.cpp\"\n\nTEST(Call, CallCreation)\n{\n\tCall* doubleCall = new Call(CallType::DOUBLE);\n\tASSERT_TRUE(doubleCall->callType == CallType::DOUBLE);\n\tdelete doubleCall;\n\n\tCall* redoubleCall = new Call(CallType::REDOUBLE);\n\tASSERT_TRUE(redoubleCall->callType == CallType::REDOUBLE);\n\tdelete redoubleCall;\n\n\tCall* passCall = new Call(CallType::PASS);\n\tASSERT_TRUE(passCall->callType == CallType::PASS);\n\tdelete passCall;\n}\n\nTEST(DeclarationCall, DeclarationCallCreation)\n{\n\tDeclarationCall* declarationCall = new DeclarationCall(Level::ACE);\n\tASSERT_TRUE(declarationCall->callType == CallType::DECLARATION);\n\tASSERT_TRUE(declarationCall->level == Level::ACE);\n\tdelete declarationCall;\n}\nDelete CallTest.cpp<|endoftext|>"} {"text":"\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \n#include \n#include \"modules\/localization\/msf\/common\/io\/velodyne_utility.h\"\n#include \"modules\/localization\/msf\/local_tool\/map_creation\/poses_interpolation\/poses_interpolation.h\"\n\nnamespace apollo {\nnamespace localization {\nnamespace msf {\nPosesInterpolation::PosesInterpolation() {}\n\nbool PosesInterpolation::Init(const std::string &input_poses_path,\n const std::string &ref_timestamps_path,\n const std::string &out_poses_path,\n const std::string &extrinsic_path) {\n this->input_poses_path_ = input_poses_path;\n this->ref_timestamps_path_ = ref_timestamps_path;\n this->out_poses_path_ = out_poses_path;\n this->extrinsic_path_ = extrinsic_path;\n\n bool success = velodyne::LoadExtrinsic(extrinsic_path_, &velodyne_extrinsic_);\n if (!success) {\n std::cerr << \"Load lidar extrinsic failed.\" << std::endl;\n return false;\n }\n\n return true;\n}\n\nvoid PosesInterpolation::DoInterpolation() {\n \/\/ Load input poses\n std::vector input_stds;\n velodyne::LoadPosesAndStds(input_poses_path_, &input_poses_, &input_stds,\n &input_poses_timestamps_);\n\n \/\/ Load pcd timestamp\n LoadPCDTimestamp();\n\n \/\/ Interpolation\n PoseInterpolationByTime(input_poses_, input_poses_timestamps_,\n ref_timestamps_, ref_ids_, &out_indexes_,\n &out_timestamps_, &out_poses_);\n\n \/\/ Write pcd poses\n WritePCDPoses();\n}\n\nvoid PosesInterpolation::LoadPCDTimestamp() {\n FILE *file = fopen(ref_timestamps_path_.c_str(), \"r\");\n if (file) {\n unsigned int index;\n double timestamp;\n constexpr int kSize = 2;\n while (fscanf(file, \"%u %lf\\n\", &index, ×tamp) == kSize) {\n ref_timestamps_.push_back(timestamp);\n ref_ids_.push_back(index);\n }\n fclose(file);\n } else {\n std::cerr << \"Can't open file to read: \" << ref_timestamps_path_;\n }\n}\n\nvoid PosesInterpolation::WritePCDPoses() {\n std::ofstream fout;\n fout.open(out_poses_path_.c_str(), std::ofstream::out);\n fout.setf(std::ios::fixed, std::ios::floatfield);\n fout.precision(6);\n\n if (fout.is_open()) {\n for (size_t i = 0; i < out_poses_.size(); i++) {\n double timestamp = out_timestamps_[i];\n\n Eigen::Affine3d pose_tem = out_poses_[i] * velodyne_extrinsic_;\n Eigen::Quaterniond quatd(pose_tem.linear());\n Eigen::Translation3d transd(pose_tem.translation());\n double qx = quatd.x();\n double qy = quatd.y();\n double qz = quatd.z();\n double qr = quatd.w();\n\n fout << out_indexes_[i] << \" \" << timestamp << \" \" << transd.x() << \" \"\n << transd.y() << \" \" << transd.z() << \" \" << qx << \" \" << qy << \" \"\n << qz << \" \" << qr << \"\\n\";\n }\n fout.close();\n } else {\n std::cerr << \"Can't open file to write: \" << out_poses_path_ << std::endl;\n }\n} \/\/ namespace msf\n\nvoid PosesInterpolation::PoseInterpolationByTime(\n const std::vector &in_poses,\n const std::vector &in_timestamps,\n const std::vector &ref_timestamps,\n const std::vector &ref_indexes,\n std::vector *out_indexes, std::vector *out_timestamps,\n std::vector *out_poses) {\n out_indexes->clear();\n out_timestamps->clear();\n out_poses->clear();\n\n unsigned int index = 0;\n for (size_t i = 0; i < ref_timestamps.size(); i++) {\n double ref_timestamp = ref_timestamps[i];\n unsigned int ref_index = ref_indexes[i];\n\n while (index < in_timestamps.size() &&\n in_timestamps.at(index) < ref_timestamp) {\n ++index;\n }\n\n if (index < in_timestamps.size()) {\n if (index >= 1) {\n double cur_timestamp = in_timestamps[index];\n double pre_timestamp = in_timestamps[index - 1];\n assert(cur_timestamp != pre_timestamp);\n\n double t =\n (cur_timestamp - ref_timestamp) \/ (cur_timestamp - pre_timestamp);\n assert(t >= 0.0);\n assert(t <= 1.0);\n\n Eigen::Affine3d pre_pose = in_poses[index - 1];\n Eigen::Affine3d cur_pose = in_poses[index];\n Eigen::Quaterniond pre_quatd(pre_pose.linear());\n Eigen::Translation3d pre_transd(pre_pose.translation());\n Eigen::Quaterniond cur_quatd(cur_pose.linear());\n Eigen::Translation3d cur_transd(cur_pose.translation());\n\n Eigen::Quaterniond res_quatd = pre_quatd.slerp(1 - t, cur_quatd);\n\n Eigen::Translation3d re_transd;\n re_transd.x() = pre_transd.x() * t + cur_transd.x() * (1 - t);\n re_transd.y() = pre_transd.y() * t + cur_transd.y() * (1 - t);\n re_transd.z() = pre_transd.z() * t + cur_transd.z() * (1 - t);\n\n out_poses->push_back(re_transd * res_quatd);\n out_indexes->push_back(ref_index);\n out_timestamps->push_back(ref_timestamp);\n }\n } else {\n std::cerr << \"[ERROR] No more poses. Exit now.\" << std::endl;\n break;\n }\n std::cout << \"Frame_id: \" << i << std::endl;\n }\n}\n\n} \/\/ namespace msf\n} \/\/ namespace localization\n} \/\/ namespace apollo\nLocalization: fix order of fstream operation in PoseInterpolation\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \n#include \n#include \"modules\/localization\/msf\/common\/io\/velodyne_utility.h\"\n#include \"modules\/localization\/msf\/local_tool\/map_creation\/poses_interpolation\/poses_interpolation.h\"\n\nnamespace apollo {\nnamespace localization {\nnamespace msf {\nPosesInterpolation::PosesInterpolation() {}\n\nbool PosesInterpolation::Init(const std::string &input_poses_path,\n const std::string &ref_timestamps_path,\n const std::string &out_poses_path,\n const std::string &extrinsic_path) {\n this->input_poses_path_ = input_poses_path;\n this->ref_timestamps_path_ = ref_timestamps_path;\n this->out_poses_path_ = out_poses_path;\n this->extrinsic_path_ = extrinsic_path;\n\n bool success = velodyne::LoadExtrinsic(extrinsic_path_, &velodyne_extrinsic_);\n if (!success) {\n std::cerr << \"Load lidar extrinsic failed.\" << std::endl;\n return false;\n }\n\n return true;\n}\n\nvoid PosesInterpolation::DoInterpolation() {\n \/\/ Load input poses\n std::vector input_stds;\n velodyne::LoadPosesAndStds(input_poses_path_, &input_poses_, &input_stds,\n &input_poses_timestamps_);\n\n \/\/ Load pcd timestamp\n LoadPCDTimestamp();\n\n \/\/ Interpolation\n PoseInterpolationByTime(input_poses_, input_poses_timestamps_,\n ref_timestamps_, ref_ids_, &out_indexes_,\n &out_timestamps_, &out_poses_);\n\n \/\/ Write pcd poses\n WritePCDPoses();\n}\n\nvoid PosesInterpolation::LoadPCDTimestamp() {\n FILE *file = fopen(ref_timestamps_path_.c_str(), \"r\");\n if (file) {\n unsigned int index;\n double timestamp;\n constexpr int kSize = 2;\n while (fscanf(file, \"%u %lf\\n\", &index, ×tamp) == kSize) {\n ref_timestamps_.push_back(timestamp);\n ref_ids_.push_back(index);\n }\n fclose(file);\n } else {\n std::cerr << \"Can't open file to read: \" << ref_timestamps_path_;\n }\n}\n\nvoid PosesInterpolation::WritePCDPoses() {\n std::ofstream fout;\n fout.open(out_poses_path_.c_str(), std::ofstream::out);\n fout.setf(std::ios::fixed, std::ios::floatfield);\n\n if (fout.is_open()) {\n for (size_t i = 0; i < out_poses_.size(); i++) {\n double timestamp = out_timestamps_[i];\n\n Eigen::Affine3d pose_tem = out_poses_[i] * velodyne_extrinsic_;\n Eigen::Quaterniond quatd(pose_tem.linear());\n Eigen::Translation3d transd(pose_tem.translation());\n double qx = quatd.x();\n double qy = quatd.y();\n double qz = quatd.z();\n double qr = quatd.w();\n\n fout.precision(6);\n fout << out_indexes_[i] << \" \" << timestamp << \" \" << transd.x() << \" \"\n << transd.y() << \" \" << transd.z() << \" \" << qx << \" \" << qy << \" \"\n << qz << \" \" << qr << \"\\n\";\n }\n fout.close();\n } else {\n std::cerr << \"Can't open file to write: \" << out_poses_path_ << std::endl;\n }\n} \/\/ namespace msf\n\nvoid PosesInterpolation::PoseInterpolationByTime(\n const std::vector &in_poses,\n const std::vector &in_timestamps,\n const std::vector &ref_timestamps,\n const std::vector &ref_indexes,\n std::vector *out_indexes, std::vector *out_timestamps,\n std::vector *out_poses) {\n out_indexes->clear();\n out_timestamps->clear();\n out_poses->clear();\n\n unsigned int index = 0;\n for (size_t i = 0; i < ref_timestamps.size(); i++) {\n double ref_timestamp = ref_timestamps[i];\n unsigned int ref_index = ref_indexes[i];\n\n while (index < in_timestamps.size() &&\n in_timestamps.at(index) < ref_timestamp) {\n ++index;\n }\n\n if (index < in_timestamps.size()) {\n if (index >= 1) {\n double cur_timestamp = in_timestamps[index];\n double pre_timestamp = in_timestamps[index - 1];\n assert(cur_timestamp != pre_timestamp);\n\n double t =\n (cur_timestamp - ref_timestamp) \/ (cur_timestamp - pre_timestamp);\n assert(t >= 0.0);\n assert(t <= 1.0);\n\n Eigen::Affine3d pre_pose = in_poses[index - 1];\n Eigen::Affine3d cur_pose = in_poses[index];\n Eigen::Quaterniond pre_quatd(pre_pose.linear());\n Eigen::Translation3d pre_transd(pre_pose.translation());\n Eigen::Quaterniond cur_quatd(cur_pose.linear());\n Eigen::Translation3d cur_transd(cur_pose.translation());\n\n Eigen::Quaterniond res_quatd = pre_quatd.slerp(1 - t, cur_quatd);\n\n Eigen::Translation3d re_transd;\n re_transd.x() = pre_transd.x() * t + cur_transd.x() * (1 - t);\n re_transd.y() = pre_transd.y() * t + cur_transd.y() * (1 - t);\n re_transd.z() = pre_transd.z() * t + cur_transd.z() * (1 - t);\n\n out_poses->push_back(re_transd * res_quatd);\n out_indexes->push_back(ref_index);\n out_timestamps->push_back(ref_timestamp);\n }\n } else {\n std::cerr << \"[ERROR] No more poses. Exit now.\" << std::endl;\n break;\n }\n std::cout << \"Frame_id: \" << i << std::endl;\n }\n}\n\n} \/\/ namespace msf\n} \/\/ namespace localization\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"#include \n\n#include \n\n#include \"ptexutils.hpp\"\n#include \"helpers.hpp\"\n\n\nint ptex_utils::ptex_conform(const char* filename,\n const char* output_filename,\n int8_t downsteps,\n int8_t clampsize,\n bool change_datatype,\n Ptex::DataType out_dt,\n Ptex::String &err_msg)\n{\n PtxPtr ptx(PtexTexture::open(filename, err_msg, 0));\n if (!ptx) {\n err_msg = \"Can't open for reading \" + std::string(filename) + \":\" + err_msg;\n return -1;\n }\n\n downsteps = std::max(0, (int) downsteps);\n clampsize = std::max(0, (int) downsteps);\n\n Ptex::DataType input_dt = ptx->dataType();\n Ptex::DataType dt = change_datatype ? out_dt : input_dt;\n int nfaces = ptx->numFaces();\n int nchannels = ptx->numChannels();\n\n WriterPtr writer(PtexWriter::open(output_filename,\n ptx->meshType(),\n dt,\n nchannels,\n ptx->alphaChannel(),\n nfaces,\n err_msg));\n if (!writer) {\n err_msg = \"Can't open for writing \" + std::string(output_filename) + \":\" + err_msg;\n return -1;\n }\n\n int8_t clamp_log = clampsize <= 0 ? 15 : clampsize;\n Ptex::Res clamp_res(clamp_log, clamp_log);\n\n const size_t input_pixel_size = Ptex::DataSize(ptx->dataType()) * nchannels;\n const size_t pixel_size = Ptex::DataSize(dt)*nchannels;\n\n std::vector in_buffer(input_pixel_size*128*128);\n std::vector out_buffer(pixel_size*128*128);\n std::vector fdata(nchannels*128*128);\n\n for (int face_id = 0; face_id < nfaces; ++face_id) {\n Ptex::FaceInfo face_info = ptx->getFaceInfo(face_id);\n\n if (!face_info.isConstant()) {\n Ptex::Res res = face_info.res;\n res.ulog2 = res.ulog2 > 2 ? std::max(1, res.ulog2 - downsteps) : res.ulog2;\n res.vlog2 = res.vlog2 > 2 ? std::max(1, res.vlog2 - downsteps) : res.vlog2;\n res.clamp(clamp_res);\n face_info.res = res;\n }\n\n const size_t input_size = input_pixel_size * face_info.res.size();\n if (in_buffer.size() < input_size) {\n in_buffer.resize(input_size);\n }\n\n ptx->getData(face_id, in_buffer.data(), 0, face_info.res);\n\n if (dt == input_dt) {\n if (face_info.isConstant()) {\n writer->writeConstantFace(face_id, face_info, in_buffer.data());\n }\n else {\n writer->writeFace(face_id, face_info, in_buffer.data(), 0);\n }\n }\n else {\n const size_t out_size = pixel_size * face_info.res.size();\n const size_t float_size = nchannels*face_info.res.size();\n if (out_buffer.size() < out_size) {\n out_buffer.resize(out_size);\n }\n if (fdata.size() < float_size) {\n fdata.resize(float_size);\n }\n\n Ptex::ConvertToFloat(fdata.data(), in_buffer.data(), input_dt,\n nchannels*face_info.res.size());\n Ptex::ConvertFromFloat(out_buffer.data(), fdata.data(),\n dt, nchannels*face_info.res.size());\n\n if (face_info.isConstant()) {\n writer->writeConstantFace(face_id, face_info, out_buffer.data());\n }\n else {\n writer->writeFace(face_id, face_info, out_buffer.data(), 0);\n }\n }\n }\n\n MetaPtr meta_ptr(ptx->getMetaData());\n writer->writeMeta(meta_ptr.get());\n\n writer->setBorderModes(ptx->vBorderMode(), ptx->uBorderMode());\n\n if (!writer->close(err_msg)){\n err_msg = \"Closing writer \" + std::string(output_filename) + \":\" + err_msg.c_str();\n\treturn -1;\n }\n\n return 0;\n}\n\nFix clamping in ptex conform#include \n\n#include \n\n#include \"ptexutils.hpp\"\n#include \"helpers.hpp\"\n\n\nint ptex_utils::ptex_conform(const char* filename,\n const char* output_filename,\n int8_t downsteps,\n int8_t clampsize,\n bool change_datatype,\n Ptex::DataType out_dt,\n Ptex::String &err_msg)\n{\n PtxPtr ptx(PtexTexture::open(filename, err_msg, 0));\n if (!ptx) {\n err_msg = \"Can't open for reading \" + std::string(filename) + \":\" + err_msg;\n return -1;\n }\n\n downsteps = std::max(0, (int) downsteps);\n clampsize = std::max(0, (int) clampsize);\n\n Ptex::DataType input_dt = ptx->dataType();\n Ptex::DataType dt = change_datatype ? out_dt : input_dt;\n int nfaces = ptx->numFaces();\n int nchannels = ptx->numChannels();\n\n WriterPtr writer(PtexWriter::open(output_filename,\n ptx->meshType(),\n dt,\n nchannels,\n ptx->alphaChannel(),\n nfaces,\n err_msg));\n if (!writer) {\n err_msg = \"Can't open for writing \" + std::string(output_filename) + \":\" + err_msg;\n return -1;\n }\n\n int8_t clamp_log = clampsize <= 0 ? 15 : clampsize;\n Ptex::Res clamp_res(clamp_log, clamp_log);\n\n const size_t input_pixel_size = Ptex::DataSize(ptx->dataType()) * nchannels;\n const size_t pixel_size = Ptex::DataSize(dt)*nchannels;\n\n std::vector in_buffer(input_pixel_size*128*128);\n std::vector out_buffer(pixel_size*128*128);\n std::vector fdata(nchannels*128*128);\n\n for (int face_id = 0; face_id < nfaces; ++face_id) {\n Ptex::FaceInfo face_info = ptx->getFaceInfo(face_id);\n\n if (!face_info.isConstant()) {\n Ptex::Res res = face_info.res;\n res.ulog2 = res.ulog2 > 2 ? std::max(1, res.ulog2 - downsteps) : res.ulog2;\n res.vlog2 = res.vlog2 > 2 ? std::max(1, res.vlog2 - downsteps) : res.vlog2;\n res.clamp(clamp_res);\n face_info.res = res;\n }\n\n const size_t input_size = input_pixel_size * face_info.res.size();\n if (in_buffer.size() < input_size) {\n in_buffer.resize(input_size);\n }\n\n ptx->getData(face_id, in_buffer.data(), 0, face_info.res);\n\n if (dt == input_dt) {\n if (face_info.isConstant()) {\n writer->writeConstantFace(face_id, face_info, in_buffer.data());\n }\n else {\n writer->writeFace(face_id, face_info, in_buffer.data(), 0);\n }\n }\n else {\n const size_t out_size = pixel_size * face_info.res.size();\n const size_t float_size = nchannels*face_info.res.size();\n if (out_buffer.size() < out_size) {\n out_buffer.resize(out_size);\n }\n if (fdata.size() < float_size) {\n fdata.resize(float_size);\n }\n\n Ptex::ConvertToFloat(fdata.data(), in_buffer.data(), input_dt,\n nchannels*face_info.res.size());\n Ptex::ConvertFromFloat(out_buffer.data(), fdata.data(),\n dt, nchannels*face_info.res.size());\n\n if (face_info.isConstant()) {\n writer->writeConstantFace(face_id, face_info, out_buffer.data());\n }\n else {\n writer->writeFace(face_id, face_info, out_buffer.data(), 0);\n }\n }\n }\n\n MetaPtr meta_ptr(ptx->getMetaData());\n writer->writeMeta(meta_ptr.get());\n\n writer->setBorderModes(ptx->vBorderMode(), ptx->uBorderMode());\n\n if (!writer->close(err_msg)){\n err_msg = \"Closing writer \" + std::string(output_filename) + \":\" + err_msg.c_str();\n\treturn -1;\n }\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"\n\/\/ Copyright (c) 2012, 2013 Pierre MOULON.\n\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License, v. 2.0. If a copy of the MPL was not distributed with this\n\/\/ file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \"software\/SfMViewer\/document.h\"\n#include \"openMVG\/multiview\/projection.hpp\"\n#include \"openMVG\/image\/image.hpp\"\n\n#include \"third_party\/cmdLine\/cmdLine.h\"\n\nstatic int running = 1;\nstatic Document m_doc;\nstatic int cur_cam = -1;\n\nstruct GLWImage {\n int width, height;\n GLuint texture;\n double opacity;\n int camera;\n };\n\nstatic GLWImage m_cur_image;\n\n\/* close callback *\/\nstatic int window_close_callback(GLFWwindow* window)\n{\n running = 0;\n return GL_TRUE;\n}\n\n\/* new window size *\/\nvoid reshape( GLFWwindow* window, int width, int height )\n{\n glViewport( 0, 0, (GLint) width, (GLint) height );\n glMatrixMode( GL_PROJECTION );\n glLoadIdentity();\n GLfloat zNear = 1e-2;\n GLfloat zFar = 1e5;\n GLfloat aspect = float(width)\/float(height);\n GLfloat fH = std::tan( float(60 \/ 360.0f * 3.14159f) ) * zNear;\n GLfloat fW = fH * aspect;\n glFrustum( -fW, fW, -fH, fH, zNear, zFar );\n glMatrixMode( GL_MODELVIEW );\n glLoadIdentity();\n}\n\nvoid glCheckError() {\n#ifndef NDEBUG\n\tstd::vector errors;\n\tunsigned error = GL_NO_ERROR;\n\tfor (; (error = glGetError()) != GL_NO_ERROR;)\n\t\terrors.push_back(error);\n\tif (errors.empty())\n\t\treturn;\n\tstd::ostringstream oss;\n\toss << \"OpenGL errors :\\n\";\n\tfor (const unsigned error : errors)\n\t\toss << \" - \" << getErrorString(error) << '\\n';\n\tthrow std::runtime_error(oss.str());\n#endif\n}\n\nvoid key( GLFWwindow* window, int k, int action)\n{\n if( action != GLFW_PRESS ) return;\n\nbool bTextureChange = false;\n\n switch (k) {\n case GLFW_KEY_ESCAPE:\n running = 0;\n break;\n case GLFW_KEY_LEFT:\n cur_cam--;\n if (cur_cam<0) {\n cur_cam = m_doc._map_camera.size()-1;\n }\n bTextureChange = true;\n break;\n case GLFW_KEY_RIGHT:\n cur_cam++;\n if (cur_cam >= m_doc._map_camera.size()) {\n cur_cam = 0;\n }\n bTextureChange = true;\n break;\n default:\n return;\n }\n\n if (bTextureChange)\n {\n std::string sImageName =\n stlplus::create_filespec(\n stlplus::folder_append_separator(m_doc._sDirectory)+\"images\",\n m_doc._vec_imageNames[cur_cam]);\n std::vector img;\n int w,h,depth;\n if (ReadImage(sImageName.c_str(),\n &img,\n &w,\n &h,\n &depth))\n {\n glEnable(GL_TEXTURE_2D);\n std::cout << \"Read image : \" << sImageName << std::endl;\n glDeleteTextures(1, &m_cur_image.texture);\n\n \/\/ Create texture\n glGenTextures( 1, &m_cur_image.texture);\n \/\/ select our current texture\n glBindTexture(GL_TEXTURE_2D, m_cur_image.texture);\n\n m_cur_image.width = w;\n m_cur_image.height = h;\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, m_cur_image.width,\n m_cur_image.height, 0, GL_RGB, GL_UNSIGNED_BYTE,\n &img[0]);\n std::cout << std::endl;\n\n glCheckError();\n glBindTexture(GL_TEXTURE_2D, m_cur_image.texture);\n }\n }\n}\n\n\/\/ the conversion matrix from OpenGL default coordinate system\n\/\/ to the camera coordinate system:\n\/\/ [ 1 0 0 0] * [ x ] = [ x ]\n\/\/ 0 -1 0 0 y -y\n\/\/ 0 0 -1 0 z -z\n\/\/ 0 0 0 1 1 1\nconst GLfloat m_convert[4][4] = {\n {1., 0., 0., 0.},\n {0., -1., 0., 0.},\n {0., 0., -1., 0.},\n {0., 0., 0., 1.}};\n\n\/\/Local to World\nstatic openMVG::Mat4 l2w_Camera(const Mat3 & R, const Vec3 & t)\n{\n \/\/World to Local\n \/\/\/ given rotation matrix R and translation vector t,\n \/\/\/ column-major matrix m is equal to:\n \/\/\/ [ R11 R12 R13 t.x ]\n \/\/\/ | R21 R22 R23 t.y |\n \/\/\/ | R31 R32 R33 t.z |\n \/\/\/ [ 0.0 0.0 0.0 1.0 ]\n\n \/\/Local to World => Coordinates of the camera in the 3d space\n openMVG::Mat4 l2wmat = Mat4::Identity();\n l2wmat.block(0,0,3,4) = HStack(R,t);\n return l2wmat;\n}\n\n\/* OpenGL draw function & timing *\/\nstatic void draw(void)\n{\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n glMatrixMode(GL_MODELVIEW);\n glLoadIdentity();\n\n {\n const PinholeCamera & camera = m_doc._map_camera.find(cur_cam)->second;\n\n glPushMatrix();\n openMVG::Mat4 l2w = l2w_Camera(camera._R, camera._t);\n glMultMatrixf((GLfloat*)m_convert); \/\/ second, convert the camera coordinates to the opengl camera coordinates\n glMultMatrixd((GLdouble*)l2w.data());\n\n glPointSize(3);\n glDisable(GL_TEXTURE_2D);\n glDisable(GL_LIGHTING);\n \/\/glCallList(m_pointcloud);\n\n \/\/Draw Structure\n size_t nbPoint = m_doc._vec_points.size()\/3;\n size_t cpt = 0;\n glBegin(GL_POINTS);\n for(size_t i = 0; i < nbPoint; i++,cpt+=3) {\n glColor3f(0.f,1.f,0.f);\n glVertex3f(m_doc._vec_points[cpt], m_doc._vec_points[cpt+1], m_doc._vec_points[cpt+2]);\n }\n glEnd();\n\n\n\/*\n \/\/-- Draw other cameras:\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n glEnable(GL_BLEND); glDisable(GL_DEPTH_TEST);\n\n glDisable(GL_CULL_FACE);\n for (std::map::const_iterator iterCam = m_doc->map_camera.begin();\n iterCam != m_doc->map_camera.end(); ++iterCam)\n {\n glPushMatrix();\n\n if (std::distance(m_doc->map_camera.begin(),iterCam) != cur_cam)\n {\n Mat4 l2w = iterCam->second.l2w();\n \/\/glMultMatrixd(l2w.data());\n glMultMatrixf((GLfloat*)m_convert); \/\/ second, convert the camera coordinates to the opengl camera coordinates\n \/\/glMultMatrixf((GLfloat*)prj); \/\/ first, project the points in the world coordinates to the camera coorrdinates\n glMultMatrixd((GLdouble*)l2w.data());\n int w = m_doc->map_imageSize.find(std::distance(m_doc->map_camera.begin(),iterCam))->second.first;\n int h = m_doc->map_imageSize.find(std::distance(m_doc->map_camera.begin(),iterCam))->second.second;\n double focal = iterCam->second.K(0,0);\n double maxx = 0.5*w\/focal;\n double maxy = 0.5*h\/focal;\n\n glBegin(GL_QUADS);\n glColor4f(0.5f,0.5f,0.5f,0.6f);\n glTexCoord2d(0.0,0.0); glVertex3d(-maxx,-maxy,-1.0);\n glTexCoord2d(1.0,0.0); glVertex3d(+maxx,-maxy,-1.0);\n glTexCoord2d(1.0,1.0); glVertex3d(+maxx,+maxy,-1.0);\n glTexCoord2d(0.0,1.0); glVertex3d(-maxx,+maxy,-1.0);\n glEnd();\n\n }\n glPopMatrix();\n }\n\n glDisable(GL_BLEND); glEnable(GL_DEPTH_TEST);\n*\/\n\n glPopMatrix();\n\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n glEnable(GL_BLEND); glDisable(GL_DEPTH_TEST);\n\n \/\/Draw the image\n\n int w = m_doc._map_imageSize.find(cur_cam)->second.first;\n int h = m_doc._map_imageSize.find(cur_cam)->second.second;\n double focal = camera._K(0,0);\n\n double maxx = 0.5 * w \/ focal;\n double maxy = 0.5 * h \/ focal;\n glEnable(GL_TEXTURE_2D);\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n\n glBindTexture(GL_TEXTURE_2D, m_cur_image.texture);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n glColor4f(0.5f,0.5f,0.5f,0.6f);\n glBegin(GL_QUADS);\n glTexCoord2d(0.0,1.0); glVertex3d(-maxx,-maxy,-1.0);\n glTexCoord2d(1.0,1.0); glVertex3d(+maxx,-maxy,-1.0);\n glTexCoord2d(1.0,0.0); glVertex3d(+maxx,+maxy,-1.0);\n glTexCoord2d(0.0,0.0); glVertex3d(-maxx,+maxy,-1.0);\n glEnd();\n glDisable(GL_TEXTURE_2D);\n glDisable(GL_BLEND); glEnable(GL_DEPTH_TEST);\n }\n}\n\nint main(int argc, char *argv[]) {\n\n CmdLine cmd;\r\n\r\n std::string sSfM_Dir;\r\n\r\n cmd.add( make_option('i', sSfM_Dir, \"sfmdir\") );\r\n\r\n try {\r\n if (argc == 1) throw std::string(\"Invalid command line parameter.\");\r\n cmd.process(argc, argv);\r\n } catch(const std::string& s) {\r\n std::cerr << \"Usage: \" << argv[0] << ' '\r\n << \"[-i|--sfmdir SfM_Output path] \"\r\n << std::endl;\r\n\r\n std::cerr << s << std::endl;\r\n return EXIT_FAILURE;\r\n }\n\n if (m_doc.load(sSfM_Dir))\n {\n cur_cam = 0;\n std::cout << \"Press left or right key to navigate ;-)\" << std::endl;\n std::cout << \"Esc to quit\" << std::endl;\n }\n else{\n exit( EXIT_FAILURE);\n }\n\n\n \/\/-- Create the GL window context\n GLFWwindow* window;\n int width, height;\n\n if( !glfwInit() )\n {\n fprintf( stderr, \"Failed to initialize GLFW\\n\" );\n exit( EXIT_FAILURE );\n }\n\n glfwWindowHint(GLFW_DEPTH_BITS, 16);\n\n window = glfwCreateWindow( 600, 300, \"SfmViewer\", NULL, NULL );\n if (!window)\n {\n fprintf( stderr, \"Failed to open GLFW window\\n\" );\n glfwTerminate();\n exit( EXIT_FAILURE );\n }\n\n \/\/ Set callback functions\n glfwSetWindowCloseCallback(window, window_close_callback);\n glfwSetWindowSizeCallback(window, reshape);\n glfwSetKeyCallback(window, key);\n\n glfwMakeContextCurrent(window);\n glfwSwapInterval( 1 );\n\n glfwGetWindowSize(window, &width, &height);\n reshape(window, width, height);\n\n m_cur_image.camera = -1;\n \/\/ Main loop\n while( running )\n {\n \/\/ Draw SfM Scene\n draw();\n\n \/\/ Swap buffers\n glfwSwapBuffers(window);\n glfwPollEvents();\n }\n\n\n \/\/ Terminate GLFW\n glfwTerminate();\n\n \/\/ Exit program\n exit( EXIT_SUCCESS );\n}\nFix compilation error for windows. #27\n\/\/ Copyright (c) 2012, 2013 Pierre MOULON.\n\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License, v. 2.0. If a copy of the MPL was not distributed with this\n\/\/ file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \"software\/SfMViewer\/document.h\"\n#include \"openMVG\/multiview\/projection.hpp\"\n#include \"openMVG\/image\/image.hpp\"\n\n#include \"third_party\/cmdLine\/cmdLine.h\"\n\nstatic int running = 1;\nstatic Document m_doc;\nstatic int cur_cam = -1;\n\nstruct GLWImage {\n int width, height;\n GLuint texture;\n double opacity;\n int camera;\n };\n\nstatic GLWImage m_cur_image;\n\n\/* close callback *\/\nstatic int window_close_callback(GLFWwindow* window)\n{\n running = 0;\n return GL_TRUE;\n}\n\n\/* new window size *\/\nvoid reshape( GLFWwindow* window, int width, int height )\n{\n glViewport( 0, 0, (GLint) width, (GLint) height );\n glMatrixMode( GL_PROJECTION );\n glLoadIdentity();\n GLfloat zNear = 1e-2;\n GLfloat zFar = 1e5;\n GLfloat aspect = float(width)\/float(height);\n GLfloat fH = std::tan( float(60 \/ 360.0f * 3.14159f) ) * zNear;\n GLfloat fW = fH * aspect;\n glFrustum( -fW, fW, -fH, fH, zNear, zFar );\n glMatrixMode( GL_MODELVIEW );\n glLoadIdentity();\n}\n\nvoid key( GLFWwindow* window, int k, int action)\n{\n if( action != GLFW_PRESS ) return;\n\n bool bTextureChange = false;\n\n switch (k) {\n case GLFW_KEY_ESCAPE:\n running = 0;\n break;\n case GLFW_KEY_LEFT:\n cur_cam--;\n if (cur_cam<0) {\n cur_cam = m_doc._map_camera.size()-1;\n }\n bTextureChange = true;\n break;\n case GLFW_KEY_RIGHT:\n cur_cam++;\n if (cur_cam >= m_doc._map_camera.size()) {\n cur_cam = 0;\n }\n bTextureChange = true;\n break;\n default:\n return;\n }\n\n if (bTextureChange)\n {\n std::string sImageName =\n stlplus::create_filespec(\n stlplus::folder_append_separator(m_doc._sDirectory)+\"images\",\n m_doc._vec_imageNames[cur_cam]);\n std::vector img;\n int w,h,depth;\n if (ReadImage(sImageName.c_str(),\n &img,\n &w,\n &h,\n &depth))\n {\n glEnable(GL_TEXTURE_2D);\n std::cout << \"Read image : \" << sImageName << \"\\n\" << std::endl;\n glDeleteTextures(1, &m_cur_image.texture);\n\n \/\/ Create texture\n glGenTextures( 1, &m_cur_image.texture);\n \/\/ select our current texture\n glBindTexture(GL_TEXTURE_2D, m_cur_image.texture);\n\n m_cur_image.width = w;\n m_cur_image.height = h;\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, m_cur_image.width,\n m_cur_image.height, 0, GL_RGB, GL_UNSIGNED_BYTE,\n &img[0]);\n\n glBindTexture(GL_TEXTURE_2D, m_cur_image.texture);\n }\n }\n}\n\n\/\/ the conversion matrix from OpenGL default coordinate system\n\/\/ to the camera coordinate system:\n\/\/ [ 1 0 0 0] * [ x ] = [ x ]\n\/\/ 0 -1 0 0 y -y\n\/\/ 0 0 -1 0 z -z\n\/\/ 0 0 0 1 1 1\nconst GLfloat m_convert[4][4] = {\n {1., 0., 0., 0.},\n {0., -1., 0., 0.},\n {0., 0., -1., 0.},\n {0., 0., 0., 1.}};\n\n\/\/Local to World\nstatic openMVG::Mat4 l2w_Camera(const Mat3 & R, const Vec3 & t)\n{\n \/\/World to Local\n \/\/\/ given rotation matrix R and translation vector t,\n \/\/\/ column-major matrix m is equal to:\n \/\/\/ [ R11 R12 R13 t.x ]\n \/\/\/ | R21 R22 R23 t.y |\n \/\/\/ | R31 R32 R33 t.z |\n \/\/\/ [ 0.0 0.0 0.0 1.0 ]\n\n \/\/Local to World => Coordinates of the camera in the 3d space\n openMVG::Mat4 l2wmat = Mat4::Identity();\n l2wmat.block(0,0,3,4) = HStack(R,t);\n return l2wmat;\n}\n\n\/* OpenGL draw function & timing *\/\nstatic void draw(void)\n{\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n glMatrixMode(GL_MODELVIEW);\n glLoadIdentity();\n\n {\n const PinholeCamera & camera = m_doc._map_camera.find(cur_cam)->second;\n\n glPushMatrix();\n openMVG::Mat4 l2w = l2w_Camera(camera._R, camera._t);\n glMultMatrixf((GLfloat*)m_convert); \/\/ second, convert the camera coordinates to the opengl camera coordinates\n glMultMatrixd((GLdouble*)l2w.data());\n\n glPointSize(3);\n glDisable(GL_TEXTURE_2D);\n glDisable(GL_LIGHTING);\n \/\/glCallList(m_pointcloud);\n\n \/\/Draw Structure\n size_t nbPoint = m_doc._vec_points.size()\/3;\n size_t cpt = 0;\n glBegin(GL_POINTS);\n for(size_t i = 0; i < nbPoint; i++,cpt+=3) {\n glColor3f(0.f,1.f,0.f);\n glVertex3f(m_doc._vec_points[cpt], m_doc._vec_points[cpt+1], m_doc._vec_points[cpt+2]);\n }\n glEnd();\n\n\n\/*\n \/\/-- Draw other cameras:\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n glEnable(GL_BLEND); glDisable(GL_DEPTH_TEST);\n\n glDisable(GL_CULL_FACE);\n for (std::map::const_iterator iterCam = m_doc->map_camera.begin();\n iterCam != m_doc->map_camera.end(); ++iterCam)\n {\n glPushMatrix();\n\n if (std::distance(m_doc->map_camera.begin(),iterCam) != cur_cam)\n {\n Mat4 l2w = iterCam->second.l2w();\n \/\/glMultMatrixd(l2w.data());\n glMultMatrixf((GLfloat*)m_convert); \/\/ second, convert the camera coordinates to the opengl camera coordinates\n \/\/glMultMatrixf((GLfloat*)prj); \/\/ first, project the points in the world coordinates to the camera coorrdinates\n glMultMatrixd((GLdouble*)l2w.data());\n int w = m_doc->map_imageSize.find(std::distance(m_doc->map_camera.begin(),iterCam))->second.first;\n int h = m_doc->map_imageSize.find(std::distance(m_doc->map_camera.begin(),iterCam))->second.second;\n double focal = iterCam->second.K(0,0);\n double maxx = 0.5*w\/focal;\n double maxy = 0.5*h\/focal;\n\n glBegin(GL_QUADS);\n glColor4f(0.5f,0.5f,0.5f,0.6f);\n glTexCoord2d(0.0,0.0); glVertex3d(-maxx,-maxy,-1.0);\n glTexCoord2d(1.0,0.0); glVertex3d(+maxx,-maxy,-1.0);\n glTexCoord2d(1.0,1.0); glVertex3d(+maxx,+maxy,-1.0);\n glTexCoord2d(0.0,1.0); glVertex3d(-maxx,+maxy,-1.0);\n glEnd();\n\n }\n glPopMatrix();\n }\n\n glDisable(GL_BLEND); glEnable(GL_DEPTH_TEST);\n*\/\n\n glPopMatrix();\n\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n glEnable(GL_BLEND); glDisable(GL_DEPTH_TEST);\n\n \/\/Draw the image\n\n int w = m_doc._map_imageSize.find(cur_cam)->second.first;\n int h = m_doc._map_imageSize.find(cur_cam)->second.second;\n double focal = camera._K(0,0);\n\n double maxx = 0.5 * w \/ focal;\n double maxy = 0.5 * h \/ focal;\n glEnable(GL_TEXTURE_2D);\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n\n glBindTexture(GL_TEXTURE_2D, m_cur_image.texture);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n glColor4f(0.5f,0.5f,0.5f,0.6f);\n glBegin(GL_QUADS);\n glTexCoord2d(0.0,1.0); glVertex3d(-maxx,-maxy,-1.0);\n glTexCoord2d(1.0,1.0); glVertex3d(+maxx,-maxy,-1.0);\n glTexCoord2d(1.0,0.0); glVertex3d(+maxx,+maxy,-1.0);\n glTexCoord2d(0.0,0.0); glVertex3d(-maxx,+maxy,-1.0);\n glEnd();\n glDisable(GL_TEXTURE_2D);\n glDisable(GL_BLEND); glEnable(GL_DEPTH_TEST);\n }\n}\n\nint main(int argc, char *argv[]) {\n\n CmdLine cmd;\r\n std::string sSfM_Dir;\r\n cmd.add( make_option('i', sSfM_Dir, \"sfmdir\") );\r\n\r\n try {\r\n if (argc == 1) throw std::string(\"Invalid command line parameter.\");\r\n cmd.process(argc, argv);\r\n } catch(const std::string& s) {\r\n std::cerr << \"Usage: \" << argv[0] << ' '\r\n << \"[-i|--sfmdir SfM_Output path] \"\r\n << std::endl;\r\n\r\n std::cerr << s << std::endl;\r\n return EXIT_FAILURE;\r\n }\n\n if (m_doc.load(sSfM_Dir))\n {\n cur_cam = 0;\n std::cout << \"Press left or right key to navigate ;-)\" << std::endl;\n std::cout << \"Esc to quit\" << std::endl;\n }\n else{\n exit( EXIT_FAILURE);\n }\n \n \/\/-- Create the GL window context\n GLFWwindow* window;\n int width, height;\n\n if( !glfwInit() )\n {\n fprintf( stderr, \"Failed to initialize GLFW\\n\" );\n exit( EXIT_FAILURE );\n }\n\n glfwWindowHint(GLFW_DEPTH_BITS, 16);\n\n window = glfwCreateWindow( 600, 300, \"SfmViewer\", NULL, NULL );\n if (!window)\n {\n fprintf( stderr, \"Failed to open GLFW window\\n\" );\n glfwTerminate();\n exit( EXIT_FAILURE );\n }\n\n \/\/ Set callback functions\n glfwSetWindowCloseCallback(window, window_close_callback);\n glfwSetWindowSizeCallback(window, reshape);\n glfwSetKeyCallback(window, key);\n\n glfwMakeContextCurrent(window);\n glfwSwapInterval( 1 );\n\n glfwGetWindowSize(window, &width, &height);\n reshape(window, width, height);\n\n m_cur_image.camera = -1;\n \/\/ Main loop\n while( running )\n {\n \/\/ Draw SfM Scene\n draw();\n\n \/\/ Swap buffers\n glfwSwapBuffers(window);\n glfwPollEvents();\n }\n \n \/\/ Terminate GLFW\n glfwTerminate();\n\n \/\/ Exit program\n exit( EXIT_SUCCESS );\n}\n<|endoftext|>"} {"text":"\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner\n\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n#include \"libmesh\/diff_system.h\"\n#include \"libmesh\/dof_map.h\"\n#include \"libmesh\/libmesh_logging.h\"\n#include \"libmesh\/petsc_diff_solver.h\"\n#include \"libmesh\/petsc_matrix.h\"\n#include \"libmesh\/petsc_vector.h\"\n\n#ifdef LIBMESH_HAVE_PETSC\n\nnamespace libMesh\n{\n\n\/\/--------------------------------------------------------------------\n\/\/ Functions with C linkage to pass to PETSc. PETSc will call these\n\/\/ methods as needed.\n\/\/\n\/\/ Since they must have C linkage they have no knowledge of a namespace.\n\/\/ Give them an obscure name to avoid namespace pollution.\nextern \"C\"\n{\n \/\/ Older versions of PETSc do not have the different int typedefs.\n \/\/ On 64-bit machines, PetscInt may actually be a long long int.\n \/\/ This change occurred in Petsc-2.2.1.\n#if PETSC_VERSION_LESS_THAN(2,2,1)\n typedef int PetscErrorCode;\n typedef int PetscInt;\n#endif\n\n\/\/ Function to hand to PETSc's SNES,\n\/\/ which monitors convergence at X\nPetscErrorCode\n__libmesh_petsc_diff_solver_monitor (SNES, PetscInt its,\n PetscReal fnorm, void *ctx)\n{\n PetscDiffSolver& solver =\n *(static_cast (ctx));\n\n if (solver.verbose)\n libMesh::out << \" PetscDiffSolver step \" << its\n << \", |residual|_2 = \" << fnorm << std::endl;\n\n return 0;\n}\n\n\/\/ Functions to hand to PETSc's SNES,\n\/\/ which compute the residual or jacobian at X\nPetscErrorCode\n__libmesh_petsc_diff_solver_residual (SNES, Vec x, Vec r, void *ctx)\n{\n libmesh_assert(x);\n libmesh_assert(r);\n libmesh_assert(ctx);\n\n PetscDiffSolver& solver =\n *(static_cast (ctx));\n ImplicitSystem &sys = solver.system();\n\n if (solver.verbose)\n libMesh::out << \"Assembling the residual\" << std::endl;\n\n PetscVector& X_system =\n *libmesh_cast_ptr*>(sys.solution.get());\n PetscVector& R_system =\n *libmesh_cast_ptr*>(sys.rhs);\n PetscVector X_input(x, sys.comm()), R_input(r, sys.comm());\n\n \/\/ DiffSystem assembles from the solution and into the rhs, so swap\n \/\/ those with our input vectors before assembling. They'll probably\n \/\/ already be references to the same vectors, but PETSc might do\n \/\/ something tricky.\n X_input.swap(X_system);\n R_input.swap(R_system);\n\n \/\/ We may need to correct a non-conforming solution\n sys.get_dof_map().enforce_constraints_exactly(sys);\n\n \/\/ We may need to localize a parallel solution\n sys.update();\n\n \/\/ Do DiffSystem assembly\n sys.assembly(true, false);\n R_system.close();\n\n \/\/ Swap back\n X_input.swap(X_system);\n R_input.swap(R_system);\n\n \/\/ No errors, we hope\n return 0;\n}\n\n\nPetscErrorCode\n__libmesh_petsc_diff_solver_jacobian (SNES, Vec x, Mat *libmesh_dbg_var(j), Mat *pc,\n MatStructure *msflag, void *ctx)\n{\n libmesh_assert(x);\n libmesh_assert(j);\n\/\/ libmesh_assert_equal_to (pc, j); \/\/ We don't use separate preconditioners yet\n libmesh_assert(ctx);\n\n PetscDiffSolver& solver =\n *(static_cast (ctx));\n ImplicitSystem &sys = solver.system();\n\n if (solver.verbose)\n libMesh::out << \"Assembling the Jacobian\" << std::endl;\n\n PetscVector& X_system =\n *libmesh_cast_ptr*>(sys.solution.get());\n PetscVector X_input(x, sys.comm());\n\n PetscMatrix J_input(*pc, sys.comm());\n PetscMatrix& J_system =\n *libmesh_cast_ptr*>(sys.matrix);\n\n \/\/ DiffSystem assembles from the solution and into the jacobian, so\n \/\/ swap those with our input vectors before assembling. They'll\n \/\/ probably already be references to the same vectors, but PETSc\n \/\/ might do something tricky.\n X_input.swap(X_system);\n J_input.swap(J_system);\n\n \/\/ We may need to correct a non-conforming solution\n sys.get_dof_map().enforce_constraints_exactly(sys);\n\n \/\/ We may need to localize a parallel solution\n sys.update();\n\n \/\/ Do DiffSystem assembly\n sys.assembly(false, true);\n J_system.close();\n\n \/\/ Swap back\n X_input.swap(X_system);\n J_input.swap(J_system);\n\n *msflag = SAME_NONZERO_PATTERN;\n\n \/\/ No errors, we hope\n return 0;\n}\n\n} \/\/ extern \"C\"\n\n\nPetscDiffSolver::PetscDiffSolver (sys_type& s)\n : Parent(s)\n{\n}\n\n\nvoid PetscDiffSolver::init ()\n{\n START_LOG(\"init()\", \"PetscDiffSolver\");\n\n Parent::init();\n\n int ierr=0;\n\n#if PETSC_VERSION_LESS_THAN(2,1,2)\n \/\/ At least until Petsc 2.1.1, the SNESCreate had a different\n \/\/ calling syntax. The second argument was of type SNESProblemType,\n \/\/ and could have a value of either SNES_NONLINEAR_EQUATIONS or\n \/\/ SNES_UNCONSTRAINED_MINIMIZATION.\n ierr = SNESCreate(this->comm().get(), SNES_NONLINEAR_EQUATIONS, &_snes);\n LIBMESH_CHKERRABORT(ierr);\n#else\n ierr = SNESCreate(this->comm().get(),&_snes);\n LIBMESH_CHKERRABORT(ierr);\n#endif\n\n#if PETSC_VERSION_LESS_THAN(2,3,3)\n ierr = SNESSetMonitor (_snes, __libmesh_petsc_diff_solver_monitor,\n this, PETSC_NULL);\n#else\n \/\/ API name change in PETSc 2.3.3\n ierr = SNESMonitorSet (_snes, __libmesh_petsc_diff_solver_monitor,\n this, PETSC_NULL);\n#endif\n LIBMESH_CHKERRABORT(ierr);\n\n ierr = SNESSetFromOptions(_snes);\n LIBMESH_CHKERRABORT(ierr);\n\n STOP_LOG(\"init()\", \"PetscDiffSolver\");\n}\n\n\n\nPetscDiffSolver::~PetscDiffSolver ()\n{\n}\n\n\n\nvoid PetscDiffSolver::clear()\n{\n START_LOG(\"clear()\", \"PetscDiffSolver\");\n\n int ierr=0;\n\n ierr = LibMeshSNESDestroy(&_snes);\n LIBMESH_CHKERRABORT(ierr);\n\n STOP_LOG(\"clear()\", \"PetscDiffSolver\");\n}\n\n\n\nvoid PetscDiffSolver::reinit()\n{\n Parent::reinit();\n}\n\n\n\nunsigned int PetscDiffSolver::solve()\n{\n this->init();\n\n START_LOG(\"solve()\", \"PetscDiffSolver\");\n\n PetscVector &x =\n *(libmesh_cast_ptr*>(_system.solution.get()));\n PetscMatrix &jac =\n *(libmesh_cast_ptr*>(_system.matrix));\n PetscVector &r =\n *(libmesh_cast_ptr*>(_system.rhs));\n\n#ifdef LIBMESH_ENABLE_CONSTRAINTS\n _system.get_dof_map().enforce_constraints_exactly(_system);\n#endif\n\n int ierr = 0;\n\n ierr = SNESSetFunction (_snes, r.vec(),\n __libmesh_petsc_diff_solver_residual, this);\n LIBMESH_CHKERRABORT(ierr);\n\n ierr = SNESSetJacobian (_snes, jac.mat(), jac.mat(),\n __libmesh_petsc_diff_solver_jacobian, this);\n LIBMESH_CHKERRABORT(ierr);\n\n# if PETSC_VERSION_LESS_THAN(2,2,0)\n\n ierr = SNESSolve (_snes, x.vec(), &_outer_iterations);\n LIBMESH_CHKERRABORT(ierr);\n\n\/\/ 2.2.x style\n#elif PETSC_VERSION_LESS_THAN(2,3,0)\n\n ierr = SNESSolve (_snes, x.vec());\n LIBMESH_CHKERRABORT(ierr);\n\n\/\/ 2.3.x & newer style\n#else\n\n ierr = SNESSolve (_snes, PETSC_NULL, x.vec());\n LIBMESH_CHKERRABORT(ierr);\n\n#endif\n\n STOP_LOG(\"solve()\", \"PetscDiffSolver\");\n\n this->clear();\n\n \/\/ FIXME - We'll worry about getting the solve result right later...\n\n return DiffSolver::CONVERGED_RELATIVE_RESIDUAL;\n}\n\n} \/\/ namespace libMesh\n\n#endif \/\/ LIBMESH_HAVE_PETSC\nReturn correct solve result\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner\n\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n#include \"libmesh\/diff_system.h\"\n#include \"libmesh\/dof_map.h\"\n#include \"libmesh\/libmesh_logging.h\"\n#include \"libmesh\/petsc_diff_solver.h\"\n#include \"libmesh\/petsc_matrix.h\"\n#include \"libmesh\/petsc_vector.h\"\n\n#ifdef LIBMESH_HAVE_PETSC\n\nnamespace libMesh\n{\n\n\/\/--------------------------------------------------------------------\n\/\/ Functions with C linkage to pass to PETSc. PETSc will call these\n\/\/ methods as needed.\n\/\/\n\/\/ Since they must have C linkage they have no knowledge of a namespace.\n\/\/ Give them an obscure name to avoid namespace pollution.\nextern \"C\"\n{\n \/\/ Older versions of PETSc do not have the different int typedefs.\n \/\/ On 64-bit machines, PetscInt may actually be a long long int.\n \/\/ This change occurred in Petsc-2.2.1.\n#if PETSC_VERSION_LESS_THAN(2,2,1)\n typedef int PetscErrorCode;\n typedef int PetscInt;\n#endif\n\n\/\/ Function to hand to PETSc's SNES,\n\/\/ which monitors convergence at X\nPetscErrorCode\n__libmesh_petsc_diff_solver_monitor (SNES, PetscInt its,\n PetscReal fnorm, void *ctx)\n{\n PetscDiffSolver& solver =\n *(static_cast (ctx));\n\n if (solver.verbose)\n libMesh::out << \" PetscDiffSolver step \" << its\n << \", |residual|_2 = \" << fnorm << std::endl;\n\n return 0;\n}\n\n\/\/ Functions to hand to PETSc's SNES,\n\/\/ which compute the residual or jacobian at X\nPetscErrorCode\n__libmesh_petsc_diff_solver_residual (SNES, Vec x, Vec r, void *ctx)\n{\n libmesh_assert(x);\n libmesh_assert(r);\n libmesh_assert(ctx);\n\n PetscDiffSolver& solver =\n *(static_cast (ctx));\n ImplicitSystem &sys = solver.system();\n\n if (solver.verbose)\n libMesh::out << \"Assembling the residual\" << std::endl;\n\n PetscVector& X_system =\n *libmesh_cast_ptr*>(sys.solution.get());\n PetscVector& R_system =\n *libmesh_cast_ptr*>(sys.rhs);\n PetscVector X_input(x, sys.comm()), R_input(r, sys.comm());\n\n \/\/ DiffSystem assembles from the solution and into the rhs, so swap\n \/\/ those with our input vectors before assembling. They'll probably\n \/\/ already be references to the same vectors, but PETSc might do\n \/\/ something tricky.\n X_input.swap(X_system);\n R_input.swap(R_system);\n\n \/\/ We may need to correct a non-conforming solution\n sys.get_dof_map().enforce_constraints_exactly(sys);\n\n \/\/ We may need to localize a parallel solution\n sys.update();\n\n \/\/ Do DiffSystem assembly\n sys.assembly(true, false);\n R_system.close();\n\n \/\/ Swap back\n X_input.swap(X_system);\n R_input.swap(R_system);\n\n \/\/ No errors, we hope\n return 0;\n}\n\n\nPetscErrorCode\n__libmesh_petsc_diff_solver_jacobian (SNES, Vec x, Mat *libmesh_dbg_var(j), Mat *pc,\n MatStructure *msflag, void *ctx)\n{\n libmesh_assert(x);\n libmesh_assert(j);\n\/\/ libmesh_assert_equal_to (pc, j); \/\/ We don't use separate preconditioners yet\n libmesh_assert(ctx);\n\n PetscDiffSolver& solver =\n *(static_cast (ctx));\n ImplicitSystem &sys = solver.system();\n\n if (solver.verbose)\n libMesh::out << \"Assembling the Jacobian\" << std::endl;\n\n PetscVector& X_system =\n *libmesh_cast_ptr*>(sys.solution.get());\n PetscVector X_input(x, sys.comm());\n\n PetscMatrix J_input(*pc, sys.comm());\n PetscMatrix& J_system =\n *libmesh_cast_ptr*>(sys.matrix);\n\n \/\/ DiffSystem assembles from the solution and into the jacobian, so\n \/\/ swap those with our input vectors before assembling. They'll\n \/\/ probably already be references to the same vectors, but PETSc\n \/\/ might do something tricky.\n X_input.swap(X_system);\n J_input.swap(J_system);\n\n \/\/ We may need to correct a non-conforming solution\n sys.get_dof_map().enforce_constraints_exactly(sys);\n\n \/\/ We may need to localize a parallel solution\n sys.update();\n\n \/\/ Do DiffSystem assembly\n sys.assembly(false, true);\n J_system.close();\n\n \/\/ Swap back\n X_input.swap(X_system);\n J_input.swap(J_system);\n\n *msflag = SAME_NONZERO_PATTERN;\n\n \/\/ No errors, we hope\n return 0;\n}\n\n} \/\/ extern \"C\"\n\n\nPetscDiffSolver::PetscDiffSolver (sys_type& s)\n : Parent(s)\n{\n}\n\n\nvoid PetscDiffSolver::init ()\n{\n START_LOG(\"init()\", \"PetscDiffSolver\");\n\n Parent::init();\n\n int ierr=0;\n\n#if PETSC_VERSION_LESS_THAN(2,1,2)\n \/\/ At least until Petsc 2.1.1, the SNESCreate had a different\n \/\/ calling syntax. The second argument was of type SNESProblemType,\n \/\/ and could have a value of either SNES_NONLINEAR_EQUATIONS or\n \/\/ SNES_UNCONSTRAINED_MINIMIZATION.\n ierr = SNESCreate(this->comm().get(), SNES_NONLINEAR_EQUATIONS, &_snes);\n LIBMESH_CHKERRABORT(ierr);\n#else\n ierr = SNESCreate(this->comm().get(),&_snes);\n LIBMESH_CHKERRABORT(ierr);\n#endif\n\n#if PETSC_VERSION_LESS_THAN(2,3,3)\n ierr = SNESSetMonitor (_snes, __libmesh_petsc_diff_solver_monitor,\n this, PETSC_NULL);\n#else\n \/\/ API name change in PETSc 2.3.3\n ierr = SNESMonitorSet (_snes, __libmesh_petsc_diff_solver_monitor,\n this, PETSC_NULL);\n#endif\n LIBMESH_CHKERRABORT(ierr);\n\n ierr = SNESSetFromOptions(_snes);\n LIBMESH_CHKERRABORT(ierr);\n\n STOP_LOG(\"init()\", \"PetscDiffSolver\");\n}\n\n\n\nPetscDiffSolver::~PetscDiffSolver ()\n{\n}\n\n\n\nvoid PetscDiffSolver::clear()\n{\n START_LOG(\"clear()\", \"PetscDiffSolver\");\n\n int ierr=0;\n\n ierr = LibMeshSNESDestroy(&_snes);\n LIBMESH_CHKERRABORT(ierr);\n\n STOP_LOG(\"clear()\", \"PetscDiffSolver\");\n}\n\n\n\nvoid PetscDiffSolver::reinit()\n{\n Parent::reinit();\n}\n\nDiffSolver::SolveResult convert_solve_result(SNESConvergedReason r) {\n\tswitch (r) {\n\t\tcase SNES_CONVERGED_FNORM_ABS:\n\t\t\treturn DiffSolver::CONVERGED_ABSOLUTE_RESIDUAL;\n\t\tcase SNES_CONVERGED_FNORM_RELATIVE:\n\t\t\treturn DiffSolver::CONVERGED_RELATIVE_RESIDUAL;\n\t\tcase SNES_CONVERGED_SNORM_RELATIVE:\n\t\t\treturn DiffSolver::CONVERGED_RELATIVE_STEP;\n\t\tcase SNES_CONVERGED_ITS:\n\t\tcase SNES_CONVERGED_TR_DELTA:\n\t\t\treturn DiffSolver::CONVERGED_NO_REASON;\n\t\tcase SNES_DIVERGED_FUNCTION_DOMAIN:\n\t\tcase SNES_DIVERGED_FUNCTION_COUNT:\n\t\tcase SNES_DIVERGED_FNORM_NAN:\n\t\tcase SNES_DIVERGED_INNER:\n\t\tcase SNES_DIVERGED_LINEAR_SOLVE:\n\t\tcase SNES_DIVERGED_LOCAL_MIN:\n\t\t\treturn DiffSolver::DIVERGED_NO_REASON;\n\t\tcase SNES_DIVERGED_MAX_IT:\n\t\t\treturn DiffSolver::DIVERGED_MAX_NONLINEAR_ITERATIONS;\n\t\tcase SNES_DIVERGED_LINE_SEARCH:\n\t\t\treturn DiffSolver::DIVERGED_BACKTRACKING_FAILURE;\n\t}\n\treturn DiffSolver::INVALID_SOLVE_RESULT;\n}\n\nunsigned int PetscDiffSolver::solve()\n{\n this->init();\n\n START_LOG(\"solve()\", \"PetscDiffSolver\");\n\n PetscVector &x =\n *(libmesh_cast_ptr*>(_system.solution.get()));\n PetscMatrix &jac =\n *(libmesh_cast_ptr*>(_system.matrix));\n PetscVector &r =\n *(libmesh_cast_ptr*>(_system.rhs));\n\n#ifdef LIBMESH_ENABLE_CONSTRAINTS\n _system.get_dof_map().enforce_constraints_exactly(_system);\n#endif\n\n int ierr = 0;\n\n ierr = SNESSetFunction (_snes, r.vec(),\n __libmesh_petsc_diff_solver_residual, this);\n LIBMESH_CHKERRABORT(ierr);\n\n ierr = SNESSetJacobian (_snes, jac.mat(), jac.mat(),\n __libmesh_petsc_diff_solver_jacobian, this);\n LIBMESH_CHKERRABORT(ierr);\n\n# if PETSC_VERSION_LESS_THAN(2,2,0)\n\n ierr = SNESSolve (_snes, x.vec(), &_outer_iterations);\n LIBMESH_CHKERRABORT(ierr);\n\n\/\/ 2.2.x style\n#elif PETSC_VERSION_LESS_THAN(2,3,0)\n\n ierr = SNESSolve (_snes, x.vec());\n LIBMESH_CHKERRABORT(ierr);\n\n\/\/ 2.3.x & newer style\n#else\n\n ierr = SNESSolve (_snes, PETSC_NULL, x.vec());\n LIBMESH_CHKERRABORT(ierr);\n\n#endif\n\n STOP_LOG(\"solve()\", \"PetscDiffSolver\");\n\n SNESConvergedReason reason;\n SNESGetConvergedReason(_snes, &reason);\n\n this->clear();\n\n return convert_solve_result(reason);\n}\n\n\n} \/\/ namespace libMesh\n\n#endif \/\/ LIBMESH_HAVE_PETSC\n<|endoftext|>"} {"text":"#include \"util\/Role.h\"\n#include \"core\/RoleFactory.h\"\n#include \"core\/global.h\"\n#include \n#include \n#include \"dcparser\/dcClass.h\"\n#include \"dcparser\/dcField.h\"\n\n#pragma region definitions\n#define STATESERVER_OBJECT_GENERATE_WITH_REQUIRED 2001\n#define STATESERVER_OBJECT_GENERATE_WITH_REQUIRED_OTHER 2003\n#define STATESERVER_OBJECT_UPDATE_FIELD 2004\n#define STATESERVER_OBJECT_UPDATE_FIELD_MULTIPLE 2005\n#define STATESERVER_OBJECT_DELETE_RAM 2007\n#define STATESERVER_OBJECT_SET_ZONE 2008\n#define STATESERVER_OBJECT_CHANGE_ZONE 2009\n#define STATESERVER_OBJECT_NOTFOUND 2015\n#define STATESERVER_QUERY_OBJECT_ALL 2020\n#define STATESERVER_QUERY_ZONE_OBJECT_ALL 2021\n#define STATESERVER_OBJECT_LOCATE 2022\n#define STATESERVER_OBJECT_LOCATE_RESP 2023\n#define STATESERVER_OBJECT_QUERY_FIELD 2024\n#define STATESERVER_QUERY_OBJECT_ALL_RESP 2030\n#define STATESERVER_OBJECT_LEAVING_AI_INTEREST 2033\n#define STATESERVER_ADD_AI_RECV 2045\n#define STATESERVER_QUERY_ZONE_OBJECT_ALL_DONE 2046\n#define STATESERVER_OBJECT_CREATE_WITH_REQUIRED_CONTEXT 2050\n#define STATESERVER_OBJECT_CREATE_WITH_REQUIR_OTHER_CONTEXT 2051\n#define STATESERVER_OBJECT_CREATE_WITH_REQUIRED_CONTEXT_RESP 2052\n#define STATESERVER_OBJECT_CREATE_WITH_REQUIR_OTHER_CONTEXT_RESP 2053\n#define STATESERVER_OBJECT_DELETE_DISK 2060\n#define STATESERVER_SHARD_REST 2061\n#define STATESERVER_OBJECT_QUERY_FIELD_RESP 2062\n#define STATESERVER_OBJECT_ENTERZONE_WITH_REQUIRED 2065\n#define STATESERVER_OBJECT_ENTERZONE_WITH_REQUIRED_OTHER 2066\n#define STATESERVER_OBJECT_ENTER_AI_RECV 2067\n#define STATESERVER_OBJECT_ENTER_OWNER_RECV 2068\n#define STATESERVER_OBJECT_CHANGE_OWNER_RECV 2069\n#define STATESERVER_OBJECT_SET_OWNER_RECV 2070\n#define STATESERVER_OBJECT_QUERY_FIELDS 2080\n#define STATESERVER_OBJECT_QUERY_FIELDS_RESP 2081\n#define STATESERVER_OBJECT_QUERY_FIELDS_STRING 2082\n#define STATESERVER_OBJECT_QUERY_MANAGING_AI 2083\n#define STATESERVER_BOUNCE_MESSAGE 2086\n#define STATESERVER_QUERY_OBJECT_CHILDREN_LOCAL 2087\n#define STATESERVER_QUERY_OBJECT_CHILDREN_LOCAL_DONE 2089\n#define STATESERVER_QUERY_OBJECT_CHILDREN_RESP 2087\n\n#define LOCATION2CHANNEL(p, z) unsigned long long(p)<<32|unsigned long long(z)\n#pragma endregion\n\nvoid UnpackFieldFromDG(DCPackerInterface *field, DatagramIterator &dgi, std::string &str)\n{\n\tif(field->has_fixed_byte_size())\n\t{\n\t\tstr += dgi.read_data(field->get_fixed_byte_size());\n\t}\n\telse if(field->get_num_length_bytes() > 0)\n\t{\n\t\tunsigned int length = field->get_num_length_bytes();\n\t\tswitch(length)\n\t\t{\n\t\tcase 2:\n\t\t{\n\t\t\tunsigned short l = dgi.read_uint16();\n\t\t\tstr += std::string((char*)&l, 2);\n\t\t\tlength = l;\n\t\t}\n\t\tbreak;\n\t\tcase 4:\n\t\t{\n\t\t\tunsigned int l = dgi.read_uint32();\n\t\t\tstr += std::string((char*)&l, 4);\n\t\t\tlength = l;\n\t\t}\n\t\tbreak;\n\t\tbreak;\n\t\t}\n\t\tstr += dgi.read_data(length);\n\t}\n\telse\n\t{\n\t\tunsigned int nNested = field->get_num_nested_fields();\n\t\tfor(unsigned int i = 0; i < nNested; ++i)\n\t\t{\n\t\t\tUnpackFieldFromDG(field->get_nested_field(i), dgi, str);\n\t\t}\n\t}\n}\n\nstruct DistributedObject\n{\n\tunsigned long long owner;\n\tunsigned int parentId;\n\tunsigned int zoneId;\n\tunsigned int doId;\n\tDCClass *dcc;\n\tstd::map fields;\n};\n\nstd::map distObjs;\n\nConfigVariable cfg_channel(\"control\", 0);\n\nclass StateServer : public Role\n{\n\tpublic:\n\t\tStateServer(RoleConfig roleconfig) : Role(roleconfig)\n\t\t{\n\t\t\tMessageDirector::singleton.subscribe_channel(this, cfg_channel.get_rval(m_roleconfig));\n\t\t}\n\n\t\tvirtual bool handle_datagram(Datagram *dg, DatagramIterator &dgi)\n\t\t{\n\t\t\tunsigned long long sender = dgi.read_uint64();\n\t\t\tunsigned short MsgType = dgi.read_uint16();\n\t\t\tswitch(MsgType)\n\t\t\t{\n\t\t\t\tcase STATESERVER_OBJECT_GENERATE_WITH_REQUIRED:\n\t\t\t\t{\n\t\t\t\t\tunsigned int parentId = dgi.read_uint32();\n\t\t\t\t\tunsigned int zoneId = dgi.read_uint32();\n\t\t\t\t\tunsigned short dcId = dgi.read_uint16();\n\t\t\t\t\tunsigned int doId = dgi.read_uint32();\n\n\t\t\t\t\tDistributedObject *obj = new DistributedObject;\n\t\t\t\t\tobj->doId = doId;\n\t\t\t\t\tobj->parentId = parentId;\n\t\t\t\t\tobj->zoneId = zoneId;\n\t\t\t\t\tobj->owner = sender;\n\t\t\t\t\tobj->dcc = gDCF->get_class(dcId);\n\t\t\t\t\tfor(int i = 0; i < obj->dcc->get_num_inherited_fields(); ++i)\n\t\t\t\t\t{\n\t\t\t\t\t\tDCField *field = obj->dcc->get_inherited_field(i);\n\t\t\t\t\t\tif(field->is_required() && !field->as_molecular_field())\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tUnpackFieldFromDG(field, dgi, obj->fields[field]);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tdistObjs[doId] = obj;\n\t\t\t\t\tMessageDirector::singleton.subscribe_channel(this, doId);\n\n\t\t\t\t\tDatagram resp;\n\t\t\t\t\tresp.add_uint8(1);\n\t\t\t\t\tresp.add_uint64(LOCATION2CHANNEL(parentId, zoneId));\n\t\t\t\t\tresp.add_uint64(doId);\n\t\t\t\t\tresp.add_uint16(STATESERVER_OBJECT_ENTERZONE_WITH_REQUIRED);\n\t\t\t\t\tresp.add_uint32(parentId);\n\t\t\t\t\tresp.add_uint32(zoneId);\n\t\t\t\t\tresp.add_uint16(dcId);\n\t\t\t\t\tresp.add_uint32(doId);\n\t\t\t\t\tfor(auto it = obj->fields.begin(); it != obj->fields.end(); ++it)\n\t\t\t\t\t{\n\t\t\t\t\t\tresp.add_data(it->second);\n\t\t\t\t\t}\n\n\t\t\t\t\tMessageDirector::singleton.handle_datagram(&resp, this);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t\tcase STATESERVER_OBJECT_DELETE_RAM:\n\t\t\t\t{\n\t\t\t\t\tunsigned int doId = dgi.read_uint32();\n\t\t\t\t\tDistributedObject *obj = distObjs[doId];\n\t\t\t\t\tif(obj)\n\t\t\t\t\t{\n\t\t\t\t\t\tunsigned long long loc = LOCATION2CHANNEL(obj->parentId, obj->zoneId);\n\t\t\t\t\t\tDatagram resp;\n\t\t\t\t\t\tresp.add_uint8(1);\n\t\t\t\t\t\tresp.add_uint64(loc);\n\t\t\t\t\t\tresp.add_uint64(doId);\n\t\t\t\t\t\tresp.add_uint16(STATESERVER_OBJECT_DELETE_RAM);\n\t\t\t\t\t\tresp.add_uint32(doId);\n\t\t\t\t\t\tMessageDirector::singleton.handle_datagram(&resp, this);\n\t\t\t\t\t\tdistObjs[doId] = NULL;\n\t\t\t\t\t\tdelete obj;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tgLogger->error() << \"StateServer recv'd unknown msgtype: \" << MsgType << std::endl;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n};\n\nRoleFactoryItem ss_fact(\"stateserver\");StateServer: Implement STATESERVER_OBJECT_UPDATE_FIELD; 2\/2 tests pass#include \"util\/Role.h\"\n#include \"core\/RoleFactory.h\"\n#include \"core\/global.h\"\n#include \n#include \n#include \"dcparser\/dcClass.h\"\n#include \"dcparser\/dcField.h\"\n\n#pragma region definitions\n#define STATESERVER_OBJECT_GENERATE_WITH_REQUIRED 2001\n#define STATESERVER_OBJECT_GENERATE_WITH_REQUIRED_OTHER 2003\n#define STATESERVER_OBJECT_UPDATE_FIELD 2004\n#define STATESERVER_OBJECT_UPDATE_FIELD_MULTIPLE 2005\n#define STATESERVER_OBJECT_DELETE_RAM 2007\n#define STATESERVER_OBJECT_SET_ZONE 2008\n#define STATESERVER_OBJECT_CHANGE_ZONE 2009\n#define STATESERVER_OBJECT_NOTFOUND 2015\n#define STATESERVER_QUERY_OBJECT_ALL 2020\n#define STATESERVER_QUERY_ZONE_OBJECT_ALL 2021\n#define STATESERVER_OBJECT_LOCATE 2022\n#define STATESERVER_OBJECT_LOCATE_RESP 2023\n#define STATESERVER_OBJECT_QUERY_FIELD 2024\n#define STATESERVER_QUERY_OBJECT_ALL_RESP 2030\n#define STATESERVER_OBJECT_LEAVING_AI_INTEREST 2033\n#define STATESERVER_ADD_AI_RECV 2045\n#define STATESERVER_QUERY_ZONE_OBJECT_ALL_DONE 2046\n#define STATESERVER_OBJECT_CREATE_WITH_REQUIRED_CONTEXT 2050\n#define STATESERVER_OBJECT_CREATE_WITH_REQUIR_OTHER_CONTEXT 2051\n#define STATESERVER_OBJECT_CREATE_WITH_REQUIRED_CONTEXT_RESP 2052\n#define STATESERVER_OBJECT_CREATE_WITH_REQUIR_OTHER_CONTEXT_RESP 2053\n#define STATESERVER_OBJECT_DELETE_DISK 2060\n#define STATESERVER_SHARD_REST 2061\n#define STATESERVER_OBJECT_QUERY_FIELD_RESP 2062\n#define STATESERVER_OBJECT_ENTERZONE_WITH_REQUIRED 2065\n#define STATESERVER_OBJECT_ENTERZONE_WITH_REQUIRED_OTHER 2066\n#define STATESERVER_OBJECT_ENTER_AI_RECV 2067\n#define STATESERVER_OBJECT_ENTER_OWNER_RECV 2068\n#define STATESERVER_OBJECT_CHANGE_OWNER_RECV 2069\n#define STATESERVER_OBJECT_SET_OWNER_RECV 2070\n#define STATESERVER_OBJECT_QUERY_FIELDS 2080\n#define STATESERVER_OBJECT_QUERY_FIELDS_RESP 2081\n#define STATESERVER_OBJECT_QUERY_FIELDS_STRING 2082\n#define STATESERVER_OBJECT_QUERY_MANAGING_AI 2083\n#define STATESERVER_BOUNCE_MESSAGE 2086\n#define STATESERVER_QUERY_OBJECT_CHILDREN_LOCAL 2087\n#define STATESERVER_QUERY_OBJECT_CHILDREN_LOCAL_DONE 2089\n#define STATESERVER_QUERY_OBJECT_CHILDREN_RESP 2087\n\n#define LOCATION2CHANNEL(p, z) unsigned long long(p)<<32|unsigned long long(z)\n#pragma endregion\n\nvoid UnpackFieldFromDG(DCPackerInterface *field, DatagramIterator &dgi, std::string &str)\n{\n\tif(field->has_fixed_byte_size())\n\t{\n\t\tstr += dgi.read_data(field->get_fixed_byte_size());\n\t}\n\telse if(field->get_num_length_bytes() > 0)\n\t{\n\t\tunsigned int length = field->get_num_length_bytes();\n\t\tswitch(length)\n\t\t{\n\t\tcase 2:\n\t\t{\n\t\t\tunsigned short l = dgi.read_uint16();\n\t\t\tstr += std::string((char*)&l, 2);\n\t\t\tlength = l;\n\t\t}\n\t\tbreak;\n\t\tcase 4:\n\t\t{\n\t\t\tunsigned int l = dgi.read_uint32();\n\t\t\tstr += std::string((char*)&l, 4);\n\t\t\tlength = l;\n\t\t}\n\t\tbreak;\n\t\tbreak;\n\t\t}\n\t\tstr += dgi.read_data(length);\n\t}\n\telse\n\t{\n\t\tunsigned int nNested = field->get_num_nested_fields();\n\t\tfor(unsigned int i = 0; i < nNested; ++i)\n\t\t{\n\t\t\tUnpackFieldFromDG(field->get_nested_field(i), dgi, str);\n\t\t}\n\t}\n}\n\nstruct DistributedObject\n{\n\tunsigned long long owner;\n\tunsigned int parentId;\n\tunsigned int zoneId;\n\tunsigned int doId;\n\tDCClass *dcc;\n\tstd::map fields;\n};\n\nstd::map distObjs;\n\nConfigVariable cfg_channel(\"control\", 0);\n\nclass StateServer : public Role\n{\n\tpublic:\n\t\tStateServer(RoleConfig roleconfig) : Role(roleconfig)\n\t\t{\n\t\t\tMessageDirector::singleton.subscribe_channel(this, cfg_channel.get_rval(m_roleconfig));\n\t\t}\n\n\t\tvirtual bool handle_datagram(Datagram *dg, DatagramIterator &dgi)\n\t\t{\n\t\t\tunsigned long long sender = dgi.read_uint64();\n\t\t\tunsigned short MsgType = dgi.read_uint16();\n\t\t\tswitch(MsgType)\n\t\t\t{\n\t\t\t\tcase STATESERVER_OBJECT_GENERATE_WITH_REQUIRED:\n\t\t\t\t{\n\t\t\t\t\tunsigned int parentId = dgi.read_uint32();\n\t\t\t\t\tunsigned int zoneId = dgi.read_uint32();\n\t\t\t\t\tunsigned short dcId = dgi.read_uint16();\n\t\t\t\t\tunsigned int doId = dgi.read_uint32();\n\n\t\t\t\t\tDistributedObject *obj = new DistributedObject;\n\t\t\t\t\tobj->doId = doId;\n\t\t\t\t\tobj->parentId = parentId;\n\t\t\t\t\tobj->zoneId = zoneId;\n\t\t\t\t\tobj->owner = sender;\n\t\t\t\t\tobj->dcc = gDCF->get_class(dcId);\n\t\t\t\t\tfor(int i = 0; i < obj->dcc->get_num_inherited_fields(); ++i)\n\t\t\t\t\t{\n\t\t\t\t\t\tDCField *field = obj->dcc->get_inherited_field(i);\n\t\t\t\t\t\tif(field->is_required() && !field->as_molecular_field())\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tUnpackFieldFromDG(field, dgi, obj->fields[field]);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tdistObjs[doId] = obj;\n\t\t\t\t\tMessageDirector::singleton.subscribe_channel(this, doId);\n\n\t\t\t\t\tDatagram resp;\n\t\t\t\t\tresp.add_uint8(1);\n\t\t\t\t\tresp.add_uint64(LOCATION2CHANNEL(parentId, zoneId));\n\t\t\t\t\tresp.add_uint64(doId);\n\t\t\t\t\tresp.add_uint16(STATESERVER_OBJECT_ENTERZONE_WITH_REQUIRED);\n\t\t\t\t\tresp.add_uint32(parentId);\n\t\t\t\t\tresp.add_uint32(zoneId);\n\t\t\t\t\tresp.add_uint16(dcId);\n\t\t\t\t\tresp.add_uint32(doId);\n\t\t\t\t\tfor(auto it = obj->fields.begin(); it != obj->fields.end(); ++it)\n\t\t\t\t\t{\n\t\t\t\t\t\tresp.add_data(it->second);\n\t\t\t\t\t}\n\n\t\t\t\t\tMessageDirector::singleton.handle_datagram(&resp, this);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t\tcase STATESERVER_OBJECT_DELETE_RAM:\n\t\t\t\t{\n\t\t\t\t\tunsigned int doId = dgi.read_uint32();\n\t\t\t\t\tDistributedObject *obj = distObjs[doId];\n\t\t\t\t\tif(obj)\n\t\t\t\t\t{\n\t\t\t\t\t\tunsigned long long loc = LOCATION2CHANNEL(obj->parentId, obj->zoneId);\n\t\t\t\t\t\tDatagram resp;\n\t\t\t\t\t\tresp.add_uint8(1);\n\t\t\t\t\t\tresp.add_uint64(loc);\n\t\t\t\t\t\tresp.add_uint64(doId);\n\t\t\t\t\t\tresp.add_uint16(STATESERVER_OBJECT_DELETE_RAM);\n\t\t\t\t\t\tresp.add_uint32(doId);\n\t\t\t\t\t\tMessageDirector::singleton.handle_datagram(&resp, this);\n\t\t\t\t\t\tdistObjs[doId] = NULL;\n\t\t\t\t\t\tdelete obj;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t\tcase STATESERVER_OBJECT_UPDATE_FIELD:\n\t\t\t\t{\n\t\t\t\t\tunsigned int doId = dgi.read_uint32();\n\t\t\t\t\tunsigned int fieldId = dgi.read_uint16();\n\t\t\t\t\tif(distObjs[doId])\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::string data;\n\t\t\t\t\t\tDCField *field = distObjs[doId]->dcc->get_field_by_index(fieldId);\n\t\t\t\t\t\tUnpackFieldFromDG(field, dgi, data);\n\t\t\t\t\t\tif(field->is_required())\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tdistObjs[doId]->fields[field] = data;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(field->is_broadcast())\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tDatagram resp;\n\t\t\t\t\t\t\tresp.add_uint8(1);\n\t\t\t\t\t\t\tresp.add_uint64(LOCATION2CHANNEL(distObjs[doId]->parentId, distObjs[doId]->zoneId));\n\t\t\t\t\t\t\tresp.add_uint64(sender);\n\t\t\t\t\t\t\tresp.add_uint16(STATESERVER_OBJECT_UPDATE_FIELD);\n\t\t\t\t\t\t\tresp.add_uint32(doId);\n\t\t\t\t\t\t\tresp.add_uint16(fieldId);\n\t\t\t\t\t\t\tresp.add_data(data);\n\t\t\t\t\t\t\tMessageDirector::singleton.handle_datagram(&resp, this);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tgLogger->error() << \"StateServer recv'd unknown msgtype: \" << MsgType << std::endl;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n};\n\nRoleFactoryItem ss_fact(\"stateserver\");<|endoftext|>"} {"text":"\/*\n* (C) 2019 Jack Lloyd\n*\n* Botan is released under the Simplified BSD License (see license.txt)\n*\/\n\n#include \"tests.h\"\n\n#if defined(BOTAN_TARGET_OS_HAS_THREADS) && defined(BOTAN_HAS_THREAD_UTILS)\n\n#include \n#include \n\nnamespace Botan_Tests {\n\n\/\/ TODO test Barrier\n\/\/ TODO test Semaphore\n\nnamespace {\n\nTest::Result thread_pool()\n {\n Test::Result result(\"Thread_Pool\");\n\n \/\/ Using lots of threads since here the works spend most of the time sleeping\n Botan::Thread_Pool pool(16);\n\n auto sleep_and_return = [](size_t x) -> size_t {\n std::this_thread::sleep_for(std::chrono::milliseconds((x*97)%127));\n return x;\n };\n\n std::vector> futures;\n for(size_t i = 0; i != 100; ++i)\n {\n auto fut = pool.run(sleep_and_return, i);\n futures.push_back(std::move(fut));\n }\n\n for(size_t i = 0; i != futures.size(); ++i)\n {\n result.test_eq(\"Expected return value\", futures[i].get(), i);\n }\n\n pool.shutdown();\n\n return result;\n }\n\nBOTAN_REGISTER_TEST_FN(\"thread_pool\", thread_pool);\n\n}\n\n}\n\n#endif\nAdd a test that Theaad_Pool is tolerant of exceptions during tasks\/*\n* (C) 2019 Jack Lloyd\n*\n* Botan is released under the Simplified BSD License (see license.txt)\n*\/\n\n#include \"tests.h\"\n\n#if defined(BOTAN_TARGET_OS_HAS_THREADS) && defined(BOTAN_HAS_THREAD_UTILS)\n\n#include \n#include \n\nnamespace Botan_Tests {\n\n\/\/ TODO test Barrier\n\/\/ TODO test Semaphore\n\nnamespace {\n\nTest::Result thread_pool()\n {\n Test::Result result(\"Thread_Pool\");\n\n \/\/ Using lots of threads since here the works spend most of the time sleeping\n Botan::Thread_Pool pool(16);\n\n auto sleep_or_throw = [](size_t x) -> size_t {\n std::this_thread::sleep_for(std::chrono::milliseconds((x*97)%127));\n\n if(x % 2 == 0)\n throw x;\n return x;\n };\n\n std::vector> futures;\n for(size_t i = 0; i != 100; ++i)\n {\n auto fut = pool.run(sleep_or_throw, i);\n futures.push_back(std::move(fut));\n }\n\n for(size_t i = 0; i != futures.size(); ++i)\n {\n if(i % 2 == 0)\n {\n try\n {\n futures[i].get();\n result.test_failure(\"Expected future to throw\");\n }\n catch(size_t x)\n {\n result.test_eq(\"Expected thrown value\", x, i);\n }\n }\n else\n {\n result.test_eq(\"Expected return value\", futures[i].get(), i);\n }\n }\n\n pool.shutdown();\n\n return result;\n }\n\nBOTAN_REGISTER_TEST_FN(\"thread_pool\", thread_pool);\n\n}\n\n}\n\n#endif\n<|endoftext|>"} {"text":"\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2010-2012 Francois Beaune, Jupiter Jazz Limited\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Project headers.\n#include \"commandlinehandler.h\"\n\n\/\/ appleseed.shared headers.\n#include \"application\/application.h\"\n#include \"application\/superlogger.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/core\/exceptions\/exception.h\"\n#include \"foundation\/core\/exceptions\/stringexception.h\"\n#include \"foundation\/image\/canvasproperties.h\"\n#include \"foundation\/image\/genericprogressiveimagefilereader.h\"\n#include \"foundation\/image\/imageattributes.h\"\n#include \"foundation\/image\/progressiveexrimagefilewriter.h\"\n#include \"foundation\/image\/tile.h\"\n#include \"foundation\/platform\/types.h\"\n#include \"foundation\/utility\/autoreleaseptr.h\"\n#include \"foundation\/utility\/log.h\"\n\n\/\/ OpenEXR headers.\n#include \"OpenEXR\/ImfChannelList.h\"\n#include \"OpenEXR\/ImfFrameBuffer.h\"\n#include \"OpenEXR\/ImfHeader.h\"\n#include \"OpenEXR\/ImfPixelType.h\"\n#include \"OpenEXR\/ImfTileDescription.h\"\n\n\/\/ Standard headers.\n#include \n\nusing namespace appleseed::maketiledexr;\nusing namespace appleseed::shared;\nusing namespace foundation;\nusing namespace std;\n\n\n\/\/\n\/\/ Entry point of maketiledexr.\n\/\/\n\nint main(int argc, const char* argv[])\n{\n SuperLogger logger;\n\n Application::check_installation(logger);\n\n CommandLineHandler cl;\n cl.parse(argc, argv, logger);\n\n \/\/ Retrieve the tile size.\n size_t tile_width = 32;\n size_t tile_height = 32;\n if (cl.m_tile_size.is_set())\n {\n const int tw = cl.m_tile_size.values()[0];\n const int th = cl.m_tile_size.values()[1];\n if (tw > 0 && th > 0)\n {\n tile_width = static_cast(tw);\n tile_height = static_cast(th);\n }\n else\n {\n LOG_ERROR(\n logger,\n \"invalid tile size, using default size %dx%d pixels.\",\n tile_width,\n tile_height);\n }\n }\n\n try\n {\n \/\/ Open the input file.\n GenericProgressiveImageFileReader reader(&logger, tile_width, tile_height);\n reader.open(cl.m_filenames.values()[0].c_str());\n\n \/\/ Read canvas properties from the input file.\n CanvasProperties props;\n reader.read_canvas_properties(props);\n\n \/\/ Read image attributes from the input file.\n ImageAttributes attrs;\n reader.read_image_attributes(attrs);\n\n \/\/ Open the output file.\n ProgressiveEXRImageFileWriter writer(&logger);\n writer.open(cl.m_filenames.values()[1].c_str(), props, attrs);\n\n \/\/ Copy the tiles.\n for (size_t y = 0; y < props.m_tile_count_y; ++y)\n {\n \/\/ Print a progress message.\n if (cl.m_progress_messages.is_set())\n {\n LOG_INFO(\n logger,\n \"processing tile row \" FMT_SIZE_T \"\/\" FMT_SIZE_T \"...\",\n y + 1,\n props.m_tile_count_y);\n }\n\n for (size_t x = 0; x < props.m_tile_count_x; ++x)\n {\n \/\/ Read the tile.\n auto_release_ptr tile(reader.read_tile(x, y));\n\n \/\/ Write the tile.\n writer.write_tile(*tile.get(), x, y);\n }\n }\n\n \/\/ Close the files.\n writer.close();\n reader.close();\n }\n catch (const StringException& e)\n {\n LOG_FATAL(logger, \"%s: %s\", e.what(), e.string());\n return 1;\n }\n catch (const Exception& e)\n {\n LOG_FATAL(logger, \"%s\", e.what());\n return 1;\n }\n\n return 0;\n}\nmaketiledexr will now generate a floating-point (32-bit) OpenEXR file if the pixel format of the input image is not supported by OpenEXR.\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2010-2012 Francois Beaune, Jupiter Jazz Limited\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Project headers.\n#include \"commandlinehandler.h\"\n\n\/\/ appleseed.shared headers.\n#include \"application\/application.h\"\n#include \"application\/superlogger.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/core\/exceptions\/exception.h\"\n#include \"foundation\/core\/exceptions\/stringexception.h\"\n#include \"foundation\/image\/canvasproperties.h\"\n#include \"foundation\/image\/exceptionunsupportedimageformat.h\"\n#include \"foundation\/image\/genericprogressiveimagefilereader.h\"\n#include \"foundation\/image\/imageattributes.h\"\n#include \"foundation\/image\/pixel.h\"\n#include \"foundation\/image\/progressiveexrimagefilewriter.h\"\n#include \"foundation\/image\/tile.h\"\n#include \"foundation\/platform\/types.h\"\n#include \"foundation\/utility\/autoreleaseptr.h\"\n#include \"foundation\/utility\/log.h\"\n\n\/\/ OpenEXR headers.\n#include \"OpenEXR\/ImfChannelList.h\"\n#include \"OpenEXR\/ImfFrameBuffer.h\"\n#include \"OpenEXR\/ImfHeader.h\"\n#include \"OpenEXR\/ImfPixelType.h\"\n#include \"OpenEXR\/ImfTileDescription.h\"\n\n\/\/ Standard headers.\n#include \n#include \n\nusing namespace appleseed::maketiledexr;\nusing namespace appleseed::shared;\nusing namespace foundation;\nusing namespace std;\n\n\n\/\/\n\/\/ Entry point of maketiledexr.\n\/\/\n\nint main(int argc, const char* argv[])\n{\n SuperLogger logger;\n Application::check_installation(logger);\n\n CommandLineHandler cl;\n cl.parse(argc, argv, logger);\n\n \/\/ Retrieve the tile size.\n size_t tile_width = 32;\n size_t tile_height = 32;\n if (cl.m_tile_size.is_set())\n {\n const int tw = cl.m_tile_size.values()[0];\n const int th = cl.m_tile_size.values()[1];\n if (tw > 0 && th > 0)\n {\n tile_width = static_cast(tw);\n tile_height = static_cast(th);\n }\n else\n {\n LOG_ERROR(\n logger,\n \"invalid tile size, using default size %dx%d pixels.\",\n tile_width,\n tile_height);\n }\n }\n\n try\n {\n \/\/ Open the input file.\n GenericProgressiveImageFileReader reader(&logger, tile_width, tile_height);\n reader.open(cl.m_filenames.values()[0].c_str());\n\n \/\/ Read canvas properties from the input file.\n CanvasProperties props;\n reader.read_canvas_properties(props);\n\n \/\/ Read image attributes from the input file.\n ImageAttributes attrs;\n reader.read_image_attributes(attrs);\n\n \/\/ Open the output file.\n ProgressiveEXRImageFileWriter writer(&logger);\n bool require_format_conversion = false;\n try\n {\n writer.open(cl.m_filenames.values()[1].c_str(), props, attrs);\n }\n catch (const ExceptionUnsupportedImageFormat&)\n {\n props =\n CanvasProperties(\n props.m_canvas_width,\n props.m_canvas_height,\n props.m_tile_width,\n props.m_tile_height,\n props.m_channel_count,\n PixelFormatFloat);\n writer.open(cl.m_filenames.values()[1].c_str(), props, attrs);\n require_format_conversion = true;\n }\n\n \/\/ Copy the tiles.\n for (size_t y = 0; y < props.m_tile_count_y; ++y)\n {\n \/\/ Print a progress message for every row.\n if (cl.m_progress_messages.is_set())\n {\n LOG_INFO(\n logger,\n \"processing tile row \" FMT_SIZE_T \"\/\" FMT_SIZE_T \"...\",\n y + 1,\n props.m_tile_count_y);\n }\n\n \/\/ Copy the tiles from this row.\n for (size_t x = 0; x < props.m_tile_count_x; ++x)\n {\n \/\/ Read the tile. Use auto_release_ptr<> because the image\n \/\/ was allocated in appleseed's shared library.\n auto_release_ptr tile(reader.read_tile(x, y));\n\n if (require_format_conversion)\n {\n \/\/ Convert and write the tile.\n auto_ptr converted_tile(new Tile(tile.ref(), PixelFormatFloat));\n writer.write_tile(*converted_tile.get(), x, y);\n }\n else\n {\n \/\/ Write the tile.\n writer.write_tile(tile.ref(), x, y);\n }\n }\n }\n\n \/\/ Close the files.\n writer.close();\n reader.close();\n }\n catch (const StringException& e)\n {\n LOG_FATAL(logger, \"%s: %s\", e.what(), e.string());\n return 1;\n }\n catch (const Exception& e)\n {\n LOG_FATAL(logger, \"%s\", e.what());\n return 1;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved\n *\/\n#ifndef _Stroika_Foundation_Containers_Private_DataStructures_STLContainerWrapper_inl_\n#define _Stroika_Foundation_Containers_Private_DataStructures_STLContainerWrapper_inl_ 1\n\n#include \n\n#include \"..\/..\/..\/Debug\/Assertions.h\"\n\n\n\nnamespace Stroika {\n namespace Foundation {\n namespace Containers {\n namespace Private {\n namespace DataStructures {\n\n\n \/*\n ********************************************************************************\n ******************* STLContainerWrapper ********************\n ********************************************************************************\n *\/\n template \n inline bool STLContainerWrapper::Contains (value_type item) const\n {\n return this->find (item) != this->end ();\n }\n template \n template \n inline void STLContainerWrapper::Apply (FUNCTION doToElement) const\n {\n for (auto i = this->begin (); i != this->end (); ++i) {\n (doToElement) (*i);\n }\n }\n template \n template \n inline typename STL_CONTAINER_OF_T::const_iterator STLContainerWrapper::ApplyUntilTrue (FUNCTION doToElement) const\n {\n for (auto i = this->begin (); i != this->end (); ++i) {\n if ((doToElement) (*i)) {\n return i;\n }\n }\n return end ();\n }\n template \n template \n inline bool STLContainerWrapper::FindIf (PREDICATE pred) const\n {\n return std::find_if (this->begin (), this->end (), pred) != this->end ();\n }\n\n\n \/*\n ********************************************************************************\n *********** STLContainerWrapper::ForwardIterator ***********\n ********************************************************************************\n *\/\n template \n inline STLContainerWrapper::ForwardIterator::ForwardIterator (STLContainerWrapper* data)\n : fData (data)\n , fStdIterator (data->begin ())\n {\n RequireNotNull (data);\n }\n template \n inline STLContainerWrapper::ForwardIterator::ForwardIterator (const ForwardIterator& from)\n : fData (from.fData)\n , fStdIterator (from.fStdIterator)\n {\n RequireNotNull (fData);\n }\n template \n inline bool STLContainerWrapper::ForwardIterator::Done () const\n {\n AssertNotNull (fData);\n return fStdIterator == fData->end ();\n }\n template \n template \n inline bool STLContainerWrapper::ForwardIterator::More (VALUE_TYPE* current, bool advance)\n {\n bool done = Done ();\n if (advance) {\n if (not done) {\n fStdIterator++;\n done = Done ();\n }\n }\n if ((current != nullptr) and (not done)) {\n *current = *fStdIterator;\n }\n return not done;\n }\n template \n template \n inline void STLContainerWrapper::ForwardIterator::More (Memory::Optional* result, bool advance)\n {\n RequireNotNull (result);\n if (advance) {\n if (not Done ()) {\n fStdIterator++;\n }\n }\n if (Done ()) {\n result->clear ();\n }\n else {\n *result = *fStdIterator;\n }\n }\n template \n inline size_t STLContainerWrapper::ForwardIterator::CurrentIndex () const\n {\n AssertNotNull (fData);\n return fStdIterator - fData->begin ();\n }\n\n\n }\n }\n }\n }\n}\n#endif \/* _Stroika_Foundation_Containers_Private_DataStructures_STLContainerWrapper_inl_ *\/\nfixed small template bug (gcc picky)\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved\n *\/\n#ifndef _Stroika_Foundation_Containers_Private_DataStructures_STLContainerWrapper_inl_\n#define _Stroika_Foundation_Containers_Private_DataStructures_STLContainerWrapper_inl_ 1\n\n#include \n\n#include \"..\/..\/..\/Debug\/Assertions.h\"\n\n\n\nnamespace Stroika {\n namespace Foundation {\n namespace Containers {\n namespace Private {\n namespace DataStructures {\n\n\n \/*\n ********************************************************************************\n ******************* STLContainerWrapper ********************\n ********************************************************************************\n *\/\n template \n inline bool STLContainerWrapper::Contains (value_type item) const\n {\n return this->find (item) != this->end ();\n }\n template \n template \n inline void STLContainerWrapper::Apply (FUNCTION doToElement) const\n {\n for (auto i = this->begin (); i != this->end (); ++i) {\n (doToElement) (*i);\n }\n }\n template \n template \n inline typename STL_CONTAINER_OF_T::const_iterator STLContainerWrapper::ApplyUntilTrue (FUNCTION doToElement) const\n {\n for (auto i = this->begin (); i != this->end (); ++i) {\n if ((doToElement) (*i)) {\n return i;\n }\n }\n return this->end ();\n }\n template \n template \n inline bool STLContainerWrapper::FindIf (PREDICATE pred) const\n {\n return std::find_if (this->begin (), this->end (), pred) != this->end ();\n }\n\n\n \/*\n ********************************************************************************\n *********** STLContainerWrapper::ForwardIterator ***********\n ********************************************************************************\n *\/\n template \n inline STLContainerWrapper::ForwardIterator::ForwardIterator (STLContainerWrapper* data)\n : fData (data)\n , fStdIterator (data->begin ())\n {\n RequireNotNull (data);\n }\n template \n inline STLContainerWrapper::ForwardIterator::ForwardIterator (const ForwardIterator& from)\n : fData (from.fData)\n , fStdIterator (from.fStdIterator)\n {\n RequireNotNull (fData);\n }\n template \n inline bool STLContainerWrapper::ForwardIterator::Done () const\n {\n AssertNotNull (fData);\n return fStdIterator == fData->end ();\n }\n template \n template \n inline bool STLContainerWrapper::ForwardIterator::More (VALUE_TYPE* current, bool advance)\n {\n bool done = Done ();\n if (advance) {\n if (not done) {\n fStdIterator++;\n done = Done ();\n }\n }\n if ((current != nullptr) and (not done)) {\n *current = *fStdIterator;\n }\n return not done;\n }\n template \n template \n inline void STLContainerWrapper::ForwardIterator::More (Memory::Optional* result, bool advance)\n {\n RequireNotNull (result);\n if (advance) {\n if (not Done ()) {\n fStdIterator++;\n }\n }\n if (Done ()) {\n result->clear ();\n }\n else {\n *result = *fStdIterator;\n }\n }\n template \n inline size_t STLContainerWrapper::ForwardIterator::CurrentIndex () const\n {\n AssertNotNull (fData);\n return fStdIterator - fData->begin ();\n }\n\n\n }\n }\n }\n }\n}\n#endif \/* _Stroika_Foundation_Containers_Private_DataStructures_STLContainerWrapper_inl_ *\/\n<|endoftext|>"} {"text":"\/\/ Copyright 2015 Google Inc. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"gtest\/gtest.h\"\n#include \"corgi\/vector_pool.h\"\n\n#define TEST_ALL_SIZES_F(MY_TEST) \\\n TEST_F(VectorPoolTests, MY_TEST##_int8) { \\\n MY_TEST##_Test(); \\\n } \\\n TEST_F(VectorPoolTests, MY_TEST##_uint8) { \\\n MY_TEST##_Test(); \\\n } \\\n TEST_F(VectorPoolTests, MY_TEST##_int16) { \\\n MY_TEST##_Test(); \\\n } \\\n TEST_F(VectorPoolTests, MY_TEST##_uint16) { \\\n MY_TEST##_Test(); \\\n } \\\n TEST_F(VectorPoolTests, MY_TEST##_int32) { \\\n MY_TEST##_Test(); \\\n } \\\n TEST_F(VectorPoolTests, MY_TEST##_uint32) { \\\n MY_TEST##_Test(); \\\n }\n\nclass VectorPoolTests : public ::testing::Test {\nprotected:\n virtual void SetUp() {}\n virtual void TearDown() {}\n};\n\ntemplate \nstruct TestStruct {\n TestStruct() { value = 123; }\n TestStruct(T val) : value(val) {}\n T value;\n};\n\n#define VECTORPOOL_REF typename \\\n corgi::VectorPool>::VectorPoolReference\n\n\/\/ Test that allocated variables are initialized according to their constructor.\ntemplate\nvoid AllocAndFree_Constructor_Test() {\n corgi::VectorPool> pool;\n for (int i = 0; i < 100; i++) {\n VECTORPOOL_REF ref = pool.GetNewElement(corgi::kAddToFront);\n EXPECT_EQ(ref->value, 123);\n }\n}\nTEST_ALL_SIZES_F(AllocAndFree_Constructor)\n\n\/\/ Test allocating and freeing one element.\ntemplate\nvoid AllocAndFree_OneElement_Test() {\n corgi::VectorPool> pool;\n VECTORPOOL_REF ref;\n EXPECT_EQ(pool.active_count(), 0);\n ref = pool.GetNewElement(corgi::kAddToFront);\n EXPECT_TRUE(ref.IsValid());\n EXPECT_EQ(pool.active_count(), 1);\n pool.FreeElement(ref);\n EXPECT_EQ(pool.active_count(), 0);\n EXPECT_FALSE(ref.IsValid());\n}\nTEST_ALL_SIZES_F(AllocAndFree_OneElement)\n\n\/\/ Test allocating and freeing two elements.\ntemplate\nvoid AllocAndFree_TwoElementsElement_Test() {\n corgi::VectorPool> pool;\n VECTORPOOL_REF ref1;\n VECTORPOOL_REF ref2;\n EXPECT_EQ(pool.active_count(), 0);\n ref1 = pool.GetNewElement(corgi::kAddToFront);\n ref2 = pool.GetNewElement(corgi::kAddToFront);\n EXPECT_TRUE(ref1.IsValid());\n EXPECT_TRUE(ref2.IsValid());\n EXPECT_EQ(pool.active_count(), 2);\n\n pool.FreeElement(ref1);\n EXPECT_FALSE(ref1.IsValid());\n EXPECT_EQ(pool.active_count(), 1);\n\n pool.FreeElement(ref2);\n EXPECT_FALSE(ref2.IsValid());\n EXPECT_EQ(pool.active_count(), 0);\n}\nTEST_ALL_SIZES_F(AllocAndFree_TwoElementsElement)\n\n\/\/ Test allocating and freeing many elements.\n\/\/ Starts out allocating 100 elements, numbered 1 to 100.\n\/\/ Then removes the odd numbered elements. Then adds 50 more elements\n\/\/ to the front and back of the list. So the final list should look like:\n\/\/ 0-49: [elements numbered 49-0]\n\/\/ 50-99: [odd numbered elements numbered 1-99]\n\/\/ 100-149: [elements numbered 50-99]\ntemplate\nvoid AllocAndFree_ManyElementsElement_Test() {\n corgi::VectorPool> pool;\n VECTORPOOL_REF ref;\n for (int i = 0; i < 100; i++) {\n ref = pool.GetNewElement(corgi::kAddToBack);\n EXPECT_TRUE(ref.IsValid());\n ref->value = i;\n }\n \/\/ Remove all the even numbers.\n for (auto iter = pool.begin(); iter != pool.end(); ++iter) {\n ref = iter.ToReference();\n ++iter;\n pool.FreeElement(ref);\n EXPECT_FALSE(ref.IsValid());\n }\n \/\/ The list now contains the even numbers between 0 and 98.\n \/\/ Add in more numbers before and after the list:\n for (int i = 0; i < 50; i++) {\n ref = pool.GetNewElement(corgi::kAddToFront);\n ref->value = i;\n ref = pool.GetNewElement(corgi::kAddToBack);\n ref->value = i + 50;\n }\n\n \/\/ Check our list contents:\n auto iter = pool.begin();\n\n \/\/ First 50 (numbered 0-49)\n for (int i = 49; i >= 0; i--) {\n EXPECT_EQ(iter->value, i);\n ++iter;\n }\n \/\/ Second 50, numbered 0-49\n for (int i = 1; i < 100; i += 2) {\n EXPECT_EQ(iter->value, i);\n ++iter;\n }\n \/\/ Final 50, numbered 50-99\n for (int i = 50; i < 100; i++) {\n EXPECT_EQ(iter->value, i);\n ++iter;\n }\n EXPECT_EQ(iter, pool.end());\n}\nTEST_ALL_SIZES_F(AllocAndFree_ManyElementsElement)\n\n\/\/ Test adding a bunch of elements to the back, and making sure the\n\/\/ order is what we expect.\ntemplate\nvoid InsertionOrder_AddToBack_Test() {\n corgi::VectorPool> pool;\n VECTORPOOL_REF ref;\n\n for (int i = 0; i < 100; i++) {\n ref = pool.GetNewElement(corgi::kAddToBack);\n EXPECT_TRUE(ref.IsValid());\n ref->value = i;\n }\n\n int i = 0;\n for (auto iter = pool.begin(); iter != pool.end(); ++iter) {\n EXPECT_EQ(i, iter->value);\n i++;\n }\n}\nTEST_ALL_SIZES_F(InsertionOrder_AddToBack)\n\n\/\/ Test adding a bunch of elements to the front, and making sure the\n\/\/ order is what we expect.\ntemplate\nvoid InsertionOrder_AddToFront_Test() {\n corgi::VectorPool> pool;\n VECTORPOOL_REF ref;\n\n for (int i = 0; i < 100; i++) {\n ref = pool.GetNewElement(corgi::kAddToFront);\n EXPECT_TRUE(ref.IsValid());\n ref->value = i;\n }\n\n int i = 99;\n for (auto iter = pool.begin(); iter != pool.end(); ++iter) {\n EXPECT_EQ(i, iter->value);\n i--;\n }\n}\nTEST_ALL_SIZES_F(InsertionOrder_AddToFront)\n\n\/\/ Tests that begin and end point to each other in an empty pool,\n\/\/ Don't point to each other in a non-empty-pool, and then do\n\/\/ point to each other again if the non-empty pool has been emptied.\ntemplate\nvoid Iterator_BeginEnd_Test() {\n corgi::VectorPool> pool;\n EXPECT_EQ(pool.begin(), pool.end());\n VECTORPOOL_REF ref = pool.GetNewElement(corgi::kAddToFront);\n EXPECT_NE(pool.begin(), pool.end());\n pool.FreeElement(ref);\n EXPECT_EQ(pool.begin(), pool.end());\n}\nTEST_ALL_SIZES_F(Iterator_BeginEnd)\n\n\/\/ Test that we can step through the pool via an iterator,\n\/\/ and that it takes us the correct number of steps.\ntemplate\nvoid Iterator_StepThrough_Test() {\n corgi::VectorPool> pool;\n for (int i = 0; i < 100; i ++) {\n VECTORPOOL_REF ref = pool.GetNewElement(corgi::kAddToBack);\n ref->value = i;\n }\n\n int counter = 0;\n for (auto iter = pool.begin(); iter != pool.end(); ++iter) {\n EXPECT_EQ(iter->value, counter);\n counter++;\n }\n EXPECT_EQ(counter, 100);\n}\nTEST_ALL_SIZES_F(Iterator_StepThrough)\n\n\/\/ Test that we can step backwards through the pool via an iterator,\n\/\/ and that it takes us the correct number of steps.\ntemplate\nvoid Iterator_StepBackwards_Test() {\n corgi::VectorPool> pool;\n for (int i = 0; i < 100; i ++) {\n VECTORPOOL_REF ref = pool.GetNewElement(corgi::kAddToBack);\n ref->value = i;\n }\n\n int counter = 0;\n\n for (auto iter = --pool.end(); iter != pool.begin(); --iter) {\n counter++;\n EXPECT_EQ(iter->value, 100 - counter);\n }\n \/\/ Not 100 here, because we had to advance it once during initialization,\n \/\/ to get our iterator off of end().\n EXPECT_EQ(counter, 99);\n}\nTEST_ALL_SIZES_F(Iterator_StepBackwards)\n\n#if !defined(__ANDROID__)\nint main(int argc, char **argv) {\n ::testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\n#endif \/\/ !defined(__ANDROID__)\nFix signed\/unsigned comparison warnings.\/\/ Copyright 2015 Google Inc. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"gtest\/gtest.h\"\n#include \"corgi\/vector_pool.h\"\n\n#define TEST_ALL_SIZES_F(MY_TEST) \\\n TEST_F(VectorPoolTests, MY_TEST##_int8) { \\\n MY_TEST##_Test(); \\\n } \\\n TEST_F(VectorPoolTests, MY_TEST##_uint8) { \\\n MY_TEST##_Test(); \\\n } \\\n TEST_F(VectorPoolTests, MY_TEST##_int16) { \\\n MY_TEST##_Test(); \\\n } \\\n TEST_F(VectorPoolTests, MY_TEST##_uint16) { \\\n MY_TEST##_Test(); \\\n } \\\n TEST_F(VectorPoolTests, MY_TEST##_int32) { \\\n MY_TEST##_Test(); \\\n } \\\n TEST_F(VectorPoolTests, MY_TEST##_uint32) { \\\n MY_TEST##_Test(); \\\n }\n\nclass VectorPoolTests : public ::testing::Test {\nprotected:\n virtual void SetUp() {}\n virtual void TearDown() {}\n};\n\ntemplate \nstruct TestStruct {\n TestStruct() { value = 123; }\n TestStruct(T val) : value(val) {}\n T value;\n};\n\n#define VECTORPOOL_REF typename \\\n corgi::VectorPool>::VectorPoolReference\n\n\/\/ Test that allocated variables are initialized according to their constructor.\ntemplate\nvoid AllocAndFree_Constructor_Test() {\n corgi::VectorPool> pool;\n for (int i = 0; i < 100; i++) {\n VECTORPOOL_REF ref = pool.GetNewElement(corgi::kAddToFront);\n EXPECT_EQ(ref->value, static_cast(123));\n }\n}\nTEST_ALL_SIZES_F(AllocAndFree_Constructor)\n\n\/\/ Test allocating and freeing one element.\ntemplate\nvoid AllocAndFree_OneElement_Test() {\n corgi::VectorPool> pool;\n VECTORPOOL_REF ref;\n EXPECT_EQ(pool.active_count(), 0u);\n ref = pool.GetNewElement(corgi::kAddToFront);\n EXPECT_TRUE(ref.IsValid());\n EXPECT_EQ(pool.active_count(), 1u);\n pool.FreeElement(ref);\n EXPECT_EQ(pool.active_count(), 0u);\n EXPECT_FALSE(ref.IsValid());\n}\nTEST_ALL_SIZES_F(AllocAndFree_OneElement)\n\n\/\/ Test allocating and freeing two elements.\ntemplate\nvoid AllocAndFree_TwoElementsElement_Test() {\n corgi::VectorPool> pool;\n VECTORPOOL_REF ref1;\n VECTORPOOL_REF ref2;\n EXPECT_EQ(pool.active_count(), 0u);\n ref1 = pool.GetNewElement(corgi::kAddToFront);\n ref2 = pool.GetNewElement(corgi::kAddToFront);\n EXPECT_TRUE(ref1.IsValid());\n EXPECT_TRUE(ref2.IsValid());\n EXPECT_EQ(pool.active_count(), 2u);\n\n pool.FreeElement(ref1);\n EXPECT_FALSE(ref1.IsValid());\n EXPECT_EQ(pool.active_count(), 1u);\n\n pool.FreeElement(ref2);\n EXPECT_FALSE(ref2.IsValid());\n EXPECT_EQ(pool.active_count(), 0u);\n}\nTEST_ALL_SIZES_F(AllocAndFree_TwoElementsElement)\n\n\/\/ Test allocating and freeing many elements.\n\/\/ Starts out allocating 100 elements, numbered 1 to 100.\n\/\/ Then removes the odd numbered elements. Then adds 50 more elements\n\/\/ to the front and back of the list. So the final list should look like:\n\/\/ 0-49: [elements numbered 49-0]\n\/\/ 50-99: [odd numbered elements numbered 1-99]\n\/\/ 100-149: [elements numbered 50-99]\ntemplate\nvoid AllocAndFree_ManyElementsElement_Test() {\n corgi::VectorPool> pool;\n VECTORPOOL_REF ref;\n for (int i = 0; i < 100; i++) {\n ref = pool.GetNewElement(corgi::kAddToBack);\n EXPECT_TRUE(ref.IsValid());\n ref->value = i;\n }\n \/\/ Remove all the even numbers.\n for (auto iter = pool.begin(); iter != pool.end(); ++iter) {\n ref = iter.ToReference();\n ++iter;\n pool.FreeElement(ref);\n EXPECT_FALSE(ref.IsValid());\n }\n \/\/ The list now contains the even numbers between 0 and 98.\n \/\/ Add in more numbers before and after the list:\n for (int i = 0; i < 50; i++) {\n ref = pool.GetNewElement(corgi::kAddToFront);\n ref->value = i;\n ref = pool.GetNewElement(corgi::kAddToBack);\n ref->value = i + 50;\n }\n\n \/\/ Check our list contents:\n auto iter = pool.begin();\n\n \/\/ First 50 (numbered 0-49)\n for (int i = 49; i >= 0; i--) {\n EXPECT_EQ(iter->value, static_cast(i));\n ++iter;\n }\n \/\/ Second 50, numbered 0-49\n for (int i = 1; i < 100; i += 2) {\n EXPECT_EQ(iter->value, static_cast(i));\n ++iter;\n }\n \/\/ Final 50, numbered 50-99\n for (int i = 50; i < 100; i++) {\n EXPECT_EQ(iter->value, static_cast(i));\n ++iter;\n }\n EXPECT_EQ(iter, pool.end());\n}\nTEST_ALL_SIZES_F(AllocAndFree_ManyElementsElement)\n\n\/\/ Test adding a bunch of elements to the back, and making sure the\n\/\/ order is what we expect.\ntemplate\nvoid InsertionOrder_AddToBack_Test() {\n corgi::VectorPool> pool;\n VECTORPOOL_REF ref;\n\n for (int i = 0; i < 100; i++) {\n ref = pool.GetNewElement(corgi::kAddToBack);\n EXPECT_TRUE(ref.IsValid());\n ref->value = i;\n }\n\n int i = 0;\n for (auto iter = pool.begin(); iter != pool.end(); ++iter) {\n EXPECT_EQ(i, static_cast(iter->value));\n i++;\n }\n}\nTEST_ALL_SIZES_F(InsertionOrder_AddToBack)\n\n\/\/ Test adding a bunch of elements to the front, and making sure the\n\/\/ order is what we expect.\ntemplate\nvoid InsertionOrder_AddToFront_Test() {\n corgi::VectorPool> pool;\n VECTORPOOL_REF ref;\n\n for (int i = 0; i < 100; i++) {\n ref = pool.GetNewElement(corgi::kAddToFront);\n EXPECT_TRUE(ref.IsValid());\n ref->value = i;\n }\n\n int i = 99;\n for (auto iter = pool.begin(); iter != pool.end(); ++iter) {\n EXPECT_EQ(i, static_cast(iter->value));\n i--;\n }\n}\nTEST_ALL_SIZES_F(InsertionOrder_AddToFront)\n\n\/\/ Tests that begin and end point to each other in an empty pool,\n\/\/ Don't point to each other in a non-empty-pool, and then do\n\/\/ point to each other again if the non-empty pool has been emptied.\ntemplate\nvoid Iterator_BeginEnd_Test() {\n corgi::VectorPool> pool;\n EXPECT_EQ(pool.begin(), pool.end());\n VECTORPOOL_REF ref = pool.GetNewElement(corgi::kAddToFront);\n EXPECT_NE(pool.begin(), pool.end());\n pool.FreeElement(ref);\n EXPECT_EQ(pool.begin(), pool.end());\n}\nTEST_ALL_SIZES_F(Iterator_BeginEnd)\n\n\/\/ Test that we can step through the pool via an iterator,\n\/\/ and that it takes us the correct number of steps.\ntemplate\nvoid Iterator_StepThrough_Test() {\n corgi::VectorPool> pool;\n for (int i = 0; i < 100; i ++) {\n VECTORPOOL_REF ref = pool.GetNewElement(corgi::kAddToBack);\n ref->value = i;\n }\n\n int counter = 0;\n for (auto iter = pool.begin(); iter != pool.end(); ++iter) {\n EXPECT_EQ(static_cast(iter->value), counter);\n counter++;\n }\n EXPECT_EQ(counter, 100);\n}\nTEST_ALL_SIZES_F(Iterator_StepThrough)\n\n\/\/ Test that we can step backwards through the pool via an iterator,\n\/\/ and that it takes us the correct number of steps.\ntemplate\nvoid Iterator_StepBackwards_Test() {\n corgi::VectorPool> pool;\n for (int i = 0; i < 100; i ++) {\n VECTORPOOL_REF ref = pool.GetNewElement(corgi::kAddToBack);\n ref->value = i;\n }\n\n int counter = 0;\n\n for (auto iter = --pool.end(); iter != pool.begin(); --iter) {\n counter++;\n EXPECT_EQ(static_cast(iter->value), 100 - counter);\n }\n \/\/ Not 100 here, because we had to advance it once during initialization,\n \/\/ to get our iterator off of end().\n EXPECT_EQ(counter, 99);\n}\nTEST_ALL_SIZES_F(Iterator_StepBackwards)\n\n#if !defined(__ANDROID__)\nint main(int argc, char **argv) {\n ::testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\n#endif \/\/ !defined(__ANDROID__)\n<|endoftext|>"} {"text":"\/\/===-- ArchSpecTest.cpp ----------------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"gtest\/gtest.h\"\n\n#include \"lldb\/Core\/ArchSpec.h\"\n\n#include \"llvm\/BinaryFormat\/MachO.h\"\n\nusing namespace lldb;\nusing namespace lldb_private;\n\nTEST(ArchSpecTest, TestParseMachCPUDashSubtypeTripleSimple) {\n\n \/\/ Success conditions. Valid cpu\/subtype combinations using both - and .\n ArchSpec AS;\n EXPECT_TRUE(ParseMachCPUDashSubtypeTriple(\"12-10\", AS));\n EXPECT_EQ(12u, AS.GetMachOCPUType());\n EXPECT_EQ(10u, AS.GetMachOCPUSubType());\n\n AS = ArchSpec();\n EXPECT_TRUE(ParseMachCPUDashSubtypeTriple(\"12-15\", AS));\n EXPECT_EQ(12u, AS.GetMachOCPUType());\n EXPECT_EQ(15u, AS.GetMachOCPUSubType());\n\n AS = ArchSpec();\n EXPECT_TRUE(ParseMachCPUDashSubtypeTriple(\"12.15\", AS));\n EXPECT_EQ(12u, AS.GetMachOCPUType());\n EXPECT_EQ(15u, AS.GetMachOCPUSubType());\n\n \/\/ Failure conditions.\n\n \/\/ Valid string, unknown cpu\/subtype.\n AS = ArchSpec();\n EXPECT_TRUE(ParseMachCPUDashSubtypeTriple(\"13.11\", AS));\n EXPECT_EQ(0u, AS.GetMachOCPUType());\n EXPECT_EQ(0u, AS.GetMachOCPUSubType());\n\n \/\/ Missing \/ invalid cpu or subtype\n AS = ArchSpec();\n EXPECT_FALSE(ParseMachCPUDashSubtypeTriple(\"13\", AS));\n\n AS = ArchSpec();\n EXPECT_FALSE(ParseMachCPUDashSubtypeTriple(\"13.A\", AS));\n\n AS = ArchSpec();\n EXPECT_FALSE(ParseMachCPUDashSubtypeTriple(\"A.13\", AS));\n\n \/\/ Empty string.\n AS = ArchSpec();\n EXPECT_FALSE(ParseMachCPUDashSubtypeTriple(\"\", AS));\n}\n\nTEST(ArchSpecTest, TestParseMachCPUDashSubtypeTripleExtra) {\n ArchSpec AS;\n EXPECT_TRUE(ParseMachCPUDashSubtypeTriple(\"12-15-vendor-os\", AS));\n EXPECT_EQ(12u, AS.GetMachOCPUType());\n EXPECT_EQ(15u, AS.GetMachOCPUSubType());\n EXPECT_EQ(\"vendor\", AS.GetTriple().getVendorName());\n EXPECT_EQ(\"os\", AS.GetTriple().getOSName());\n\n AS = ArchSpec();\n EXPECT_TRUE(ParseMachCPUDashSubtypeTriple(\"12-10-vendor-os-name\", AS));\n EXPECT_EQ(12u, AS.GetMachOCPUType());\n EXPECT_EQ(10u, AS.GetMachOCPUSubType());\n EXPECT_EQ(\"vendor\", AS.GetTriple().getVendorName());\n EXPECT_EQ(\"os\", AS.GetTriple().getOSName());\n\n AS = ArchSpec();\n EXPECT_TRUE(ParseMachCPUDashSubtypeTriple(\"12-15-vendor.os-name\", AS));\n EXPECT_EQ(12u, AS.GetMachOCPUType());\n EXPECT_EQ(15u, AS.GetMachOCPUSubType());\n EXPECT_EQ(\"vendor.os\", AS.GetTriple().getVendorName());\n EXPECT_EQ(\"name\", AS.GetTriple().getOSName());\n\n \/\/ These there should parse correctly, but the vendor \/ OS should be defaulted\n \/\/ since they are unrecognized.\n AS = ArchSpec();\n EXPECT_TRUE(ParseMachCPUDashSubtypeTriple(\"12-10-vendor\", AS));\n EXPECT_EQ(12u, AS.GetMachOCPUType());\n EXPECT_EQ(10u, AS.GetMachOCPUSubType());\n EXPECT_EQ(\"apple\", AS.GetTriple().getVendorName());\n EXPECT_EQ(\"\", AS.GetTriple().getOSName());\n\n AS = ArchSpec();\n EXPECT_FALSE(ParseMachCPUDashSubtypeTriple(\"12.10.10\", AS));\n\n AS = ArchSpec();\n EXPECT_FALSE(ParseMachCPUDashSubtypeTriple(\"12-10.10\", AS));\n}\n\nTEST(ArchSpecTest, TestSetTriple) {\n ArchSpec AS;\n\n \/\/ Various flavors of valid triples.\n EXPECT_TRUE(AS.SetTriple(\"12-10-apple-darwin\"));\n EXPECT_EQ(uint32_t(llvm::MachO::CPU_TYPE_ARM), AS.GetMachOCPUType());\n EXPECT_EQ(10u, AS.GetMachOCPUSubType());\n EXPECT_TRUE(llvm::StringRef(AS.GetTriple().str())\n .consume_front(\"armv7f-apple-darwin\"));\n EXPECT_EQ(ArchSpec::eCore_arm_armv7f, AS.GetCore());\n\n AS = ArchSpec();\n EXPECT_TRUE(AS.SetTriple(\"18.100-apple-darwin\"));\n EXPECT_EQ(uint32_t(llvm::MachO::CPU_TYPE_POWERPC), AS.GetMachOCPUType());\n EXPECT_EQ(100u, AS.GetMachOCPUSubType());\n EXPECT_TRUE(llvm::StringRef(AS.GetTriple().str())\n .consume_front(\"powerpc-apple-darwin\"));\n EXPECT_EQ(ArchSpec::eCore_ppc_ppc970, AS.GetCore());\n\n AS = ArchSpec();\n EXPECT_TRUE(AS.SetTriple(\"i686-pc-windows\"));\n EXPECT_EQ(llvm::Triple::x86, AS.GetTriple().getArch());\n EXPECT_EQ(llvm::Triple::PC, AS.GetTriple().getVendor());\n EXPECT_EQ(llvm::Triple::Win32, AS.GetTriple().getOS());\n EXPECT_TRUE(\n llvm::StringRef(AS.GetTriple().str()).consume_front(\"i686-pc-windows\"));\n EXPECT_STREQ(\"i686\", AS.GetArchitectureName());\n EXPECT_EQ(ArchSpec::eCore_x86_32_i686, AS.GetCore());\n\n \/\/ Various flavors of invalid triples.\n AS = ArchSpec();\n EXPECT_FALSE(AS.SetTriple(\"unknown-unknown-unknown\"));\n\n AS = ArchSpec();\n EXPECT_FALSE(AS.SetTriple(\"unknown\"));\n\n AS = ArchSpec();\n EXPECT_FALSE(AS.SetTriple(\"\"));\n}\n\nTEST(ArchSpecTest, MergeFrom) {\n ArchSpec A;\n ArchSpec B(\"x86_64-pc-linux\");\n\n EXPECT_FALSE(A.IsValid());\n ASSERT_TRUE(B.IsValid());\n EXPECT_EQ(llvm::Triple::ArchType::x86_64, B.GetTriple().getArch());\n EXPECT_EQ(llvm::Triple::VendorType::PC, B.GetTriple().getVendor());\n EXPECT_EQ(llvm::Triple::OSType::Linux, B.GetTriple().getOS());\n EXPECT_EQ(ArchSpec::eCore_x86_64_x86_64, B.GetCore());\n\n A.MergeFrom(B);\n ASSERT_TRUE(A.IsValid());\n EXPECT_EQ(llvm::Triple::ArchType::x86_64, A.GetTriple().getArch());\n EXPECT_EQ(llvm::Triple::VendorType::PC, A.GetTriple().getVendor());\n EXPECT_EQ(llvm::Triple::OSType::Linux, A.GetTriple().getOS());\n EXPECT_EQ(ArchSpec::eCore_x86_64_x86_64, A.GetCore());\n}\n[ArchSpec] Add a unittest to complement the change in r321856.\/\/===-- ArchSpecTest.cpp ----------------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"gtest\/gtest.h\"\n\n#include \"lldb\/Core\/ArchSpec.h\"\n\n#include \"llvm\/BinaryFormat\/MachO.h\"\n\nusing namespace lldb;\nusing namespace lldb_private;\n\nTEST(ArchSpecTest, TestParseMachCPUDashSubtypeTripleSimple) {\n\n \/\/ Success conditions. Valid cpu\/subtype combinations using both - and .\n ArchSpec AS;\n EXPECT_TRUE(ParseMachCPUDashSubtypeTriple(\"12-10\", AS));\n EXPECT_EQ(12u, AS.GetMachOCPUType());\n EXPECT_EQ(10u, AS.GetMachOCPUSubType());\n\n AS = ArchSpec();\n EXPECT_TRUE(ParseMachCPUDashSubtypeTriple(\"12-15\", AS));\n EXPECT_EQ(12u, AS.GetMachOCPUType());\n EXPECT_EQ(15u, AS.GetMachOCPUSubType());\n\n AS = ArchSpec();\n EXPECT_TRUE(ParseMachCPUDashSubtypeTriple(\"12.15\", AS));\n EXPECT_EQ(12u, AS.GetMachOCPUType());\n EXPECT_EQ(15u, AS.GetMachOCPUSubType());\n\n \/\/ Failure conditions.\n\n \/\/ Valid string, unknown cpu\/subtype.\n AS = ArchSpec();\n EXPECT_TRUE(ParseMachCPUDashSubtypeTriple(\"13.11\", AS));\n EXPECT_EQ(0u, AS.GetMachOCPUType());\n EXPECT_EQ(0u, AS.GetMachOCPUSubType());\n\n \/\/ Missing \/ invalid cpu or subtype\n AS = ArchSpec();\n EXPECT_FALSE(ParseMachCPUDashSubtypeTriple(\"13\", AS));\n\n AS = ArchSpec();\n EXPECT_FALSE(ParseMachCPUDashSubtypeTriple(\"13.A\", AS));\n\n AS = ArchSpec();\n EXPECT_FALSE(ParseMachCPUDashSubtypeTriple(\"A.13\", AS));\n\n \/\/ Empty string.\n AS = ArchSpec();\n EXPECT_FALSE(ParseMachCPUDashSubtypeTriple(\"\", AS));\n}\n\nTEST(ArchSpecTest, TestParseMachCPUDashSubtypeTripleExtra) {\n ArchSpec AS;\n EXPECT_TRUE(ParseMachCPUDashSubtypeTriple(\"12-15-vendor-os\", AS));\n EXPECT_EQ(12u, AS.GetMachOCPUType());\n EXPECT_EQ(15u, AS.GetMachOCPUSubType());\n EXPECT_EQ(\"vendor\", AS.GetTriple().getVendorName());\n EXPECT_EQ(\"os\", AS.GetTriple().getOSName());\n\n AS = ArchSpec();\n EXPECT_TRUE(ParseMachCPUDashSubtypeTriple(\"12-10-vendor-os-name\", AS));\n EXPECT_EQ(12u, AS.GetMachOCPUType());\n EXPECT_EQ(10u, AS.GetMachOCPUSubType());\n EXPECT_EQ(\"vendor\", AS.GetTriple().getVendorName());\n EXPECT_EQ(\"os\", AS.GetTriple().getOSName());\n\n AS = ArchSpec();\n EXPECT_TRUE(ParseMachCPUDashSubtypeTriple(\"12-15-vendor.os-name\", AS));\n EXPECT_EQ(12u, AS.GetMachOCPUType());\n EXPECT_EQ(15u, AS.GetMachOCPUSubType());\n EXPECT_EQ(\"vendor.os\", AS.GetTriple().getVendorName());\n EXPECT_EQ(\"name\", AS.GetTriple().getOSName());\n\n \/\/ These there should parse correctly, but the vendor \/ OS should be defaulted\n \/\/ since they are unrecognized.\n AS = ArchSpec();\n EXPECT_TRUE(ParseMachCPUDashSubtypeTriple(\"12-10-vendor\", AS));\n EXPECT_EQ(12u, AS.GetMachOCPUType());\n EXPECT_EQ(10u, AS.GetMachOCPUSubType());\n EXPECT_EQ(\"apple\", AS.GetTriple().getVendorName());\n EXPECT_EQ(\"\", AS.GetTriple().getOSName());\n\n AS = ArchSpec();\n EXPECT_FALSE(ParseMachCPUDashSubtypeTriple(\"12.10.10\", AS));\n\n AS = ArchSpec();\n EXPECT_FALSE(ParseMachCPUDashSubtypeTriple(\"12-10.10\", AS));\n}\n\nTEST(ArchSpecTest, TestSetTriple) {\n ArchSpec AS;\n\n \/\/ Various flavors of valid triples.\n EXPECT_TRUE(AS.SetTriple(\"12-10-apple-darwin\"));\n EXPECT_EQ(uint32_t(llvm::MachO::CPU_TYPE_ARM), AS.GetMachOCPUType());\n EXPECT_EQ(10u, AS.GetMachOCPUSubType());\n EXPECT_TRUE(llvm::StringRef(AS.GetTriple().str())\n .consume_front(\"armv7f-apple-darwin\"));\n EXPECT_EQ(ArchSpec::eCore_arm_armv7f, AS.GetCore());\n\n AS = ArchSpec();\n EXPECT_TRUE(AS.SetTriple(\"18.100-apple-darwin\"));\n EXPECT_EQ(uint32_t(llvm::MachO::CPU_TYPE_POWERPC), AS.GetMachOCPUType());\n EXPECT_EQ(100u, AS.GetMachOCPUSubType());\n EXPECT_TRUE(llvm::StringRef(AS.GetTriple().str())\n .consume_front(\"powerpc-apple-darwin\"));\n EXPECT_EQ(ArchSpec::eCore_ppc_ppc970, AS.GetCore());\n\n AS = ArchSpec();\n EXPECT_TRUE(AS.SetTriple(\"i686-pc-windows\"));\n EXPECT_EQ(llvm::Triple::x86, AS.GetTriple().getArch());\n EXPECT_EQ(llvm::Triple::PC, AS.GetTriple().getVendor());\n EXPECT_EQ(llvm::Triple::Win32, AS.GetTriple().getOS());\n EXPECT_TRUE(\n llvm::StringRef(AS.GetTriple().str()).consume_front(\"i686-pc-windows\"));\n EXPECT_STREQ(\"i686\", AS.GetArchitectureName());\n EXPECT_EQ(ArchSpec::eCore_x86_32_i686, AS.GetCore());\n\n \/\/ Various flavors of invalid triples.\n AS = ArchSpec();\n EXPECT_FALSE(AS.SetTriple(\"unknown-unknown-unknown\"));\n\n AS = ArchSpec();\n EXPECT_FALSE(AS.SetTriple(\"unknown\"));\n\n AS = ArchSpec();\n EXPECT_FALSE(AS.SetTriple(\"\"));\n}\n\nTEST(ArchSpecTest, MergeFrom) {\n ArchSpec A;\n ArchSpec B(\"x86_64-pc-linux\");\n\n EXPECT_FALSE(A.IsValid());\n ASSERT_TRUE(B.IsValid());\n EXPECT_EQ(llvm::Triple::ArchType::x86_64, B.GetTriple().getArch());\n EXPECT_EQ(llvm::Triple::VendorType::PC, B.GetTriple().getVendor());\n EXPECT_EQ(llvm::Triple::OSType::Linux, B.GetTriple().getOS());\n EXPECT_EQ(ArchSpec::eCore_x86_64_x86_64, B.GetCore());\n\n A.MergeFrom(B);\n ASSERT_TRUE(A.IsValid());\n EXPECT_EQ(llvm::Triple::ArchType::x86_64, A.GetTriple().getArch());\n EXPECT_EQ(llvm::Triple::VendorType::PC, A.GetTriple().getVendor());\n EXPECT_EQ(llvm::Triple::OSType::Linux, A.GetTriple().getOS());\n EXPECT_EQ(ArchSpec::eCore_x86_64_x86_64, A.GetCore());\n}\n\nTEST(ArchSpecTest, MergeFromMachOUnknown) {\n class MyArchSpec : public ArchSpec {\n public:\n MyArchSpec() {\n this->SetTriple(\"unknown-mach-64\");\n this->m_core = ArchSpec::eCore_uknownMach64;\n this->m_byte_order = eByteOrderLittle;\n this->m_flags = 0;\n }\n };\n\n MyArchSpec A;\n ASSERT_TRUE(A.IsValid());\n MyArchSpec B;\n ASSERT_TRUE(B.IsValid());\n A.MergeFrom(B);\n ASSERT_EQ(A.GetCore(), ArchSpec::eCore_uknownMach64);\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: OOXMLDocumentImpl.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: hbrinkm $ $Date: 2007-02-21 15:06:33 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _COM_SUN_STAR_XML_SAX_XPARSER_HPP_\n#include \n#endif\n\n#include \"OOXMLDocumentImpl.hxx\"\n#include \"OOXMLSaxHandler.hxx\"\n\nnamespace ooxml\n{\n\nOOXMLDocumentImpl::OOXMLDocumentImpl\n(OOXMLStream::Pointer_t pStream)\n: mpStream(pStream)\n{\n}\n\nOOXMLDocumentImpl::~OOXMLDocumentImpl()\n{\n}\n\nvoid OOXMLDocumentImpl::resolve(Stream & rStream)\n{\n uno::Reference < xml::sax::XParser > oSaxParser = mpStream->getParser();\n\n if (oSaxParser.is())\n {\n uno::Reference\n xDocumentHandler\n (static_cast\n (new OOXMLSaxHandler(rStream)), uno::UNO_QUERY);\n oSaxParser->setDocumentHandler( xDocumentHandler );\n\n uno::Reference xInputStream =\n mpStream->getInputStream();\n\n struct xml::sax::InputSource oInputSource;\n oInputSource.aInputStream = xInputStream;\n oSaxParser->parseStream(oInputSource);\n\n xInputStream->closeInput();\n }\n\n rStream.info(\"Test\");\n}\n\nstring OOXMLDocumentImpl::getType() const\n{\n return \"OOXMLDocumentImpl\";\n}\n\nOOXMLDocument *\nOOXMLDocumentFactory::createDocument\n(OOXMLStream::Pointer_t pStream)\n{\n return new OOXMLDocumentImpl(pStream);\n}\n\n}\nresolve styles stream\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: OOXMLDocumentImpl.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: hbrinkm $ $Date: 2007-03-16 12:48:46 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _COM_SUN_STAR_XML_SAX_XPARSER_HPP_\n#include \n#endif\n\n#include \"OOXMLDocumentImpl.hxx\"\n#include \"OOXMLSaxHandler.hxx\"\n\n#include \n\nnamespace ooxml\n{\n\nusing namespace ::std;\n\nOOXMLDocumentImpl::OOXMLDocumentImpl\n(OOXMLStream::Pointer_t pStream)\n: mpStream(pStream)\n{\n}\n\nOOXMLDocumentImpl::~OOXMLDocumentImpl()\n{\n}\n\nvoid OOXMLDocumentImpl::resolve(Stream & rStream)\n{\n {\n uno::Reference < xml::sax::XParser > oSaxParser = mpStream->getParser();\n\n if (oSaxParser.is())\n {\n uno::Reference\n xDocumentHandler\n (static_cast\n (new OOXMLSaxHandler(rStream)), uno::UNO_QUERY);\n oSaxParser->setDocumentHandler( xDocumentHandler );\n\n OOXMLStream::Pointer_t pStylesStream\n (OOXMLDocumentFactory::createStream(mpStream,\n OOXMLStream::TYPES));\n\n uno::Reference < xml::sax::XParser > oStylesSaxParser =\n pStylesStream->getParser();\n\n if (oStylesSaxParser.is())\n {\n uno::Reference\n xStylesDocumentHandler\n (static_cast\n (new OOXMLSaxHandler(rStream)), uno::UNO_QUERY);\n oStylesSaxParser->setDocumentHandler( xStylesDocumentHandler );\n\n uno::Reference xStylesInputStream =\n pStylesStream->getInputStream();\n\n\/\/ uno::Sequence aSeq(1024);\n\/\/ while (xStylesInputStream->readBytes(aSeq, 1024) > 0)\n\/\/ {\n\/\/ string tmpStr(reinterpret_cast(&aSeq[0]));\n\n\/\/ clog << tmpStr;\n\/\/ }\n struct xml::sax::InputSource oStylesInputSource;\n oStylesInputSource.aInputStream = xStylesInputStream;\n oStylesSaxParser->parseStream(oStylesInputSource);\n\n xStylesInputStream->closeInput();\n\n }\n\n uno::Reference xInputStream =\n mpStream->getInputStream();\n\n struct xml::sax::InputSource oInputSource;\n oInputSource.aInputStream = xInputStream;\n oSaxParser->parseStream(oInputSource);\n\n xInputStream->closeInput();\n }\n }\n}\n\nstring OOXMLDocumentImpl::getType() const\n{\n return \"OOXMLDocumentImpl\";\n}\n\nOOXMLDocument *\nOOXMLDocumentFactory::createDocument\n(OOXMLStream::Pointer_t pStream)\n{\n return new OOXMLDocumentImpl(pStream);\n}\n\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: xmllib_export.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: hr $ $Date: 2004-11-09 12:36:32 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \n#include \n\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star;\nusing namespace rtl;\n\nnamespace xmlscript\n{\n\nstatic OUString aTrueStr ( RTL_CONSTASCII_USTRINGPARAM(\"true\") );\nstatic OUString aFalseStr( RTL_CONSTASCII_USTRINGPARAM(\"false\") );\n\n\/\/##################################################################################################\n\n\n\/\/==================================================================================================\n\nvoid\nSAL_CALL exportLibraryContainer(\n Reference< xml::sax::XExtendedDocumentHandler > const & xOut,\n const LibDescriptorArray* pLibArray )\n SAL_THROW( (Exception) )\n{\n xOut->startDocument();\n\n OUString aDocTypeStr( RTL_CONSTASCII_USTRINGPARAM(\n \"\" ) );\n xOut->unknown( aDocTypeStr );\n xOut->ignorableWhitespace( OUString() );\n\n\n OUString aLibrariesName( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX \":libraries\") );\n XMLElement* pLibsElement = new XMLElement( aLibrariesName );\n Reference< xml::sax::XAttributeList > xAttributes( pLibsElement );\n\n pLibsElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(\"xmlns:\" XMLNS_LIBRARY_PREFIX) ),\n OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_URI) ) );\n pLibsElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(\"xmlns:\" XMLNS_XLINK_PREFIX) ),\n OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_XLINK_URI) ) );\n\n\n xOut->ignorableWhitespace( OUString() );\n xOut->startElement( aLibrariesName, xAttributes );\n\n int nLibCount = pLibArray->mnLibCount;\n for( sal_Int32 i = 0 ; i < nLibCount ; i++ )\n {\n LibDescriptor& rLib = pLibArray->mpLibs[i];\n\n OUString aLibraryName( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX \":library\") );\n XMLElement* pLibElement = new XMLElement( aLibraryName );\n Reference< xml::sax::XAttributeList > xLibElementAttribs;\n xLibElementAttribs = static_cast< xml::sax::XAttributeList* >( pLibElement );\n\n pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX \":name\") ),\n rLib.aName );\n\n\n if( rLib.aStorageURL.getLength() )\n {\n pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_XLINK_PREFIX \":href\") ),\n rLib.aStorageURL );\n pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_XLINK_PREFIX \":type\") ),\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"simple\") ) );\n }\n\n pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX \":link\") ),\n rLib.bLink ? aTrueStr : aFalseStr );\n\n if( rLib.bLink )\n {\n pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX \":readonly\") ),\n rLib.bReadOnly ? aTrueStr : aFalseStr );\n }\n\n pLibElement->dump( xOut.get() );\n }\n\n xOut->ignorableWhitespace( OUString() );\n xOut->endElement( aLibrariesName );\n\n xOut->endDocument();\n}\n\n\/\/==================================================================================================\n\nvoid\nSAL_CALL exportLibrary(\n ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XExtendedDocumentHandler > const & xOut,\n const LibDescriptor& rLib )\n SAL_THROW( (::com::sun::star::uno::Exception) )\n{\n xOut->startDocument();\n\n OUString aDocTypeStr( RTL_CONSTASCII_USTRINGPARAM(\n \"\" ) );\n xOut->unknown( aDocTypeStr );\n xOut->ignorableWhitespace( OUString() );\n\n\n OUString aLibraryName( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX \":library\") );\n XMLElement* pLibElement = new XMLElement( aLibraryName );\n Reference< xml::sax::XAttributeList > xAttributes( pLibElement );\n\n pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(\"xmlns:\" XMLNS_LIBRARY_PREFIX) ),\n OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_URI) ) );\n\n pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX \":name\") ),\n rLib.aName );\n\n pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX \":readonly\") ),\n rLib.bReadOnly ? aTrueStr : aFalseStr );\n\n pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX \":passwordprotected\") ),\n rLib.bPasswordProtected ? aTrueStr : aFalseStr );\n\n if( rLib.bPreload )\n pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX \":preload\") ), aTrueStr );\n\n sal_Int32 nElementCount = rLib.aElementNames.getLength();\n if( nElementCount )\n {\n const OUString* pElementNames = rLib.aElementNames.getConstArray();\n for( sal_Int32 i = 0 ; i < nElementCount ; i++ )\n {\n XMLElement* pElement = new XMLElement( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX \":element\" ) ) );\n Reference< xml::sax::XAttributeList > xElementAttribs;\n xElementAttribs = static_cast< xml::sax::XAttributeList* >( pElement );\n\n pElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX \":name\") ),\n pElementNames[i] );\n\n pLibElement->addSubElement( pElement );\n }\n }\n\n pLibElement->dump( xOut.get() );\n\n xOut->endDocument();\n}\n\n};\n\nINTEGRATION: CWS ooo19126 (1.9.8); FILE MERGED 2005\/09\/05 18:40:24 rt 1.9.8.1: #i54170# Change license header: remove SISSL\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: xmllib_export.cxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 16:16:31 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#include \n#include \n\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star;\nusing namespace rtl;\n\nnamespace xmlscript\n{\n\nstatic OUString aTrueStr ( RTL_CONSTASCII_USTRINGPARAM(\"true\") );\nstatic OUString aFalseStr( RTL_CONSTASCII_USTRINGPARAM(\"false\") );\n\n\/\/##################################################################################################\n\n\n\/\/==================================================================================================\n\nvoid\nSAL_CALL exportLibraryContainer(\n Reference< xml::sax::XExtendedDocumentHandler > const & xOut,\n const LibDescriptorArray* pLibArray )\n SAL_THROW( (Exception) )\n{\n xOut->startDocument();\n\n OUString aDocTypeStr( RTL_CONSTASCII_USTRINGPARAM(\n \"\" ) );\n xOut->unknown( aDocTypeStr );\n xOut->ignorableWhitespace( OUString() );\n\n\n OUString aLibrariesName( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX \":libraries\") );\n XMLElement* pLibsElement = new XMLElement( aLibrariesName );\n Reference< xml::sax::XAttributeList > xAttributes( pLibsElement );\n\n pLibsElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(\"xmlns:\" XMLNS_LIBRARY_PREFIX) ),\n OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_URI) ) );\n pLibsElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(\"xmlns:\" XMLNS_XLINK_PREFIX) ),\n OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_XLINK_URI) ) );\n\n\n xOut->ignorableWhitespace( OUString() );\n xOut->startElement( aLibrariesName, xAttributes );\n\n int nLibCount = pLibArray->mnLibCount;\n for( sal_Int32 i = 0 ; i < nLibCount ; i++ )\n {\n LibDescriptor& rLib = pLibArray->mpLibs[i];\n\n OUString aLibraryName( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX \":library\") );\n XMLElement* pLibElement = new XMLElement( aLibraryName );\n Reference< xml::sax::XAttributeList > xLibElementAttribs;\n xLibElementAttribs = static_cast< xml::sax::XAttributeList* >( pLibElement );\n\n pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX \":name\") ),\n rLib.aName );\n\n\n if( rLib.aStorageURL.getLength() )\n {\n pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_XLINK_PREFIX \":href\") ),\n rLib.aStorageURL );\n pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_XLINK_PREFIX \":type\") ),\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"simple\") ) );\n }\n\n pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX \":link\") ),\n rLib.bLink ? aTrueStr : aFalseStr );\n\n if( rLib.bLink )\n {\n pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX \":readonly\") ),\n rLib.bReadOnly ? aTrueStr : aFalseStr );\n }\n\n pLibElement->dump( xOut.get() );\n }\n\n xOut->ignorableWhitespace( OUString() );\n xOut->endElement( aLibrariesName );\n\n xOut->endDocument();\n}\n\n\/\/==================================================================================================\n\nvoid\nSAL_CALL exportLibrary(\n ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XExtendedDocumentHandler > const & xOut,\n const LibDescriptor& rLib )\n SAL_THROW( (::com::sun::star::uno::Exception) )\n{\n xOut->startDocument();\n\n OUString aDocTypeStr( RTL_CONSTASCII_USTRINGPARAM(\n \"\" ) );\n xOut->unknown( aDocTypeStr );\n xOut->ignorableWhitespace( OUString() );\n\n\n OUString aLibraryName( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX \":library\") );\n XMLElement* pLibElement = new XMLElement( aLibraryName );\n Reference< xml::sax::XAttributeList > xAttributes( pLibElement );\n\n pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(\"xmlns:\" XMLNS_LIBRARY_PREFIX) ),\n OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_URI) ) );\n\n pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX \":name\") ),\n rLib.aName );\n\n pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX \":readonly\") ),\n rLib.bReadOnly ? aTrueStr : aFalseStr );\n\n pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX \":passwordprotected\") ),\n rLib.bPasswordProtected ? aTrueStr : aFalseStr );\n\n if( rLib.bPreload )\n pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX \":preload\") ), aTrueStr );\n\n sal_Int32 nElementCount = rLib.aElementNames.getLength();\n if( nElementCount )\n {\n const OUString* pElementNames = rLib.aElementNames.getConstArray();\n for( sal_Int32 i = 0 ; i < nElementCount ; i++ )\n {\n XMLElement* pElement = new XMLElement( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX \":element\" ) ) );\n Reference< xml::sax::XAttributeList > xElementAttribs;\n xElementAttribs = static_cast< xml::sax::XAttributeList* >( pElement );\n\n pElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX \":name\") ),\n pElementNames[i] );\n\n pLibElement->addSubElement( pElement );\n }\n }\n\n pLibElement->dump( xOut.get() );\n\n xOut->endDocument();\n}\n\n};\n\n<|endoftext|>"} {"text":"Broken code<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: saltimer.cxx,v $\n *\n * $Revision: 1.11 $\n *\n * last change: $Author: hr $ $Date: 2006-08-11 17:50:28 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#include \n#if defined(IRIX)\n#include \n#endif\n#include \n#include \n#include \n#include \n\n#include \n\n#ifndef _SV_SALDATA_HXX\n#include \n#endif\n#ifndef _SV_SALDISP_HXX\n#include \n#endif\n#ifndef _SV_SALTIMER_H\n#include \n#endif\n#ifndef _SV_SALINST_H\n#include \n#endif\n\n\/\/ -=-= SalData =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\/\/ -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\nvoid X11SalData::Timeout() const\n{\n ImplSVData* pSVData = ImplGetSVData();\n if( pSVData->mpSalTimer )\n pSVData->mpSalTimer->CallCallback();\n}\n\n\/\/ -=-= SalXLib =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\/\/ -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\nvoid SalXLib::StopTimer()\n{\n m_aTimeout.tv_sec = 0;\n m_aTimeout.tv_usec = 0;\n m_nTimeoutMS = 0;\n}\n\nvoid SalXLib::StartTimer( ULONG nMS )\n{\n timeval Timeout (m_aTimeout); \/\/ previous timeout.\n gettimeofday (&m_aTimeout, 0);\n\n m_nTimeoutMS = nMS;\n m_aTimeout += m_nTimeoutMS;\n\n if ((Timeout > m_aTimeout) || (Timeout.tv_sec == 0))\n {\n \/\/ Wakeup from previous timeout (or stopped timer).\n Wakeup();\n }\n}\n\n\/\/ -=-= SalTimer -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\/\/ -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\nSalTimer* X11SalInstance::CreateSalTimer()\n{\n return new X11SalTimer();\n}\n\nX11SalTimer::~X11SalTimer()\n{\n}\n\nvoid X11SalTimer::Stop()\n{\n GetX11SalData()->GetLib()->StopTimer();\n}\n\nvoid X11SalTimer::Start( ULONG nMS )\n{\n GetX11SalData()->GetLib()->StartTimer( nMS );\n}\n\nINTEGRATION: CWS pchfix02 (1.11.4); FILE MERGED 2006\/09\/01 17:58:06 kaib 1.11.4.1: #i68856# Added header markers and pch files\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: saltimer.cxx,v $\n *\n * $Revision: 1.12 $\n *\n * last change: $Author: obo $ $Date: 2006-09-17 12:35:56 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_vcl.hxx\"\n\n#include \n#if defined(IRIX)\n#include \n#endif\n#include \n#include \n#include \n#include \n\n#include \n\n#ifndef _SV_SALDATA_HXX\n#include \n#endif\n#ifndef _SV_SALDISP_HXX\n#include \n#endif\n#ifndef _SV_SALTIMER_H\n#include \n#endif\n#ifndef _SV_SALINST_H\n#include \n#endif\n\n\/\/ -=-= SalData =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\/\/ -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\nvoid X11SalData::Timeout() const\n{\n ImplSVData* pSVData = ImplGetSVData();\n if( pSVData->mpSalTimer )\n pSVData->mpSalTimer->CallCallback();\n}\n\n\/\/ -=-= SalXLib =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\/\/ -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\nvoid SalXLib::StopTimer()\n{\n m_aTimeout.tv_sec = 0;\n m_aTimeout.tv_usec = 0;\n m_nTimeoutMS = 0;\n}\n\nvoid SalXLib::StartTimer( ULONG nMS )\n{\n timeval Timeout (m_aTimeout); \/\/ previous timeout.\n gettimeofday (&m_aTimeout, 0);\n\n m_nTimeoutMS = nMS;\n m_aTimeout += m_nTimeoutMS;\n\n if ((Timeout > m_aTimeout) || (Timeout.tv_sec == 0))\n {\n \/\/ Wakeup from previous timeout (or stopped timer).\n Wakeup();\n }\n}\n\n\/\/ -=-= SalTimer -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\/\/ -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\nSalTimer* X11SalInstance::CreateSalTimer()\n{\n return new X11SalTimer();\n}\n\nX11SalTimer::~X11SalTimer()\n{\n}\n\nvoid X11SalTimer::Stop()\n{\n GetX11SalData()->GetLib()->StopTimer();\n}\n\nvoid X11SalTimer::Start( ULONG nMS )\n{\n GetX11SalData()->GetLib()->StartTimer( nMS );\n}\n\n<|endoftext|>"} {"text":"\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nnamespace po = boost::program_options;\n\nnamespace {\n\ntypedef std::vector strvect;\n\nstrvect tokenize(const std::string& inp)\n{\n strvect ret;\n size_t pos = 0;\n while(true) {\n size_t sep = inp.find_first_of(',', pos);\n if(sep==inp.npos) {\n ret.push_back(inp.substr(pos));\n break;\n } else if(sep!=pos) {\n ret.push_back(inp.substr(pos, sep-pos));\n } else {\n \/\/ ignore empty\n }\n pos = sep+1;\n }\n return ret;\n}\n\nstatic\nvoid getargs(int argc, char *argv[], po::variables_map& args)\n{\n std::ostringstream caption;\n caption<\";\n po::options_description opts(caption.str());\n opts.add_options()\n (\"help,h\", \"Display this message\")\n (\"verbose,v\", po::value()->default_value(\"0\")->value_name(\"NUM\"),\n \"Make some noise\")\n (\"define,D\", po::value >()->composing()->value_name(\"name=val\"),\n \"Override variable value (\\\"-Dname=value\\\")\")\n (\"lattice\", po::value()->value_name(\"FILE\"),\n \"Input lattice file\")\n (\"max,M\", po::value()->value_name(\"NUM\"),\n \"Maximum number of elements propagate through. (default is all)\")\n (\"format,F\", po::value()->value_name(\"FMT\")->default_value(\"txt\"),\n \"output format (txt or hdf5)\")\n (\"select-all,A\", \"Select all elements for output\")\n (\"select-type,T\", po::value()->value_name(\"ETYPE\"),\n \"Select all elements of the given type for output\")\n (\"select-last,L\", \"Select last element for output\")\n ;\n\n po::positional_options_description pos;\n pos.add(\"lattice\", 1);\n\n po::store(po::command_line_parser(argc, argv).options(opts).positional(pos).run(), args);\n po::notify(args);\n\n if(args.count(\"help\") || !args.count(\"lattice\")) {\n std::cout<\n{\n const std::string& value;\n update_define(const std::string& val) : value(val) {}\n\n Config::value_t operator()(double v) const\n {\n return boost::lexical_cast(value);\n }\n Config::value_t operator()(const std::string& v) const\n {\n return value;\n }\n Config::value_t operator()(const std::vector& v) const\n {\n throw std::runtime_error(\"-D can't set vector values\");\n }\n Config::value_t operator()(const Config::vector_t& v) const\n {\n throw std::runtime_error(\"-D can't set Config values\");\n }\n};\n\nstruct ObserverFactory\n{\n virtual ~ObserverFactory() {}\n virtual Observer *observe(Machine& M, ElementVoid* E) = 0;\n virtual void before_sim(Machine&) {}\n virtual void after_sim(Machine&) {}\n};\n\nstruct StreamObserver : public Observer\n{\n std::ostream *strm;\n StreamObserver(std::ostream& strm) :strm(&strm) {}\n virtual ~StreamObserver() {}\n virtual void view(const ElementVoid* elem, const StateBase* state)\n {\n (*strm)<index<<\" \"<<*state;\n }\n\n struct Factory : public ObserverFactory\n {\n std::auto_ptr owned_strm;\n std::ostream *strm;\n Factory(const strvect& fmt) :strm(&std::cout)\n {\n assert(!fmt.empty() && fmt[0]==\"txt\");\n\n for(strvect::const_iterator it=fmt.begin()+1, end=fmt.end(); it!=end; ++it)\n {\n const std::string& cmd = *it;\n if(cmd.substr(0,5)==\"file=\") {\n owned_strm.reset(new std::ofstream(cmd.substr(5).c_str()));\n strm = owned_strm.get();\n } else {\n std::cerr<<\"Warning: -F \"<flush();\n }\n };\n};\n\nstruct H5Observer : public Observer\n{\n H5StateWriter *writer;\n H5Observer(H5StateWriter *writer) : writer(writer) {}\n virtual ~H5Observer() {}\n\n struct Factory : public ObserverFactory\n {\n virtual ~Factory() {}\n std::auto_ptr writer;\n Factory(const strvect& fmt)\n {\n assert(!fmt.empty() && fmt[0]==\"hdf5\");\n\n for(strvect::const_iterator it=fmt.begin()+1, end=fmt.end(); it!=end; ++it)\n {\n const std::string& cmd = *it;\n if(cmd.substr(0,5)==\"file=\") {\n writer.reset(new H5StateWriter(cmd.substr(5)));\n } else {\n std::cerr<<\"Warning: -F \"<setAttr(\"sim_type\", M.simtype());\n }\n virtual void after_sim(Machine&)\n {\n if(writer.get()) writer->close();\n writer.reset();\n }\n };\n\n virtual void view(const ElementVoid *, const StateBase *state)\n {\n writer->append(state);\n }\n};\n\n} \/\/ namespace\n\nint main(int argc, char *argv[])\n{\ntry {\n po::variables_map args;\n getargs(argc, argv, args);\n\n std::auto_ptr conf;\n\n size_t verb = boost::lexical_cast(args[\"verbose\"].as());\n if(verb<=2)\n H5StateWriter::dontPrint();\n\n try {\n GLPSParser P;\n conf.reset(P.parse_file(args[\"lattice\"].as().c_str()));\n }catch(std::exception& e){\n std::cerr<<\"Parse error: \"<& defs = args[\"define\"].as >();\n\n BOOST_FOREACH(const std::string& def, defs) {\n size_t sep = def.find_first_of('=');\n if(sep==def.npos) {\n std::cerr<<\"-D \"<set_observer(ofact->observe(sim, elem));\n }\n }\n }\n }\n if(args.count(\"select-last\") && sim.size()>0) {\n ElementVoid *elem = sim[sim.size()-1];\n\n if(elem->observer()==NULL) {\n \/\/ don't replace existing Observer\n elem->set_observer(ofact->observe(sim, elem));\n }\n }\n\n ofact->before_sim(sim);\n\n if(verb) {\n sim.set_trace(&std::cout);\n\n std::cout<<\"# Machine configuration\\n\"< state(sim.allocState());\n sim.propagate(state.get(), 0, maxelem);\n\n ofact->after_sim(sim);\n\n if(verb) {\n std::cout << \"\\n# Final \" << *state << \"\\n\";\n }\n\n Machine::registeryCleanup();\n\n return 0;\n}catch(std::exception& e){\n std::cerr<<\"Error \"<more online help for run_flame\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nnamespace po = boost::program_options;\n\nnamespace {\n\ntypedef std::vector strvect;\n\nstrvect tokenize(const std::string& inp)\n{\n strvect ret;\n size_t pos = 0;\n while(true) {\n size_t sep = inp.find_first_of(',', pos);\n if(sep==inp.npos) {\n ret.push_back(inp.substr(pos));\n break;\n } else if(sep!=pos) {\n ret.push_back(inp.substr(pos, sep-pos));\n } else {\n \/\/ ignore empty\n }\n pos = sep+1;\n }\n return ret;\n}\n\nstatic\nvoid getargs(int argc, char *argv[], po::variables_map& args)\n{\n std::ostringstream caption;\n caption<\";\n po::options_description opts(caption.str());\n opts.add_options()\n (\"help,h\", \"Display this message\")\n (\"verbose,v\", po::value()->default_value(\"0\")->value_name(\"NUM\"),\n \"Make some noise\")\n (\"define,D\", po::value >()->composing()->value_name(\"name=val\"),\n \"Override variable value (\\\"-Dname=value\\\")\")\n (\"lattice\", po::value()->value_name(\"FILE\"),\n \"Input lattice file\")\n (\"max,M\", po::value()->value_name(\"NUM\"),\n \"Maximum number of elements propagate through. (default is all)\")\n (\"format,F\", po::value()->value_name(\"FMT\")->default_value(\"txt\"),\n \"output format (txt or hdf5)\")\n (\"select-all,A\", \"Select all elements for output\")\n (\"select-type,T\", po::value()->value_name(\"ETYPE\"),\n \"Select all elements of the given type for output\")\n (\"select-last,L\", \"Select last element for output\")\n ;\n\n po::positional_options_description pos;\n pos.add(\"lattice\", 1);\n\n po::store(po::command_line_parser(argc, argv).options(opts).positional(pos).run(), args);\n po::notify(args);\n\n if(args.count(\"help\") || !args.count(\"lattice\")) {\n std::cout<\n{\n const std::string& value;\n update_define(const std::string& val) : value(val) {}\n\n Config::value_t operator()(double v) const\n {\n return boost::lexical_cast(value);\n }\n Config::value_t operator()(const std::string& v) const\n {\n return value;\n }\n Config::value_t operator()(const std::vector& v) const\n {\n throw std::runtime_error(\"-D can't set vector values\");\n }\n Config::value_t operator()(const Config::vector_t& v) const\n {\n throw std::runtime_error(\"-D can't set Config values\");\n }\n};\n\nstruct ObserverFactory\n{\n virtual ~ObserverFactory() {}\n virtual Observer *observe(Machine& M, ElementVoid* E) = 0;\n virtual void before_sim(Machine&) {}\n virtual void after_sim(Machine&) {}\n};\n\nstruct StreamObserver : public Observer\n{\n std::ostream *strm;\n StreamObserver(std::ostream& strm) :strm(&strm) {}\n virtual ~StreamObserver() {}\n virtual void view(const ElementVoid* elem, const StateBase* state)\n {\n (*strm)<<\"After Element [\"<index<<\"] \"<name<<\" \"<<*state<<\"\\n\";\n }\n\n struct Factory : public ObserverFactory\n {\n std::auto_ptr owned_strm;\n std::ostream *strm;\n Factory(const strvect& fmt) :strm(&std::cout)\n {\n assert(!fmt.empty() && fmt[0]==\"txt\");\n\n for(strvect::const_iterator it=fmt.begin()+1, end=fmt.end(); it!=end; ++it)\n {\n const std::string& cmd = *it;\n if(cmd.substr(0,5)==\"file=\") {\n owned_strm.reset(new std::ofstream(cmd.substr(5).c_str()));\n strm = owned_strm.get();\n } else {\n std::cerr<<\"Warning: -F \"<flush();\n }\n };\n};\n\nstruct H5Observer : public Observer\n{\n H5StateWriter *writer;\n H5Observer(H5StateWriter *writer) : writer(writer) {}\n virtual ~H5Observer() {}\n\n struct Factory : public ObserverFactory\n {\n virtual ~Factory() {}\n std::auto_ptr writer;\n Factory(const strvect& fmt)\n {\n assert(!fmt.empty() && fmt[0]==\"hdf5\");\n\n for(strvect::const_iterator it=fmt.begin()+1, end=fmt.end(); it!=end; ++it)\n {\n const std::string& cmd = *it;\n if(cmd.substr(0,5)==\"file=\") {\n writer.reset(new H5StateWriter(cmd.substr(5)));\n } else {\n std::cerr<<\"Warning: -F \"<setAttr(\"sim_type\", M.simtype());\n }\n virtual void after_sim(Machine&)\n {\n if(writer.get()) writer->close();\n writer.reset();\n }\n };\n\n virtual void view(const ElementVoid *, const StateBase *state)\n {\n writer->append(state);\n }\n};\n\n} \/\/ namespace\n\nint main(int argc, char *argv[])\n{\ntry {\n po::variables_map args;\n getargs(argc, argv, args);\n\n std::auto_ptr conf;\n\n size_t verb = boost::lexical_cast(args[\"verbose\"].as());\n if(verb<=2)\n H5StateWriter::dontPrint();\n\n try {\n GLPSParser P;\n conf.reset(P.parse_file(args[\"lattice\"].as().c_str()));\n }catch(std::exception& e){\n std::cerr<<\"Parse error: \"<& defs = args[\"define\"].as >();\n\n BOOST_FOREACH(const std::string& def, defs) {\n size_t sep = def.find_first_of('=');\n if(sep==def.npos) {\n std::cerr<<\"-D \"<set_observer(ofact->observe(sim, elem));\n }\n }\n }\n }\n if(args.count(\"select-last\") && sim.size()>0) {\n ElementVoid *elem = sim[sim.size()-1];\n\n if(elem->observer()==NULL) {\n \/\/ don't replace existing Observer\n elem->set_observer(ofact->observe(sim, elem));\n }\n }\n\n ofact->before_sim(sim);\n\n if(verb) {\n sim.set_trace(&std::cout);\n\n std::cout<<\"# Machine configuration\\n\"< state(sim.allocState());\n sim.propagate(state.get(), 0, maxelem);\n\n ofact->after_sim(sim);\n\n if(verb) {\n std::cout << \"\\n# Final \" << *state << \"\\n\";\n }\n\n Machine::registeryCleanup();\n\n return 0;\n}catch(std::exception& e){\n std::cerr<<\"Error \"<"} {"text":"\/\/ Range-based algorithms\n\/\/ C++11\n\n#include \n#include \n\ntemplate \nvoid algorithm(ForwardRange& range)\n{\n\tusing std::begin;\n\tusing std::end;\n\n\tusing iterator = decltype(begin(range));\n\n\titerator it_begin = begin(range);\n\titerator it_end = end(range);\n\n\t\/\/ Now perform algorithm on elements between begin and end\n}\n\n\/\/ Implement algorithms that can be applied to any generic range of\n\/\/ elements.\n\/\/ \n\/\/ **Note**: The existing algorithms in the standard library are not\n\/\/ range-based but iterator-based. However, the Ranges Technical\n\/\/ Specification is experimenting with introducing ranges and\n\/\/ range-based algorithms to the standard, which are more flexible and\n\/\/ provide a simpler interface to client code.\n\/\/ \n\/\/ [!7-19] define a function template representing a range-based\n\/\/ algorithm. It takes a single range argument, which is\n\/\/ any type that supports `begin` and `end` functions that provide\n\/\/ iterators to the beginning and end of the range. A range may\n\/\/ be classified depending on the iterators that it provides:\n\/\/ \n\/\/ - *Forward Range* - provides\n\/\/ [Forward Iterators](cpp\/concept\/ForwardIterator)\n\/\/ - *Bidirectional Range* - provides\n\/\/ [Bidirectional Iterators](cpp\/concept\/BidirectionalIterator)\n\/\/ - *Random Access Range* - provides\n\/\/ [Random Access Iterators](cpp\/concept\/RandomAccessIterator)\n\/\/ \n\/\/ For this sample, we assume that the algorithm requires only Forward\n\/\/ Iterators, so can be applied to any Forward Range. We therefore\n\/\/ name the template parameter `ForwardRange` on [7] to illustrate\n\/\/ this.\n\/\/ \n\/\/ On [15-16], we call `begin` and `end` on the range to get the\n\/\/ respective iterators to the beginning and end of the range.\n\/\/ We use using-declarations on [10-11] to\n\/\/ allow these calls to be found via [argument-dependent\n\/\/ lookup](http:\/\/en.wikipedia.org\/wiki\/Argument-dependent_name_lookup)\n\/\/ before using the standard [`std::begin`](cpp\/iterator\/begin) and\n\/\/ [`std::end`](cpp\/iterator\/end) functions. With these iterators, we\n\/\/ can now implement the algorithm over the elements between them.\n\/\/ \n\/\/ If the iterators are not necessary to implement the algorithm, we\n\/\/ may instead be able to use a simple\n\/\/ [range-based `for` loop](\/common-tasks\/range-iteration.cpp).\n \n#include \n\nint main()\n{\n\tstd::forward_list arr = {6, 12, 5, 2, 3};\n\talgorithm(arr);\n}\nCorrect comment in range-based algorithm code\/\/ Range-based algorithms\n\/\/ C++11\n\n#include \n#include \n\ntemplate \nvoid algorithm(ForwardRange& range)\n{\n\tusing std::begin;\n\tusing std::end;\n\n\tusing iterator = decltype(begin(range));\n\n\titerator it_begin = begin(range);\n\titerator it_end = end(range);\n\n\t\/\/ Now use it_begin and it_end to implement algorithm\n}\n\n\/\/ Implement algorithms that can be applied to any generic range of\n\/\/ elements.\n\/\/ \n\/\/ **Note**: The existing algorithms in the standard library are not\n\/\/ range-based but iterator-based. However, the Ranges Technical\n\/\/ Specification is experimenting with introducing ranges and\n\/\/ range-based algorithms to the standard, which are more flexible and\n\/\/ provide a simpler interface to client code.\n\/\/ \n\/\/ [!7-19] define a function template representing a range-based\n\/\/ algorithm. It takes a single range argument, which is\n\/\/ any type that supports `begin` and `end` functions that provide\n\/\/ iterators to the beginning and end of the range. A range may\n\/\/ be classified depending on the iterators that it provides:\n\/\/ \n\/\/ - *Forward Range* - provides\n\/\/ [Forward Iterators](cpp\/concept\/ForwardIterator)\n\/\/ - *Bidirectional Range* - provides\n\/\/ [Bidirectional Iterators](cpp\/concept\/BidirectionalIterator)\n\/\/ - *Random Access Range* - provides\n\/\/ [Random Access Iterators](cpp\/concept\/RandomAccessIterator)\n\/\/ \n\/\/ For this sample, we assume that the algorithm requires only Forward\n\/\/ Iterators, so can be applied to any Forward Range. We therefore\n\/\/ name the template parameter `ForwardRange` on [7] to illustrate\n\/\/ this.\n\/\/ \n\/\/ On [15-16], we call `begin` and `end` on the range to get the\n\/\/ respective iterators to the beginning and end of the range.\n\/\/ We use using-declarations on [10-11] to\n\/\/ allow these calls to be found via [argument-dependent\n\/\/ lookup](http:\/\/en.wikipedia.org\/wiki\/Argument-dependent_name_lookup)\n\/\/ before using the standard [`std::begin`](cpp\/iterator\/begin) and\n\/\/ [`std::end`](cpp\/iterator\/end) functions. With these iterators, we\n\/\/ can now implement the algorithm over the elements between them.\n\/\/ \n\/\/ If the iterators are not necessary to implement the algorithm, we\n\/\/ may instead be able to use a simple\n\/\/ [range-based `for` loop](\/common-tasks\/range-iteration.cpp).\n \n#include \n\nint main()\n{\n\tstd::forward_list arr = {6, 12, 5, 2, 3};\n\talgorithm(arr);\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n\nProgram: Medical Imaging & Interaction Toolkit\nModule: $RCSfile$\nLanguage: C++\nDate: $Date$\nVersion: $Revision: -1 $\n\nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n\nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"itkRegularStepGradientDescentOptimizer.h\"\n#include \n#include \n#include \"QmitkDemonsRegistrationView.h\"\n#include \"ui_QmitkDemonsRegistrationViewControls.h\"\n#include \"mitkITKImageImport.h\"\n\nQmitkDemonsRegistrationView::QmitkDemonsRegistrationView(QWidget* parent, Qt::WindowFlags f ) : QWidget( parent, f ),\nm_FixedNode(NULL), m_MovingNode(NULL), m_ResultImage(NULL), m_ResultDeformationField(NULL)\n{\n m_Controls.setupUi(parent);\n\n QValidator* validatorHistogramLevels = new QIntValidator(1, 20000000, this);\n m_Controls.m_NumberOfHistogramLevels->setValidator(validatorHistogramLevels);\n\n QValidator* validatorMatchPoints = new QIntValidator(1, 20000000, this);\n m_Controls.m_NumberOfMatchPoints->setValidator(validatorMatchPoints);\n\n QValidator* validatorIterations = new QIntValidator(1, 20000000, this);\n m_Controls.m_Iterations->setValidator(validatorIterations);\n\n QValidator* validatorStandardDeviation = new QDoubleValidator(0, 20000000, 2, this);\n m_Controls.m_StandardDeviation->setValidator(validatorStandardDeviation);\n}\n\nQmitkDemonsRegistrationView::~QmitkDemonsRegistrationView()\n{\n}\n\n\nint QmitkDemonsRegistrationView::GetNumberOfIterations()\n{\n return atoi(m_Controls.m_Iterations->text().toLatin1());\n}\n\nfloat QmitkDemonsRegistrationView::GetStandardDeviation()\n{\n return atof(m_Controls.m_StandardDeviation->text().toLatin1());\n}\n\nmitk::Image::Pointer QmitkDemonsRegistrationView::GetResultImage()\n{\n return m_ResultImage;\n}\n\nmitk::Image::Pointer QmitkDemonsRegistrationView::GetResultDeformationfield()\n{\n return m_ResultDeformationField;\n}\n\nvoid QmitkDemonsRegistrationView::CalculateTransformation()\n{\n if (m_FixedNode.IsNotNull() && m_MovingNode.IsNotNull())\n {\n mitk::Image::Pointer fimage = dynamic_cast(m_FixedNode->GetData());\n mitk::Image::Pointer mimage = dynamic_cast(m_MovingNode->GetData());\n if ( m_Controls.m_RegistrationSelection->currentIndex() == 0)\n {\n mitk::DemonsRegistration::Pointer registration = mitk::DemonsRegistration::New();\n registration->SetSaveDeformationField(false);\n registration->SetSaveResult(false);\n registration->SetReferenceImage(fimage);\n registration->SetNumberOfIterations(atoi(m_Controls.m_Iterations->text().toLatin1()));\n registration->SetStandardDeviation(atof(m_Controls.m_StandardDeviation->text().toLatin1()));\n if (m_Controls.m_UseHistogramMatching->isChecked())\n {\n mitk::HistogramMatching::Pointer histogramMatching = mitk::HistogramMatching::New();\n histogramMatching->SetReferenceImage(fimage);\n histogramMatching->SetInput(mimage);\n histogramMatching->SetNumberOfHistogramLevels(atoi(m_Controls.m_NumberOfHistogramLevels->text().toLatin1()));\n histogramMatching->SetNumberOfMatchPoints(atoi(m_Controls.m_NumberOfMatchPoints->text().toLatin1()));\n histogramMatching->SetThresholdAtMeanIntensity(m_Controls.m_ThresholdAtMeanIntensity->isChecked());\n histogramMatching->Update();\n mitk::Image::Pointer histimage = histogramMatching->GetOutput();\n if (histimage.IsNotNull())\n {\n registration->SetInput(histimage);\n }\n else\n {\n registration->SetInput(mimage);\n }\n }\n else\n {\n registration->SetInput(mimage);\n }\n try\n {\n registration->Update();\n }\n catch (itk::ExceptionObject& excpt)\n {\n QMessageBox::information( this, \"Registration exception\", excpt.GetDescription(), QMessageBox::Ok );\n }\n m_ResultImage = registration->GetOutput();\n typedef itk::Image, 3> VectorImageType;\n VectorImageType::Pointer deformationField = registration->GetDeformationField();\n m_ResultDeformationField = mitk::ImportItkImage(deformationField);\n }\n else if(m_Controls.m_RegistrationSelection->currentIndex() == 1)\n {\n mitk::SymmetricForcesDemonsRegistration::Pointer registration = mitk::SymmetricForcesDemonsRegistration::New();\n registration->SetSaveDeformationField(false);\n registration->SetSaveResult(false);\n registration->SetReferenceImage(fimage);\n registration->SetNumberOfIterations(atoi(m_Controls.m_Iterations->text().toLatin1()));\n registration->SetStandardDeviation(atof(m_Controls.m_StandardDeviation->text().toLatin1()));\n if (m_Controls.m_UseHistogramMatching->isChecked())\n {\n mitk::HistogramMatching::Pointer histogramMatching = mitk::HistogramMatching::New();\n histogramMatching->SetReferenceImage(fimage);\n histogramMatching->SetInput(mimage);\n histogramMatching->SetNumberOfHistogramLevels(atoi(m_Controls.m_NumberOfHistogramLevels->text().toLatin1()));\n histogramMatching->SetNumberOfMatchPoints(atoi(m_Controls.m_NumberOfMatchPoints->text().toLatin1()));\n histogramMatching->SetThresholdAtMeanIntensity(m_Controls.m_ThresholdAtMeanIntensity->isChecked());\n histogramMatching->Update();\n mitk::Image::Pointer histimage = histogramMatching->GetOutput();\n if (histimage.IsNotNull())\n {\n registration->SetInput(histimage);\n }\n else\n {\n registration->SetInput(mimage);\n }\n }\n else\n {\n registration->SetInput(mimage);\n }\n try\n {\n registration->Update();\n }\n catch (itk::ExceptionObject& excpt)\n {\n QMessageBox::information( this, \"Registration exception\", excpt.GetDescription(), QMessageBox::Ok );\n }\n m_ResultImage = registration->GetOutput();\n typedef itk::Image, 3> VectorImageType;\n VectorImageType::Pointer deformationField = registration->GetDeformationField();\n m_ResultDeformationField = mitk::ImportItkImage(deformationField);\n }\n }\n}\n\nvoid QmitkDemonsRegistrationView::SetFixedNode( mitk::DataTreeNode * fixedNode )\n{\n m_FixedNode = fixedNode;\n}\n\nvoid QmitkDemonsRegistrationView::SetMovingNode( mitk::DataTreeNode * movingNode )\n{\n m_MovingNode = movingNode;\n}\n\nvoid QmitkDemonsRegistrationView::UseHistogramMatching( bool useHM )\n{\n if (useHM)\n {\n m_Controls.numberOfHistogramLevels->setEnabled(true);\n m_Controls.m_NumberOfHistogramLevels->setEnabled(true);\n m_Controls.numberOfMatchPoints->setEnabled(true);\n m_Controls.m_NumberOfMatchPoints->setEnabled(true);\n m_Controls.thresholdAtMeanIntensity->setEnabled(true);\n m_Controls.m_ThresholdAtMeanIntensity->setEnabled(true);\n }\n else\n {\n m_Controls.numberOfHistogramLevels->setEnabled(false);\n m_Controls.m_NumberOfHistogramLevels->setEnabled(false);\n m_Controls.numberOfMatchPoints->setEnabled(false);\n m_Controls.m_NumberOfMatchPoints->setEnabled(false);\n m_Controls.thresholdAtMeanIntensity->setEnabled(false);\n m_Controls.m_ThresholdAtMeanIntensity->setEnabled(false);\n }\n}\nFIX (#3020): added workaround to check if fixed image is bigger than moving image\/*=========================================================================\n\nProgram: Medical Imaging & Interaction Toolkit\nModule: $RCSfile$\nLanguage: C++\nDate: $Date$\nVersion: $Revision: -1 $\n\nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n\nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"itkRegularStepGradientDescentOptimizer.h\"\n#include \n#include \n#include \"QmitkDemonsRegistrationView.h\"\n#include \"ui_QmitkDemonsRegistrationViewControls.h\"\n#include \"mitkITKImageImport.h\"\n\nQmitkDemonsRegistrationView::QmitkDemonsRegistrationView(QWidget* parent, Qt::WindowFlags f ) : QWidget( parent, f ),\nm_FixedNode(NULL), m_MovingNode(NULL), m_ResultImage(NULL), m_ResultDeformationField(NULL)\n{\n m_Controls.setupUi(parent);\n\n QValidator* validatorHistogramLevels = new QIntValidator(1, 20000000, this);\n m_Controls.m_NumberOfHistogramLevels->setValidator(validatorHistogramLevels);\n\n QValidator* validatorMatchPoints = new QIntValidator(1, 20000000, this);\n m_Controls.m_NumberOfMatchPoints->setValidator(validatorMatchPoints);\n\n QValidator* validatorIterations = new QIntValidator(1, 20000000, this);\n m_Controls.m_Iterations->setValidator(validatorIterations);\n\n QValidator* validatorStandardDeviation = new QDoubleValidator(0, 20000000, 2, this);\n m_Controls.m_StandardDeviation->setValidator(validatorStandardDeviation);\n}\n\nQmitkDemonsRegistrationView::~QmitkDemonsRegistrationView()\n{\n}\n\n\nint QmitkDemonsRegistrationView::GetNumberOfIterations()\n{\n return atoi(m_Controls.m_Iterations->text().toLatin1());\n}\n\nfloat QmitkDemonsRegistrationView::GetStandardDeviation()\n{\n return atof(m_Controls.m_StandardDeviation->text().toLatin1());\n}\n\nmitk::Image::Pointer QmitkDemonsRegistrationView::GetResultImage()\n{\n return m_ResultImage;\n}\n\nmitk::Image::Pointer QmitkDemonsRegistrationView::GetResultDeformationfield()\n{\n return m_ResultDeformationField;\n}\n\nvoid QmitkDemonsRegistrationView::CalculateTransformation()\n{\n if (m_FixedNode.IsNotNull() && m_MovingNode.IsNotNull())\n {\n mitk::Image::Pointer fimage = dynamic_cast(m_FixedNode->GetData());\n mitk::Image::Pointer mimage = dynamic_cast(m_MovingNode->GetData());\n \/\/ workaround to ensure that fimage covers a bigger region than mimage\n mitk::Image::RegionType fimageRegion = fimage->GetLargestPossibleRegion();\n mitk::Image::RegionType mimageRegion = mimage->GetLargestPossibleRegion();\n if (!((fimageRegion.GetSize(0)>=mimageRegion.GetSize(0))&&(fimageRegion.GetSize(1)>=mimageRegion.GetSize(1))\n &&(fimageRegion.GetSize(2)>=mimageRegion.GetSize(2))))\n {\n QMessageBox::information(NULL,\"Registration\",\"Fixed image must be equal or bigger in size than moving image\");\n return;\n }\n if ( m_Controls.m_RegistrationSelection->currentIndex() == 0)\n {\n mitk::DemonsRegistration::Pointer registration = mitk::DemonsRegistration::New();\n registration->SetSaveDeformationField(false);\n registration->SetSaveResult(false);\n registration->SetReferenceImage(fimage);\n registration->SetNumberOfIterations(atoi(m_Controls.m_Iterations->text().toLatin1()));\n registration->SetStandardDeviation(atof(m_Controls.m_StandardDeviation->text().toLatin1()));\n if (m_Controls.m_UseHistogramMatching->isChecked())\n {\n mitk::HistogramMatching::Pointer histogramMatching = mitk::HistogramMatching::New();\n histogramMatching->SetReferenceImage(fimage);\n histogramMatching->SetInput(mimage);\n histogramMatching->SetNumberOfHistogramLevels(atoi(m_Controls.m_NumberOfHistogramLevels->text().toLatin1()));\n histogramMatching->SetNumberOfMatchPoints(atoi(m_Controls.m_NumberOfMatchPoints->text().toLatin1()));\n histogramMatching->SetThresholdAtMeanIntensity(m_Controls.m_ThresholdAtMeanIntensity->isChecked());\n histogramMatching->Update();\n mitk::Image::Pointer histimage = histogramMatching->GetOutput();\n if (histimage.IsNotNull())\n {\n registration->SetInput(histimage);\n }\n else\n {\n registration->SetInput(mimage);\n }\n }\n else\n {\n registration->SetInput(mimage);\n }\n try\n {\n registration->Update();\n }\n catch (itk::ExceptionObject& excpt)\n {\n QMessageBox::information( this, \"Registration exception\", excpt.GetDescription(), QMessageBox::Ok );\n return;\n }\n m_ResultImage = registration->GetOutput();\n typedef itk::Image, 3> VectorImageType;\n VectorImageType::Pointer deformationField = registration->GetDeformationField();\n m_ResultDeformationField = mitk::ImportItkImage(deformationField);\n }\n else if(m_Controls.m_RegistrationSelection->currentIndex() == 1)\n {\n mitk::SymmetricForcesDemonsRegistration::Pointer registration = mitk::SymmetricForcesDemonsRegistration::New();\n registration->SetSaveDeformationField(false);\n registration->SetSaveResult(false);\n registration->SetReferenceImage(fimage);\n registration->SetNumberOfIterations(atoi(m_Controls.m_Iterations->text().toLatin1()));\n registration->SetStandardDeviation(atof(m_Controls.m_StandardDeviation->text().toLatin1()));\n if (m_Controls.m_UseHistogramMatching->isChecked())\n {\n mitk::HistogramMatching::Pointer histogramMatching = mitk::HistogramMatching::New();\n histogramMatching->SetReferenceImage(fimage);\n histogramMatching->SetInput(mimage);\n histogramMatching->SetNumberOfHistogramLevels(atoi(m_Controls.m_NumberOfHistogramLevels->text().toLatin1()));\n histogramMatching->SetNumberOfMatchPoints(atoi(m_Controls.m_NumberOfMatchPoints->text().toLatin1()));\n histogramMatching->SetThresholdAtMeanIntensity(m_Controls.m_ThresholdAtMeanIntensity->isChecked());\n histogramMatching->Update();\n mitk::Image::Pointer histimage = histogramMatching->GetOutput();\n if (histimage.IsNotNull())\n {\n registration->SetInput(histimage);\n }\n else\n {\n registration->SetInput(mimage);\n }\n }\n else\n {\n registration->SetInput(mimage);\n }\n try\n {\n registration->Update();\n }\n catch (itk::ExceptionObject& excpt)\n {\n QMessageBox::information( this, \"Registration exception\", excpt.GetDescription(), QMessageBox::Ok );\n }\n m_ResultImage = registration->GetOutput();\n typedef itk::Image, 3> VectorImageType;\n VectorImageType::Pointer deformationField = registration->GetDeformationField();\n m_ResultDeformationField = mitk::ImportItkImage(deformationField);\n }\n }\n}\n\nvoid QmitkDemonsRegistrationView::SetFixedNode( mitk::DataTreeNode * fixedNode )\n{\n m_FixedNode = fixedNode;\n}\n\nvoid QmitkDemonsRegistrationView::SetMovingNode( mitk::DataTreeNode * movingNode )\n{\n m_MovingNode = movingNode;\n}\n\nvoid QmitkDemonsRegistrationView::UseHistogramMatching( bool useHM )\n{\n if (useHM)\n {\n m_Controls.numberOfHistogramLevels->setEnabled(true);\n m_Controls.m_NumberOfHistogramLevels->setEnabled(true);\n m_Controls.numberOfMatchPoints->setEnabled(true);\n m_Controls.m_NumberOfMatchPoints->setEnabled(true);\n m_Controls.thresholdAtMeanIntensity->setEnabled(true);\n m_Controls.m_ThresholdAtMeanIntensity->setEnabled(true);\n }\n else\n {\n m_Controls.numberOfHistogramLevels->setEnabled(false);\n m_Controls.m_NumberOfHistogramLevels->setEnabled(false);\n m_Controls.numberOfMatchPoints->setEnabled(false);\n m_Controls.m_NumberOfMatchPoints->setEnabled(false);\n m_Controls.thresholdAtMeanIntensity->setEnabled(false);\n m_Controls.m_ThresholdAtMeanIntensity->setEnabled(false);\n }\n}\n<|endoftext|>"} {"text":"\/**\n * Copyright (c) 2008 Will Roberts\n * All Rights Reserved.\n *\n * Name: count\n *\n * Author: wildwilhelm@gmail.com (WKR)\n * Creation Date: 11 November 2008\n *\n * Purpose: Standard input line counter\n *\n * Description:\n * count counts the number of unique lines on the standard input,\n * outputting the counts after all the input is read. The output\n * of the program can be piped through sort -nr to sort it in order\n * of descending frequency.\n *\n * Revision Information:\n *\n * (WKR) 11 November 2008\n * - Initial version.\n *\n * \\file count.cpp\n *\/\n\n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\nvoid\nprintHelp()\n{\n cout << \"Counts unique lines on standard input, outputting the counts after all\" << endl;\n cout << \"input is read. Output is sorted in alphabetical order of lines. The\" << endl;\n cout << \"output of the program can be sort it in order of descending frequency\" << endl;\n cout << \"using the -f option or by piping through sort -nr.\" << endl;\n cout << endl;\n cout << \"Syntax:\" << endl;\n cout << endl;\n cout << \" count [OPTIONS]\" << endl;\n cout << endl;\n cout << \"Options:\" << endl;\n cout << endl;\n cout << \" -e always count the last line of the input, even if it is\" << endl;\n cout << \" empty\" << endl;\n cout << \" -f sort output in order of descending frequency\" << endl;\n cout << \" -? display this help message and exit\" << endl;\n}\n\ntemplate\npair flip_pair(const pair &p)\n{\n return pair(p.second, p.first);\n}\n\ntemplate\nmap flip_map(const map &src)\n{\n map dst;\n transform(src.begin(), src.end(), inserter(dst, dst.begin()),\n flip_pair);\n return dst;\n}\n\nint\nmain ( int argc,\n char **argv )\n{\n bool fIncludeLastLine = false;\n bool fSortDecreasingFreq = false;\n int c;\n while ((c = getopt(argc, argv, \"ef?\")) != -1)\n {\n switch(c)\n {\n case 'e':\n fIncludeLastLine = true;\n break;\n case 'f':\n fSortDecreasingFreq = true;\n break;\n case '?':\n printHelp();\n exit(1);\n break;\n default:\n break;\n }\n }\n\n int nNumLines = 0;\n map LineDict;\n while ( cin.good() )\n {\n string sLine;\n getline ( cin, sLine );\n if (fIncludeLastLine || !cin.eof() || sLine.length() != 0)\n {\n LineDict[sLine] += 1;\n }\n nNumLines += 1;\n }\n \/\/int nWidth = 0;\n \/\/while ( nNumLines > 0 )\n \/\/{\n \/\/ nWidth++;\n \/\/ nNumLines \/= 10;\n \/\/}\n if (fSortDecreasingFreq)\n {\n map FlippedLineDict = flip_map(LineDict);\n for ( map::reverse_iterator iterator =\n FlippedLineDict.rbegin();\n iterator != FlippedLineDict.rend(); iterator++ )\n {\n cout << iterator->first << \"\\t\" << iterator->second << endl;\n }\n }\n else\n {\n for ( map::iterator iterator = LineDict.begin();\n iterator != LineDict.end(); iterator++ )\n {\n cout << iterator->second << \"\\t\" << iterator->first << endl;\n }\n }\n return 0;\n}\ncount.cpp: fix -? output\/**\n * Copyright (c) 2008 Will Roberts\n * All Rights Reserved.\n *\n * Name: count\n *\n * Author: wildwilhelm@gmail.com (WKR)\n * Creation Date: 11 November 2008\n *\n * Purpose: Standard input line counter\n *\n * Description:\n * count counts the number of unique lines on the standard input,\n * outputting the counts after all the input is read. The output\n * of the program can be piped through sort -nr to sort it in order\n * of descending frequency.\n *\n * Revision Information:\n *\n * (WKR) 11 November 2008\n * - Initial version.\n *\n * \\file count.cpp\n *\/\n\n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\nvoid\nprintHelp()\n{\n cout << \"Counts unique lines on standard input, outputting the counts after all\" << endl;\n cout << \"input is read. Output is sorted in alphabetical order of lines. The\" << endl;\n cout << \"output of the program can be sort it in order of descending frequency\" << endl;\n cout << \"using the -f option or by piping through sort -nr.\" << endl;\n cout << endl;\n cout << \"Syntax:\" << endl;\n cout << endl;\n cout << \" count [OPTIONS]\" << endl;\n cout << endl;\n cout << \"Options:\" << endl;\n cout << endl;\n cout << \" -e always count the last line of the input, even if it is\" << endl;\n cout << \" empty\" << endl;\n cout << \" -f sort output in order of descending frequency\" << endl;\n cout << \" -? display this help message and exit\" << endl;\n}\n\ntemplate\npair flip_pair(const pair &p)\n{\n return pair(p.second, p.first);\n}\n\ntemplate\nmap flip_map(const map &src)\n{\n map dst;\n transform(src.begin(), src.end(), inserter(dst, dst.begin()),\n flip_pair);\n return dst;\n}\n\nint\nmain ( int argc,\n char **argv )\n{\n bool fIncludeLastLine = false;\n bool fSortDecreasingFreq = false;\n int c;\n while ((c = getopt(argc, argv, \"ef?\")) != -1)\n {\n switch(c)\n {\n case 'e':\n fIncludeLastLine = true;\n break;\n case 'f':\n fSortDecreasingFreq = true;\n break;\n case '?':\n printHelp();\n exit(1);\n break;\n default:\n break;\n }\n }\n\n int nNumLines = 0;\n map LineDict;\n while ( cin.good() )\n {\n string sLine;\n getline ( cin, sLine );\n if (fIncludeLastLine || !cin.eof() || sLine.length() != 0)\n {\n LineDict[sLine] += 1;\n }\n nNumLines += 1;\n }\n \/\/int nWidth = 0;\n \/\/while ( nNumLines > 0 )\n \/\/{\n \/\/ nWidth++;\n \/\/ nNumLines \/= 10;\n \/\/}\n if (fSortDecreasingFreq)\n {\n map FlippedLineDict = flip_map(LineDict);\n for ( map::reverse_iterator iterator =\n FlippedLineDict.rbegin();\n iterator != FlippedLineDict.rend(); iterator++ )\n {\n cout << iterator->first << \"\\t\" << iterator->second << endl;\n }\n }\n else\n {\n for ( map::iterator iterator = LineDict.begin();\n iterator != LineDict.end(); iterator++ )\n {\n cout << iterator->second << \"\\t\" << iterator->first << endl;\n }\n }\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2015 The Subzone Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"crypto\/p256_key_exchange.h\"\n\n#include \"base\/logging.h\"\n#include \"gtest\/gtest.h\"\n\nnamespace crypto {\nnamespace test {\n\n\/\/ SharedKeyX509 tests that the basic key exchange identity holds: that both\n\/\/ parties end up with the same key, exchanged in the X.509 network format.\nTEST(P256KeyExchange, SharedKeyX509) {\n for (int i = 0; i < 5; i++) {\n scoped_ptr alice(new P256KeyExchange());\n scoped_ptr bob(new P256KeyExchange());\n ASSERT_TRUE(alice.get() != nullptr);\n ASSERT_TRUE(bob.get() != nullptr);\n\n const base::StringPiece alice_public_x509(alice->GetX509Public());\n const base::StringPiece bob_public_x509(bob->GetX509Public());\n\n ASSERT_FALSE(alice_public_x509.empty());\n ASSERT_FALSE(bob_public_x509.empty());\n ASSERT_NE(alice_public_x509, bob_public_x509);\n\n \/\/ Convert X.509 format to public key value\n std::string alice_public, bob_public;\n ASSERT_TRUE(P256KeyExchange::GetPublicValueFromX509(alice_public_x509,\n &alice_public));\n ASSERT_TRUE(P256KeyExchange::GetPublicValueFromX509(bob_public_x509,\n &bob_public));\n\n \/\/ These public keys must match\n ASSERT_EQ(alice_public, alice->public_value());\n ASSERT_EQ(bob_public, bob->public_value());\n }\n}\n\n\/\/ The signature test generates a key exchange (public\/private key pair) and\n\/\/ takes the public key value and signs it. Finally it verifies that the\n\/\/ signature matches with the public key signature. We repeat this test 5 times.\nTEST(P256KeyExchange, Signature) {\n for (int i = 0; i < 5; i++) {\n P256KeyExchange alice;\n const base::StringPiece alice_sig(alice.GetSignature());\n ASSERT_FALSE(alice_sig.empty());\n\n \/\/ Take the public key in DER format. This is the string that is going to be\n \/\/ passed through the SHA256 and then signed.\n const base::StringPiece public_x509(alice.GetX509Public());\n ASSERT_FALSE(public_x509.empty());\n\n \/\/ Verify the signature against it's public key.\n ASSERT_TRUE(P256KeyExchange::VerifySignature(public_x509, alice_sig));\n }\n}\n\n} \/\/ namespace test\n} \/\/ namespace crypto\n\nVerify test with values coming from fred\/\/ Copyright 2015 The Subzone Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"crypto\/p256_key_exchange.h\"\n\n#include \"base\/logging.h\"\n#include \"gtest\/gtest.h\"\n\nnamespace crypto {\nnamespace test {\n\n\/\/ SharedKeyX509 tests that the basic key exchange identity holds: that both\n\/\/ parties end up with the same key, exchanged in the X.509 network format.\nTEST(P256KeyExchange, SharedKeyX509) {\n for (int i = 0; i < 5; i++) {\n scoped_ptr alice(new P256KeyExchange());\n scoped_ptr bob(new P256KeyExchange());\n ASSERT_TRUE(alice.get() != nullptr);\n ASSERT_TRUE(bob.get() != nullptr);\n\n const base::StringPiece alice_public_x509(alice->GetX509Public());\n const base::StringPiece bob_public_x509(bob->GetX509Public());\n\n ASSERT_FALSE(alice_public_x509.empty());\n ASSERT_FALSE(bob_public_x509.empty());\n ASSERT_NE(alice_public_x509, bob_public_x509);\n\n \/\/ Convert X.509 format to public key value\n std::string alice_public, bob_public;\n ASSERT_TRUE(P256KeyExchange::GetPublicValueFromX509(alice_public_x509,\n &alice_public));\n ASSERT_TRUE(P256KeyExchange::GetPublicValueFromX509(bob_public_x509,\n &bob_public));\n\n \/\/ These public keys must match\n ASSERT_EQ(alice_public, alice->public_value());\n ASSERT_EQ(bob_public, bob->public_value());\n }\n}\n\n\/\/ The SignAndVerify test generates a key exchange (public\/private key pair) and\n\/\/ takes the public key value and signs it. Finally it verifies that the\n\/\/ signature matches with the public key signature. We repeat this test 5 times.\nTEST(P256KeyExchange, SignAndVerify) {\n for (int i = 0; i < 5; i++) {\n P256KeyExchange alice;\n const base::StringPiece alice_sig(alice.GetSignature());\n ASSERT_FALSE(alice_sig.empty());\n\n \/\/ Take the public key in DER format. This is the string that is going to be\n \/\/ passed through the SHA256 and then signed.\n const base::StringPiece public_x509(alice.GetX509Public());\n ASSERT_FALSE(public_x509.empty());\n\n \/\/ Verify the signature against it's public key.\n ASSERT_TRUE(P256KeyExchange::VerifySignature(public_x509, alice_sig));\n }\n}\n\n\/\/ The Verify test takes a public key sample value from the Freenet reference\n\/\/ implementation with a valid signature and checks that our implementation\n\/\/ can verify the signature appropriatelly.\nTEST(P256KeyExchange, Verify) {\n \/\/ Public key in X509 network format.\n const uint8_t pubx509[P256KeyExchange::kP256PublicKeyX509Bytes] = {\n 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02,\n 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03,\n 0x42, 0x00, 0x04, 0xb3, 0x74, 0x41, 0xcc, 0x7e, 0x36, 0x76, 0xe1, 0x3f,\n 0x13, 0xd9, 0x8c, 0x50, 0x8f, 0xb9, 0x53, 0x6e, 0xae, 0x01, 0xe5, 0x2b,\n 0x20, 0x8f, 0x44, 0x1a, 0x58, 0xc3, 0x85, 0xf8, 0x58, 0x82, 0x79, 0x0a,\n 0xf8, 0xae, 0xb2, 0xdb, 0xa7, 0x30, 0x88, 0x36, 0x10, 0xd2, 0x20, 0x3c,\n 0xb6, 0xa8, 0xab, 0x2f, 0x76, 0xfe, 0x50, 0xc3, 0x2c, 0xc4, 0xa8, 0xb8,\n 0xc3, 0xbb, 0x52, 0xa7, 0x5b, 0x9b, 0x6d\n };\n\n \/\/ Signature in DER export format.\n const uint8_t sig[] = {\n 0x30, 0x45, 0x02, 0x20, 0x6c, 0x0c, 0x5b, 0x93, 0x30, 0xb9, 0x59, 0xf8,\n 0xcb, 0x23, 0x38, 0xec, 0x13, 0xc3, 0x51, 0xb9, 0x72, 0x61, 0x14, 0xa9,\n 0xc2, 0xf5, 0x59, 0x97, 0x23, 0x09, 0x00, 0x52, 0x57, 0xab, 0x49, 0x22,\n 0x02, 0x21, 0x00, 0x95, 0xe3, 0xd4, 0xa1, 0xcd, 0x7e, 0xe3, 0x84, 0x48,\n 0x5f, 0x56, 0x23, 0xd3, 0x2b, 0x0b, 0x15, 0x43, 0xce, 0x3a, 0x35, 0x68,\n 0xc6, 0xaa, 0x2a, 0xf2, 0x80, 0x0a, 0x0d, 0x22, 0x38, 0xb2, 0x38\n };\n\n \/\/ Convert the byte arrays to strings to be able to call VerifySignature()\n const base::StringPiece pubx509_str(reinterpret_cast(pubx509),\n sizeof(pubx509));\n const base::StringPiece sig_str(reinterpret_cast(sig),\n sizeof(sig));\n\n \/\/ It must return true, as this is a valid signature from the public key above\n ASSERT_TRUE(P256KeyExchange::VerifySignature(pubx509_str, sig_str));\n}\n\n} \/\/ namespace test\n} \/\/ namespace crypto\n\n<|endoftext|>"} {"text":"\/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/*\n * Copyright 2016 Couchbase, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \n#include \n\nvoid ship_mcbp_tap_log(McbpConnection* c) {\n bool more_data = true;\n bool send_data = false;\n bool disconnect = false;\n item* it;\n uint32_t bodylen;\n int ii = 0;\n\n c->addMsgHdr(true);\n \/* @todo add check for buffer overflow of c->write.buf) *\/\n c->write.bytes = 0;\n c->write.curr = c->write.buf;\n\n auto tap_iterator = c->getTapIterator();\n do {\n \/* @todo fixme! *\/\n void* engine;\n uint16_t nengine;\n uint8_t ttl;\n uint16_t tap_flags;\n uint32_t seqno;\n uint16_t vbucket;\n tap_event_t event;\n bool inflate = false;\n size_t inflated_length = 0;\n\n union {\n protocol_binary_request_tap_mutation mutation;\n protocol_binary_request_tap_delete del;\n protocol_binary_request_tap_flush flush;\n protocol_binary_request_tap_opaque opaque;\n protocol_binary_request_noop noop;\n } msg;\n item_info_holder info;\n\n if (ii++ == 10) {\n break;\n }\n\n event = tap_iterator(c->getBucketEngineAsV0(), c->getCookie(), &it,\n &engine, &nengine, &ttl,\n &tap_flags, &seqno, &vbucket);\n memset(&msg, 0, sizeof(msg));\n msg.opaque.message.header.request.magic = (uint8_t)PROTOCOL_BINARY_REQ;\n msg.opaque.message.header.request.opaque = htonl(seqno);\n msg.opaque.message.body.tap.enginespecific_length = htons(nengine);\n msg.opaque.message.body.tap.ttl = ttl;\n msg.opaque.message.body.tap.flags = htons(tap_flags);\n msg.opaque.message.header.request.extlen = 8;\n msg.opaque.message.header.request.vbucket = htons(vbucket);\n info.info.nvalue = IOV_MAX;\n\n switch (event) {\n case TAP_NOOP :\n send_data = true;\n msg.noop.message.header.request.opcode = PROTOCOL_BINARY_CMD_NOOP;\n msg.noop.message.header.request.extlen = 0;\n msg.noop.message.header.request.bodylen = htonl(0);\n memcpy(c->write.curr, msg.noop.bytes, sizeof(msg.noop.bytes));\n c->addIov(c->write.curr, sizeof(msg.noop.bytes));\n c->write.curr += sizeof(msg.noop.bytes);\n c->write.bytes += sizeof(msg.noop.bytes);\n break;\n case TAP_PAUSE :\n more_data = false;\n break;\n case TAP_CHECKPOINT_START:\n case TAP_CHECKPOINT_END:\n case TAP_MUTATION:\n if (!bucket_get_item_info(c, it, &info.info)) {\n bucket_release_item(c, it);\n LOG_WARNING(c, \"%u: Failed to get item info\", c->getId());\n break;\n }\n\n if (!c->reserveItem(it)) {\n bucket_release_item(c, it);\n LOG_WARNING(c, \"%u: Failed to grow item array\", c->getId());\n break;\n }\n send_data = true;\n\n if (event == TAP_CHECKPOINT_START) {\n msg.mutation.message.header.request.opcode =\n PROTOCOL_BINARY_CMD_TAP_CHECKPOINT_START;\n tap_stats.sent.checkpoint_start++;\n } else if (event == TAP_CHECKPOINT_END) {\n msg.mutation.message.header.request.opcode =\n PROTOCOL_BINARY_CMD_TAP_CHECKPOINT_END;\n tap_stats.sent.checkpoint_end++;\n } else if (event == TAP_MUTATION) {\n msg.mutation.message.header.request.opcode = PROTOCOL_BINARY_CMD_TAP_MUTATION;\n tap_stats.sent.mutation++;\n }\n\n msg.mutation.message.header.request.cas = htonll(info.info.cas);\n msg.mutation.message.header.request.keylen = htons(info.info.nkey);\n msg.mutation.message.header.request.extlen = 16;\n if (c->isSupportsDatatype()) {\n msg.mutation.message.header.request.datatype = info.info.datatype;\n } else {\n inflate = mcbp::datatype::is_compressed(info.info.datatype);\n msg.mutation.message.header.request.datatype = 0;\n }\n\n bodylen = 16 + info.info.nkey + nengine;\n if ((tap_flags & TAP_FLAG_NO_VALUE) == 0) {\n if (inflate) {\n if (snappy_uncompressed_length\n (reinterpret_cast(info.info.value[0].iov_base),\n info.info.nbytes, &inflated_length) == SNAPPY_OK) {\n bodylen += (uint32_t)inflated_length;\n } else {\n LOG_WARNING(c,\n \"<%u Failed to determine inflated size. \"\n \"Sending as compressed\",\n c->getId());\n inflate = false;\n bodylen += info.info.nbytes;\n }\n } else {\n bodylen += info.info.nbytes;\n }\n }\n msg.mutation.message.header.request.bodylen = htonl(bodylen);\n\n if ((tap_flags & TAP_FLAG_NETWORK_BYTE_ORDER) == 0) {\n msg.mutation.message.body.item.flags = htonl(info.info.flags);\n } else {\n msg.mutation.message.body.item.flags = info.info.flags;\n }\n msg.mutation.message.body.item.expiration = htonl(\n info.info.exptime);\n msg.mutation.message.body.tap.enginespecific_length = htons(\n nengine);\n msg.mutation.message.body.tap.ttl = ttl;\n msg.mutation.message.body.tap.flags = htons(tap_flags);\n memcpy(c->write.curr, msg.mutation.bytes,\n sizeof(msg.mutation.bytes));\n\n c->addIov(c->write.curr, sizeof(msg.mutation.bytes));\n c->write.curr += sizeof(msg.mutation.bytes);\n c->write.bytes += sizeof(msg.mutation.bytes);\n\n if (nengine > 0) {\n memcpy(c->write.curr, engine, nengine);\n c->addIov(c->write.curr, nengine);\n c->write.curr += nengine;\n c->write.bytes += nengine;\n }\n\n c->addIov(info.info.key, info.info.nkey);\n if ((tap_flags & TAP_FLAG_NO_VALUE) == 0) {\n if (inflate) {\n char* buf = reinterpret_cast(cb_malloc(\n inflated_length));\n if (buf == NULL) {\n LOG_WARNING(c,\n \"%u: FATAL: failed to allocate buffer \"\n \"of size %\" PRIu64\n \" to inflate object into. Shutting \"\n \"down connection\",\n c->getId(), inflated_length);\n c->setState(conn_closing);\n return;\n }\n const char* body = reinterpret_cast(info.info.value[0].iov_base);\n size_t input_length = info.info.value[0].iov_len;\n if (snappy_uncompress(body, input_length,\n buf, &inflated_length) == SNAPPY_OK) {\n if (!c->pushTempAlloc(buf)) {\n cb_free(buf);\n LOG_WARNING(c,\n \"%u: FATAL: failed to allocate space \"\n \"to keep temporary buffer\",\n c->getId());\n c->setState(conn_closing);\n return;\n }\n c->addIov(buf, inflated_length);\n } else {\n cb_free(buf);\n LOG_WARNING(c,\n \"%u: FATAL: failed to inflate object. \"\n \"shutting down connection\",\n c->getId());\n c->setState(conn_closing);\n return;\n }\n } else {\n int xx;\n for (xx = 0; xx < info.info.nvalue; ++xx) {\n c->addIov(info.info.value[xx].iov_base,\n info.info.value[xx].iov_len);\n }\n }\n }\n\n break;\n case TAP_DELETION:\n \/* This is a delete *\/\n if (!bucket_get_item_info(c, it, &info.info)) {\n bucket_release_item(c, it);\n LOG_WARNING(c, \"%u: Failed to get item info\", c->getId());\n break;\n }\n\n if (!c->reserveItem(it)) {\n bucket_release_item(c, it);\n LOG_WARNING(c, \"%u: Failed to grow item array\", c->getId());\n break;\n }\n send_data = true;\n msg.del.message.header.request.opcode = PROTOCOL_BINARY_CMD_TAP_DELETE;\n msg.del.message.header.request.cas = htonll(info.info.cas);\n msg.del.message.header.request.keylen = htons(info.info.nkey);\n\n bodylen = 8 + info.info.nkey + nengine;\n if ((tap_flags & TAP_FLAG_NO_VALUE) == 0) {\n bodylen += info.info.nbytes;\n }\n msg.del.message.header.request.bodylen = htonl(bodylen);\n\n memcpy(c->write.curr, msg.del.bytes, sizeof(msg.del.bytes));\n c->addIov(c->write.curr, sizeof(msg.del.bytes));\n c->write.curr += sizeof(msg.del.bytes);\n c->write.bytes += sizeof(msg.del.bytes);\n\n if (nengine > 0) {\n memcpy(c->write.curr, engine, nengine);\n c->addIov(c->write.curr, nengine);\n c->write.curr += nengine;\n c->write.bytes += nengine;\n }\n\n c->addIov(info.info.key, info.info.nkey);\n if ((tap_flags & TAP_FLAG_NO_VALUE) == 0) {\n int xx;\n for (xx = 0; xx < info.info.nvalue; ++xx) {\n c->addIov(info.info.value[xx].iov_base,\n info.info.value[xx].iov_len);\n }\n }\n\n tap_stats.sent.del++;\n break;\n\n case TAP_DISCONNECT:\n disconnect = true;\n more_data = false;\n break;\n case TAP_VBUCKET_SET:\n case TAP_FLUSH:\n case TAP_OPAQUE:\n send_data = true;\n\n if (event == TAP_OPAQUE) {\n msg.flush.message.header.request.opcode = PROTOCOL_BINARY_CMD_TAP_OPAQUE;\n tap_stats.sent.opaque++;\n } else if (event == TAP_FLUSH) {\n msg.flush.message.header.request.opcode = PROTOCOL_BINARY_CMD_TAP_FLUSH;\n tap_stats.sent.flush++;\n } else if (event == TAP_VBUCKET_SET) {\n msg.flush.message.header.request.opcode = PROTOCOL_BINARY_CMD_TAP_VBUCKET_SET;\n msg.flush.message.body.tap.flags = htons(tap_flags);\n tap_stats.sent.vbucket_set++;\n }\n\n msg.flush.message.header.request.bodylen = htonl(8 + nengine);\n memcpy(c->write.curr, msg.flush.bytes, sizeof(msg.flush.bytes));\n c->addIov(c->write.curr, sizeof(msg.flush.bytes));\n c->write.curr += sizeof(msg.flush.bytes);\n c->write.bytes += sizeof(msg.flush.bytes);\n if (nengine > 0) {\n memcpy(c->write.curr, engine, nengine);\n c->addIov(c->write.curr, nengine);\n c->write.curr += nengine;\n c->write.bytes += nengine;\n }\n break;\n default:\n LOG_WARNING(c,\n \"%u: ship_tap_log: event (which is %d) is not a valid \"\n \"tap_event_t - closing connection\", event);\n c->setState(conn_closing);\n return;\n }\n } while (more_data);\n\n c->setEwouldblock(false);\n if (send_data) {\n c->setState(conn_mwrite);\n if (disconnect) {\n c->setWriteAndGo(conn_closing);\n } else {\n c->setWriteAndGo(conn_ship_log);\n }\n } else {\n if (disconnect) {\n c->setState(conn_closing);\n } else {\n \/* No more items to ship to the slave at this time.. suspend.. *\/\n LOG_DEBUG(c, \"%u: No more items in tap log.. waiting\", c->getId());\n c->setEwouldblock(true);\n }\n }\n}Refactor: simplify logic, iov not supported\/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/*\n * Copyright 2016 Couchbase, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \n#include \n\nvoid ship_mcbp_tap_log(McbpConnection* c) {\n bool more_data = true;\n bool send_data = false;\n bool disconnect = false;\n item* it;\n uint32_t bodylen;\n int ii = 0;\n\n c->addMsgHdr(true);\n \/* @todo add check for buffer overflow of c->write.buf) *\/\n c->write.bytes = 0;\n c->write.curr = c->write.buf;\n\n auto tap_iterator = c->getTapIterator();\n do {\n \/* @todo fixme! *\/\n void* engine;\n uint16_t nengine;\n uint8_t ttl;\n uint16_t tap_flags;\n uint32_t seqno;\n uint16_t vbucket;\n tap_event_t event;\n bool inflate = false;\n size_t inflated_length = 0;\n\n union {\n protocol_binary_request_tap_mutation mutation;\n protocol_binary_request_tap_delete del;\n protocol_binary_request_tap_flush flush;\n protocol_binary_request_tap_opaque opaque;\n protocol_binary_request_noop noop;\n } msg;\n item_info info;\n\n if (ii++ == 10) {\n break;\n }\n\n event = tap_iterator(c->getBucketEngineAsV0(), c->getCookie(), &it,\n &engine, &nengine, &ttl,\n &tap_flags, &seqno, &vbucket);\n memset(&msg, 0, sizeof(msg));\n msg.opaque.message.header.request.magic = (uint8_t)PROTOCOL_BINARY_REQ;\n msg.opaque.message.header.request.opaque = htonl(seqno);\n msg.opaque.message.body.tap.enginespecific_length = htons(nengine);\n msg.opaque.message.body.tap.ttl = ttl;\n msg.opaque.message.body.tap.flags = htons(tap_flags);\n msg.opaque.message.header.request.extlen = 8;\n msg.opaque.message.header.request.vbucket = htons(vbucket);\n info.nvalue = 1;\n\n switch (event) {\n case TAP_NOOP :\n send_data = true;\n msg.noop.message.header.request.opcode = PROTOCOL_BINARY_CMD_NOOP;\n msg.noop.message.header.request.extlen = 0;\n msg.noop.message.header.request.bodylen = htonl(0);\n memcpy(c->write.curr, msg.noop.bytes, sizeof(msg.noop.bytes));\n c->addIov(c->write.curr, sizeof(msg.noop.bytes));\n c->write.curr += sizeof(msg.noop.bytes);\n c->write.bytes += sizeof(msg.noop.bytes);\n break;\n case TAP_PAUSE :\n more_data = false;\n break;\n case TAP_CHECKPOINT_START:\n case TAP_CHECKPOINT_END:\n case TAP_MUTATION:\n if (!bucket_get_item_info(c, it, &info)) {\n bucket_release_item(c, it);\n LOG_WARNING(c, \"%u: Failed to get item info\", c->getId());\n break;\n }\n\n if (!c->reserveItem(it)) {\n bucket_release_item(c, it);\n LOG_WARNING(c, \"%u: Failed to grow item array\", c->getId());\n break;\n }\n send_data = true;\n\n if (event == TAP_CHECKPOINT_START) {\n msg.mutation.message.header.request.opcode =\n PROTOCOL_BINARY_CMD_TAP_CHECKPOINT_START;\n tap_stats.sent.checkpoint_start++;\n } else if (event == TAP_CHECKPOINT_END) {\n msg.mutation.message.header.request.opcode =\n PROTOCOL_BINARY_CMD_TAP_CHECKPOINT_END;\n tap_stats.sent.checkpoint_end++;\n } else if (event == TAP_MUTATION) {\n msg.mutation.message.header.request.opcode = PROTOCOL_BINARY_CMD_TAP_MUTATION;\n tap_stats.sent.mutation++;\n }\n\n msg.mutation.message.header.request.cas = htonll(info.cas);\n msg.mutation.message.header.request.keylen = htons(info.nkey);\n msg.mutation.message.header.request.extlen = 16;\n if (c->isSupportsDatatype()) {\n msg.mutation.message.header.request.datatype = info.datatype;\n } else {\n inflate = mcbp::datatype::is_compressed(info.datatype);\n msg.mutation.message.header.request.datatype = 0;\n }\n\n bodylen = 16 + info.nkey + nengine;\n if ((tap_flags & TAP_FLAG_NO_VALUE) == 0) {\n if (inflate) {\n if (snappy_uncompressed_length\n (reinterpret_cast(info.value[0].iov_base),\n info.nbytes, &inflated_length) == SNAPPY_OK) {\n bodylen += (uint32_t)inflated_length;\n } else {\n LOG_WARNING(c,\n \"<%u Failed to determine inflated size. \"\n \"Sending as compressed\",\n c->getId());\n inflate = false;\n bodylen += info.nbytes;\n }\n } else {\n bodylen += info.nbytes;\n }\n }\n msg.mutation.message.header.request.bodylen = htonl(bodylen);\n\n if ((tap_flags & TAP_FLAG_NETWORK_BYTE_ORDER) == 0) {\n msg.mutation.message.body.item.flags = htonl(info.flags);\n } else {\n msg.mutation.message.body.item.flags = info.flags;\n }\n msg.mutation.message.body.item.expiration = htonl(\n info.exptime);\n msg.mutation.message.body.tap.enginespecific_length = htons(\n nengine);\n msg.mutation.message.body.tap.ttl = ttl;\n msg.mutation.message.body.tap.flags = htons(tap_flags);\n memcpy(c->write.curr, msg.mutation.bytes,\n sizeof(msg.mutation.bytes));\n\n c->addIov(c->write.curr, sizeof(msg.mutation.bytes));\n c->write.curr += sizeof(msg.mutation.bytes);\n c->write.bytes += sizeof(msg.mutation.bytes);\n\n if (nengine > 0) {\n memcpy(c->write.curr, engine, nengine);\n c->addIov(c->write.curr, nengine);\n c->write.curr += nengine;\n c->write.bytes += nengine;\n }\n\n c->addIov(info.key, info.nkey);\n if ((tap_flags & TAP_FLAG_NO_VALUE) == 0) {\n if (inflate) {\n char* buf = reinterpret_cast(cb_malloc(\n inflated_length));\n if (buf == NULL) {\n LOG_WARNING(c,\n \"%u: FATAL: failed to allocate buffer \"\n \"of size %\" PRIu64\n \" to inflate object into. Shutting \"\n \"down connection\",\n c->getId(), inflated_length);\n c->setState(conn_closing);\n return;\n }\n const char* body = reinterpret_cast(info.value[0].iov_base);\n size_t input_length = info.value[0].iov_len;\n if (snappy_uncompress(body, input_length,\n buf, &inflated_length) == SNAPPY_OK) {\n if (!c->pushTempAlloc(buf)) {\n cb_free(buf);\n LOG_WARNING(c,\n \"%u: FATAL: failed to allocate space \"\n \"to keep temporary buffer\",\n c->getId());\n c->setState(conn_closing);\n return;\n }\n c->addIov(buf, inflated_length);\n } else {\n cb_free(buf);\n LOG_WARNING(c,\n \"%u: FATAL: failed to inflate object. \"\n \"shutting down connection\",\n c->getId());\n c->setState(conn_closing);\n return;\n }\n } else {\n c->addIov(info.value[0].iov_base, info.value[0].iov_len);\n }\n }\n\n break;\n case TAP_DELETION:\n \/* This is a delete *\/\n if (!bucket_get_item_info(c, it, &info)) {\n bucket_release_item(c, it);\n LOG_WARNING(c, \"%u: Failed to get item info\", c->getId());\n break;\n }\n\n if (!c->reserveItem(it)) {\n bucket_release_item(c, it);\n LOG_WARNING(c, \"%u: Failed to grow item array\", c->getId());\n break;\n }\n send_data = true;\n msg.del.message.header.request.opcode = PROTOCOL_BINARY_CMD_TAP_DELETE;\n msg.del.message.header.request.cas = htonll(info.cas);\n msg.del.message.header.request.keylen = htons(info.nkey);\n\n bodylen = 8 + info.nkey + nengine;\n if ((tap_flags & TAP_FLAG_NO_VALUE) == 0) {\n bodylen += info.nbytes;\n }\n msg.del.message.header.request.bodylen = htonl(bodylen);\n\n memcpy(c->write.curr, msg.del.bytes, sizeof(msg.del.bytes));\n c->addIov(c->write.curr, sizeof(msg.del.bytes));\n c->write.curr += sizeof(msg.del.bytes);\n c->write.bytes += sizeof(msg.del.bytes);\n\n if (nengine > 0) {\n memcpy(c->write.curr, engine, nengine);\n c->addIov(c->write.curr, nengine);\n c->write.curr += nengine;\n c->write.bytes += nengine;\n }\n\n c->addIov(info.key, info.nkey);\n if ((tap_flags & TAP_FLAG_NO_VALUE) == 0) {\n c->addIov(info.value[0].iov_base, info.value[0].iov_len);\n }\n\n tap_stats.sent.del++;\n break;\n\n case TAP_DISCONNECT:\n disconnect = true;\n more_data = false;\n break;\n case TAP_VBUCKET_SET:\n case TAP_FLUSH:\n case TAP_OPAQUE:\n send_data = true;\n\n if (event == TAP_OPAQUE) {\n msg.flush.message.header.request.opcode = PROTOCOL_BINARY_CMD_TAP_OPAQUE;\n tap_stats.sent.opaque++;\n } else if (event == TAP_FLUSH) {\n msg.flush.message.header.request.opcode = PROTOCOL_BINARY_CMD_TAP_FLUSH;\n tap_stats.sent.flush++;\n } else if (event == TAP_VBUCKET_SET) {\n msg.flush.message.header.request.opcode = PROTOCOL_BINARY_CMD_TAP_VBUCKET_SET;\n msg.flush.message.body.tap.flags = htons(tap_flags);\n tap_stats.sent.vbucket_set++;\n }\n\n msg.flush.message.header.request.bodylen = htonl(8 + nengine);\n memcpy(c->write.curr, msg.flush.bytes, sizeof(msg.flush.bytes));\n c->addIov(c->write.curr, sizeof(msg.flush.bytes));\n c->write.curr += sizeof(msg.flush.bytes);\n c->write.bytes += sizeof(msg.flush.bytes);\n if (nengine > 0) {\n memcpy(c->write.curr, engine, nengine);\n c->addIov(c->write.curr, nengine);\n c->write.curr += nengine;\n c->write.bytes += nengine;\n }\n break;\n default:\n LOG_WARNING(c,\n \"%u: ship_tap_log: event (which is %d) is not a valid \"\n \"tap_event_t - closing connection\", event);\n c->setState(conn_closing);\n return;\n }\n } while (more_data);\n\n c->setEwouldblock(false);\n if (send_data) {\n c->setState(conn_mwrite);\n if (disconnect) {\n c->setWriteAndGo(conn_closing);\n } else {\n c->setWriteAndGo(conn_ship_log);\n }\n } else {\n if (disconnect) {\n c->setState(conn_closing);\n } else {\n \/* No more items to ship to the slave at this time.. suspend.. *\/\n LOG_DEBUG(c, \"%u: No more items in tap log.. waiting\", c->getId());\n c->setEwouldblock(true);\n }\n }\n}<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Monteverdi2\n Language: C++\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See Copyright.txt for details.\n\n Monteverdi2 is distributed under the CeCILL licence version 2. See\n Licence_CeCILL_V2-en.txt or\n http:\/\/www.cecill.info\/licences\/Licence_CeCILL_V2-en.txt for more details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"mvdLayerStackWidget.h\"\n#include \"ui_mvdLayerStackWidget.h\"\n\n\n\/*****************************************************************************\/\n\/* INCLUDE SECTION *\/\n\n\/\/\n\/\/ Qt includes (sorted by alphabetic order)\n\/\/\/\/ Must be included before system\/custom includes.\n\n\/\/\n\/\/ System includes (sorted by alphabetic order)\n#include \n\n\/\/\n\/\/ ITK includes (sorted by alphabetic order)\n\n\/\/\n\/\/ OTB includes (sorted by alphabetic order)\n\n\/\/\n\/\/ Monteverdi includes (sorted by alphabetic order)\n#include \"Gui\/mvdGui.h\"\n#include \"Gui\/mvdLayerStackItemModel.h\"\n\nnamespace mvd\n{\n\n\/*\n TRANSLATOR mvd::LayerStackWidget\n\n Necessary for lupdate to be aware of C++ namespaces.\n\n Context comment for translator.\n*\/\n\n\n\/*****************************************************************************\/\n\/* CONSTANTS *\/\n\n\n\/*****************************************************************************\/\n\/* STATIC IMPLEMENTATION SECTION *\/\n\n\n\/*****************************************************************************\/\n\/* CLASS IMPLEMENTATION SECTION *\/\n\n\/*******************************************************************************\/\nLayerStackWidget\n::LayerStackWidget( QWidget* parent, Qt::WindowFlags flags ):\n QWidget( parent, flags ),\n m_UI( new mvd::Ui::LayerStackWidget() )\n{\n m_UI->setupUi( this );\n\n m_UI->reloadButton->setVisible( false );\n\n {\n QItemSelectionModel * ism = m_UI->treeView->selectionModel();\n\n m_UI->treeView->setModel( new LayerStackItemModel( m_UI->treeView ) );\n\n delete ism;\n ism = NULL;\n }\n\n InstallEventFilter( this );\n\n QObject::connect(\n m_UI->treeView->selectionModel(),\n SIGNAL( currentRowChanged( const QModelIndex &, const QModelIndex & ) ),\n \/\/ to:\n this,\n SLOT( OnCurrentRowChanged( const QModelIndex &, const QModelIndex & ) )\n );\n\n QObject::connect(\n m_UI->treeView->selectionModel(),\n SIGNAL( selectionChanged( const QItemSelection &, const QItemSelection & ) ),\n \/\/ to:\n this,\n SLOT( OnSelectionChanged( const QItemSelection &, const QItemSelection & ) )\n );\n\n QObject::connect(\n m_UI->topButton,\n SIGNAL( clicked() ),\n \/\/ to:\n this,\n SIGNAL( TopButtonClicked() )\n );\n\n QObject::connect(\n m_UI->bottomButton,\n SIGNAL( clicked() ),\n \/\/ to:\n this,\n SIGNAL( BottomButtonClicked() )\n );\n\n QObject::connect(\n m_UI->upButton,\n SIGNAL( clicked() ),\n \/\/ to:\n this,\n SIGNAL( UpButtonClicked() )\n );\n\n QObject::connect(\n m_UI->downButton,\n SIGNAL( clicked() ),\n \/\/ to:\n this,\n SIGNAL( DownButtonClicked() )\n );\n\n QObject::connect(\n m_UI->deleteButton,\n SIGNAL( clicked() ),\n \/\/ to:\n this,\n SIGNAL( DeleteLayerRequested() )\n );\n\n QObject::connect(\n m_UI->projectionButton,\n SIGNAL( clicked() ),\n \/\/ to:\n this,\n SIGNAL( ProjectionButtonClicked() )\n );\n\n QObject::connect(\n m_UI->applyButton,\n SIGNAL( clicked() ),\n \/\/ to:\n this,\n SIGNAL( ApplyButtonClicked() )\n );\n}\n\n\/*******************************************************************************\/\nLayerStackWidget\n::~LayerStackWidget()\n{\n delete m_UI;\n m_UI = NULL;\n}\n\n\/*******************************************************************************\/\nbool\nLayerStackWidget\n::eventFilter( QObject * object, QEvent * event )\n{\n assert( object==m_UI->treeView );\n assert( event!=NULL );\n\n if( object!=m_UI->treeView )\n return false;\n\n switch( event->type() )\n {\n \/\/\n \/\/ KEY RELEASE\n case QEvent::KeyRelease :\n {\n QKeyEvent * keyEvent = dynamic_cast< QKeyEvent * >( event );\n assert( keyEvent!=NULL );\n\n switch( keyEvent->key() )\n {\n case Qt::Key_Delete:\n\tif( keyEvent->modifiers()==Qt::NoModifier )\n\t {\n\t emit DeleteLayerRequested();\n\n\t return true;\n\t }\n\telse if( keyEvent->modifiers()==Qt::ShiftModifier )\n\t {\n\t emit DeleteAllLayersRequested();\n\n\t return true;\n\t }\n\tbreak;\n }\n }\n break;\n \/\/\n \/\/ MOUSE-WHEEL\n case QEvent::Wheel :\n {\n QWheelEvent * wheelEvent = dynamic_cast< QWheelEvent * >( event );\n assert( wheelEvent!=NULL );\n\n if( wheelEvent->modifiers()==Qt::ControlModifier )\n {\n emit RotateLayersRequested(\n \twheelEvent->delta() \/ (MOUSE_WHEEL_STEP_FACTOR * MOUSE_WHEEL_STEP_DEGREES)\n );\n\n return true;\n }\n }\n break;\n \/\/\n \/\/ other.\n default:\n break;\n }\n\n return false;\n}\n\n\/*******************************************************************************\/\nconst LayerStackItemModel *\nLayerStackWidget\n::GetItemModel() const\n{\n return const_cast< LayerStackWidget * >( this )->GetItemModel();\n}\n\n\/*******************************************************************************\/\nLayerStackItemModel *\nLayerStackWidget\n::GetItemModel()\n{\n assert(\n m_UI->treeView->model()==\n qobject_cast< LayerStackItemModel * >( m_UI->treeView->model() )\n );\n\n return qobject_cast< LayerStackItemModel * >( m_UI->treeView->model() );\n}\n\n\/*******************************************************************************\/\nvoid\nLayerStackWidget\n::InstallEventFilter( QObject * filter )\n{\n assert( m_UI!=NULL );\n assert( m_UI->treeView!=NULL );\n\n m_UI->treeView->installEventFilter( filter );\n}\n\n\/*******************************************************************************\/\n\/\/ void\n\/\/ LayerStackWidget\n\/\/ ::SetModel( LayerStackItemModel * itemModel )\n\/\/ {\n\/\/ \/\/ See http:\/\/qt-project.org\/doc\/qt-4.8\/qabstractitemview.html#setModel .\n\/\/ QItemSelectionModel * itemSelectionModel = m_UI->treeView->selectionModel();\n\n\/\/ m_UI->treeView->setModel( itemModel );\n\n\/\/ itemModel->setParent( m_UI->treeView );\n\n\/\/ delete itemSelectionModel;\n\/\/ itemSelectionModel = NULL;\n\/\/ }\n\n\/*******************************************************************************\/\nvoid\nLayerStackWidget\n::SetApplyEnabled( bool enabled )\n{\n assert( m_UI->applyButton!=NULL );\n\n m_UI->applyButton->setEnabled( enabled );\n}\n\n\/*******************************************************************************\/\nvoid\nLayerStackWidget\n::SetCurrent( int row )\n{\n assert( m_UI->treeView->selectionModel()!=NULL );\n\n \/\/ if( m_UI->treeView->selectionModel()->currentIndex().row()==row )\n \/\/ return;\n\n if( row<0 )\n m_UI->treeView->selectionModel()->clearSelection();\n\n else\n m_UI->treeView->selectionModel()->select(\n m_UI->treeView->model()->index( row, 1 ),\n QItemSelectionModel::ClearAndSelect |\n QItemSelectionModel::Rows\n );\n\n \/*\n m_UI->treeView->selectionModel()->setCurrentIndex(\n m_UI->treeView->model()->index( row, 1 ),\n QItemSelectionModel::ClearAndSelect |\n \/\/ QItemSelectionModel::Current |\n QItemSelectionModel::Rows\n );\n *\/\n}\n\n\/*******************************************************************************\/\nvoid\nLayerStackWidget\n::SetDeleteEnabled( bool enabled )\n{\n assert( m_UI!=NULL );\n\n assert( m_UI->deleteButton!=NULL );\n\n m_UI->deleteButton->setEnabled( enabled );\n}\n\n\/*******************************************************************************\/\nvoid\nLayerStackWidget\n::SetMoveEnabled( bool enabled )\n{\n assert( m_UI!=NULL );\n\n assert( m_UI->upButton!=NULL );\n assert( m_UI->downButton!=NULL );\n assert( m_UI->topButton!=NULL );\n assert( m_UI->bottomButton!=NULL );\n\n m_UI->upButton->setEnabled( enabled );\n m_UI->downButton->setEnabled( enabled );\n m_UI->topButton->setEnabled( enabled );\n m_UI->bottomButton->setEnabled( enabled );\n}\n\n\/*******************************************************************************\/\nvoid\nLayerStackWidget\n::SetProjectionEnabled( bool enabled )\n{\n assert( m_UI!=NULL );\n\n assert( m_UI->projectionButton!=NULL );\n\n m_UI->projectionButton->setEnabled( enabled );\n}\n\n\/*******************************************************************************\/\nvoid\nLayerStackWidget\n::SetReloadEnabled( bool enabled )\n{\n assert( m_UI!=NULL );\n\n assert( m_UI->reloadButton!=NULL );\n\n m_UI->reloadButton->setEnabled( enabled );\n}\n\n\/*******************************************************************************\/\n\/* SLOTS *\/\n\/*******************************************************************************\/\nvoid\nLayerStackWidget\n::OnCurrentRowChanged( const QModelIndex & current,\n const QModelIndex & )\n{\n \/\/ qDebug()\n \/\/ << this\n \/\/ << \"::OnCurrentRowChange(\" << current.row() << \",\" << previous.row() << \")\";\n\n emit CurrentChanged( current.row() );\n}\n\n\/*******************************************************************************\/\nvoid\nLayerStackWidget\n::OnSelectionChanged( const QItemSelection & selected,\n const QItemSelection & )\n{\n \/\/ qDebug()\n \/\/ << this\n \/\/ << \"::OnSelectionChanged(\" << selected << \",\" << deselected << \")\";\n\n QModelIndexList indexes( selected.indexes() );\n \/\/ assert( indexes.empty() || indexes.size()==1 );\n\n emit SelectionChanged(\n indexes.empty()\n ? -1\n : indexes.front().row()\n );\n}\n\n} \/\/ end namespace 'mvd'\nENH: Connected layer-stack delete-all layers button.\/*=========================================================================\n\n Program: Monteverdi2\n Language: C++\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See Copyright.txt for details.\n\n Monteverdi2 is distributed under the CeCILL licence version 2. See\n Licence_CeCILL_V2-en.txt or\n http:\/\/www.cecill.info\/licences\/Licence_CeCILL_V2-en.txt for more details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"mvdLayerStackWidget.h\"\n#include \"ui_mvdLayerStackWidget.h\"\n\n\n\/*****************************************************************************\/\n\/* INCLUDE SECTION *\/\n\n\/\/\n\/\/ Qt includes (sorted by alphabetic order)\n\/\/\/\/ Must be included before system\/custom includes.\n\n\/\/\n\/\/ System includes (sorted by alphabetic order)\n#include \n\n\/\/\n\/\/ ITK includes (sorted by alphabetic order)\n\n\/\/\n\/\/ OTB includes (sorted by alphabetic order)\n\n\/\/\n\/\/ Monteverdi includes (sorted by alphabetic order)\n#include \"Gui\/mvdGui.h\"\n#include \"Gui\/mvdLayerStackItemModel.h\"\n\nnamespace mvd\n{\n\n\/*\n TRANSLATOR mvd::LayerStackWidget\n\n Necessary for lupdate to be aware of C++ namespaces.\n\n Context comment for translator.\n*\/\n\n\n\/*****************************************************************************\/\n\/* CONSTANTS *\/\n\n\n\/*****************************************************************************\/\n\/* STATIC IMPLEMENTATION SECTION *\/\n\n\n\/*****************************************************************************\/\n\/* CLASS IMPLEMENTATION SECTION *\/\n\n\/*******************************************************************************\/\nLayerStackWidget\n::LayerStackWidget( QWidget* parent, Qt::WindowFlags flags ):\n QWidget( parent, flags ),\n m_UI( new mvd::Ui::LayerStackWidget() )\n{\n m_UI->setupUi( this );\n\n m_UI->reloadButton->setVisible( false );\n\n {\n QItemSelectionModel * ism = m_UI->treeView->selectionModel();\n\n m_UI->treeView->setModel( new LayerStackItemModel( m_UI->treeView ) );\n\n delete ism;\n ism = NULL;\n }\n\n InstallEventFilter( this );\n\n QObject::connect(\n m_UI->treeView->selectionModel(),\n SIGNAL( currentRowChanged( const QModelIndex &, const QModelIndex & ) ),\n \/\/ to:\n this,\n SLOT( OnCurrentRowChanged( const QModelIndex &, const QModelIndex & ) )\n );\n\n QObject::connect(\n m_UI->treeView->selectionModel(),\n SIGNAL( selectionChanged( const QItemSelection &, const QItemSelection & ) ),\n \/\/ to:\n this,\n SLOT( OnSelectionChanged( const QItemSelection &, const QItemSelection & ) )\n );\n\n QObject::connect(\n m_UI->topButton,\n SIGNAL( clicked() ),\n \/\/ to:\n this,\n SIGNAL( TopButtonClicked() )\n );\n\n QObject::connect(\n m_UI->bottomButton,\n SIGNAL( clicked() ),\n \/\/ to:\n this,\n SIGNAL( BottomButtonClicked() )\n );\n\n QObject::connect(\n m_UI->upButton,\n SIGNAL( clicked() ),\n \/\/ to:\n this,\n SIGNAL( UpButtonClicked() )\n );\n\n QObject::connect(\n m_UI->downButton,\n SIGNAL( clicked() ),\n \/\/ to:\n this,\n SIGNAL( DownButtonClicked() )\n );\n\n QObject::connect(\n m_UI->deleteButton,\n SIGNAL( clicked() ),\n \/\/ to:\n this,\n SIGNAL( DeleteLayerRequested() )\n );\n\n QObject::connect(\n m_UI->deleteAllButton,\n SIGNAL( clicked() ),\n \/\/ to:\n this,\n SIGNAL( DeleteAllLayersRequested() )\n );\n\n QObject::connect(\n m_UI->projectionButton,\n SIGNAL( clicked() ),\n \/\/ to:\n this,\n SIGNAL( ProjectionButtonClicked() )\n );\n\n QObject::connect(\n m_UI->applyButton,\n SIGNAL( clicked() ),\n \/\/ to:\n this,\n SIGNAL( ApplyButtonClicked() )\n );\n}\n\n\/*******************************************************************************\/\nLayerStackWidget\n::~LayerStackWidget()\n{\n delete m_UI;\n m_UI = NULL;\n}\n\n\/*******************************************************************************\/\nbool\nLayerStackWidget\n::eventFilter( QObject * object, QEvent * event )\n{\n assert( object==m_UI->treeView );\n assert( event!=NULL );\n\n if( object!=m_UI->treeView )\n return false;\n\n switch( event->type() )\n {\n \/\/\n \/\/ KEY RELEASE\n case QEvent::KeyRelease :\n {\n QKeyEvent * keyEvent = dynamic_cast< QKeyEvent * >( event );\n assert( keyEvent!=NULL );\n\n switch( keyEvent->key() )\n {\n case Qt::Key_Delete:\n\tif( keyEvent->modifiers()==Qt::NoModifier )\n\t {\n\t emit DeleteLayerRequested();\n\n\t return true;\n\t }\n\telse if( keyEvent->modifiers()==Qt::ShiftModifier )\n\t {\n\t emit DeleteAllLayersRequested();\n\n\t return true;\n\t }\n\tbreak;\n }\n }\n break;\n \/\/\n \/\/ MOUSE-WHEEL\n case QEvent::Wheel :\n {\n QWheelEvent * wheelEvent = dynamic_cast< QWheelEvent * >( event );\n assert( wheelEvent!=NULL );\n\n if( wheelEvent->modifiers()==Qt::ControlModifier )\n {\n emit RotateLayersRequested(\n \twheelEvent->delta() \/ (MOUSE_WHEEL_STEP_FACTOR * MOUSE_WHEEL_STEP_DEGREES)\n );\n\n return true;\n }\n }\n break;\n \/\/\n \/\/ other.\n default:\n break;\n }\n\n return false;\n}\n\n\/*******************************************************************************\/\nconst LayerStackItemModel *\nLayerStackWidget\n::GetItemModel() const\n{\n return const_cast< LayerStackWidget * >( this )->GetItemModel();\n}\n\n\/*******************************************************************************\/\nLayerStackItemModel *\nLayerStackWidget\n::GetItemModel()\n{\n assert(\n m_UI->treeView->model()==\n qobject_cast< LayerStackItemModel * >( m_UI->treeView->model() )\n );\n\n return qobject_cast< LayerStackItemModel * >( m_UI->treeView->model() );\n}\n\n\/*******************************************************************************\/\nvoid\nLayerStackWidget\n::InstallEventFilter( QObject * filter )\n{\n assert( m_UI!=NULL );\n assert( m_UI->treeView!=NULL );\n\n m_UI->treeView->installEventFilter( filter );\n}\n\n\/*******************************************************************************\/\n\/\/ void\n\/\/ LayerStackWidget\n\/\/ ::SetModel( LayerStackItemModel * itemModel )\n\/\/ {\n\/\/ \/\/ See http:\/\/qt-project.org\/doc\/qt-4.8\/qabstractitemview.html#setModel .\n\/\/ QItemSelectionModel * itemSelectionModel = m_UI->treeView->selectionModel();\n\n\/\/ m_UI->treeView->setModel( itemModel );\n\n\/\/ itemModel->setParent( m_UI->treeView );\n\n\/\/ delete itemSelectionModel;\n\/\/ itemSelectionModel = NULL;\n\/\/ }\n\n\/*******************************************************************************\/\nvoid\nLayerStackWidget\n::SetApplyEnabled( bool enabled )\n{\n assert( m_UI->applyButton!=NULL );\n\n m_UI->applyButton->setEnabled( enabled );\n}\n\n\/*******************************************************************************\/\nvoid\nLayerStackWidget\n::SetCurrent( int row )\n{\n assert( m_UI->treeView->selectionModel()!=NULL );\n\n \/\/ if( m_UI->treeView->selectionModel()->currentIndex().row()==row )\n \/\/ return;\n\n if( row<0 )\n m_UI->treeView->selectionModel()->clearSelection();\n\n else\n m_UI->treeView->selectionModel()->select(\n m_UI->treeView->model()->index( row, 1 ),\n QItemSelectionModel::ClearAndSelect |\n QItemSelectionModel::Rows\n );\n\n \/*\n m_UI->treeView->selectionModel()->setCurrentIndex(\n m_UI->treeView->model()->index( row, 1 ),\n QItemSelectionModel::ClearAndSelect |\n \/\/ QItemSelectionModel::Current |\n QItemSelectionModel::Rows\n );\n *\/\n}\n\n\/*******************************************************************************\/\nvoid\nLayerStackWidget\n::SetDeleteEnabled( bool enabled )\n{\n assert( m_UI!=NULL );\n\n assert( m_UI->deleteButton!=NULL );\n\n m_UI->deleteButton->setEnabled( enabled );\n}\n\n\/*******************************************************************************\/\nvoid\nLayerStackWidget\n::SetMoveEnabled( bool enabled )\n{\n assert( m_UI!=NULL );\n\n assert( m_UI->upButton!=NULL );\n assert( m_UI->downButton!=NULL );\n assert( m_UI->topButton!=NULL );\n assert( m_UI->bottomButton!=NULL );\n\n m_UI->upButton->setEnabled( enabled );\n m_UI->downButton->setEnabled( enabled );\n m_UI->topButton->setEnabled( enabled );\n m_UI->bottomButton->setEnabled( enabled );\n}\n\n\/*******************************************************************************\/\nvoid\nLayerStackWidget\n::SetProjectionEnabled( bool enabled )\n{\n assert( m_UI!=NULL );\n\n assert( m_UI->projectionButton!=NULL );\n\n m_UI->projectionButton->setEnabled( enabled );\n}\n\n\/*******************************************************************************\/\nvoid\nLayerStackWidget\n::SetReloadEnabled( bool enabled )\n{\n assert( m_UI!=NULL );\n\n assert( m_UI->reloadButton!=NULL );\n\n m_UI->reloadButton->setEnabled( enabled );\n}\n\n\/*******************************************************************************\/\n\/* SLOTS *\/\n\/*******************************************************************************\/\nvoid\nLayerStackWidget\n::OnCurrentRowChanged( const QModelIndex & current,\n const QModelIndex & )\n{\n \/\/ qDebug()\n \/\/ << this\n \/\/ << \"::OnCurrentRowChange(\" << current.row() << \",\" << previous.row() << \")\";\n\n emit CurrentChanged( current.row() );\n}\n\n\/*******************************************************************************\/\nvoid\nLayerStackWidget\n::OnSelectionChanged( const QItemSelection & selected,\n const QItemSelection & )\n{\n \/\/ qDebug()\n \/\/ << this\n \/\/ << \"::OnSelectionChanged(\" << selected << \",\" << deselected << \")\";\n\n QModelIndexList indexes( selected.indexes() );\n \/\/ assert( indexes.empty() || indexes.size()==1 );\n\n emit SelectionChanged(\n indexes.empty()\n ? -1\n : indexes.front().row()\n );\n}\n\n} \/\/ end namespace 'mvd'\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkInformationKeyLookup.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\n#include \"vtkInformationKeyLookup.h\"\n\n#include \"vtkObjectFactory.h\"\n\nvtkStandardNewMacro(vtkInformationKeyLookup)\n\n\/\/------------------------------------------------------------------------------\nvoid vtkInformationKeyLookup::PrintSelf(std::ostream &os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os, indent);\n os << indent << \"Registered Keys:\\n\";\n indent = indent.GetNextIndent();\n KeyMap &keys = Keys();\n for (KeyMap::iterator i = keys.begin(), iEnd = keys.end(); i != iEnd; ++i)\n {\n os << indent << i->first.first << \"::\" << i->first.second\n << \" @\" << i->second << \"\\n\";\n }\n}\n\n\/\/------------------------------------------------------------------------------\nvtkInformationKey *vtkInformationKeyLookup::Find(const std::string &name,\n const std::string &location)\n{\n KeyMap &keys = Keys();\n KeyMap::iterator it = keys.find(std::make_pair(location, name));\n return it != keys.end() ? it->second : NULL;\n}\n\n\/\/------------------------------------------------------------------------------\nvtkInformationKeyLookup::vtkInformationKeyLookup()\n{\n}\n\n\/\/------------------------------------------------------------------------------\nvtkInformationKeyLookup::~vtkInformationKeyLookup()\n{\n \/\/ Keys are owned \/ cleaned up by the vtk*InformationKeyManagers.\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkInformationKeyLookup::RegisterKey(vtkInformationKey *key,\n const std::string &name,\n const std::string &location)\n{\n vtkInformationKeyLookup::Keys().insert(\n std::make_pair(std::make_pair(location, name), key));\n}\n\n\/\/------------------------------------------------------------------------------\nvtkInformationKeyLookup::KeyMap &vtkInformationKeyLookup::Keys()\n{\n \/\/ Ensure that the map is initialized before using from other static\n \/\/ initializations:\n static vtkInformationKeyLookup::KeyMap keys;\n return keys;\n}\nPrint key types in vtkInformationKeyLookup::PrintSelf.\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkInformationKeyLookup.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\n#include \"vtkInformationKeyLookup.h\"\n\n#include \"vtkInformationKey.h\"\n#include \"vtkObjectFactory.h\"\n\nvtkStandardNewMacro(vtkInformationKeyLookup)\n\n\/\/------------------------------------------------------------------------------\nvoid vtkInformationKeyLookup::PrintSelf(std::ostream &os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os, indent);\n os << indent << \"Registered Keys:\\n\";\n indent = indent.GetNextIndent();\n KeyMap &keys = Keys();\n for (KeyMap::iterator i = keys.begin(), iEnd = keys.end(); i != iEnd; ++i)\n {\n os << indent << i->first.first << \"::\" << i->first.second\n << \" @\" << i->second << \" (\" << i->second->GetClassName() << \")\\n\";\n }\n}\n\n\/\/------------------------------------------------------------------------------\nvtkInformationKey *vtkInformationKeyLookup::Find(const std::string &name,\n const std::string &location)\n{\n KeyMap &keys = Keys();\n KeyMap::iterator it = keys.find(std::make_pair(location, name));\n return it != keys.end() ? it->second : NULL;\n}\n\n\/\/------------------------------------------------------------------------------\nvtkInformationKeyLookup::vtkInformationKeyLookup()\n{\n}\n\n\/\/------------------------------------------------------------------------------\nvtkInformationKeyLookup::~vtkInformationKeyLookup()\n{\n \/\/ Keys are owned \/ cleaned up by the vtk*InformationKeyManagers.\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkInformationKeyLookup::RegisterKey(vtkInformationKey *key,\n const std::string &name,\n const std::string &location)\n{\n vtkInformationKeyLookup::Keys().insert(\n std::make_pair(std::make_pair(location, name), key));\n}\n\n\/\/------------------------------------------------------------------------------\nvtkInformationKeyLookup::KeyMap &vtkInformationKeyLookup::Keys()\n{\n \/\/ Ensure that the map is initialized before using from other static\n \/\/ initializations:\n static vtkInformationKeyLookup::KeyMap keys;\n return keys;\n}\n<|endoftext|>"} {"text":"#include \"mitkDICOMFileReader.h\"\n#include \n\nextern \"C\"\n{\n#include \"ipDicom\/ipDicom.h\"\n}\n\nvoid mitk::DICOMFileReader::GenerateOutputInformation()\n{\n mitk::Image::Pointer output = this->GetOutput();\n\n if ((output->IsInitialized()) && (this->GetMTime() <= m_ReadHeaderTime.GetMTime()))\n return;\n\n itkDebugMacro(<<\"Reading file for GenerateOutputInformation()\" << m_FileName);\n\n \/\/ Check to see if we can read the file given the name or prefix\n \/\/\n if ( m_FileName == \"\" )\n {\n throw itk::ImageFileReaderException(__FILE__, __LINE__, \"One of FileName or FilePrefix must be non-empty\");\n }\n\n if( m_FileName != \"\")\n {\n ipUInt4_t header_size;\n ipUInt4_t image_size;\n ipUInt1_t *header = NULL;\n unsigned char *image = NULL;\n ipBool_t color=ipFalse;\n outputfile_name = m_FileName;\n dicomGetHeaderAndImage( const_cast(m_FileName.c_str()),\n &header, &header_size,\n &image, &image_size );\n\n if( !image )\n exit(-1);\n pic = _dicomToPic( header, header_size,\n image, image_size, color );\n pic->dim--;\n\n if( pic == NULL)\n {\n itk::ImageFileReaderException e(__FILE__, __LINE__);\n itk::OStringStream msg;\n msg << \" Could not read file \"\n << outputfile_name.c_str();\n e.SetDescription(msg.str().c_str());\n throw e;\n return;\n }\n\n output->Initialize(pic);\n }\n\n m_ReadHeaderTime.Modified();\n}\n\n\/\/##ModelId=3E187255016C\nvoid mitk::DICOMFileReader::GenerateData()\n{\n mitk::Image::Pointer output = this->GetOutput();\n\n \/\/ Check to see if we can read the file given the name or prefix\n \/\/\n if ( m_FileName == \"\" && m_FilePrefix == \"\" )\n {\n throw itk::ImageFileReaderException(__FILE__, __LINE__, \"One of FileName or FilePrefix must be non-empty\");\n }\n\n if( m_FileName != \"\")\n {\n\n \/\/left to right handed conversion\n if(pic->dim==3)\n {\n ipPicDescriptor* slice=ipPicCopyHeader(pic, NULL);\n slice->dim=2;\n int size=_ipPicSize(slice);\n slice->data=malloc(size);\n unsigned char *p_first=(unsigned char *)pic->data;\n unsigned char *p_last=(unsigned char *)pic->data;\n p_last+=size*(pic->n[2]-1);\n\n int i, smid=pic->n[2]\/2;\n for(i=0; idata, p_last, size);\n memcpy(p_last, p_first, size);\n memcpy(p_first, slice->data, size);\n }\n ipPicFree(slice);\n }\n output->SetPicVolume(pic);\n }\n}\n\n\/\/##ModelId=3E1874D202D0\nmitk::DICOMFileReader::DICOMFileReader()\n: m_FileName(\"\"), m_FilePrefix(\"\"), m_FilePattern(\"\")\n{\n}\n\n\/\/##ModelId=3E1874E50179\nmitk::DICOMFileReader::~DICOMFileReader()\n{\n}\nexception instead of exit#include \"mitkDICOMFileReader.h\"\n#include \n\nextern \"C\"\n{\n#include \"ipDicom\/ipDicom.h\"\n}\n\nvoid mitk::DICOMFileReader::GenerateOutputInformation()\n{\n mitk::Image::Pointer output = this->GetOutput();\n\n if ((output->IsInitialized()) && (this->GetMTime() <= m_ReadHeaderTime.GetMTime()))\n return;\n\n itkDebugMacro(<<\"Reading file for GenerateOutputInformation()\" << m_FileName);\n\n \/\/ Check to see if we can read the file given the name or prefix\n \/\/\n if ( m_FileName == \"\" )\n {\n throw itk::ImageFileReaderException(__FILE__, __LINE__, \"One of FileName or FilePrefix must be non-empty\");\n }\n\n if( m_FileName != \"\")\n {\n ipUInt4_t header_size;\n ipUInt4_t image_size;\n ipUInt1_t *header = NULL;\n unsigned char *image = NULL;\n ipBool_t color=ipFalse;\n outputfile_name = m_FileName;\n dicomGetHeaderAndImage( const_cast(m_FileName.c_str()),\n &header, &header_size,\n &image, &image_size );\n\n if( !header )\n throw itk::ImageFileReaderException(__FILE__, __LINE__, \"Could not get header.\");;\n if( !image )\n throw itk::ImageFileReaderException(__FILE__, __LINE__, \"Could not get image.\");;\n pic = _dicomToPic( header, header_size,\n image, image_size, color );\n pic->dim--;\n\n if( pic == NULL)\n {\n itk::ImageFileReaderException e(__FILE__, __LINE__);\n itk::OStringStream msg;\n msg << \" Could not read file \"\n << outputfile_name.c_str();\n e.SetDescription(msg.str().c_str());\n throw e;\n return;\n }\n\n output->Initialize(pic);\n }\n\n m_ReadHeaderTime.Modified();\n}\n\n\/\/##ModelId=3E187255016C\nvoid mitk::DICOMFileReader::GenerateData()\n{\n mitk::Image::Pointer output = this->GetOutput();\n\n \/\/ Check to see if we can read the file given the name or prefix\n \/\/\n if ( m_FileName == \"\" && m_FilePrefix == \"\" )\n {\n throw itk::ImageFileReaderException(__FILE__, __LINE__, \"One of FileName or FilePrefix must be non-empty\");\n }\n\n if( m_FileName != \"\")\n {\n\n \/\/left to right handed conversion\n if(pic->dim==3)\n {\n ipPicDescriptor* slice=ipPicCopyHeader(pic, NULL);\n slice->dim=2;\n int size=_ipPicSize(slice);\n slice->data=malloc(size);\n unsigned char *p_first=(unsigned char *)pic->data;\n unsigned char *p_last=(unsigned char *)pic->data;\n p_last+=size*(pic->n[2]-1);\n\n int i, smid=pic->n[2]\/2;\n for(i=0; idata, p_last, size);\n memcpy(p_last, p_first, size);\n memcpy(p_first, slice->data, size);\n }\n ipPicFree(slice);\n }\n output->SetPicVolume(pic);\n }\n}\n\n\/\/##ModelId=3E1874D202D0\nmitk::DICOMFileReader::DICOMFileReader()\n: m_FileName(\"\"), m_FilePrefix(\"\"), m_FilePattern(\"\")\n{\n}\n\n\/\/##ModelId=3E1874E50179\nmitk::DICOMFileReader::~DICOMFileReader()\n{\n}\n<|endoftext|>"} {"text":"\/*\n Copyright (C) 2011 by Ivan Safrin\n \n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n \n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n \n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE.\n*\/\n\n#include \"PolyScreenMesh.h\"\n#include \"PolyCoreServices.h\"\n#include \"PolyMaterialManager.h\"\n#include \"PolyMesh.h\"\n#include \"PolyRenderer.h\"\n\nusing namespace Polycode;\n\nScreenMesh::ScreenMesh(const String& fileName) : ScreenEntity(), texture(NULL) {\n\tmesh = new Mesh(fileName);\n}\n\nScreenMesh::ScreenMesh(int meshType) : ScreenEntity(), texture(NULL) {\n\tmesh = new Mesh(meshType);\n}\n\n\nScreenMesh::~ScreenMesh() {\n\n}\n\nMesh *ScreenMesh::getMesh() const {\n\treturn mesh;\n}\n\nTexture *ScreenMesh::getTexture() const {\n\treturn texture;\n}\n\nvoid ScreenMesh::setTexture(Texture *texture) {\n\tthis->texture = texture;\n}\n\nvoid ScreenMesh::loadTexture(const String& fileName) {\n\ttexture = CoreServices::getInstance()->getMaterialManager()->createTextureFromFile(fileName, true, false);\n}\n\nvoid ScreenMesh::loadTexture(Image *image) {\n\ttexture = CoreServices::getInstance()->getMaterialManager()->createTextureFromImage(image, true, false);\n}\n\nvoid ScreenMesh::Render() {\t\n\tRenderer *renderer = CoreServices::getInstance()->getRenderer();\n\trenderer->setTexture(texture);\n\tif(mesh->useVertexColors) {\n\t\trenderer->pushDataArrayForMesh(mesh, RenderDataArray::COLOR_DATA_ARRAY);\n\t}\n\trenderer->pushDataArrayForMesh(mesh, RenderDataArray::VERTEX_DATA_ARRAY);\n\trenderer->pushDataArrayForMesh(mesh, RenderDataArray::TEXCOORD_DATA_ARRAY);\t\n\trenderer->drawArrays(mesh->getMeshType());\n}\nScreenMesh wasn't deleting mesh\/*\n Copyright (C) 2011 by Ivan Safrin\n \n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n \n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n \n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE.\n*\/\n\n#include \"PolyScreenMesh.h\"\n#include \"PolyCoreServices.h\"\n#include \"PolyMaterialManager.h\"\n#include \"PolyMesh.h\"\n#include \"PolyRenderer.h\"\n\nusing namespace Polycode;\n\nScreenMesh::ScreenMesh(const String& fileName) : ScreenEntity(), texture(NULL) {\n\tmesh = new Mesh(fileName);\n}\n\nScreenMesh::ScreenMesh(int meshType) : ScreenEntity(), texture(NULL) {\n\tmesh = new Mesh(meshType);\n}\n\n\nScreenMesh::~ScreenMesh() {\n\tdelete mesh;\n\t\/\/ TODO: Should have ownsTexture field?\n}\n\nMesh *ScreenMesh::getMesh() const {\n\treturn mesh;\n}\n\nTexture *ScreenMesh::getTexture() const {\n\treturn texture;\n}\n\nvoid ScreenMesh::setTexture(Texture *texture) {\n\tthis->texture = texture;\n}\n\nvoid ScreenMesh::loadTexture(const String& fileName) {\n\ttexture = CoreServices::getInstance()->getMaterialManager()->createTextureFromFile(fileName, true, false);\n}\n\nvoid ScreenMesh::loadTexture(Image *image) {\n\ttexture = CoreServices::getInstance()->getMaterialManager()->createTextureFromImage(image, true, false);\n}\n\nvoid ScreenMesh::Render() {\t\n\tRenderer *renderer = CoreServices::getInstance()->getRenderer();\n\trenderer->setTexture(texture);\n\tif(mesh->useVertexColors) {\n\t\trenderer->pushDataArrayForMesh(mesh, RenderDataArray::COLOR_DATA_ARRAY);\n\t}\n\trenderer->pushDataArrayForMesh(mesh, RenderDataArray::VERTEX_DATA_ARRAY);\n\trenderer->pushDataArrayForMesh(mesh, RenderDataArray::TEXCOORD_DATA_ARRAY);\t\n\trenderer->drawArrays(mesh->getMeshType());\n}\n<|endoftext|>"} {"text":"\/**\n ******************************************************************************\n * Xenia : Xbox 360 Emulator Research Project *\n ******************************************************************************\n * Copyright 2013 Ben Vanik. All rights reserved. *\n * Released under the BSD license - see LICENSE in the root for more details. *\n ******************************************************************************\n *\/\n\n#include \"xenia\/base\/logging.h\"\n#include \"xenia\/kernel\/kernel_state.h\"\n#include \"xenia\/kernel\/objects\/xthread.h\"\n#include \"xenia\/kernel\/objects\/xsemaphore.h\"\n#include \"xenia\/kernel\/util\/shim_utils.h\"\n#include \"xenia\/kernel\/xboxkrnl_private.h\"\n#include \"xenia\/kernel\/xobject.h\"\n#include \"xenia\/xbox.h\"\n\nnamespace xe {\nnamespace kernel {\n\nSHIM_CALL ObOpenObjectByName_shim(PPCContext* ppc_context,\n KernelState* kernel_state) {\n \/\/ r3 = ptr to info?\n \/\/ +0 = -4\n \/\/ +4 = name ptr\n \/\/ +8 = 0\n \/\/ r4 = ExEventObjectType | ExSemaphoreObjectType | ExTimerObjectType\n \/\/ r5 = 0\n \/\/ r6 = out_ptr (handle?)\n uint32_t obj_attributes_ptr = SHIM_GET_ARG_32(0);\n uint32_t object_type_ptr = SHIM_GET_ARG_32(1);\n uint32_t unk = SHIM_GET_ARG_32(2);\n uint32_t handle_ptr = SHIM_GET_ARG_32(3);\n\n uint32_t name_str_ptr = SHIM_MEM_32(obj_attributes_ptr + 4);\n X_ANSI_STRING name_str(SHIM_MEM_BASE, name_str_ptr);\n auto name = name_str.to_string();\n\n XELOGD(\"ObOpenObjectByName(%.8X(name=%s), %.8X, %.8X, %.8X)\",\n obj_attributes_ptr, name.c_str(), object_type_ptr, unk, handle_ptr);\n\n X_HANDLE handle = X_INVALID_HANDLE_VALUE;\n X_STATUS result =\n kernel_state->object_table()->GetObjectByName(name, &handle);\n if (XSUCCEEDED(result)) {\n SHIM_SET_MEM_32(handle_ptr, handle);\n }\n\n SHIM_SET_RETURN_32(result);\n}\n\nSHIM_CALL ObReferenceObjectByHandle_shim(PPCContext* ppc_context,\n KernelState* kernel_state) {\n uint32_t handle = SHIM_GET_ARG_32(0);\n uint32_t object_type_ptr = SHIM_GET_ARG_32(1);\n uint32_t out_object_ptr = SHIM_GET_ARG_32(2);\n\n XELOGD(\"ObReferenceObjectByHandle(%.8X, %.8X, %.8X)\", handle, object_type_ptr,\n out_object_ptr);\n\n X_STATUS result = X_STATUS_SUCCESS;\n\n auto object = kernel_state->object_table()->LookupObject(handle);\n if (object) {\n \/\/ TODO(benvanik): verify type with object_type_ptr\n\n \/\/ TODO(benvanik): get native value, if supported.\n uint32_t native_ptr;\n switch (object_type_ptr) {\n case 0x00000000: { \/\/ whatever?\n switch (object->type()) {\n \/\/ TODO(benvanik): need to track native_ptr in XObject, allocate as\n \/\/ needed?\n \/*case XObject::kTypeEvent: {\n XEvent* ev = (XEvent*)object;\n } break;*\/\n case XObject::kTypeThread: {\n auto thread = object.get();\n native_ptr = thread->guest_object();\n } break;\n default: {\n assert_unhandled_case(object->type());\n native_ptr = 0xDEADF00D;\n } break;\n }\n } break;\n case 0xD017BEEF: { \/\/ ExSemaphoreObjectType\n assert(object->type() == XObject::kTypeSemaphore);\n auto sem = object.get();\n\n native_ptr = sem->guest_object();\n\n \/\/ TODO(benvanik): implement.\n assert_unhandled_case(object_type_ptr);\n native_ptr = 0xDEADF00D;\n } break;\n case 0xD01BBEEF: { \/\/ ExThreadObjectType\n assert(object->type() == XObject::kTypeThread);\n auto thread = object.get();\n\n native_ptr = thread->guest_object();\n } break;\n default: {\n assert_unhandled_case(object_type_ptr);\n native_ptr = 0xDEADF00D;\n } break;\n }\n\n \/\/ Caller takes the reference.\n \/\/ It's released in ObDereferenceObject.\n object->Retain();\n if (out_object_ptr) {\n SHIM_SET_MEM_32(out_object_ptr, native_ptr);\n }\n } else {\n result = X_STATUS_INVALID_HANDLE;\n }\n\n SHIM_SET_RETURN_32(result);\n}\n\nSHIM_CALL ObDereferenceObject_shim(PPCContext* ppc_context,\n KernelState* kernel_state) {\n uint32_t native_ptr = SHIM_GET_ARG_32(0);\n\n XELOGD(\"ObDereferenceObject(%.8X)\", native_ptr);\n\n \/\/ Check if a dummy value from ObReferenceObjectByHandle.\n if (native_ptr == 0xDEADF00D) {\n SHIM_SET_RETURN_32(0);\n return;\n }\n\n void* object_ptr = SHIM_MEM_ADDR(native_ptr);\n auto object = XObject::GetNativeObject(kernel_state, object_ptr);\n if (object) {\n object->Release();\n }\n\n SHIM_SET_RETURN_32(0);\n}\n\ndword_result_t NtDuplicateObject(dword_t handle, lpdword_t new_handle_ptr,\n dword_t options) {\n \/\/ NOTE: new_handle_ptr can be zero to just close a handle.\n \/\/ NOTE: this function seems to be used to get the current thread handle\n \/\/ (passed handle=-2).\n \/\/ This function actually just creates a new handle to the same object.\n \/\/ Most games use it to get real handles to the current thread or whatever.\n\n X_HANDLE new_handle = X_INVALID_HANDLE_VALUE;\n X_STATUS result =\n kernel_state()->object_table()->DuplicateHandle(handle, &new_handle);\n\n if (new_handle_ptr) {\n *new_handle_ptr = new_handle;\n }\n\n if (options == 1 \/* DUPLICATE_CLOSE_SOURCE *\/) {\n \/\/ Always close the source object.\n kernel_state()->object_table()->RemoveHandle(handle);\n }\n\n return result;\n}\nDECLARE_XBOXKRNL_EXPORT(NtDuplicateObject, ExportTag::kImplemented);\n\ndword_result_t NtClose(dword_t handle) {\n return kernel_state()->object_table()->RemoveHandle(handle);\n}\nDECLARE_XBOXKRNL_EXPORT(NtClose, ExportTag::kImplemented);\n\n} \/\/ namespace kernel\n} \/\/ namespace xe\n\nvoid xe::kernel::xboxkrnl::RegisterObExports(\n xe::cpu::ExportResolver* export_resolver, KernelState* kernel_state) {\n SHIM_SET_MAPPING(\"xboxkrnl.exe\", ObOpenObjectByName, state);\n SHIM_SET_MAPPING(\"xboxkrnl.exe\", ObReferenceObjectByHandle, state);\n SHIM_SET_MAPPING(\"xboxkrnl.exe\", ObDereferenceObject, state);\n}\nWhoops\/**\n ******************************************************************************\n * Xenia : Xbox 360 Emulator Research Project *\n ******************************************************************************\n * Copyright 2013 Ben Vanik. All rights reserved. *\n * Released under the BSD license - see LICENSE in the root for more details. *\n ******************************************************************************\n *\/\n\n#include \"xenia\/base\/logging.h\"\n#include \"xenia\/kernel\/kernel_state.h\"\n#include \"xenia\/kernel\/objects\/xthread.h\"\n#include \"xenia\/kernel\/objects\/xsemaphore.h\"\n#include \"xenia\/kernel\/util\/shim_utils.h\"\n#include \"xenia\/kernel\/xboxkrnl_private.h\"\n#include \"xenia\/kernel\/xobject.h\"\n#include \"xenia\/xbox.h\"\n\nnamespace xe {\nnamespace kernel {\n\nSHIM_CALL ObOpenObjectByName_shim(PPCContext* ppc_context,\n KernelState* kernel_state) {\n \/\/ r3 = ptr to info?\n \/\/ +0 = -4\n \/\/ +4 = name ptr\n \/\/ +8 = 0\n \/\/ r4 = ExEventObjectType | ExSemaphoreObjectType | ExTimerObjectType\n \/\/ r5 = 0\n \/\/ r6 = out_ptr (handle?)\n uint32_t obj_attributes_ptr = SHIM_GET_ARG_32(0);\n uint32_t object_type_ptr = SHIM_GET_ARG_32(1);\n uint32_t unk = SHIM_GET_ARG_32(2);\n uint32_t handle_ptr = SHIM_GET_ARG_32(3);\n\n uint32_t name_str_ptr = SHIM_MEM_32(obj_attributes_ptr + 4);\n X_ANSI_STRING name_str(SHIM_MEM_BASE, name_str_ptr);\n auto name = name_str.to_string();\n\n XELOGD(\"ObOpenObjectByName(%.8X(name=%s), %.8X, %.8X, %.8X)\",\n obj_attributes_ptr, name.c_str(), object_type_ptr, unk, handle_ptr);\n\n X_HANDLE handle = X_INVALID_HANDLE_VALUE;\n X_STATUS result =\n kernel_state->object_table()->GetObjectByName(name, &handle);\n if (XSUCCEEDED(result)) {\n SHIM_SET_MEM_32(handle_ptr, handle);\n }\n\n SHIM_SET_RETURN_32(result);\n}\n\nSHIM_CALL ObReferenceObjectByHandle_shim(PPCContext* ppc_context,\n KernelState* kernel_state) {\n uint32_t handle = SHIM_GET_ARG_32(0);\n uint32_t object_type_ptr = SHIM_GET_ARG_32(1);\n uint32_t out_object_ptr = SHIM_GET_ARG_32(2);\n\n XELOGD(\"ObReferenceObjectByHandle(%.8X, %.8X, %.8X)\", handle, object_type_ptr,\n out_object_ptr);\n\n X_STATUS result = X_STATUS_SUCCESS;\n\n auto object = kernel_state->object_table()->LookupObject(handle);\n if (object) {\n \/\/ TODO(benvanik): verify type with object_type_ptr\n\n \/\/ TODO(benvanik): get native value, if supported.\n uint32_t native_ptr;\n switch (object_type_ptr) {\n case 0x00000000: { \/\/ whatever?\n switch (object->type()) {\n \/\/ TODO(benvanik): need to track native_ptr in XObject, allocate as\n \/\/ needed?\n \/*case XObject::kTypeEvent: {\n XEvent* ev = (XEvent*)object;\n } break;*\/\n case XObject::kTypeThread: {\n auto thread = object.get();\n native_ptr = thread->guest_object();\n } break;\n default: {\n assert_unhandled_case(object->type());\n native_ptr = 0xDEADF00D;\n } break;\n }\n } break;\n case 0xD017BEEF: { \/\/ ExSemaphoreObjectType\n assert(object->type() == XObject::kTypeSemaphore);\n auto sem = object.get();\n\n native_ptr = sem->guest_object();\n } break;\n case 0xD01BBEEF: { \/\/ ExThreadObjectType\n assert(object->type() == XObject::kTypeThread);\n auto thread = object.get();\n\n native_ptr = thread->guest_object();\n } break;\n default: {\n assert_unhandled_case(object_type_ptr);\n native_ptr = 0xDEADF00D;\n } break;\n }\n\n \/\/ Caller takes the reference.\n \/\/ It's released in ObDereferenceObject.\n object->Retain();\n if (out_object_ptr) {\n SHIM_SET_MEM_32(out_object_ptr, native_ptr);\n }\n } else {\n result = X_STATUS_INVALID_HANDLE;\n }\n\n SHIM_SET_RETURN_32(result);\n}\n\nSHIM_CALL ObDereferenceObject_shim(PPCContext* ppc_context,\n KernelState* kernel_state) {\n uint32_t native_ptr = SHIM_GET_ARG_32(0);\n\n XELOGD(\"ObDereferenceObject(%.8X)\", native_ptr);\n\n \/\/ Check if a dummy value from ObReferenceObjectByHandle.\n if (native_ptr == 0xDEADF00D) {\n SHIM_SET_RETURN_32(0);\n return;\n }\n\n void* object_ptr = SHIM_MEM_ADDR(native_ptr);\n auto object = XObject::GetNativeObject(kernel_state, object_ptr);\n if (object) {\n object->Release();\n }\n\n SHIM_SET_RETURN_32(0);\n}\n\ndword_result_t NtDuplicateObject(dword_t handle, lpdword_t new_handle_ptr,\n dword_t options) {\n \/\/ NOTE: new_handle_ptr can be zero to just close a handle.\n \/\/ NOTE: this function seems to be used to get the current thread handle\n \/\/ (passed handle=-2).\n \/\/ This function actually just creates a new handle to the same object.\n \/\/ Most games use it to get real handles to the current thread or whatever.\n\n X_HANDLE new_handle = X_INVALID_HANDLE_VALUE;\n X_STATUS result =\n kernel_state()->object_table()->DuplicateHandle(handle, &new_handle);\n\n if (new_handle_ptr) {\n *new_handle_ptr = new_handle;\n }\n\n if (options == 1 \/* DUPLICATE_CLOSE_SOURCE *\/) {\n \/\/ Always close the source object.\n kernel_state()->object_table()->RemoveHandle(handle);\n }\n\n return result;\n}\nDECLARE_XBOXKRNL_EXPORT(NtDuplicateObject, ExportTag::kImplemented);\n\ndword_result_t NtClose(dword_t handle) {\n return kernel_state()->object_table()->RemoveHandle(handle);\n}\nDECLARE_XBOXKRNL_EXPORT(NtClose, ExportTag::kImplemented);\n\n} \/\/ namespace kernel\n} \/\/ namespace xe\n\nvoid xe::kernel::xboxkrnl::RegisterObExports(\n xe::cpu::ExportResolver* export_resolver, KernelState* kernel_state) {\n SHIM_SET_MAPPING(\"xboxkrnl.exe\", ObOpenObjectByName, state);\n SHIM_SET_MAPPING(\"xboxkrnl.exe\", ObReferenceObjectByHandle, state);\n SHIM_SET_MAPPING(\"xboxkrnl.exe\", ObDereferenceObject, state);\n}\n<|endoftext|>"} {"text":"\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include \"opengl\/x11\/X11DeviceInfo.hxx\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\nnamespace glx {\n\nstatic int glxtest_pipe = 0;\n\nstatic pid_t glxtest_pid = 0;\n\n}\n\npid_t* getGlxPid()\n{\n return &glx::glxtest_pid;\n}\n\nint* getGlxPipe()\n{\n return &glx::glxtest_pipe;\n}\n\nnamespace {\n\nconst char*\nstrspnp_wrapper(const char* aDelims, const char* aStr)\n{\n const char* d;\n do {\n for (d = aDelims; *d != '\\0'; ++d) {\n if (*aStr == *d) {\n ++aStr;\n break;\n }\n }\n } while (*d);\n\n return aStr;\n}\n\nchar* strtok_wrapper(const char* aDelims, char** aStr)\n{\n if (!*aStr) {\n return nullptr;\n }\n\n char* ret = (char*)strspnp_wrapper(aDelims, *aStr);\n\n if (!*ret) {\n *aStr = ret;\n return nullptr;\n }\n\n char* i = ret;\n do {\n for (const char* d = aDelims; *d != '\\0'; ++d) {\n if (*i == *d) {\n *i = '\\0';\n *aStr = ++i;\n return ret;\n }\n }\n ++i;\n } while (*i);\n\n *aStr = nullptr;\n return ret;\n}\n\nuint64_t version(uint32_t major, uint32_t minor, uint32_t revision = 0)\n{\n return (uint64_t(major) << 32) + (uint64_t(minor) << 16) + uint64_t(revision);\n}\n\n}\n\nX11OpenGLDeviceInfo::X11OpenGLDeviceInfo():\n mbIsMesa(false),\n mbIsNVIDIA(false),\n mbIsFGLRX(false),\n mbIsNouveau(false),\n mbIsIntel(false),\n mbIsOldSwrast(false),\n mbIsLlvmpipe(false),\n mbHasTextureFromPixmap(false),\n mnGLMajorVersion(0),\n mnMajorVersion(0),\n mnMinorVersion(0),\n mnRevisionVersion(0)\n{\n GetData();\n}\n\nX11OpenGLDeviceInfo::~X11OpenGLDeviceInfo()\n{\n}\n\nvoid X11OpenGLDeviceInfo::GetData()\n{\n if (!glx::glxtest_pipe)\n return;\n\n \/\/ to understand this function, see bug 639842. We retrieve the OpenGL driver information in a\n \/\/ separate process to protect against bad drivers.\n\n enum { buf_size = 1024 };\n char buf[buf_size];\n ssize_t bytesread = read(glx::glxtest_pipe,\n &buf,\n buf_size-1); \/\/ -1 because we'll append a zero\n close(glx::glxtest_pipe);\n glx::glxtest_pipe = 0;\n\n \/\/ bytesread < 0 would mean that the above read() call failed.\n \/\/ This should never happen. If it did, the outcome would be to blacklist anyway.\n if (bytesread < 0)\n bytesread = 0;\n\n \/\/ let buf be a zero-terminated string\n buf[bytesread] = 0;\n\n \/\/ Wait for the glxtest process to finish. This serves 2 purposes:\n \/\/ * avoid having a zombie glxtest process laying around\n \/\/ * get the glxtest process status info.\n int glxtest_status = 0;\n bool wait_for_glxtest_process = true;\n bool waiting_for_glxtest_process_failed = false;\n int waitpid_errno = 0;\n while(wait_for_glxtest_process) {\n wait_for_glxtest_process = false;\n if (waitpid(glx::glxtest_pid, &glxtest_status, 0) == -1) {\n waitpid_errno = errno;\n if (waitpid_errno == EINTR) {\n wait_for_glxtest_process = true;\n } else {\n \/\/ Bug 718629\n \/\/ ECHILD happens when the glxtest process got reaped got reaped after a PR_CreateProcess\n \/\/ as per bug 227246. This shouldn't matter, as we still seem to get the data\n \/\/ from the pipe, and if we didn't, the outcome would be to blacklist anyway.\n waiting_for_glxtest_process_failed = (waitpid_errno != ECHILD);\n }\n }\n }\n\n bool exited_with_error_code = !waiting_for_glxtest_process_failed &&\n WIFEXITED(glxtest_status) &&\n WEXITSTATUS(glxtest_status) != EXIT_SUCCESS;\n bool received_signal = !waiting_for_glxtest_process_failed &&\n WIFSIGNALED(glxtest_status);\n\n bool error = waiting_for_glxtest_process_failed || exited_with_error_code || received_signal;\n\n OString textureFromPixmap;\n OString *stringToFill = nullptr;\n char *bufptr = buf;\n if (!error) {\n while(true) {\n char *line = strtok_wrapper(\"\\n\", &bufptr);\n if (!line)\n break;\n if (stringToFill) {\n *stringToFill = OString(line);\n stringToFill = nullptr;\n }\n else if(!strcmp(line, \"VENDOR\"))\n stringToFill = &maVendor;\n else if(!strcmp(line, \"RENDERER\"))\n stringToFill = &maRenderer;\n else if(!strcmp(line, \"VERSION\"))\n stringToFill = &maVersion;\n else if(!strcmp(line, \"TFP\"))\n stringToFill = &textureFromPixmap;\n }\n }\n\n if (!strcmp(textureFromPixmap.getStr(), \"TRUE\"))\n mbHasTextureFromPixmap = true;\n\n \/\/ only useful for Linux kernel version check for FGLRX driver.\n \/\/ assumes X client == X server, which is sad.\n struct utsname unameobj;\n if (!uname(&unameobj))\n {\n maOS = OString(unameobj.sysname);\n maOSRelease = OString(unameobj.release);\n }\n\n \/\/ determine the major OpenGL version. That's the first integer in the version string.\n mnGLMajorVersion = strtol(maVersion.getStr(), 0, 10);\n\n \/\/ determine driver type (vendor) and where in the version string\n \/\/ the actual driver version numbers should be expected to be found (whereToReadVersionNumbers)\n const char *whereToReadVersionNumbers = nullptr;\n const char *Mesa_in_version_string = strstr(maVersion.getStr(), \"Mesa\");\n if (Mesa_in_version_string) {\n mbIsMesa = true;\n \/\/ with Mesa, the version string contains \"Mesa major.minor\" and that's all the version information we get:\n \/\/ there is no actual driver version info.\n whereToReadVersionNumbers = Mesa_in_version_string + strlen(\"Mesa\");\n if (strcasestr(maVendor.getStr(), \"nouveau\"))\n mbIsNouveau = true;\n if (strcasestr(maRenderer.getStr(), \"intel\")) \/\/ yes, intel is in the renderer string\n mbIsIntel = true;\n if (strcasestr(maRenderer.getStr(), \"llvmpipe\"))\n mbIsLlvmpipe = true;\n if (strcasestr(maRenderer.getStr(), \"software rasterizer\"))\n mbIsOldSwrast = true;\n } else if (strstr(maVendor.getStr(), \"NVIDIA Corporation\")) {\n mbIsNVIDIA = true;\n \/\/ with the NVIDIA driver, the version string contains \"NVIDIA major.minor\"\n \/\/ note that here the vendor and version strings behave differently, that's why we don't put this above\n \/\/ alongside Mesa_in_version_string.\n const char *NVIDIA_in_version_string = strstr(maVersion.getStr(), \"NVIDIA\");\n if (NVIDIA_in_version_string)\n whereToReadVersionNumbers = NVIDIA_in_version_string + strlen(\"NVIDIA\");\n } else if (strstr(maVendor.getStr(), \"ATI Technologies Inc\")) {\n mbIsFGLRX = true;\n \/\/ with the FGLRX driver, the version string only gives a OpenGL version :\/ so let's return that.\n \/\/ that can at least give a rough idea of how old the driver is.\n whereToReadVersionNumbers = maVersion.getStr();\n }\n\n \/\/ read major.minor version numbers of the driver (not to be confused with the OpenGL version)\n if (whereToReadVersionNumbers) {\n \/\/ copy into writable buffer, for tokenization\n strncpy(buf, whereToReadVersionNumbers, buf_size);\n bufptr = buf;\n\n \/\/ now try to read major.minor version numbers. In case of failure, gracefully exit: these numbers have\n \/\/ been initialized as 0 anyways\n char *token = strtok_wrapper(\".\", &bufptr);\n if (token) {\n mnMajorVersion = strtol(token, 0, 10);\n token = strtok_wrapper(\".\", &bufptr);\n if (token) {\n mnMinorVersion = strtol(token, 0, 10);\n token = strtok_wrapper(\".\", &bufptr);\n if (token)\n mnRevisionVersion = strtol(token, 0, 10);\n }\n }\n }\n}\n\nbool X11OpenGLDeviceInfo::isDeviceBlocked()\n{\n \/\/ don't even try to use OpenGL 1.x\n if (mnGLMajorVersion == 1)\n return true;\n\n SAL_INFO(\"vcl.opengl\", \"Vendor: \" << maVendor);\n SAL_INFO(\"vcl.opengl\", \"Renderer: \" << maRenderer);\n SAL_INFO(\"vcl.opengl\", \"Version: \" << maVersion);\n SAL_INFO(\"vcl.opengl\", \"OS: \" << maOS);\n SAL_INFO(\"vcl.opengl\", \"OSRelease: \" << maOSRelease);\n\n\n if (mbIsMesa) {\n if (mbIsNouveau && version(mnMajorVersion, mnMinorVersion) < version(8,0)) {\n SAL_WARN(\"vcl.opengl\", \"blocked driver version: old nouveau driver (requires mesa 8.0+)\");\n return true;\n }\n else if (version(mnMajorVersion, mnMinorVersion, mnRevisionVersion) < version(7,10,3)) {\n SAL_WARN(\"vcl.opengl\", \"blocked driver version: requires at least mesa 7.10.3\");\n return true;\n }\n else if (mbIsOldSwrast) {\n SAL_WARN(\"vcl.opengl\", \"blocked driver version: software rasterizer\");\n return true;\n }\n else if (mbIsLlvmpipe && version(mnMajorVersion, mnMinorVersion) < version(9, 1)) {\n \/\/ bug 791905, Mesa bug 57733, fixed in Mesa 9.1 according to\n \/\/ https:\/\/bugs.freedesktop.org\/show_bug.cgi?id=57733#c3\n SAL_WARN(\"vcl.opengl\", \"blocked driver version: fdo#57733\");\n return true;\n }\n\n } else if (mbIsNVIDIA) {\n if (version(mnMajorVersion, mnMinorVersion, mnRevisionVersion) < version(257,21)) {\n SAL_WARN(\"vcl.opengl\", \"blocked driver version: nvidia requires at least 257.21\");\n return true;\n }\n } else if (mbIsFGLRX) {\n \/\/ FGLRX does not report a driver version number, so we have the OpenGL version instead.\n \/\/ by requiring OpenGL 3, we effectively require recent drivers.\n if (version(mnMajorVersion, mnMinorVersion, mnRevisionVersion) < version(3, 0)) {\n SAL_WARN(\"vcl.opengl\", \"blocked driver version: require at least OpenGL 3 for fglrx\");\n return true;\n }\n \/\/ Bug 724640: FGLRX + Linux 2.6.32 is a crashy combo\n bool unknownOS = maOS.isEmpty() || maOSRelease.isEmpty();\n OUString aOS = rtl::OStringToOUString(maOS, RTL_TEXTENCODING_UTF8);\n OUString aOSRelease = rtl::OStringToOUString(maOSRelease, RTL_TEXTENCODING_UTF8);\n bool badOS = aOS.indexOf(\"Linux\") != -1 &&\n maOSRelease.indexOf(\"2.6.32\") != -1;\n if (unknownOS || badOS) {\n SAL_WARN(\"vcl.opengl\", \"blocked OS version with fglrx\");\n return true;\n }\n } else {\n \/\/ like on windows, let's block unknown vendors. Think of virtual machines.\n \/\/ Also, this case is hit whenever the GLXtest probe failed to get driver info or crashed.\n SAL_WARN(\"vcl.opengl\", \"unknown vendor => blocked\");\n return true;\n }\n\n return false;\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\nWaE: unused variable 'aOSRelease'\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include \"opengl\/x11\/X11DeviceInfo.hxx\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\nnamespace glx {\n\nstatic int glxtest_pipe = 0;\n\nstatic pid_t glxtest_pid = 0;\n\n}\n\npid_t* getGlxPid()\n{\n return &glx::glxtest_pid;\n}\n\nint* getGlxPipe()\n{\n return &glx::glxtest_pipe;\n}\n\nnamespace {\n\nconst char*\nstrspnp_wrapper(const char* aDelims, const char* aStr)\n{\n const char* d;\n do {\n for (d = aDelims; *d != '\\0'; ++d) {\n if (*aStr == *d) {\n ++aStr;\n break;\n }\n }\n } while (*d);\n\n return aStr;\n}\n\nchar* strtok_wrapper(const char* aDelims, char** aStr)\n{\n if (!*aStr) {\n return nullptr;\n }\n\n char* ret = (char*)strspnp_wrapper(aDelims, *aStr);\n\n if (!*ret) {\n *aStr = ret;\n return nullptr;\n }\n\n char* i = ret;\n do {\n for (const char* d = aDelims; *d != '\\0'; ++d) {\n if (*i == *d) {\n *i = '\\0';\n *aStr = ++i;\n return ret;\n }\n }\n ++i;\n } while (*i);\n\n *aStr = nullptr;\n return ret;\n}\n\nuint64_t version(uint32_t major, uint32_t minor, uint32_t revision = 0)\n{\n return (uint64_t(major) << 32) + (uint64_t(minor) << 16) + uint64_t(revision);\n}\n\n}\n\nX11OpenGLDeviceInfo::X11OpenGLDeviceInfo():\n mbIsMesa(false),\n mbIsNVIDIA(false),\n mbIsFGLRX(false),\n mbIsNouveau(false),\n mbIsIntel(false),\n mbIsOldSwrast(false),\n mbIsLlvmpipe(false),\n mbHasTextureFromPixmap(false),\n mnGLMajorVersion(0),\n mnMajorVersion(0),\n mnMinorVersion(0),\n mnRevisionVersion(0)\n{\n GetData();\n}\n\nX11OpenGLDeviceInfo::~X11OpenGLDeviceInfo()\n{\n}\n\nvoid X11OpenGLDeviceInfo::GetData()\n{\n if (!glx::glxtest_pipe)\n return;\n\n \/\/ to understand this function, see bug 639842. We retrieve the OpenGL driver information in a\n \/\/ separate process to protect against bad drivers.\n\n enum { buf_size = 1024 };\n char buf[buf_size];\n ssize_t bytesread = read(glx::glxtest_pipe,\n &buf,\n buf_size-1); \/\/ -1 because we'll append a zero\n close(glx::glxtest_pipe);\n glx::glxtest_pipe = 0;\n\n \/\/ bytesread < 0 would mean that the above read() call failed.\n \/\/ This should never happen. If it did, the outcome would be to blacklist anyway.\n if (bytesread < 0)\n bytesread = 0;\n\n \/\/ let buf be a zero-terminated string\n buf[bytesread] = 0;\n\n \/\/ Wait for the glxtest process to finish. This serves 2 purposes:\n \/\/ * avoid having a zombie glxtest process laying around\n \/\/ * get the glxtest process status info.\n int glxtest_status = 0;\n bool wait_for_glxtest_process = true;\n bool waiting_for_glxtest_process_failed = false;\n int waitpid_errno = 0;\n while(wait_for_glxtest_process) {\n wait_for_glxtest_process = false;\n if (waitpid(glx::glxtest_pid, &glxtest_status, 0) == -1) {\n waitpid_errno = errno;\n if (waitpid_errno == EINTR) {\n wait_for_glxtest_process = true;\n } else {\n \/\/ Bug 718629\n \/\/ ECHILD happens when the glxtest process got reaped got reaped after a PR_CreateProcess\n \/\/ as per bug 227246. This shouldn't matter, as we still seem to get the data\n \/\/ from the pipe, and if we didn't, the outcome would be to blacklist anyway.\n waiting_for_glxtest_process_failed = (waitpid_errno != ECHILD);\n }\n }\n }\n\n bool exited_with_error_code = !waiting_for_glxtest_process_failed &&\n WIFEXITED(glxtest_status) &&\n WEXITSTATUS(glxtest_status) != EXIT_SUCCESS;\n bool received_signal = !waiting_for_glxtest_process_failed &&\n WIFSIGNALED(glxtest_status);\n\n bool error = waiting_for_glxtest_process_failed || exited_with_error_code || received_signal;\n\n OString textureFromPixmap;\n OString *stringToFill = nullptr;\n char *bufptr = buf;\n if (!error) {\n while(true) {\n char *line = strtok_wrapper(\"\\n\", &bufptr);\n if (!line)\n break;\n if (stringToFill) {\n *stringToFill = OString(line);\n stringToFill = nullptr;\n }\n else if(!strcmp(line, \"VENDOR\"))\n stringToFill = &maVendor;\n else if(!strcmp(line, \"RENDERER\"))\n stringToFill = &maRenderer;\n else if(!strcmp(line, \"VERSION\"))\n stringToFill = &maVersion;\n else if(!strcmp(line, \"TFP\"))\n stringToFill = &textureFromPixmap;\n }\n }\n\n if (!strcmp(textureFromPixmap.getStr(), \"TRUE\"))\n mbHasTextureFromPixmap = true;\n\n \/\/ only useful for Linux kernel version check for FGLRX driver.\n \/\/ assumes X client == X server, which is sad.\n struct utsname unameobj;\n if (!uname(&unameobj))\n {\n maOS = OString(unameobj.sysname);\n maOSRelease = OString(unameobj.release);\n }\n\n \/\/ determine the major OpenGL version. That's the first integer in the version string.\n mnGLMajorVersion = strtol(maVersion.getStr(), 0, 10);\n\n \/\/ determine driver type (vendor) and where in the version string\n \/\/ the actual driver version numbers should be expected to be found (whereToReadVersionNumbers)\n const char *whereToReadVersionNumbers = nullptr;\n const char *Mesa_in_version_string = strstr(maVersion.getStr(), \"Mesa\");\n if (Mesa_in_version_string) {\n mbIsMesa = true;\n \/\/ with Mesa, the version string contains \"Mesa major.minor\" and that's all the version information we get:\n \/\/ there is no actual driver version info.\n whereToReadVersionNumbers = Mesa_in_version_string + strlen(\"Mesa\");\n if (strcasestr(maVendor.getStr(), \"nouveau\"))\n mbIsNouveau = true;\n if (strcasestr(maRenderer.getStr(), \"intel\")) \/\/ yes, intel is in the renderer string\n mbIsIntel = true;\n if (strcasestr(maRenderer.getStr(), \"llvmpipe\"))\n mbIsLlvmpipe = true;\n if (strcasestr(maRenderer.getStr(), \"software rasterizer\"))\n mbIsOldSwrast = true;\n } else if (strstr(maVendor.getStr(), \"NVIDIA Corporation\")) {\n mbIsNVIDIA = true;\n \/\/ with the NVIDIA driver, the version string contains \"NVIDIA major.minor\"\n \/\/ note that here the vendor and version strings behave differently, that's why we don't put this above\n \/\/ alongside Mesa_in_version_string.\n const char *NVIDIA_in_version_string = strstr(maVersion.getStr(), \"NVIDIA\");\n if (NVIDIA_in_version_string)\n whereToReadVersionNumbers = NVIDIA_in_version_string + strlen(\"NVIDIA\");\n } else if (strstr(maVendor.getStr(), \"ATI Technologies Inc\")) {\n mbIsFGLRX = true;\n \/\/ with the FGLRX driver, the version string only gives a OpenGL version :\/ so let's return that.\n \/\/ that can at least give a rough idea of how old the driver is.\n whereToReadVersionNumbers = maVersion.getStr();\n }\n\n \/\/ read major.minor version numbers of the driver (not to be confused with the OpenGL version)\n if (whereToReadVersionNumbers) {\n \/\/ copy into writable buffer, for tokenization\n strncpy(buf, whereToReadVersionNumbers, buf_size);\n bufptr = buf;\n\n \/\/ now try to read major.minor version numbers. In case of failure, gracefully exit: these numbers have\n \/\/ been initialized as 0 anyways\n char *token = strtok_wrapper(\".\", &bufptr);\n if (token) {\n mnMajorVersion = strtol(token, 0, 10);\n token = strtok_wrapper(\".\", &bufptr);\n if (token) {\n mnMinorVersion = strtol(token, 0, 10);\n token = strtok_wrapper(\".\", &bufptr);\n if (token)\n mnRevisionVersion = strtol(token, 0, 10);\n }\n }\n }\n}\n\nbool X11OpenGLDeviceInfo::isDeviceBlocked()\n{\n \/\/ don't even try to use OpenGL 1.x\n if (mnGLMajorVersion == 1)\n return true;\n\n SAL_INFO(\"vcl.opengl\", \"Vendor: \" << maVendor);\n SAL_INFO(\"vcl.opengl\", \"Renderer: \" << maRenderer);\n SAL_INFO(\"vcl.opengl\", \"Version: \" << maVersion);\n SAL_INFO(\"vcl.opengl\", \"OS: \" << maOS);\n SAL_INFO(\"vcl.opengl\", \"OSRelease: \" << maOSRelease);\n\n\n if (mbIsMesa) {\n if (mbIsNouveau && version(mnMajorVersion, mnMinorVersion) < version(8,0)) {\n SAL_WARN(\"vcl.opengl\", \"blocked driver version: old nouveau driver (requires mesa 8.0+)\");\n return true;\n }\n else if (version(mnMajorVersion, mnMinorVersion, mnRevisionVersion) < version(7,10,3)) {\n SAL_WARN(\"vcl.opengl\", \"blocked driver version: requires at least mesa 7.10.3\");\n return true;\n }\n else if (mbIsOldSwrast) {\n SAL_WARN(\"vcl.opengl\", \"blocked driver version: software rasterizer\");\n return true;\n }\n else if (mbIsLlvmpipe && version(mnMajorVersion, mnMinorVersion) < version(9, 1)) {\n \/\/ bug 791905, Mesa bug 57733, fixed in Mesa 9.1 according to\n \/\/ https:\/\/bugs.freedesktop.org\/show_bug.cgi?id=57733#c3\n SAL_WARN(\"vcl.opengl\", \"blocked driver version: fdo#57733\");\n return true;\n }\n\n } else if (mbIsNVIDIA) {\n if (version(mnMajorVersion, mnMinorVersion, mnRevisionVersion) < version(257,21)) {\n SAL_WARN(\"vcl.opengl\", \"blocked driver version: nvidia requires at least 257.21\");\n return true;\n }\n } else if (mbIsFGLRX) {\n \/\/ FGLRX does not report a driver version number, so we have the OpenGL version instead.\n \/\/ by requiring OpenGL 3, we effectively require recent drivers.\n if (version(mnMajorVersion, mnMinorVersion, mnRevisionVersion) < version(3, 0)) {\n SAL_WARN(\"vcl.opengl\", \"blocked driver version: require at least OpenGL 3 for fglrx\");\n return true;\n }\n \/\/ Bug 724640: FGLRX + Linux 2.6.32 is a crashy combo\n bool unknownOS = maOS.isEmpty() || maOSRelease.isEmpty();\n bool badOS = maOS.indexOf(\"Linux\") != -1 &&\n maOSRelease.indexOf(\"2.6.32\") != -1;\n if (unknownOS || badOS) {\n SAL_WARN(\"vcl.opengl\", \"blocked OS version with fglrx\");\n return true;\n }\n } else {\n \/\/ like on windows, let's block unknown vendors. Think of virtual machines.\n \/\/ Also, this case is hit whenever the GLXtest probe failed to get driver info or crashed.\n SAL_WARN(\"vcl.opengl\", \"unknown vendor => blocked\");\n return true;\n }\n\n return false;\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: TestSmplMail.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: hr $ $Date: 2007-01-02 16:13:41 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_shell.hxx\"\n\n\n\/\/-----------------------------------------------------------\n\/\/ interface includes\n\/\/-----------------------------------------------------------\n\n#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_REGISTRY_XSIMPLEREGISTRY_HPP_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_SYSTEM_XSIMPLEMAILCLIENTSUPPLIER_HPP_\n#include \n#endif\n\n#ifndef _CPPUHELPER_SERVICEFACTORY_HXX_\n#include \n#endif\n\n#ifndef _CPPUHELPER_SERVICEFACTORY_HXX_\n#include \n#endif\n\n#ifndef _RTL_USTRING_HXX_\n#include \n#endif\n\n#ifndef _SAL_TYPES_H_\n#include \n#endif\n\n#ifndef _OSL_DIAGNOSE_H_\n#include \n#endif\n\n#include \n#if defined _MSC_VER\n#pragma warning(push, 1)\n#endif\n#include \n#if defined _MSC_VER\n#pragma warning(pop)\n#endif\n\n#include \n\n\/\/--------------------------------------------------------------\n\/\/ namesapces\n\/\/--------------------------------------------------------------\n\nusing namespace ::rtl ;\nusing namespace ::cppu ;\nusing namespace ::com::sun::star::uno ;\nusing namespace ::com::sun::star::lang ;\nusing namespace std ;\nusing namespace com::sun::star::system;\n\n\/\/--------------------------------------------------------------\n\/\/ defines\n\/\/--------------------------------------------------------------\n\n#define RDB_SYSPATH \"D:\\\\Projects\\\\gsl\\\\shell\\\\wntmsci7\\\\bin\\\\applicat.rdb\"\n\n\/\/--------------------------------------------------------------\n\/\/ global variables\n\/\/--------------------------------------------------------------\n\nReference< XMultiServiceFactory > g_xFactory;\n\n\/\/--------------------------------------------------------------\n\/\/ main\n\/\/--------------------------------------------------------------\n\n\n\/\/ int SAL_CALL main(int nArgc, char* Argv[], char* pEnv[] )\n\/\/ make Warning free, leave out typename\nint SAL_CALL main(int , char*, char* )\n{\n \/\/-------------------------------------------------\n \/\/ get the global service-manager\n \/\/-------------------------------------------------\n\n \/\/ Get global factory for uno services.\n OUString rdbName = OUString( RTL_CONSTASCII_USTRINGPARAM( RDB_SYSPATH ) );\n Reference< XMultiServiceFactory > g_xFactory( createRegistryServiceFactory( rdbName ) );\n\n \/\/ Print a message if an error occured.\n if ( g_xFactory.is() == sal_False )\n {\n OSL_ENSURE(sal_False, \"Can't create RegistryServiceFactory\");\n return(-1);\n }\n\n printf(\"Creating RegistryServiceFactory successful\\n\");\n\n \/\/-------------------------------------------------\n \/\/ try to get an Interface to a XFilePicker Service\n \/\/-------------------------------------------------\n\n try\n {\n Reference< XSimpleMailClientSupplier > xSmplMailClientSuppl(\n g_xFactory->createInstance( OUString::createFromAscii( \"com.sun.star.system.SimpleSystemMail\" ) ), UNO_QUERY );\n\n if ( !xSmplMailClientSuppl.is() )\n {\n OSL_ENSURE( sal_False, \"Error creating SimpleSystemMail Service\" );\n return(-1);\n }\n\n Reference< XSimpleMailClient > xSmplMailClient(\n xSmplMailClientSuppl->querySimpleMailClient( ) );\n\n if ( xSmplMailClient.is( ) )\n {\n Reference< XSimpleMailMessage > xSmplMailMsg(\n xSmplMailClient->createSimpleMailMessage( ) );\n\n if ( xSmplMailMsg.is( ) )\n {\n xSmplMailMsg->setRecipient( OUString::createFromAscii(\"tino.rachui@germany.sun.com\") );\n xSmplMailMsg->setOriginator( OUString::createFromAscii( \"tino.rachui@germany.sun.com\" ) );\n\n Sequence< OUString > ccRecips( 1 );\n ccRecips[0] = OUString::createFromAscii( \"tino.rachui@germany.sun.com\" );\n\n xSmplMailMsg->setCcRecipient( ccRecips );\n\n Sequence< OUString > bccRecips( 1 );\n bccRecips[0] = OUString::createFromAscii( \"tino.rachui@germany.sun.com\" );\n\n xSmplMailMsg->setBccRecipient( bccRecips );\n\n xSmplMailMsg->setSubject( OUString::createFromAscii( \"Mapi Test\" ) );\n\n Sequence< OUString > attachements( 2 );\n\n OUString aFile = OUString::createFromAscii( \"D:\\\\Projects\\\\gsl\\\\shell\\\\wntmsci7\\\\bin\\\\testprx.exe\" );\n OUString aFileURL;\n\n osl::FileBase::getFileURLFromSystemPath( aFile, aFileURL );\n attachements[0] = aFileURL;\n\n aFile = OUString::createFromAscii( \"D:\\\\Projects\\\\gsl\\\\shell\\\\wntmsci7\\\\bin\\\\testsyssh.exe\" );\n osl::FileBase::getFileURLFromSystemPath( aFile, aFileURL );\n\n attachements[1] = aFile;\n\n xSmplMailMsg->setAttachement( attachements );\n\n xSmplMailClient->sendSimpleMailMessage( xSmplMailMsg, 0 );\n }\n }\n }\n catch( Exception& )\n {\n }\n\n \/\/--------------------------------------------------\n \/\/ shutdown\n \/\/--------------------------------------------------\n\n \/\/ Cast factory to XComponent\n Reference< XComponent > xComponent( g_xFactory, UNO_QUERY );\n\n \/\/ Print a message if an error occured.\n if ( xComponent.is() == sal_False )\n {\n OSL_ENSURE(sal_False, \"Error shuting down\");\n }\n\n \/\/ Dispose and clear factory\n xComponent->dispose();\n g_xFactory.clear();\n g_xFactory = Reference< XMultiServiceFactory >();\n\n printf(\"Test successful\\n\");\n\n return 0;\n}\nINTEGRATION: CWS changefileheader (1.6.100); FILE MERGED 2008\/04\/01 15:40:30 thb 1.6.100.3: #i85898# Stripping all external header guards 2008\/04\/01 12:41:18 thb 1.6.100.2: #i85898# Stripping all external header guards 2008\/03\/31 13:17:15 rt 1.6.100.1: #i87441# Change license header to LPGL v3.\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: TestSmplMail.cxx,v $\n * $Revision: 1.7 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_shell.hxx\"\n\n\n\/\/-----------------------------------------------------------\n\/\/ interface includes\n\/\/-----------------------------------------------------------\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#if defined _MSC_VER\n#pragma warning(push, 1)\n#endif\n#include \n#if defined _MSC_VER\n#pragma warning(pop)\n#endif\n\n#include \n\n\/\/--------------------------------------------------------------\n\/\/ namesapces\n\/\/--------------------------------------------------------------\n\nusing namespace ::rtl ;\nusing namespace ::cppu ;\nusing namespace ::com::sun::star::uno ;\nusing namespace ::com::sun::star::lang ;\nusing namespace std ;\nusing namespace com::sun::star::system;\n\n\/\/--------------------------------------------------------------\n\/\/ defines\n\/\/--------------------------------------------------------------\n\n#define RDB_SYSPATH \"D:\\\\Projects\\\\gsl\\\\shell\\\\wntmsci7\\\\bin\\\\applicat.rdb\"\n\n\/\/--------------------------------------------------------------\n\/\/ global variables\n\/\/--------------------------------------------------------------\n\nReference< XMultiServiceFactory > g_xFactory;\n\n\/\/--------------------------------------------------------------\n\/\/ main\n\/\/--------------------------------------------------------------\n\n\n\/\/ int SAL_CALL main(int nArgc, char* Argv[], char* pEnv[] )\n\/\/ make Warning free, leave out typename\nint SAL_CALL main(int , char*, char* )\n{\n \/\/-------------------------------------------------\n \/\/ get the global service-manager\n \/\/-------------------------------------------------\n\n \/\/ Get global factory for uno services.\n OUString rdbName = OUString( RTL_CONSTASCII_USTRINGPARAM( RDB_SYSPATH ) );\n Reference< XMultiServiceFactory > g_xFactory( createRegistryServiceFactory( rdbName ) );\n\n \/\/ Print a message if an error occured.\n if ( g_xFactory.is() == sal_False )\n {\n OSL_ENSURE(sal_False, \"Can't create RegistryServiceFactory\");\n return(-1);\n }\n\n printf(\"Creating RegistryServiceFactory successful\\n\");\n\n \/\/-------------------------------------------------\n \/\/ try to get an Interface to a XFilePicker Service\n \/\/-------------------------------------------------\n\n try\n {\n Reference< XSimpleMailClientSupplier > xSmplMailClientSuppl(\n g_xFactory->createInstance( OUString::createFromAscii( \"com.sun.star.system.SimpleSystemMail\" ) ), UNO_QUERY );\n\n if ( !xSmplMailClientSuppl.is() )\n {\n OSL_ENSURE( sal_False, \"Error creating SimpleSystemMail Service\" );\n return(-1);\n }\n\n Reference< XSimpleMailClient > xSmplMailClient(\n xSmplMailClientSuppl->querySimpleMailClient( ) );\n\n if ( xSmplMailClient.is( ) )\n {\n Reference< XSimpleMailMessage > xSmplMailMsg(\n xSmplMailClient->createSimpleMailMessage( ) );\n\n if ( xSmplMailMsg.is( ) )\n {\n xSmplMailMsg->setRecipient( OUString::createFromAscii(\"tino.rachui@germany.sun.com\") );\n xSmplMailMsg->setOriginator( OUString::createFromAscii( \"tino.rachui@germany.sun.com\" ) );\n\n Sequence< OUString > ccRecips( 1 );\n ccRecips[0] = OUString::createFromAscii( \"tino.rachui@germany.sun.com\" );\n\n xSmplMailMsg->setCcRecipient( ccRecips );\n\n Sequence< OUString > bccRecips( 1 );\n bccRecips[0] = OUString::createFromAscii( \"tino.rachui@germany.sun.com\" );\n\n xSmplMailMsg->setBccRecipient( bccRecips );\n\n xSmplMailMsg->setSubject( OUString::createFromAscii( \"Mapi Test\" ) );\n\n Sequence< OUString > attachements( 2 );\n\n OUString aFile = OUString::createFromAscii( \"D:\\\\Projects\\\\gsl\\\\shell\\\\wntmsci7\\\\bin\\\\testprx.exe\" );\n OUString aFileURL;\n\n osl::FileBase::getFileURLFromSystemPath( aFile, aFileURL );\n attachements[0] = aFileURL;\n\n aFile = OUString::createFromAscii( \"D:\\\\Projects\\\\gsl\\\\shell\\\\wntmsci7\\\\bin\\\\testsyssh.exe\" );\n osl::FileBase::getFileURLFromSystemPath( aFile, aFileURL );\n\n attachements[1] = aFile;\n\n xSmplMailMsg->setAttachement( attachements );\n\n xSmplMailClient->sendSimpleMailMessage( xSmplMailMsg, 0 );\n }\n }\n }\n catch( Exception& )\n {\n }\n\n \/\/--------------------------------------------------\n \/\/ shutdown\n \/\/--------------------------------------------------\n\n \/\/ Cast factory to XComponent\n Reference< XComponent > xComponent( g_xFactory, UNO_QUERY );\n\n \/\/ Print a message if an error occured.\n if ( xComponent.is() == sal_False )\n {\n OSL_ENSURE(sal_False, \"Error shuting down\");\n }\n\n \/\/ Dispose and clear factory\n xComponent->dispose();\n g_xFactory.clear();\n g_xFactory = Reference< XMultiServiceFactory >();\n\n printf(\"Test successful\\n\");\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/* -*- mode: C++; c-file-style: \"gnu\" -*-\n\n This file is part of kdepim.\n Copyright (c) 2004 KDEPIM developers\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n Boston, MA 02111-1307, USA.\n*\/\n\n#include \"email.h\"\n#include \n#include \n#include \n\n\/\/-----------------------------------------------------------------------------\nQStringList KPIM::splitEmailAddrList(const QString& aStr)\n{\n \/\/ Features:\n \/\/ - always ignores quoted characters\n \/\/ - ignores everything (including parentheses and commas)\n \/\/ inside quoted strings\n \/\/ - supports nested comments\n \/\/ - ignores everything (including double quotes and commas)\n \/\/ inside comments\n\n QStringList list;\n\n if (aStr.isEmpty())\n return list;\n\n QString addr;\n uint addrstart = 0;\n int commentlevel = 0;\n bool insidequote = false;\n\n for (uint index=0; index 0)\n commentlevel--;\n else {\n kdDebug(5300) << \"Error in address splitting: Unmatched ')'\"\n << endl;\n return list;\n }\n }\n break;\n case '\\\\' : \/\/ quoted character\n index++; \/\/ ignore the quoted character\n break;\n case ',' :\n if (!insidequote && (commentlevel == 0)) {\n addr = aStr.mid(addrstart, index-addrstart);\n if (!addr.isEmpty())\n list += addr.simplifyWhiteSpace();\n addrstart = index+1;\n }\n break;\n }\n }\n \/\/ append the last address to the list\n if (!insidequote && (commentlevel == 0)) {\n addr = aStr.mid(addrstart, aStr.length()-addrstart);\n if (!addr.isEmpty())\n list += addr.simplifyWhiteSpace();\n }\n else\n kdDebug(5300) << \"Error in address splitting: \"\n << \"Unexpected end of address list\"\n << endl;\n\n return list;\n}\n\n\/\/-----------------------------------------------------------------------------\nKPIM::EmailParseResult KPIM::isValidEmailAddress( const QString& aStr )\n{\n \/\/ If we are passed an empty string bail right away no need to process further \n \/\/ and waste resources\n if ( aStr.isEmpty() ) {\n return AddressEmpty;\n }\n\n \/\/ count how many @'s are in the string that is passed to us\n \/\/ if 0 or > 1 take action\n \/\/ at this point to many @'s cannot bail out right away since\n \/\/ @ is allowed in qoutes, so we use a bool to keep track\n \/\/ and then make a judgement further down in the parser\n \/\/ FIXME count only @ not in double quotes\n\n bool tooManyAtsFlag = false;\n\n int atCount = aStr.contains('@');\n if ( atCount > 1 ) {\n tooManyAtsFlag = true;;\n } else if ( atCount == 0 ) {\n\t return TooFewAts;\n }\n\n \/\/ The main parser, try and catch all weird and wonderful\n \/\/ mistakes users and\/or machines can create\n\n enum { TopLevel, InComment, InAngleAddress } context = TopLevel;\n bool inQuotedString = false;\n int commentLevel = 0;\n\n unsigned int strlen = aStr.length();\n\n for ( unsigned int index=0; index < strlen; index++ ) {\n switch ( context ) {\n case TopLevel : {\n switch ( aStr[index].latin1() ) {\n case '\"' : inQuotedString = !inQuotedString; \n break;\n case '(' : \n if ( !inQuotedString ) {\n context = InComment;\n commentLevel = 1;\n }\n break;\n case '<' : \n if ( !inQuotedString ) {\n context = InAngleAddress;\n }\n break;\n case '\\\\' : \/\/ quoted character\n ++index; \/\/ skip the '\\'\n if ( ++index > strlen )\n return UnexpectedEnd;\n break;\n case ',' : \n if ( !inQuotedString )\n return UnexpectedComma;\n break;\n case ')' : \n if ( !inQuotedString )\n return UnbalancedParens;\n break;\n case '>' : \n if ( !inQuotedString )\n return UnopenedAngleAddr;\n break;\n case '@' : \n if ( !inQuotedString ) {\n if ( index == 0 ) { \/\/ Missing local part\n return MissingLocalPart;\n } else if( index == strlen-1 ) {\n return MissingDomainPart;\n break;\n } \n } else if ( inQuotedString ) {\n --atCount;\n if ( atCount == 1 ) {\n tooManyAtsFlag = false;\n }\n }\n break;\n } \n break; \n }\n case InComment : {\n switch ( aStr[index] ) {\n case '(' : ++commentLevel;\n break;\n case ')' : --commentLevel;\n if ( commentLevel == 0 ) {\n context = TopLevel;\n }\n break;\n case '\\\\' : \/\/ quoted character\n ++index; \/\/ skip the '\\'\n if ( ++index > strlen )\n return UnexpectedEnd;\n break;\n }\n break;\n }\n\n case InAngleAddress : {\n switch ( aStr[index] ) {\n case '\"' : inQuotedString = !inQuotedString;\n break;\n case '@' :\n if ( inQuotedString ) {\n --atCount;\n if ( atCount == 1 ) {\n tooManyAtsFlag = false;\n }\n }\n break;\n case '>' : \n if ( !inQuotedString ) {\n context = TopLevel;\n break;\n }\n break;\n case '\\\\' : \/\/ quoted character\n ++index; \/\/ skip the '\\'\n if ( ++index > strlen )\n return UnexpectedEnd;\n break;\n }\n break;\n }\n }\n }\n if ( context == InComment )\n return UnbalancedParens;\n \n if ( context == TopLevel && !tooManyAtsFlag ) {\n return AddressOk;\n }\n\n if ( context == InAngleAddress )\n return UnclosedAngleAddr;\n\n if ( tooManyAtsFlag ) {\n return TooManyAts;\n }\n} \n\n\/\/-----------------------------------------------------------------------------\nQString KPIM::emailParseResultToString( EmailParseResult errorCode )\n{\n switch ( errorCode ) {\n case TooManyAts : \n return i18n(\"The email address you entered is not valid because it \"\n \"contains more than one @ \"\n \"you will not create valid messages if you do not \"\n \"change your address.\");\n case TooFewAts : \n return i18n(\"The email address you entered is not valid because it \"\n \"does not contain a @ \"\n \"you will not create valid messages if you do not \"\n \"change your address.\");\n case AddressEmpty : \n return i18n(\"You have to enter something in the email address field.\");\n case MissingLocalPart : \n return i18n(\"The email address you entered is not valid because it \"\n \"does not contain a local part.\");\n case MissingDomainPart : \n return i18n(\"The email address you entered is not valid because it \"\n \"does not contain a domain part.\");\n case UnbalancedParens : \n return i18n(\"The email address you entered is not valid because it \"\n \"contains unclosed comments\/brackets.\");\n case AddressOk : \n return i18n(\"The email address you entered is valid.\");\n case UnclosedAngleAddr : \n return i18n(\"The email address you entered is not valid because it \"\n \"contains an unclosed anglebracket.\");\n case UnopenedAngleAddr : \n return i18n(\"The email address you entered is not valid because it \"\n \"contains an unopened anglebracket.\");\n case UnexpectedComma :\n return i18n(\"The email address you have entered is not valid because it \"\n \"contains an unexpected comma.\");\n case UnexpectedEnd : \n return i18n(\"The email address you entered is not valid because it ended \"\n \"unexpectadly, this probably means you have used an escaping type \"\n \"character like an \\\\ as the last character in your email \"\n \"address.\");\n }\n return i18n(\"Unknown problem with email address\");\n}\n\n\/\/-----------------------------------------------------------------------------\nbool KPIM::isValidSimpleEmailAddress( const QString& aStr )\n{\n \/\/ If we are passed an empty string bail right away no need to process further\n \/\/ and waste resources\n if ( aStr.isEmpty() ) {\n return false;\n }\n\n int atChar = aStr.findRev( '@' );\n QString domainPart = aStr.mid( atChar + 1);\n QString localPart = aStr.left( atChar );\n bool tooManyAtsFlag = false;\n bool inQuotedString = false;\n int atCount = localPart.contains( '@' );\n\n unsigned int strlen = localPart.length();\n for ( unsigned int index=0; index < strlen; index++ ) {\n switch( localPart[ index ].latin1() ) {\n case '\"' : inQuotedString = !inQuotedString;\n break;\n case '@' :\n if ( inQuotedString ) {\n --atCount;\n if ( atCount == 0 ) {\n tooManyAtsFlag = false;\n }\n }\n break;\n }\n }\n\n QString addrRx = \"[a-zA-Z]*[\\\\w.-]*[a-zA-Z0-9]@\";\n if ( localPart[ 0 ] == '\\\"' || localPart[ localPart.length()-1 ] == '\\\"' ) {\n addrRx = \"\\\"[a-zA-Z@]*[\\\\w.@-]*[a-zA-Z0-9@]\\\"@\";\n }\n if ( domainPart[ 0 ] == '[' || domainPart[ domainPart.length()-1 ] == ']' ) {\n addrRx += \"\\\\[[0-9]{,3}(\\\\.[0-9]{,3}){3}\\\\]\";\n } else {\n addrRx += \"[\\\\w-]+(\\\\.[\\\\w-]+)\";\n }\n QRegExp rx( addrRx );\n return rx.exactMatch( aStr ) && !tooManyAtsFlag;\n}\n\n\/\/-----------------------------------------------------------------------------\nQCString KPIM::getEmailAddr(const QString& aStr)\n{\n int a, i, j, len, found = 0;\n QChar c;\n \/\/ Find the '@' in the email address:\n a = aStr.find('@');\n if (a<0) return aStr.latin1();\n \/\/ Loop backwards until we find '<', '(', ' ', or beginning of string.\n for (i = a - 1; i >= 0; i--) {\n c = aStr[i];\n if (c == '<' || c == '(' || c == ' ') found = 1;\n if (found) break;\n }\n \/\/ Reset found for next loop.\n found = 0;\n \/\/ Loop forwards until we find '>', ')', ' ', or end of string.\n for (j = a + 1; j < (int)aStr.length(); j++) {\n c = aStr[j];\n if (c == '>' || c == ')' || c == ' ') found = 1;\n if (found) break;\n }\n \/\/ Calculate the length and return the result.\n len = j - (i + 1);\n return aStr.mid(i+1,len).latin1();\n}\n\nbool KPIM::getNameAndMail(const QString& aStr, QString& name, QString& mail)\n{\n name = QString::null;\n mail = QString::null;\n\n const int len=aStr.length();\n const char cQuotes = '\"';\n\n bool bInComment, bInQuotesOutsideOfEmail;\n int i=0, iAd=0, iMailStart=0, iMailEnd=0;\n QChar c;\n\n \/\/ Find the '@' of the email address\n \/\/ skipping all '@' inside \"(...)\" comments:\n bInComment = false;\n while( i < len ){\n c = aStr[i];\n if( !bInComment ){\n if( '(' == c ){\n bInComment = true;\n }else{\n if( '@' == c ){\n iAd = i;\n break; \/\/ found it\n }\n }\n }else{\n if( ')' == c ){\n bInComment = false;\n }\n }\n ++i;\n }\n\n if( !iAd ){\n \/\/ We suppose the user is typing the string manually and just\n \/\/ has not finished typing the mail address part.\n \/\/ So we take everything that's left of the '<' as name and the rest as mail\n for( i = 0; len > i; ++i ) {\n c = aStr[i];\n if( '<' != c )\n name.append( c );\n else\n break;\n }\n mail = aStr.mid( i+1 );\n if ( mail.endsWith( \">\" ) )\n mail.truncate( mail.length() - 1 );\n\n }else{\n\n \/\/ Loop backwards until we find the start of the string\n \/\/ or a ',' that is outside of a comment\n \/\/ and outside of quoted text before the leading '<'.\n bInComment = false;\n bInQuotesOutsideOfEmail = false;\n for( i = iAd-1; 0 <= i; --i ) {\n c = aStr[i];\n if( bInComment ){\n if( '(' == c ){\n if( !name.isEmpty() )\n name.prepend( ' ' );\n bInComment = false;\n }else{\n name.prepend( c ); \/\/ all comment stuff is part of the name\n }\n }else if( bInQuotesOutsideOfEmail ){\n if( cQuotes == c )\n bInQuotesOutsideOfEmail = false;\n else\n name.prepend( c );\n }else{\n \/\/ found the start of this addressee ?\n if( ',' == c )\n break;\n \/\/ stuff is before the leading '<' ?\n if( iMailStart ){\n if( cQuotes == c )\n bInQuotesOutsideOfEmail = true; \/\/ end of quoted text found\n else\n name.prepend( c );\n }else{\n switch( c ){\n case '<':\n iMailStart = i;\n break;\n case ')':\n if( !name.isEmpty() )\n name.prepend( ' ' );\n bInComment = true;\n break;\n default:\n if( ' ' != c )\n mail.prepend( c );\n }\n }\n }\n }\n\n name = name.simplifyWhiteSpace();\n mail = mail.simplifyWhiteSpace();\n\n if( mail.isEmpty() )\n return false;\n\n mail.append('@');\n\n \/\/ Loop forward until we find the end of the string\n \/\/ or a ',' that is outside of a comment\n \/\/ and outside of quoted text behind the trailing '>'.\n bInComment = false;\n bInQuotesOutsideOfEmail = false;\n for( i = iAd+1; len > i; ++i ) {\n c = aStr[i];\n if( bInComment ){\n if( ')' == c ){\n if( !name.isEmpty() )\n name.append( ' ' );\n bInComment = false;\n }else{\n name.append( c ); \/\/ all comment stuff is part of the name\n }\n }else if( bInQuotesOutsideOfEmail ){\n if( cQuotes == c )\n bInQuotesOutsideOfEmail = false;\n else\n name.append( c );\n }else{\n \/\/ found the end of this addressee ?\n if( ',' == c )\n break;\n \/\/ stuff is behind the trailing '>' ?\n if( iMailEnd ){\n if( cQuotes == c )\n bInQuotesOutsideOfEmail = true; \/\/ start of quoted text found\n else\n name.append( c );\n }else{\n switch( c ){\n case '>':\n iMailEnd = i;\n break;\n case '(':\n if( !name.isEmpty() )\n name.append( ' ' );\n bInComment = true;\n break;\n default:\n if( ' ' != c )\n mail.append( c );\n }\n }\n }\n }\n }\n\n name = name.simplifyWhiteSpace();\n mail = mail.simplifyWhiteSpace();\n\n return ! (name.isEmpty() || mail.isEmpty());\n}\n\nbool KPIM::compareEmail( const QString& email1, const QString& email2,\n bool matchName )\n{\n QString e1Name, e1Email, e2Name, e2Email;\n\n getNameAndMail( email1, e1Name, e1Email );\n getNameAndMail( email2, e2Name, e2Email );\n\n return e1Email == e2Email &&\n ( !matchName || ( e1Name == e2Name ) );\n}\nFix compiler warning\/* -*- mode: C++; c-file-style: \"gnu\" -*-\n\n This file is part of kdepim.\n Copyright (c) 2004 KDEPIM developers\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n Boston, MA 02111-1307, USA.\n*\/\n\n#include \"email.h\"\n#include \n#include \n#include \n\n\/\/-----------------------------------------------------------------------------\nQStringList KPIM::splitEmailAddrList(const QString& aStr)\n{\n \/\/ Features:\n \/\/ - always ignores quoted characters\n \/\/ - ignores everything (including parentheses and commas)\n \/\/ inside quoted strings\n \/\/ - supports nested comments\n \/\/ - ignores everything (including double quotes and commas)\n \/\/ inside comments\n\n QStringList list;\n\n if (aStr.isEmpty())\n return list;\n\n QString addr;\n uint addrstart = 0;\n int commentlevel = 0;\n bool insidequote = false;\n\n for (uint index=0; index 0)\n commentlevel--;\n else {\n kdDebug(5300) << \"Error in address splitting: Unmatched ')'\"\n << endl;\n return list;\n }\n }\n break;\n case '\\\\' : \/\/ quoted character\n index++; \/\/ ignore the quoted character\n break;\n case ',' :\n if (!insidequote && (commentlevel == 0)) {\n addr = aStr.mid(addrstart, index-addrstart);\n if (!addr.isEmpty())\n list += addr.simplifyWhiteSpace();\n addrstart = index+1;\n }\n break;\n }\n }\n \/\/ append the last address to the list\n if (!insidequote && (commentlevel == 0)) {\n addr = aStr.mid(addrstart, aStr.length()-addrstart);\n if (!addr.isEmpty())\n list += addr.simplifyWhiteSpace();\n }\n else\n kdDebug(5300) << \"Error in address splitting: \"\n << \"Unexpected end of address list\"\n << endl;\n\n return list;\n}\n\n\/\/-----------------------------------------------------------------------------\nKPIM::EmailParseResult KPIM::isValidEmailAddress( const QString& aStr )\n{\n \/\/ If we are passed an empty string bail right away no need to process further \n \/\/ and waste resources\n if ( aStr.isEmpty() ) {\n return AddressEmpty;\n }\n\n \/\/ count how many @'s are in the string that is passed to us\n \/\/ if 0 or > 1 take action\n \/\/ at this point to many @'s cannot bail out right away since\n \/\/ @ is allowed in qoutes, so we use a bool to keep track\n \/\/ and then make a judgement further down in the parser\n \/\/ FIXME count only @ not in double quotes\n\n bool tooManyAtsFlag = false;\n\n int atCount = aStr.contains('@');\n if ( atCount > 1 ) {\n tooManyAtsFlag = true;;\n } else if ( atCount == 0 ) {\n\t return TooFewAts;\n }\n\n \/\/ The main parser, try and catch all weird and wonderful\n \/\/ mistakes users and\/or machines can create\n\n enum { TopLevel, InComment, InAngleAddress } context = TopLevel;\n bool inQuotedString = false;\n int commentLevel = 0;\n\n unsigned int strlen = aStr.length();\n\n for ( unsigned int index=0; index < strlen; index++ ) {\n switch ( context ) {\n case TopLevel : {\n switch ( aStr[index].latin1() ) {\n case '\"' : inQuotedString = !inQuotedString; \n break;\n case '(' : \n if ( !inQuotedString ) {\n context = InComment;\n commentLevel = 1;\n }\n break;\n case '<' : \n if ( !inQuotedString ) {\n context = InAngleAddress;\n }\n break;\n case '\\\\' : \/\/ quoted character\n ++index; \/\/ skip the '\\'\n if ( ++index > strlen )\n return UnexpectedEnd;\n break;\n case ',' : \n if ( !inQuotedString )\n return UnexpectedComma;\n break;\n case ')' : \n if ( !inQuotedString )\n return UnbalancedParens;\n break;\n case '>' : \n if ( !inQuotedString )\n return UnopenedAngleAddr;\n break;\n case '@' : \n if ( !inQuotedString ) {\n if ( index == 0 ) { \/\/ Missing local part\n return MissingLocalPart;\n } else if( index == strlen-1 ) {\n return MissingDomainPart;\n break;\n } \n } else if ( inQuotedString ) {\n --atCount;\n if ( atCount == 1 ) {\n tooManyAtsFlag = false;\n }\n }\n break;\n } \n break; \n }\n case InComment : {\n switch ( aStr[index] ) {\n case '(' : ++commentLevel;\n break;\n case ')' : --commentLevel;\n if ( commentLevel == 0 ) {\n context = TopLevel;\n }\n break;\n case '\\\\' : \/\/ quoted character\n ++index; \/\/ skip the '\\'\n if ( ++index > strlen )\n return UnexpectedEnd;\n break;\n }\n break;\n }\n\n case InAngleAddress : {\n switch ( aStr[index] ) {\n case '\"' : inQuotedString = !inQuotedString;\n break;\n case '@' :\n if ( inQuotedString ) {\n --atCount;\n if ( atCount == 1 ) {\n tooManyAtsFlag = false;\n }\n }\n break;\n case '>' : \n if ( !inQuotedString ) {\n context = TopLevel;\n break;\n }\n break;\n case '\\\\' : \/\/ quoted character\n ++index; \/\/ skip the '\\'\n if ( ++index > strlen )\n return UnexpectedEnd;\n break;\n }\n break;\n }\n }\n }\n if ( context == InComment )\n return UnbalancedParens;\n \n if ( context == TopLevel && !tooManyAtsFlag ) {\n return AddressOk;\n }\n\n if ( context == InAngleAddress )\n return UnclosedAngleAddr;\n\n if ( tooManyAtsFlag ) {\n return TooManyAts;\n }\n return AddressEmpty;\n} \n\n\/\/-----------------------------------------------------------------------------\nQString KPIM::emailParseResultToString( EmailParseResult errorCode )\n{\n switch ( errorCode ) {\n case TooManyAts : \n return i18n(\"The email address you entered is not valid because it \"\n \"contains more than one @ \"\n \"you will not create valid messages if you do not \"\n \"change your address.\");\n case TooFewAts : \n return i18n(\"The email address you entered is not valid because it \"\n \"does not contain a @ \"\n \"you will not create valid messages if you do not \"\n \"change your address.\");\n case AddressEmpty : \n return i18n(\"You have to enter something in the email address field.\");\n case MissingLocalPart : \n return i18n(\"The email address you entered is not valid because it \"\n \"does not contain a local part.\");\n case MissingDomainPart : \n return i18n(\"The email address you entered is not valid because it \"\n \"does not contain a domain part.\");\n case UnbalancedParens : \n return i18n(\"The email address you entered is not valid because it \"\n \"contains unclosed comments\/brackets.\");\n case AddressOk : \n return i18n(\"The email address you entered is valid.\");\n case UnclosedAngleAddr : \n return i18n(\"The email address you entered is not valid because it \"\n \"contains an unclosed anglebracket.\");\n case UnopenedAngleAddr : \n return i18n(\"The email address you entered is not valid because it \"\n \"contains an unopened anglebracket.\");\n case UnexpectedComma :\n return i18n(\"The email address you have entered is not valid because it \"\n \"contains an unexpected comma.\");\n case UnexpectedEnd : \n return i18n(\"The email address you entered is not valid because it ended \"\n \"unexpectadly, this probably means you have used an escaping type \"\n \"character like an \\\\ as the last character in your email \"\n \"address.\");\n }\n return i18n(\"Unknown problem with email address\");\n}\n\n\/\/-----------------------------------------------------------------------------\nbool KPIM::isValidSimpleEmailAddress( const QString& aStr )\n{\n \/\/ If we are passed an empty string bail right away no need to process further\n \/\/ and waste resources\n if ( aStr.isEmpty() ) {\n return false;\n }\n\n int atChar = aStr.findRev( '@' );\n QString domainPart = aStr.mid( atChar + 1);\n QString localPart = aStr.left( atChar );\n bool tooManyAtsFlag = false;\n bool inQuotedString = false;\n int atCount = localPart.contains( '@' );\n\n unsigned int strlen = localPart.length();\n for ( unsigned int index=0; index < strlen; index++ ) {\n switch( localPart[ index ].latin1() ) {\n case '\"' : inQuotedString = !inQuotedString;\n break;\n case '@' :\n if ( inQuotedString ) {\n --atCount;\n if ( atCount == 0 ) {\n tooManyAtsFlag = false;\n }\n }\n break;\n }\n }\n\n QString addrRx = \"[a-zA-Z]*[\\\\w.-]*[a-zA-Z0-9]@\";\n if ( localPart[ 0 ] == '\\\"' || localPart[ localPart.length()-1 ] == '\\\"' ) {\n addrRx = \"\\\"[a-zA-Z@]*[\\\\w.@-]*[a-zA-Z0-9@]\\\"@\";\n }\n if ( domainPart[ 0 ] == '[' || domainPart[ domainPart.length()-1 ] == ']' ) {\n addrRx += \"\\\\[[0-9]{,3}(\\\\.[0-9]{,3}){3}\\\\]\";\n } else {\n addrRx += \"[\\\\w-]+(\\\\.[\\\\w-]+)\";\n }\n QRegExp rx( addrRx );\n return rx.exactMatch( aStr ) && !tooManyAtsFlag;\n}\n\n\/\/-----------------------------------------------------------------------------\nQCString KPIM::getEmailAddr(const QString& aStr)\n{\n int a, i, j, len, found = 0;\n QChar c;\n \/\/ Find the '@' in the email address:\n a = aStr.find('@');\n if (a<0) return aStr.latin1();\n \/\/ Loop backwards until we find '<', '(', ' ', or beginning of string.\n for (i = a - 1; i >= 0; i--) {\n c = aStr[i];\n if (c == '<' || c == '(' || c == ' ') found = 1;\n if (found) break;\n }\n \/\/ Reset found for next loop.\n found = 0;\n \/\/ Loop forwards until we find '>', ')', ' ', or end of string.\n for (j = a + 1; j < (int)aStr.length(); j++) {\n c = aStr[j];\n if (c == '>' || c == ')' || c == ' ') found = 1;\n if (found) break;\n }\n \/\/ Calculate the length and return the result.\n len = j - (i + 1);\n return aStr.mid(i+1,len).latin1();\n}\n\nbool KPIM::getNameAndMail(const QString& aStr, QString& name, QString& mail)\n{\n name = QString::null;\n mail = QString::null;\n\n const int len=aStr.length();\n const char cQuotes = '\"';\n\n bool bInComment, bInQuotesOutsideOfEmail;\n int i=0, iAd=0, iMailStart=0, iMailEnd=0;\n QChar c;\n\n \/\/ Find the '@' of the email address\n \/\/ skipping all '@' inside \"(...)\" comments:\n bInComment = false;\n while( i < len ){\n c = aStr[i];\n if( !bInComment ){\n if( '(' == c ){\n bInComment = true;\n }else{\n if( '@' == c ){\n iAd = i;\n break; \/\/ found it\n }\n }\n }else{\n if( ')' == c ){\n bInComment = false;\n }\n }\n ++i;\n }\n\n if( !iAd ){\n \/\/ We suppose the user is typing the string manually and just\n \/\/ has not finished typing the mail address part.\n \/\/ So we take everything that's left of the '<' as name and the rest as mail\n for( i = 0; len > i; ++i ) {\n c = aStr[i];\n if( '<' != c )\n name.append( c );\n else\n break;\n }\n mail = aStr.mid( i+1 );\n if ( mail.endsWith( \">\" ) )\n mail.truncate( mail.length() - 1 );\n\n }else{\n\n \/\/ Loop backwards until we find the start of the string\n \/\/ or a ',' that is outside of a comment\n \/\/ and outside of quoted text before the leading '<'.\n bInComment = false;\n bInQuotesOutsideOfEmail = false;\n for( i = iAd-1; 0 <= i; --i ) {\n c = aStr[i];\n if( bInComment ){\n if( '(' == c ){\n if( !name.isEmpty() )\n name.prepend( ' ' );\n bInComment = false;\n }else{\n name.prepend( c ); \/\/ all comment stuff is part of the name\n }\n }else if( bInQuotesOutsideOfEmail ){\n if( cQuotes == c )\n bInQuotesOutsideOfEmail = false;\n else\n name.prepend( c );\n }else{\n \/\/ found the start of this addressee ?\n if( ',' == c )\n break;\n \/\/ stuff is before the leading '<' ?\n if( iMailStart ){\n if( cQuotes == c )\n bInQuotesOutsideOfEmail = true; \/\/ end of quoted text found\n else\n name.prepend( c );\n }else{\n switch( c ){\n case '<':\n iMailStart = i;\n break;\n case ')':\n if( !name.isEmpty() )\n name.prepend( ' ' );\n bInComment = true;\n break;\n default:\n if( ' ' != c )\n mail.prepend( c );\n }\n }\n }\n }\n\n name = name.simplifyWhiteSpace();\n mail = mail.simplifyWhiteSpace();\n\n if( mail.isEmpty() )\n return false;\n\n mail.append('@');\n\n \/\/ Loop forward until we find the end of the string\n \/\/ or a ',' that is outside of a comment\n \/\/ and outside of quoted text behind the trailing '>'.\n bInComment = false;\n bInQuotesOutsideOfEmail = false;\n for( i = iAd+1; len > i; ++i ) {\n c = aStr[i];\n if( bInComment ){\n if( ')' == c ){\n if( !name.isEmpty() )\n name.append( ' ' );\n bInComment = false;\n }else{\n name.append( c ); \/\/ all comment stuff is part of the name\n }\n }else if( bInQuotesOutsideOfEmail ){\n if( cQuotes == c )\n bInQuotesOutsideOfEmail = false;\n else\n name.append( c );\n }else{\n \/\/ found the end of this addressee ?\n if( ',' == c )\n break;\n \/\/ stuff is behind the trailing '>' ?\n if( iMailEnd ){\n if( cQuotes == c )\n bInQuotesOutsideOfEmail = true; \/\/ start of quoted text found\n else\n name.append( c );\n }else{\n switch( c ){\n case '>':\n iMailEnd = i;\n break;\n case '(':\n if( !name.isEmpty() )\n name.append( ' ' );\n bInComment = true;\n break;\n default:\n if( ' ' != c )\n mail.append( c );\n }\n }\n }\n }\n }\n\n name = name.simplifyWhiteSpace();\n mail = mail.simplifyWhiteSpace();\n\n return ! (name.isEmpty() || mail.isEmpty());\n}\n\nbool KPIM::compareEmail( const QString& email1, const QString& email2,\n bool matchName )\n{\n QString e1Name, e1Email, e2Name, e2Email;\n\n getNameAndMail( email1, e1Name, e1Email );\n getNameAndMail( email2, e2Name, e2Email );\n\n return e1Email == e2Email &&\n ( !matchName || ( e1Name == e2Name ) );\n}\n<|endoftext|>"} {"text":"\/*\n This file is part of libkdepim.\n\n Copyright (c) 2003 Cornelius Schumacher \n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n*\/\n\n#include \"kconfigwizard.h\"\n#include \"kconfigpropagator.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace KPIM;\n\nKConfigWizard::KConfigWizard( QWidget *parent, bool modal )\n : KPageDialog( parent ), mPropagator( 0 ), mChangesPage( 0 )\n{\n setModal( modal );\n init();\n}\n\nKConfigWizard::KConfigWizard( KConfigPropagator *propagator, QWidget *parent,\n bool modal )\n : KPageDialog( parent ), mPropagator( propagator ), mChangesPage( 0 )\n{\n setModal( modal );\n init();\n}\n\nKConfigWizard::~KConfigWizard()\n{\n delete mPropagator;\n}\n\nvoid KConfigWizard::init()\n{\n setFaceType( KPageDialog::Tree );\n setWindowTitle(\n KGlobal::mainComponent().aboutData()->programName().isEmpty()\n ? i18nc( \"@title:window\", \"Configuration Wizard\" )\n : KGlobal::mainComponent().aboutData()->programName() );\n setWindowIcon( KIcon(\"tools-wizard\") );\n setButtons( Ok|Cancel );\n setDefaultButton( Ok );\n\n connect( this, SIGNAL( currentPageChanged(KPageWidgetItem *, KPageWidgetItem * )),\n SLOT( slotAboutToShowPage(KPageWidgetItem *, KPageWidgetItem *) ) );\n connect( this, SIGNAL(okClicked()),\n SLOT( slotOk()));\n QTimer::singleShot( 0, this, SLOT( readConfig() ) );\n}\n\nvoid KConfigWizard::setPropagator( KConfigPropagator *p )\n{\n mPropagator = p;\n}\n\nvoid KConfigWizard::slotAboutToShowPage( KPageWidgetItem *page, KPageWidgetItem * )\n{\n if ( page == mChangesPage ) {\n updateChanges();\n }\n}\n\nQWidget *KConfigWizard::createWizardPage( const QString &title )\n{\n QFrame *page = new QFrame(this);\n addPage( page, title );\n return page;\n}\n\nvoid KConfigWizard::setupRulesPage()\n{\n QFrame *page = new QFrame(this);\n KPageWidgetItem *item = addPage( page, i18nc( \"@title:tab\", \"Rules\" ) );\n item->setHeader( i18nc( \"@title:window\", \"Setup Rules\" ) );\n \/\/TODO: set item icon\n \/\/rame *topFrame = new QFrame( this );\n QVBoxLayout *topLayout = new QVBoxLayout;\n page->setLayout(topLayout);\n mRuleView = new Q3ListView;\n topLayout->addWidget( mRuleView );\n\n mRuleView->addColumn( i18nc( \"@title:column source file,group,entry\", \"Source\" ) );\n mRuleView->addColumn( i18nc( \"@title:column target file,group,entry\", \"Target\" ) );\n mRuleView->addColumn( i18nc( \"@title:column file,group,key,value\", \"Condition\" ) );\n\n updateRules();\n}\n\nvoid KConfigWizard::updateRules()\n{\n if ( !mPropagator ) {\n kError() << \"KConfigWizard: No KConfigPropagator set.\";\n return;\n }\n\n mRuleView->clear();\n\n const KConfigPropagator::Rule::List rules = mPropagator->rules();\n KConfigPropagator::Rule::List::ConstIterator it;\n for ( it = rules.constBegin(); it != rules.constEnd(); ++it ) {\n KConfigPropagator::Rule r = *it;\n QString source = r.sourceFile + '\/' + r.sourceGroup + '\/' +\n r.sourceEntry;\n QString target = r.targetFile + '\/' + r.targetGroup + '\/' +\n r.targetEntry;\n QString condition;\n KConfigPropagator::Condition c = r.condition;\n if ( c.isValid ) {\n condition = c.file + '\/' + c.group + '\/' + c.key + \" = \" + c.value;\n }\n new Q3ListViewItem( mRuleView, source, target, condition );\n }\n}\n\nvoid KConfigWizard::setupChangesPage()\n{\n QFrame *page = new QFrame( this );\n KPageWidgetItem *item = addPage( page, i18nc( \"@title:tab\", \"Changes\" ) );\n item->setHeader( i18nc( \"@title:window\", \"Setup Changes\" ) );\n \/\/TODO: set item icon\n QVBoxLayout *topLayout = new QVBoxLayout;\n page->setLayout(topLayout);\n mChangeView = new Q3ListView;\n topLayout->addWidget( mChangeView );\n\n mChangeView->addColumn( i18nc( \"@title:column change action\", \"Action\" ) );\n mChangeView->addColumn( i18nc( \"@title:column option to change\", \"Option\" ) );\n mChangeView->addColumn( i18nc( \"@title:column value for option\", \"Value\" ) );\n mChangeView->setSorting( -1 );\n\n mChangesPage = item;\n}\n\nvoid KConfigWizard::updateChanges()\n{\n kDebug() << \"KConfigWizard::updateChanges()\";\n\n if ( !mPropagator ) {\n kError() << \"KConfigWizard: No KConfigPropagator set.\";\n return;\n }\n\n usrWriteConfig();\n\n mPropagator->updateChanges();\n\n mChangeView->clear();\n\n KConfigPropagator::Change::List changes = mPropagator->changes();\n KConfigPropagator::Change *c;\n for ( c = changes.first(); c; c = changes.next() ) {\n new Q3ListViewItem( mChangeView, mChangeView->lastItem(), c->title(), c->arg1(), c->arg2() );\n }\n}\n\nvoid KConfigWizard::readConfig()\n{\n kDebug() << \"KConfigWizard::readConfig()\";\n\n setEnabled( false );\n int result = KMessageBox::warningContinueCancel(\n 0,\n i18nc( \"@info\", \"Please make sure that the programs which are \"\n \"configured by the wizard do not run in parallel to the wizard; \"\n \"otherwise, changes done by the wizard could be lost.\" ),\n i18nc( \"@title:window warn about running instances\", \"Warning\" ),\n KGuiItem( i18nc( \"@action:button\", \"Run Wizard Now\" ) ),\n KStandardGuiItem::cancel(), \"warning_running_instances\" );\n if ( result != KMessageBox::Continue ) {\n qApp->quit();\n }\n setEnabled( true );\n\n usrReadConfig();\n}\n\nvoid KConfigWizard::slotOk()\n{\n QString error = validate();\n if ( error.isNull() ) {\n usrWriteConfig();\n\n if ( !mPropagator ) {\n kError() << \"KConfigWizard: No KConfigPropagator set.\";\n return;\n } else {\n if ( mPropagator->skeleton() ) {\n mPropagator->skeleton()->writeConfig();\n }\n mPropagator->commit();\n }\n\n accept();\n } else {\n KMessageBox::sorry( this, error );\n }\n}\n\n#include \"kconfigwizard.moc\"\nGrammar\/*\n This file is part of libkdepim.\n\n Copyright (c) 2003 Cornelius Schumacher \n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n*\/\n\n#include \"kconfigwizard.h\"\n#include \"kconfigpropagator.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace KPIM;\n\nKConfigWizard::KConfigWizard( QWidget *parent, bool modal )\n : KPageDialog( parent ), mPropagator( 0 ), mChangesPage( 0 )\n{\n setModal( modal );\n init();\n}\n\nKConfigWizard::KConfigWizard( KConfigPropagator *propagator, QWidget *parent,\n bool modal )\n : KPageDialog( parent ), mPropagator( propagator ), mChangesPage( 0 )\n{\n setModal( modal );\n init();\n}\n\nKConfigWizard::~KConfigWizard()\n{\n delete mPropagator;\n}\n\nvoid KConfigWizard::init()\n{\n setFaceType( KPageDialog::Tree );\n setWindowTitle(\n KGlobal::mainComponent().aboutData()->programName().isEmpty()\n ? i18nc( \"@title:window\", \"Configuration Wizard\" )\n : KGlobal::mainComponent().aboutData()->programName() );\n setWindowIcon( KIcon(\"tools-wizard\") );\n setButtons( Ok|Cancel );\n setDefaultButton( Ok );\n\n connect( this, SIGNAL( currentPageChanged(KPageWidgetItem *, KPageWidgetItem * )),\n SLOT( slotAboutToShowPage(KPageWidgetItem *, KPageWidgetItem *) ) );\n connect( this, SIGNAL(okClicked()),\n SLOT( slotOk()));\n QTimer::singleShot( 0, this, SLOT( readConfig() ) );\n}\n\nvoid KConfigWizard::setPropagator( KConfigPropagator *p )\n{\n mPropagator = p;\n}\n\nvoid KConfigWizard::slotAboutToShowPage( KPageWidgetItem *page, KPageWidgetItem * )\n{\n if ( page == mChangesPage ) {\n updateChanges();\n }\n}\n\nQWidget *KConfigWizard::createWizardPage( const QString &title )\n{\n QFrame *page = new QFrame(this);\n addPage( page, title );\n return page;\n}\n\nvoid KConfigWizard::setupRulesPage()\n{\n QFrame *page = new QFrame(this);\n KPageWidgetItem *item = addPage( page, i18nc( \"@title:tab\", \"Rules\" ) );\n item->setHeader( i18nc( \"@title:window\", \"Set Up Rules\" ) );\n \/\/TODO: set item icon\n \/\/rame *topFrame = new QFrame( this );\n QVBoxLayout *topLayout = new QVBoxLayout;\n page->setLayout(topLayout);\n mRuleView = new Q3ListView;\n topLayout->addWidget( mRuleView );\n\n mRuleView->addColumn( i18nc( \"@title:column source file,group,entry\", \"Source\" ) );\n mRuleView->addColumn( i18nc( \"@title:column target file,group,entry\", \"Target\" ) );\n mRuleView->addColumn( i18nc( \"@title:column file,group,key,value\", \"Condition\" ) );\n\n updateRules();\n}\n\nvoid KConfigWizard::updateRules()\n{\n if ( !mPropagator ) {\n kError() << \"KConfigWizard: No KConfigPropagator set.\";\n return;\n }\n\n mRuleView->clear();\n\n const KConfigPropagator::Rule::List rules = mPropagator->rules();\n KConfigPropagator::Rule::List::ConstIterator it;\n for ( it = rules.constBegin(); it != rules.constEnd(); ++it ) {\n KConfigPropagator::Rule r = *it;\n QString source = r.sourceFile + '\/' + r.sourceGroup + '\/' +\n r.sourceEntry;\n QString target = r.targetFile + '\/' + r.targetGroup + '\/' +\n r.targetEntry;\n QString condition;\n KConfigPropagator::Condition c = r.condition;\n if ( c.isValid ) {\n condition = c.file + '\/' + c.group + '\/' + c.key + \" = \" + c.value;\n }\n new Q3ListViewItem( mRuleView, source, target, condition );\n }\n}\n\nvoid KConfigWizard::setupChangesPage()\n{\n QFrame *page = new QFrame( this );\n KPageWidgetItem *item = addPage( page, i18nc( \"@title:tab\", \"Changes\" ) );\n item->setHeader( i18nc( \"@title:window\", \"Set Up Changes\" ) );\n \/\/TODO: set item icon\n QVBoxLayout *topLayout = new QVBoxLayout;\n page->setLayout(topLayout);\n mChangeView = new Q3ListView;\n topLayout->addWidget( mChangeView );\n\n mChangeView->addColumn( i18nc( \"@title:column change action\", \"Action\" ) );\n mChangeView->addColumn( i18nc( \"@title:column option to change\", \"Option\" ) );\n mChangeView->addColumn( i18nc( \"@title:column value for option\", \"Value\" ) );\n mChangeView->setSorting( -1 );\n\n mChangesPage = item;\n}\n\nvoid KConfigWizard::updateChanges()\n{\n kDebug() << \"KConfigWizard::updateChanges()\";\n\n if ( !mPropagator ) {\n kError() << \"KConfigWizard: No KConfigPropagator set.\";\n return;\n }\n\n usrWriteConfig();\n\n mPropagator->updateChanges();\n\n mChangeView->clear();\n\n KConfigPropagator::Change::List changes = mPropagator->changes();\n KConfigPropagator::Change *c;\n for ( c = changes.first(); c; c = changes.next() ) {\n new Q3ListViewItem( mChangeView, mChangeView->lastItem(), c->title(), c->arg1(), c->arg2() );\n }\n}\n\nvoid KConfigWizard::readConfig()\n{\n kDebug() << \"KConfigWizard::readConfig()\";\n\n setEnabled( false );\n int result = KMessageBox::warningContinueCancel(\n 0,\n i18nc( \"@info\", \"Please make sure that the programs which are \"\n \"configured by the wizard do not run in parallel to the wizard; \"\n \"otherwise, changes done by the wizard could be lost.\" ),\n i18nc( \"@title:window warn about running instances\", \"Warning\" ),\n KGuiItem( i18nc( \"@action:button\", \"Run Wizard Now\" ) ),\n KStandardGuiItem::cancel(), \"warning_running_instances\" );\n if ( result != KMessageBox::Continue ) {\n qApp->quit();\n }\n setEnabled( true );\n\n usrReadConfig();\n}\n\nvoid KConfigWizard::slotOk()\n{\n QString error = validate();\n if ( error.isNull() ) {\n usrWriteConfig();\n\n if ( !mPropagator ) {\n kError() << \"KConfigWizard: No KConfigPropagator set.\";\n return;\n } else {\n if ( mPropagator->skeleton() ) {\n mPropagator->skeleton()->writeConfig();\n }\n mPropagator->commit();\n }\n\n accept();\n } else {\n KMessageBox::sorry( this, error );\n }\n}\n\n#include \"kconfigwizard.moc\"\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n =========================================================================*\/\n#include \"otbWrapperApplication.h\"\n#include \"otbWrapperApplicationFactory.h\"\n\n#include \"otbPerBandVectorImageFilter.h\"\n#include \"itkDiscreteGaussianImageFilter.h\"\n#include \"itkShrinkImageFilter.h\"\n\n#include \"otbWrapperParameter.h\"\n#include \"otbWrapperOutputImageParameter.h\"\n\nnamespace otb\n{\nnamespace Wrapper\n{\n\nclass MultiResolutionPyramid : public Application\n{\n\npublic:\n \/** Standard class typedefs. *\/\n typedef MultiResolutionPyramid Self;\n typedef Application Superclass;\n typedef itk::SmartPointer Pointer;\n typedef itk::SmartPointer ConstPointer;\n\n \/** Standard macro *\/\n itkNewMacro(Self);\n\n itkTypeMacro(MultiResolutionPyramid, otb::Application);\n\n \/** Image and filters typedef *\/\n typedef itk::DiscreteGaussianImageFilter SmoothingImageFilterType;\n\n typedef otb::PerBandVectorImageFilter SmoothingVectorImageFilterType;\n\n typedef itk::ShrinkImageFilter ShrinkFilterType;\n\nprivate:\n void DoInit()\n {\n SetName(\"MultiResolutionPyramid\");\n SetDescription(\"Build a multi-resolution pyramid of the image.\");\n\n \/\/ Documentation\n SetDocName(\"Multi Resolution Pyramid\");\n SetDocLongDescription(\"This application builds a multi-resolution pyramid of the input image. User can specified the number of levels of the pyramid and the subsampling factor. To speed up the process, you can use the fast scheme option\");\n SetDocLimitations(\"None\");\n SetDocAuthors(\"OTB-Team\");\n SetDocSeeAlso(\" \");\n\n AddDocTag(\"Conversion\");\n AddDocTag(Tags::Manip);\n AddDocTag(Tags::Multi);\n AddDocTag(\"Util\");\n\n AddParameter(ParameterType_InputImage, \"in\", \"Input Image\");\n\n AddParameter(ParameterType_OutputImage, \"out\", \"Output Image\");\n SetParameterDescription(\"out\",\"will be used to get the prefix and the extension of the images to write\");\n\n AddRAMParameter();\n\n AddParameter(ParameterType_Int, \"level\", \"Number Of Levels\");\n SetDefaultParameterInt(\"level\", 1);\n SetParameterDescription( \"level\", \"Number of levels in the pyramid (default is 1).\");\n\n AddParameter(ParameterType_Int, \"sfactor\", \"Subsampling factor\");\n SetDefaultParameterInt(\"sfactor\", 2);\n SetParameterDescription( \"sfactor\", \"Subsampling factor between each level of the pyramid (default is 2).\");\n\n AddParameter(ParameterType_Float, \"vfactor\", \"Variance factor\");\n SetDefaultParameterFloat(\"vfactor\", 0.6);\n SetParameterDescription( \"vfactor\", \"Variance factor use in smoothing. It is multiplied by the subsampling factor of each level in the pyramid (default is 0.6).\");\n\n \/\/ Boolean Fast scheme\n AddParameter(ParameterType_Empty, \"fast\", \"Use Fast Scheme\");\n std::ostringstream desc;\n desc<<\"If used, this option allows to speed-up computation by iteratively\"\n <<\" subsampling previous level of pyramid instead of processing the full input.\";\n SetParameterDescription(\"fast\", desc.str());\n MandatoryOff(\"fast\");\n\n \/\/ Doc example parameter settings\n SetDocExampleParameterValue(\"in\", \"QB_Toulouse_Ortho_XS.tif\");\n SetDocExampleParameterValue(\"out\", \"multiResolutionImage.tif\");\n SetDocExampleParameterValue(\"level\", \"1\");\n SetDocExampleParameterValue(\"sfactor\", \"2\");\n SetDocExampleParameterValue(\"vfactor\", \"0.6\");\n SetDocExampleParameterValue(\"fast\", \"false\");\n }\n\n void DoUpdateParameters()\n {\n \/\/ Nothing to do here for the parameters : all are independent\n\n \/\/ Reinitialize the internal process used\n }\n\n void DoExecute()\n {\n \/\/ Initializing the process\n m_SmoothingFilter = SmoothingVectorImageFilterType::New();\n m_ShrinkFilter = ShrinkFilterType::New();\n\n \/\/ Extract Parameters\n unsigned int nbLevels = GetParameterInt(\"level\");\n unsigned int shrinkFactor = GetParameterInt(\"sfactor\");\n double varianceFactor = GetParameterFloat(\"vfactor\");\n\n bool fastScheme = IsParameterEnabled(\"fast\");\n\n \/\/ Get the input image\n FloatVectorImageType::Pointer inImage = GetParameterImage(\"in\");\n\n \/\/ Get the Initial Output Image FileName\n std::string path, fname, ext;\n std::string ofname = GetParameterString(\"out\");\n\n \/\/ Get the extension and the prefix of the filename\n path = itksys::SystemTools::GetFilenamePath(ofname);\n fname = itksys::SystemTools::GetFilenameWithoutExtension(ofname);\n ext = itksys::SystemTools::GetFilenameExtension(ofname);\n\n unsigned int currentLevel = 1;\n unsigned int currentFactor = shrinkFactor;\n\n while(currentLevel <= nbLevels)\n {\n otbAppLogDEBUG( << \"Processing level \" << currentLevel\n << \" with shrink factor \"<SetInput(inImage);\n\n \/\/ According to\n \/\/ http:\/\/www.ipol.im\/pub\/algo\/gjmr_line_segment_detector\/\n \/\/ This is a good balance between blur and aliasing\n double variance = varianceFactor * static_cast(currentFactor);\n m_SmoothingFilter->GetFilter()->SetVariance(variance);\n\n m_ShrinkFilter->SetInput(m_SmoothingFilter->GetOutput());\n m_ShrinkFilter->SetShrinkFactors(currentFactor);\n\n if(!fastScheme)\n {\n currentFactor *= shrinkFactor;\n }\n else\n {\n std::cout <<\"fast scheme enabled : not implemented for the moment \" << std::endl;\n }\n\n \/\/ Create an output parameter to write the current output image\n OutputImageParameter::Pointer paramOut = OutputImageParameter::New();\n\n \/\/ build the current image filename\n std::ostringstream oss;\n if (!path.empty())\n {\n oss <SetFileName(oss.str());\n paramOut->SetValue(m_ShrinkFilter->GetOutput());\n paramOut->SetPixelType(this->GetParameterOutputImagePixelType(\"out\"));\n \/\/ Add the current level to be written\n paramOut->InitializeWriters();\n AddProcess(paramOut->GetWriter(), osswriter.str());\n paramOut->Write();\n\n ++currentLevel;\n }\n\n \/\/ Disable this parameter since the images have already been produced\n DisableParameter(\"out\");\n }\n\n SmoothingVectorImageFilterType::Pointer m_SmoothingFilter;\n ShrinkFilterType::Pointer m_ShrinkFilter;\n};\n}\n}\n\nOTB_APPLICATION_EXPORT(otb::Wrapper::MultiResolutionPyramid)\nBUG: multiresolution pyramid level parameter must not have negative value. ref mantis #864\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n =========================================================================*\/\n#include \"otbWrapperApplication.h\"\n#include \"otbWrapperApplicationFactory.h\"\n\n#include \"otbPerBandVectorImageFilter.h\"\n#include \"itkDiscreteGaussianImageFilter.h\"\n#include \"itkShrinkImageFilter.h\"\n\n#include \"otbWrapperParameter.h\"\n#include \"otbWrapperOutputImageParameter.h\"\n\nnamespace otb\n{\nnamespace Wrapper\n{\n\nclass MultiResolutionPyramid : public Application\n{\n\npublic:\n \/** Standard class typedefs. *\/\n typedef MultiResolutionPyramid Self;\n typedef Application Superclass;\n typedef itk::SmartPointer Pointer;\n typedef itk::SmartPointer ConstPointer;\n\n \/** Standard macro *\/\n itkNewMacro(Self);\n\n itkTypeMacro(MultiResolutionPyramid, otb::Application);\n\n \/** Image and filters typedef *\/\n typedef itk::DiscreteGaussianImageFilter SmoothingImageFilterType;\n\n typedef otb::PerBandVectorImageFilter SmoothingVectorImageFilterType;\n\n typedef itk::ShrinkImageFilter ShrinkFilterType;\n\nprivate:\n void DoInit()\n {\n SetName(\"MultiResolutionPyramid\");\n SetDescription(\"Build a multi-resolution pyramid of the image.\");\n\n \/\/ Documentation\n SetDocName(\"Multi Resolution Pyramid\");\n SetDocLongDescription(\"This application builds a multi-resolution pyramid of the input image. User can specified the number of levels of the pyramid and the subsampling factor. To speed up the process, you can use the fast scheme option\");\n SetDocLimitations(\"None\");\n SetDocAuthors(\"OTB-Team\");\n SetDocSeeAlso(\" \");\n\n AddDocTag(\"Conversion\");\n AddDocTag(Tags::Manip);\n AddDocTag(Tags::Multi);\n AddDocTag(\"Util\");\n\n AddParameter(ParameterType_InputImage, \"in\", \"Input Image\");\n\n AddParameter(ParameterType_OutputImage, \"out\", \"Output Image\");\n SetParameterDescription(\"out\",\"will be used to get the prefix and the extension of the images to write\");\n\n AddRAMParameter();\n\n AddParameter(ParameterType_Int, \"level\", \"Number Of Levels\");\n SetDefaultParameterInt(\"level\", 1);\n SetParameterDescription( \"level\", \"Number of levels in the pyramid (default is 1).\");\n SetMinimumParameterIntValue(\"level\", 1);\n\n AddParameter(ParameterType_Int, \"sfactor\", \"Subsampling factor\");\n SetDefaultParameterInt(\"sfactor\", 2);\n SetParameterDescription( \"sfactor\", \"Subsampling factor between each level of the pyramid (default is 2).\");\n\n AddParameter(ParameterType_Float, \"vfactor\", \"Variance factor\");\n SetDefaultParameterFloat(\"vfactor\", 0.6);\n SetParameterDescription( \"vfactor\", \"Variance factor use in smoothing. It is multiplied by the subsampling factor of each level in the pyramid (default is 0.6).\");\n\n \/\/ Boolean Fast scheme\n AddParameter(ParameterType_Empty, \"fast\", \"Use Fast Scheme\");\n std::ostringstream desc;\n desc<<\"If used, this option allows to speed-up computation by iteratively\"\n <<\" subsampling previous level of pyramid instead of processing the full input.\";\n SetParameterDescription(\"fast\", desc.str());\n MandatoryOff(\"fast\");\n\n \/\/ Doc example parameter settings\n SetDocExampleParameterValue(\"in\", \"QB_Toulouse_Ortho_XS.tif\");\n SetDocExampleParameterValue(\"out\", \"multiResolutionImage.tif\");\n SetDocExampleParameterValue(\"level\", \"1\");\n SetDocExampleParameterValue(\"sfactor\", \"2\");\n SetDocExampleParameterValue(\"vfactor\", \"0.6\");\n SetDocExampleParameterValue(\"fast\", \"false\");\n }\n\n void DoUpdateParameters()\n {\n \/\/ Nothing to do here for the parameters : all are independent\n\n \/\/ Reinitialize the internal process used\n }\n\n void DoExecute()\n {\n \/\/ Initializing the process\n m_SmoothingFilter = SmoothingVectorImageFilterType::New();\n m_ShrinkFilter = ShrinkFilterType::New();\n\n \/\/ Extract Parameters\n unsigned int nbLevels = GetParameterInt(\"level\");\n unsigned int shrinkFactor = GetParameterInt(\"sfactor\");\n double varianceFactor = GetParameterFloat(\"vfactor\");\n\n bool fastScheme = IsParameterEnabled(\"fast\");\n\n \/\/ Get the input image\n FloatVectorImageType::Pointer inImage = GetParameterImage(\"in\");\n\n \/\/ Get the Initial Output Image FileName\n std::string path, fname, ext;\n std::string ofname = GetParameterString(\"out\");\n\n \/\/ Get the extension and the prefix of the filename\n path = itksys::SystemTools::GetFilenamePath(ofname);\n fname = itksys::SystemTools::GetFilenameWithoutExtension(ofname);\n ext = itksys::SystemTools::GetFilenameExtension(ofname);\n\n unsigned int currentLevel = 1;\n unsigned int currentFactor = shrinkFactor;\n\n while(currentLevel <= nbLevels)\n {\n otbAppLogDEBUG( << \"Processing level \" << currentLevel\n << \" with shrink factor \"<SetInput(inImage);\n\n \/\/ According to\n \/\/ http:\/\/www.ipol.im\/pub\/algo\/gjmr_line_segment_detector\/\n \/\/ This is a good balance between blur and aliasing\n double variance = varianceFactor * static_cast(currentFactor);\n m_SmoothingFilter->GetFilter()->SetVariance(variance);\n\n m_ShrinkFilter->SetInput(m_SmoothingFilter->GetOutput());\n m_ShrinkFilter->SetShrinkFactors(currentFactor);\n\n if(!fastScheme)\n {\n currentFactor *= shrinkFactor;\n }\n else\n {\n std::cout <<\"fast scheme enabled : not implemented for the moment \" << std::endl;\n }\n\n \/\/ Create an output parameter to write the current output image\n OutputImageParameter::Pointer paramOut = OutputImageParameter::New();\n\n \/\/ build the current image filename\n std::ostringstream oss;\n if (!path.empty())\n {\n oss <SetFileName(oss.str());\n paramOut->SetValue(m_ShrinkFilter->GetOutput());\n paramOut->SetPixelType(this->GetParameterOutputImagePixelType(\"out\"));\n \/\/ Add the current level to be written\n paramOut->InitializeWriters();\n AddProcess(paramOut->GetWriter(), osswriter.str());\n paramOut->Write();\n\n ++currentLevel;\n }\n\n \/\/ Disable this parameter since the images have already been produced\n DisableParameter(\"out\");\n }\n\n SmoothingVectorImageFilterType::Pointer m_SmoothingFilter;\n ShrinkFilterType::Pointer m_ShrinkFilter;\n};\n}\n}\n\nOTB_APPLICATION_EXPORT(otb::Wrapper::MultiResolutionPyramid)\n<|endoftext|>"} {"text":"\/*-------------------------------------------------------------------------\n *\n * FILE\n *\tlargeobject.cxx\n *\n * DESCRIPTION\n * Implementation of the Large Objects interface\n * Allows access to large objects directly, or though I\/O streams\n *\n * Copyright (c) 2003-2004, Jeroen T. Vermeulen \n *\n * See COPYING for copyright license. If you did not receive a file called\n * COPYING with this source code, please notify the distributor of this mistake,\n * or contact the author.\n *\n *-------------------------------------------------------------------------\n *\/\n#include \"pqxx\/compiler.h\"\n\n#include \n#include \n\n#include \"libpq\/libpq-fs.h\"\n\n#include \"pqxx\/largeobject\"\n\nusing namespace PGSTD;\nusing namespace pqxx::internal::pq;\n\nnamespace\n{\n\ninline int StdModeToPQMode(ios::openmode mode)\n{\n return ((mode & ios::in) ? INV_READ : 0) |\n ((mode & ios::out) ? INV_WRITE : 0);\n}\n\n\ninline int StdDirToPQDir(ios::seekdir dir) throw ()\n{\n int pqdir;\n switch (dir)\n {\n case ios::beg: pqdir=SEEK_SET; break;\n case ios::cur: pqdir=SEEK_CUR; break;\n case ios::end: pqdir=SEEK_END; break;\n\n \/* Default clause added for two reasons: one, to silence compiler warning\n * about values not handled in switch (due to tackiness in std headers), and\n * two, to help the optimizer recognize implementations where the numerical\n * values of dir and pqdir are always equal.\n *\/\n default: pqdir = dir; break;\n }\n\n return pqdir;\n}\n\n} \/\/ namespace\n\n\npqxx::largeobject::largeobject() throw () :\n m_ID(oid_none)\n{\n}\n\n\npqxx::largeobject::largeobject(dbtransaction &T) :\n m_ID()\n{\n m_ID = lo_creat(RawConnection(T), INV_READ|INV_WRITE);\n if (m_ID == oid_none)\n throw runtime_error(\"Could not create large object: \" +\n\t string(strerror(errno)));\n}\n\n\npqxx::largeobject::largeobject(dbtransaction &T, const string &File) :\n m_ID()\n{\n m_ID = lo_import(RawConnection(T), File.c_str());\n if (m_ID == oid_none)\n {\n const int err = errno;\n throw runtime_error(\"Could not import file '\" + File + \"' \"\n\t \"to large object: \" + strerror(err));\n }\n}\n\n\npqxx::largeobject::largeobject(const largeobjectaccess &O) throw () :\n m_ID(O.id())\n{\n}\n\n\nvoid pqxx::largeobject::to_file(dbtransaction &T, const string &File) const\n{\n if (lo_export(RawConnection(T), id(), File.c_str()) == -1)\n throw runtime_error(\"Could not export large object \" + to_string(m_ID) + \" \"\n\t \"to file '\" + File + \"': \" +\n\t\t\tReason());\n}\n\n\nvoid pqxx::largeobject::remove(dbtransaction &T) const\n{\n if (lo_unlink(RawConnection(T), id()) == -1)\n throw runtime_error(\"Could not delete large object \" + \n\t to_string(m_ID) + \": \" +\n\t\t\tReason());\n}\n\n\nstring pqxx::largeobject::Reason() const\n{\n return (id() == oid_none) ? \"No object selected\" : strerror(errno);\n}\n\n\npqxx::largeobjectaccess::largeobjectaccess(dbtransaction &T, openmode mode) :\n largeobject(T),\n m_Trans(T),\n m_fd(-1)\n{\n open(mode);\n}\n\n\npqxx::largeobjectaccess::largeobjectaccess(dbtransaction &T,\n \t\t\t\t\t oid O,\n\t\t\t\t\t openmode mode) :\n largeobject(O),\n m_Trans(T),\n m_fd(-1)\n{\n open(mode);\n}\n\n\npqxx::largeobjectaccess::largeobjectaccess(dbtransaction &T,\n \t\t\t\t\t largeobject O,\n\t\t\t\t\t openmode mode) :\n largeobject(O),\n m_Trans(T),\n m_fd(-1)\n{\n open(mode);\n}\n\n\npqxx::largeobjectaccess::largeobjectaccess(dbtransaction &T,\n\t\t\t\t\t const string &File,\n\t\t\t\t\t openmode mode) :\n largeobject(T, File),\n m_Trans(T),\n m_fd(-1)\n{\n open(mode);\n}\n\n\npqxx::largeobjectaccess::size_type \npqxx::largeobjectaccess::seek(size_type dest, seekdir dir)\n{\n const size_type Result = cseek(dest, dir);\n if (Result == -1)\n throw runtime_error(\"Error seeking in large object: \" + Reason()); \n\n return Result;\n}\n\n\nlong pqxx::largeobjectaccess::cseek(off_type dest, seekdir dir) throw ()\n{\n return lo_lseek(RawConnection(), m_fd, dest, StdDirToPQDir(dir));\n}\n\n\nlong pqxx::largeobjectaccess::cwrite(const char Buf[], size_type Len) throw ()\n{\n return max(lo_write(RawConnection(), m_fd, const_cast(Buf), Len), -1);\n}\n\n\nlong pqxx::largeobjectaccess::cread(char Buf[], size_type Bytes) throw ()\n{\n return max(lo_read(RawConnection(), m_fd, Buf, Bytes), -1);\n}\n\n\nvoid pqxx::largeobjectaccess::write(const char Buf[], size_type Len)\n{\n const long Bytes = cwrite(Buf, Len);\n if (Bytes < Len)\n {\n if (Bytes < 0)\n throw runtime_error(\"Error writing to large object \"\n \"#\" + to_string(id()) + \": \" +\n\t Reason());\n if (Bytes == 0)\n throw runtime_error(\"Could not write to large object #\" + \n\t to_string(id()) + \": \" + Reason());\n\n throw runtime_error(\"Wanted to write \" + to_string(Len) + \" bytes \"\n\t \"to large object #\" + to_string(id()) + \"; \"\n\t\t\t\"could only write \" + to_string(Bytes));\n }\n}\n\n\npqxx::largeobjectaccess::size_type \npqxx::largeobjectaccess::read(char Buf[], size_type Len)\n{\n const long Bytes = cread(Buf, Len);\n if (Bytes < 0)\n throw runtime_error(\"Error reading from large object #\" + to_string(id()) +\n\t \": \" + Reason());\n return Bytes;\n}\n\n\nvoid pqxx::largeobjectaccess::open(openmode mode)\n{\n m_fd = lo_open(RawConnection(), id(), StdModeToPQMode(mode));\n if (m_fd < 0)\n throw runtime_error(\"Could not open large object \" + to_string(id()) + \":\"\n\t\t\t\" \" + Reason());\n}\n\n\nvoid pqxx::largeobjectaccess::close() throw ()\n{\n if (m_fd >= 0) lo_close(RawConnection(), m_fd);\n}\n\n\nstring pqxx::largeobjectaccess::Reason() const\n{\n return (m_fd == -1) ? \"No object opened\" : largeobject::Reason();\n}\n\n\nvoid pqxx::largeobjectaccess::process_notice(const string &s) throw ()\n{\n m_Trans.process_notice(s);\n}\n\nQualified min()\/max() to catch any regressions of Visual C++ bug\/*-------------------------------------------------------------------------\n *\n * FILE\n *\tlargeobject.cxx\n *\n * DESCRIPTION\n * Implementation of the Large Objects interface\n * Allows access to large objects directly, or though I\/O streams\n *\n * Copyright (c) 2003-2004, Jeroen T. Vermeulen \n *\n * See COPYING for copyright license. If you did not receive a file called\n * COPYING with this source code, please notify the distributor of this mistake,\n * or contact the author.\n *\n *-------------------------------------------------------------------------\n *\/\n#include \"pqxx\/compiler.h\"\n\n#include \n#include \n\n#include \"libpq\/libpq-fs.h\"\n\n#include \"pqxx\/largeobject\"\n\nusing namespace PGSTD;\nusing namespace pqxx::internal::pq;\n\nnamespace\n{\n\ninline int StdModeToPQMode(ios::openmode mode)\n{\n return ((mode & ios::in) ? INV_READ : 0) |\n ((mode & ios::out) ? INV_WRITE : 0);\n}\n\n\ninline int StdDirToPQDir(ios::seekdir dir) throw ()\n{\n int pqdir;\n switch (dir)\n {\n case ios::beg: pqdir=SEEK_SET; break;\n case ios::cur: pqdir=SEEK_CUR; break;\n case ios::end: pqdir=SEEK_END; break;\n\n \/* Default clause added for two reasons: one, to silence compiler warning\n * about values not handled in switch (due to tackiness in std headers), and\n * two, to help the optimizer recognize implementations where the numerical\n * values of dir and pqdir are always equal.\n *\/\n default: pqdir = dir; break;\n }\n\n return pqdir;\n}\n\n} \/\/ namespace\n\n\npqxx::largeobject::largeobject() throw () :\n m_ID(oid_none)\n{\n}\n\n\npqxx::largeobject::largeobject(dbtransaction &T) :\n m_ID()\n{\n m_ID = lo_creat(RawConnection(T), INV_READ|INV_WRITE);\n if (m_ID == oid_none)\n throw runtime_error(\"Could not create large object: \" +\n\t string(strerror(errno)));\n}\n\n\npqxx::largeobject::largeobject(dbtransaction &T, const string &File) :\n m_ID()\n{\n m_ID = lo_import(RawConnection(T), File.c_str());\n if (m_ID == oid_none)\n {\n const int err = errno;\n throw runtime_error(\"Could not import file '\" + File + \"' \"\n\t \"to large object: \" + strerror(err));\n }\n}\n\n\npqxx::largeobject::largeobject(const largeobjectaccess &O) throw () :\n m_ID(O.id())\n{\n}\n\n\nvoid pqxx::largeobject::to_file(dbtransaction &T, const string &File) const\n{\n if (lo_export(RawConnection(T), id(), File.c_str()) == -1)\n throw runtime_error(\"Could not export large object \" + to_string(m_ID) + \" \"\n\t \"to file '\" + File + \"': \" +\n\t\t\tReason());\n}\n\n\nvoid pqxx::largeobject::remove(dbtransaction &T) const\n{\n if (lo_unlink(RawConnection(T), id()) == -1)\n throw runtime_error(\"Could not delete large object \" + \n\t to_string(m_ID) + \": \" +\n\t\t\tReason());\n}\n\n\nstring pqxx::largeobject::Reason() const\n{\n return (id() == oid_none) ? \"No object selected\" : strerror(errno);\n}\n\n\npqxx::largeobjectaccess::largeobjectaccess(dbtransaction &T, openmode mode) :\n largeobject(T),\n m_Trans(T),\n m_fd(-1)\n{\n open(mode);\n}\n\n\npqxx::largeobjectaccess::largeobjectaccess(dbtransaction &T,\n \t\t\t\t\t oid O,\n\t\t\t\t\t openmode mode) :\n largeobject(O),\n m_Trans(T),\n m_fd(-1)\n{\n open(mode);\n}\n\n\npqxx::largeobjectaccess::largeobjectaccess(dbtransaction &T,\n \t\t\t\t\t largeobject O,\n\t\t\t\t\t openmode mode) :\n largeobject(O),\n m_Trans(T),\n m_fd(-1)\n{\n open(mode);\n}\n\n\npqxx::largeobjectaccess::largeobjectaccess(dbtransaction &T,\n\t\t\t\t\t const string &File,\n\t\t\t\t\t openmode mode) :\n largeobject(T, File),\n m_Trans(T),\n m_fd(-1)\n{\n open(mode);\n}\n\n\npqxx::largeobjectaccess::size_type \npqxx::largeobjectaccess::seek(size_type dest, seekdir dir)\n{\n const size_type Result = cseek(dest, dir);\n if (Result == -1)\n throw runtime_error(\"Error seeking in large object: \" + Reason()); \n\n return Result;\n}\n\n\nlong pqxx::largeobjectaccess::cseek(off_type dest, seekdir dir) throw ()\n{\n return lo_lseek(RawConnection(), m_fd, dest, StdDirToPQDir(dir));\n}\n\n\nlong pqxx::largeobjectaccess::cwrite(const char Buf[], size_type Len) throw ()\n{\n return\n PGSTD::max(lo_write(RawConnection(),m_fd,const_cast(Buf), Len), -1);\n}\n\n\nlong pqxx::largeobjectaccess::cread(char Buf[], size_type Bytes) throw ()\n{\n return PGSTD::max(lo_read(RawConnection(), m_fd, Buf, Bytes), -1);\n}\n\n\nvoid pqxx::largeobjectaccess::write(const char Buf[], size_type Len)\n{\n const long Bytes = cwrite(Buf, Len);\n if (Bytes < Len)\n {\n if (Bytes < 0)\n throw runtime_error(\"Error writing to large object \"\n \"#\" + to_string(id()) + \": \" +\n\t Reason());\n if (Bytes == 0)\n throw runtime_error(\"Could not write to large object #\" + \n\t to_string(id()) + \": \" + Reason());\n\n throw runtime_error(\"Wanted to write \" + to_string(Len) + \" bytes \"\n\t \"to large object #\" + to_string(id()) + \"; \"\n\t\t\t\"could only write \" + to_string(Bytes));\n }\n}\n\n\npqxx::largeobjectaccess::size_type \npqxx::largeobjectaccess::read(char Buf[], size_type Len)\n{\n const long Bytes = cread(Buf, Len);\n if (Bytes < 0)\n throw runtime_error(\"Error reading from large object #\" + to_string(id()) +\n\t \": \" + Reason());\n return Bytes;\n}\n\n\nvoid pqxx::largeobjectaccess::open(openmode mode)\n{\n m_fd = lo_open(RawConnection(), id(), StdModeToPQMode(mode));\n if (m_fd < 0)\n throw runtime_error(\"Could not open large object \" + to_string(id()) + \":\"\n\t\t\t\" \" + Reason());\n}\n\n\nvoid pqxx::largeobjectaccess::close() throw ()\n{\n if (m_fd >= 0) lo_close(RawConnection(), m_fd);\n}\n\n\nstring pqxx::largeobjectaccess::Reason() const\n{\n return (m_fd == -1) ? \"No object opened\" : largeobject::Reason();\n}\n\n\nvoid pqxx::largeobjectaccess::process_notice(const string &s) throw ()\n{\n m_Trans.process_notice(s);\n}\n\n<|endoftext|>"} {"text":"\/***************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of libmeegotouch.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n\n#include \n#include \n#include \n#include \n\n#include \n#include \"mcontainer_p.h\"\n#include \n#include \"views\/mcontainerview_p.h\"\n\n#include \"ut_mcontainer.h\"\n#include \"mapplication.h\"\n\n#include \"mcancelevent.h\"\n\nvoid Ut_MContainer::init()\n{\n m_subject = new MContainer();\n}\n\nvoid Ut_MContainer::cleanup()\n{\n delete m_subject;\n m_subject = 0;\n}\nMApplication *app;\n\nvoid Ut_MContainer::initTestCase()\n{\n static int argc = 1;\n static char *app_name[1] = { (char *) \".\/ut_mcontainer\" };\n app = new MApplication(argc, app_name);\n}\n\nvoid Ut_MContainer::cleanupTestCase()\n{\n delete app;\n}\n\nvoid Ut_MContainer::centralWidget()\n{\n \/\/ check that there exists centralWidget\n QVERIFY(m_subject->centralWidget() != NULL);\n}\n\nvoid Ut_MContainer::setCentralWidget()\n{\n MWidget *tmp = new MWidget();\n\n m_subject->setCentralWidget(tmp);\n\n \/\/ check that there exists centralWidget\n QVERIFY(m_subject->centralWidget() == tmp);\n\n delete tmp;\n}\n\nvoid Ut_MContainer::title()\n{\n QString myQString(\"testing title()\");\n\n m_subject->setTitle(myQString);\n QCOMPARE(m_subject->title(), myQString);\n}\n\nvoid Ut_MContainer::text()\n{\n QString myQString(\"testing text()\");\n\n m_subject->setText(myQString);\n QCOMPARE(m_subject->text(), myQString);\n}\n\nvoid Ut_MContainer::iconID()\n{\n QString myIconID(\"testing iconID()\");\n\n m_subject->setIconID(myIconID);\n QCOMPARE(m_subject->iconID(), myIconID);\n}\n\nvoid Ut_MContainer::headerVisible()\n{\n \/\/ default state\n QVERIFY(m_subject->headerVisible() == true);\n\n m_subject->setHeaderVisible(false);\n\n QVERIFY(m_subject->headerVisible() == false);\n}\n\nvoid Ut_MContainer::toggleHeaderVisible()\n{\n \/\/ default state\n QVERIFY(m_subject->headerVisible() == true);\n\n m_subject->toggleHeaderVisible();\n\n QVERIFY(m_subject->headerVisible() == false);\n\n m_subject->toggleHeaderVisible();\n\n QVERIFY(m_subject->headerVisible() == true);\n}\n\n\nvoid Ut_MContainer::toggleProgressIndicatorVisible()\n{\n \/\/ default state\n QVERIFY(m_subject->isProgressIndicatorVisible() == false);\n\n m_subject->toggleProgressIndicatorVisible();\n\n QVERIFY(m_subject->isProgressIndicatorVisible() == true);\n\n m_subject->toggleProgressIndicatorVisible();\n\n QVERIFY(m_subject->isProgressIndicatorVisible() == false);\n}\n\nvoid Ut_MContainer::testCreatingViewImmediatelyInLayout()\n{\n \/\/Add the container to a layout then force the view to be created by calling minimumSize()\n QGraphicsLinearLayout layout(Qt::Horizontal);\n layout.addItem(m_subject);\n m_subject->minimumSize();\n\n}\nvoid Ut_MContainer::testCreatingViewImmediately()\n{\n \/\/Force the view to be created by calling minimumSize()\n \/\/This checks BUG:126088 which causes a segmentation fault\n m_subject->minimumSize();\n}\n\nvoid Ut_MContainer::testCancelEvent()\n{\n QSignalSpy spy(m_subject, SIGNAL(headerClicked()));\n\n QGraphicsSceneMouseEvent mouseEvent(QEvent::GraphicsSceneMousePress);\n m_subject->mousePressEvent(&mouseEvent);\n\n MCancelEvent event;\n m_subject->cancelEvent(&event);\n\n QVERIFY(spy.count() == 0);\n}\n\n\/\/ test all of the set\/get with both visible and invisble header, because it should work for instance\n\/\/ that one sets the e.g. iconID now and makes the header visible later\n\nvoid Ut_MContainer::setTitleWithHeaderVisible()\n{\n m_subject->setHeaderVisible(true);\n m_subject->setTitle(\"title\");\n\n QCOMPARE(m_subject->title(), QString(\"title\"));\n}\n\nvoid Ut_MContainer::setTitleWithHeaderInvisible()\n{\n m_subject->setHeaderVisible(false);\n m_subject->setTitle(\"title\");\n\n QCOMPARE(m_subject->title(), QString(\"title\"));\n}\n\nvoid Ut_MContainer::setIconIDWithHeaderVisible()\n{\n m_subject->setHeaderVisible(true);\n m_subject->setIconID(\"icon-m-framework-close\");\n\n QCOMPARE(m_subject->iconID(), QString(\"icon-m-framework-close\"));\n}\n\nvoid Ut_MContainer::setIconIDWithHeaderInvisible()\n{\n m_subject->setHeaderVisible(false);\n m_subject->setIconID(\"icon-m-framework-close\");\n\n QCOMPARE(m_subject->iconID(), QString(\"icon-m-framework-close\"));\n}\n\nvoid Ut_MContainer::setTextWithHeaderVisible()\n{\n m_subject->setHeaderVisible(true);\n m_subject->setText(\"text\");\n\n QCOMPARE(m_subject->text(), QString(\"text\"));\n}\n\nvoid Ut_MContainer::setTextWithHeaderInvisible()\n{\n m_subject->setHeaderVisible(false);\n m_subject->setText(\"text\");\n\n QCOMPARE(m_subject->text(), QString(\"text\"));\n}\n\nvoid Ut_MContainer::setProgressIndicatorVisible()\n{\n m_subject->setProgressIndicatorVisible(true);\n QCOMPARE(m_subject->isProgressIndicatorVisible(), true);\n}\n\nvoid Ut_MContainer::setProgressIndicatorInVisible()\n{\n m_subject->setProgressIndicatorVisible(false);\n QCOMPARE(m_subject->isProgressIndicatorVisible(), false);\n}\n\nvoid Ut_MContainer::setProgressIndicatorWithHeaderVisible()\n{\n m_subject->setHeaderVisible(true);\n m_subject->setProgressIndicatorVisible(true);\n QCOMPARE(m_subject->isProgressIndicatorVisible(), true);\n}\n\nvoid Ut_MContainer::setProgressIndicatorWithHeaderInvisible()\n{\n m_subject->setHeaderVisible(false);\n m_subject->setProgressIndicatorVisible(true);\n QCOMPARE(m_subject->isProgressIndicatorVisible(), true);\n}\n\n\nQTEST_APPLESS_MAIN(Ut_MContainer)\nFixes: MContainer setCentralWidget unit test.\/***************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of libmeegotouch.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n\n#include \n#include \n#include \n#include \n\n#include \n#include \"mcontainer_p.h\"\n#include \n#include \"views\/mcontainerview_p.h\"\n\n#include \"ut_mcontainer.h\"\n#include \"mapplication.h\"\n\n#include \"mcancelevent.h\"\n\nvoid Ut_MContainer::init()\n{\n m_subject = new MContainer();\n}\n\nvoid Ut_MContainer::cleanup()\n{\n delete m_subject;\n m_subject = 0;\n}\nMApplication *app;\n\nvoid Ut_MContainer::initTestCase()\n{\n static int argc = 1;\n static char *app_name[1] = { (char *) \".\/ut_mcontainer\" };\n app = new MApplication(argc, app_name);\n}\n\nvoid Ut_MContainer::cleanupTestCase()\n{\n delete app;\n}\n\nvoid Ut_MContainer::centralWidget()\n{\n \/\/ check that there exists centralWidget\n QVERIFY(m_subject->centralWidget() != NULL);\n}\n\nvoid Ut_MContainer::setCentralWidget()\n{\n MWidget *tmp = new MWidget();\n\n m_subject->setCentralWidget(tmp);\n\n \/\/ check that there exists centralWidget\n QVERIFY(m_subject->centralWidget() == tmp);\n}\n\nvoid Ut_MContainer::title()\n{\n QString myQString(\"testing title()\");\n\n m_subject->setTitle(myQString);\n QCOMPARE(m_subject->title(), myQString);\n}\n\nvoid Ut_MContainer::text()\n{\n QString myQString(\"testing text()\");\n\n m_subject->setText(myQString);\n QCOMPARE(m_subject->text(), myQString);\n}\n\nvoid Ut_MContainer::iconID()\n{\n QString myIconID(\"testing iconID()\");\n\n m_subject->setIconID(myIconID);\n QCOMPARE(m_subject->iconID(), myIconID);\n}\n\nvoid Ut_MContainer::headerVisible()\n{\n \/\/ default state\n QVERIFY(m_subject->headerVisible() == true);\n\n m_subject->setHeaderVisible(false);\n\n QVERIFY(m_subject->headerVisible() == false);\n}\n\nvoid Ut_MContainer::toggleHeaderVisible()\n{\n \/\/ default state\n QVERIFY(m_subject->headerVisible() == true);\n\n m_subject->toggleHeaderVisible();\n\n QVERIFY(m_subject->headerVisible() == false);\n\n m_subject->toggleHeaderVisible();\n\n QVERIFY(m_subject->headerVisible() == true);\n}\n\n\nvoid Ut_MContainer::toggleProgressIndicatorVisible()\n{\n \/\/ default state\n QVERIFY(m_subject->isProgressIndicatorVisible() == false);\n\n m_subject->toggleProgressIndicatorVisible();\n\n QVERIFY(m_subject->isProgressIndicatorVisible() == true);\n\n m_subject->toggleProgressIndicatorVisible();\n\n QVERIFY(m_subject->isProgressIndicatorVisible() == false);\n}\n\nvoid Ut_MContainer::testCreatingViewImmediatelyInLayout()\n{\n \/\/Add the container to a layout then force the view to be created by calling minimumSize()\n QGraphicsLinearLayout layout(Qt::Horizontal);\n layout.addItem(m_subject);\n m_subject->minimumSize();\n\n}\nvoid Ut_MContainer::testCreatingViewImmediately()\n{\n \/\/Force the view to be created by calling minimumSize()\n \/\/This checks BUG:126088 which causes a segmentation fault\n m_subject->minimumSize();\n}\n\nvoid Ut_MContainer::testCancelEvent()\n{\n QSignalSpy spy(m_subject, SIGNAL(headerClicked()));\n\n QGraphicsSceneMouseEvent mouseEvent(QEvent::GraphicsSceneMousePress);\n m_subject->mousePressEvent(&mouseEvent);\n\n MCancelEvent event;\n m_subject->cancelEvent(&event);\n\n QVERIFY(spy.count() == 0);\n}\n\n\/\/ test all of the set\/get with both visible and invisble header, because it should work for instance\n\/\/ that one sets the e.g. iconID now and makes the header visible later\n\nvoid Ut_MContainer::setTitleWithHeaderVisible()\n{\n m_subject->setHeaderVisible(true);\n m_subject->setTitle(\"title\");\n\n QCOMPARE(m_subject->title(), QString(\"title\"));\n}\n\nvoid Ut_MContainer::setTitleWithHeaderInvisible()\n{\n m_subject->setHeaderVisible(false);\n m_subject->setTitle(\"title\");\n\n QCOMPARE(m_subject->title(), QString(\"title\"));\n}\n\nvoid Ut_MContainer::setIconIDWithHeaderVisible()\n{\n m_subject->setHeaderVisible(true);\n m_subject->setIconID(\"icon-m-framework-close\");\n\n QCOMPARE(m_subject->iconID(), QString(\"icon-m-framework-close\"));\n}\n\nvoid Ut_MContainer::setIconIDWithHeaderInvisible()\n{\n m_subject->setHeaderVisible(false);\n m_subject->setIconID(\"icon-m-framework-close\");\n\n QCOMPARE(m_subject->iconID(), QString(\"icon-m-framework-close\"));\n}\n\nvoid Ut_MContainer::setTextWithHeaderVisible()\n{\n m_subject->setHeaderVisible(true);\n m_subject->setText(\"text\");\n\n QCOMPARE(m_subject->text(), QString(\"text\"));\n}\n\nvoid Ut_MContainer::setTextWithHeaderInvisible()\n{\n m_subject->setHeaderVisible(false);\n m_subject->setText(\"text\");\n\n QCOMPARE(m_subject->text(), QString(\"text\"));\n}\n\nvoid Ut_MContainer::setProgressIndicatorVisible()\n{\n m_subject->setProgressIndicatorVisible(true);\n QCOMPARE(m_subject->isProgressIndicatorVisible(), true);\n}\n\nvoid Ut_MContainer::setProgressIndicatorInVisible()\n{\n m_subject->setProgressIndicatorVisible(false);\n QCOMPARE(m_subject->isProgressIndicatorVisible(), false);\n}\n\nvoid Ut_MContainer::setProgressIndicatorWithHeaderVisible()\n{\n m_subject->setHeaderVisible(true);\n m_subject->setProgressIndicatorVisible(true);\n QCOMPARE(m_subject->isProgressIndicatorVisible(), true);\n}\n\nvoid Ut_MContainer::setProgressIndicatorWithHeaderInvisible()\n{\n m_subject->setHeaderVisible(false);\n m_subject->setProgressIndicatorVisible(true);\n QCOMPARE(m_subject->isProgressIndicatorVisible(), true);\n}\n\n\nQTEST_APPLESS_MAIN(Ut_MContainer)\n<|endoftext|>"} {"text":"\/*\n* This file is part of the PySide project.\n*\n* Copyright (C) 2009-2010 Nokia Corporation and\/or its subsidiary(-ies).\n*\n* Contact: PySide team \n*\n* This library is free software; you can redistribute it and\/or\n* modify it under the terms of the GNU Lesser General Public\n* License as published by the Free Software Foundation; either\n* version 2.1 of the License, or (at your option) any later version.\n*\n* This library is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n* Lesser General Public License for more details.\n*\n* You should have received a copy of the GNU Lesser General Public\n* License along with this library; if not, write to the Free Software\n* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n#include \"signalmanager.h\"\n#include \"pysidesignal.h\"\n#include \"pysideproperty.h\"\n#include \"pysideproperty_p.h\"\n#include \"pyside.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#if QSLOT_CODE != 1 || QSIGNAL_CODE != 2\n#error QSLOT_CODE and\/or QSIGNAL_CODE changed! change the hardcoded stuff to the correct value!\n#endif\n#define PYSIDE_SLOT '1'\n#define PYSIDE_SIGNAL '2'\n#include \"globalreceiver.h\"\n\n#define PYTHON_TYPE \"PyObject\"\n\nnamespace PySide {\n\nstatic int callMethod(QObject* object, int id, void** args);\n\nPyObjectWrapper::PyObjectWrapper()\n :m_me(Py_None)\n{\n Py_INCREF(m_me);\n}\n\nPyObjectWrapper::PyObjectWrapper(PyObject* me)\n : m_me(me)\n{\n Py_INCREF(m_me);\n}\n\nPyObjectWrapper::PyObjectWrapper(const PyObjectWrapper &other)\n : m_me(other.m_me)\n{\n Py_INCREF(m_me);\n}\n\nPyObjectWrapper::~PyObjectWrapper()\n{\n Py_DECREF(m_me);\n}\n\n\nPyObjectWrapper::operator PyObject*() const\n{\n return m_me;\n}\n\n};\n\nnamespace Shiboken {\n\ntemplate<>\nstruct Converter\n{\n static PySide::PyObjectWrapper toCpp(PyObject* obj)\n {\n return PySide::PyObjectWrapper(obj);\n }\n\n static PyObject* toPython(void* obj)\n {\n return toPython(*reinterpret_cast(obj));\n }\n\n static PyObject* toPython(const PySide::PyObjectWrapper& obj)\n {\n Py_INCREF((PyObject*)obj);\n return obj;\n }\n};\n\n};\n\nusing namespace PySide;\n\nstruct SignalManager::SignalManagerPrivate\n{\n GlobalReceiver m_globalReceiver;\n};\n\nstatic void clearSignalManager()\n{\n PySide::SignalManager::instance().clear();\n}\n\nSignalManager::SignalManager() : m_d(new SignalManagerPrivate)\n{\n \/\/ Register Qt primitive typedefs used on signals.\n using namespace Shiboken;\n\n \/\/ Register PyObject type to use in queued signal and slot connections\n qRegisterMetaType(PYTHON_TYPE);\n\n TypeResolver::createValueTypeResolver(PYTHON_TYPE);\n TypeResolver::createValueTypeResolver(\"object\");\n TypeResolver::createValueTypeResolver(\"PySide::PyObjectWrapper\");\n PySide::registerCleanupFunction(clearSignalManager);\n}\n\nvoid SignalManager::clear()\n{\n delete m_d;\n m_d = new SignalManagerPrivate();\n}\n\nSignalManager::~SignalManager()\n{\n delete m_d;\n}\n\nSignalManager& SignalManager::instance()\n{\n static SignalManager me;\n return me;\n}\n\nQObject* SignalManager::globalReceiver()\n{\n return &m_d->m_globalReceiver;\n}\n\nvoid SignalManager::globalReceiverConnectNotify(QObject* source, int slotIndex)\n{\n m_d->m_globalReceiver.connectNotify(source, slotIndex);\n}\n\nvoid SignalManager::globalReceiverDisconnectNotify(QObject* source, int slotIndex)\n{\n m_d->m_globalReceiver.disconnectNotify(source, slotIndex);\n}\n\nvoid SignalManager::addGlobalSlot(const char* slot, PyObject* callback)\n{\n m_d->m_globalReceiver.addSlot(slot, callback);\n}\n\nstatic bool emitShortCircuitSignal(QObject* source, int signalIndex, PyObject* args)\n{\n void* signalArgs[2] = {0, args};\n QMetaObject::activate(source, signalIndex, signalArgs);\n return true;\n}\n\nstatic bool emitNormalSignal(QObject* source, int signalIndex, const char* signal, PyObject* args, const QStringList& argTypes)\n{\n Shiboken::AutoDecRef sequence(PySequence_Fast(args, 0));\n int argsGiven = PySequence_Fast_GET_SIZE(sequence.object());\n if (argsGiven > argTypes.count()) {\n PyErr_Format(PyExc_TypeError, \"%s only accepts %d arguments, %d given!\", signal, argTypes.count(), argsGiven);\n return false;\n }\n\n void** signalArgs = new void*[argsGiven+1];\n void** signalValues = new void*[argsGiven];\n signalArgs[0] = 0;\n\n int i;\n for (i = 0; i < argsGiven; ++i) {\n Shiboken::TypeResolver* typeResolver = Shiboken::TypeResolver::get(qPrintable(argTypes[i]));\n if (typeResolver) {\n typeResolver->toCpp(PySequence_Fast_GET_ITEM(sequence.object(), i), &signalValues[i], true);\n if (Shiboken::TypeResolver::getType(qPrintable(argTypes[i])) == Shiboken::TypeResolver::ObjectType)\n signalArgs[i+1] = &signalValues[i];\n else\n signalArgs[i+1] = signalValues[i];\n } else {\n PyErr_Format(PyExc_TypeError, \"Unknown type used to emit a signal: %s\", qPrintable(argTypes[i]));\n break;\n }\n }\n\n bool ok = i == argsGiven;\n if (ok)\n QMetaObject::activate(source, signalIndex, signalArgs);\n\n \/\/cleanup memory\n for (int j = 0; j < i; ++j)\n Shiboken::TypeResolver::get(qPrintable(argTypes[j]))->deleteObject(signalArgs[j+1]);\n\n delete[] signalArgs;\n delete[] signalValues;\n\n return ok;\n}\n\nbool SignalManager::emitSignal(QObject* source, const char* signal, PyObject* args)\n{\n if (!Signal::checkQtSignal(signal))\n return false;\n signal++;\n\n int signalIndex = source->metaObject()->indexOfSignal(signal);\n if (signalIndex != -1) {\n bool isShortCircuit;\n QStringList argTypes = Signal::getArgsFromSignature(signal, &isShortCircuit);\n\n if (isShortCircuit)\n return emitShortCircuitSignal(source, signalIndex, args);\n else\n return emitNormalSignal(source, signalIndex, signal, args, argTypes);\n }\n return false;\n}\n\nint SignalManager::qt_metacall(QObject* object, QMetaObject::Call call, int id, void** args)\n{\n const QMetaObject* metaObject = object->metaObject();\n PySideProperty* pp = 0;\n PyObject* pp_name = 0;\n QMetaProperty mp;\n Shiboken::TypeResolver* typeResolver = 0;\n PyObject* pySelf = 0;\n\n if (call != QMetaObject::InvokeMetaMethod) {\n mp = metaObject->property(id);\n if (!mp.isValid())\n return id - metaObject->methodCount();\n\n Shiboken::GilState gil;\n pySelf = Shiboken::BindingManager::instance().retrieveWrapper(object);\n Q_ASSERT(pySelf);\n pp_name = PyString_FromString(mp.name());\n pp = Property::getObject(pySelf, pp_name);\n if (!pp) {\n qWarning(\"Invalid property.\");\n Py_XDECREF(pp_name);\n return id - metaObject->methodCount();\n }\n typeResolver = Shiboken::TypeResolver::get(mp.typeName());\n Q_ASSERT(typeResolver);\n }\n\n switch(call) {\n#ifndef QT_NO_PROPERTIES\n case QMetaObject::ReadProperty:\n {\n Shiboken::GilState gil;\n PyObject* value = Property::getValue(pp, pySelf);\n if (value) {\n typeResolver->toCpp(value, &args[0]);\n Py_DECREF(value);\n } else if (PyErr_Occurred()) {\n PyErr_Print(); \/\/ Clear any errors but print them to stderr\n }\n break;\n }\n\n case QMetaObject::WriteProperty:\n {\n Shiboken::GilState gil;\n Shiboken::AutoDecRef value(typeResolver->toPython(args[0]));\n Property::setValue(pp, pySelf, value);\n break;\n }\n\n case QMetaObject::ResetProperty:\n {\n Shiboken::GilState gil;\n Property::reset(pp, pp_name);\n break;\n }\n\n case QMetaObject::QueryPropertyDesignable:\n case QMetaObject::QueryPropertyScriptable:\n case QMetaObject::QueryPropertyStored:\n case QMetaObject::QueryPropertyEditable:\n case QMetaObject::QueryPropertyUser:\n break;\n#endif\n case QMetaObject::InvokeMetaMethod:\n id = callMethod(object, id, args);\n break;\n\n default:\n qWarning(\"Unsupported meta invocation type.\");\n }\n\n if (call == QMetaObject::InvokeMetaMethod)\n id = id - metaObject->methodCount();\n else\n id = id - metaObject->propertyCount();\n\n if (pp || pp_name) {\n Shiboken::GilState gil;\n Py_XDECREF(pp);\n Py_XDECREF(pp_name);\n }\n return id;\n}\n\nstatic int PySide::callMethod(QObject* object, int id, void** args)\n{\n const QMetaObject* metaObject = object->metaObject();\n QMetaMethod method = metaObject->method(id);\n\n if (method.methodType() == QMetaMethod::Signal) {\n \/\/ emit python signal\n QMetaObject::activate(object, id, args);\n } else {\n \/\/ call python slot\n Shiboken::GilState gil;\n QList paramTypes = method.parameterTypes();\n PyObject* self = Shiboken::BindingManager::instance().retrieveWrapper(object);\n PyObject* preparedArgs = NULL;\n Py_ssize_t args_size = paramTypes.count();\n\n if (args_size)\n preparedArgs = PyTuple_New(args_size);\n\n for (int i = 0, max = paramTypes.count(); i < max; ++i) {\n void* data = args[i+1];\n const char* dataType = paramTypes[i].constData();\n\n PyObject* arg = Shiboken::TypeResolver::get(dataType)->toPython(data);\n PyTuple_SET_ITEM(preparedArgs, i, arg);\n }\n\n QString methodName = method.signature();\n methodName = methodName.left(methodName.indexOf('('));\n\n Shiboken::AutoDecRef pyMethod(PyObject_GetAttrString(self, qPrintable(methodName)));\n if (!pyMethod.isNull()) {\n Shiboken::AutoDecRef retval(PyObject_CallObject(pyMethod, preparedArgs));\n if (retval.isNull()) {\n qWarning() << \"Error calling slot\" << methodName;\n PyErr_Print();\n }\n } else {\n qWarning() << \"Dynamic slot\" << methodName << \"not found!\";\n }\n Py_XDECREF(preparedArgs);\n }\n return -1;\n}\n\nbool SignalManager::registerMetaMethod(QObject* source, const char* signature, QMetaMethod::MethodType type)\n{\n Q_ASSERT(source);\n const QMetaObject* metaObject = source->metaObject();\n int methodIndex = metaObject->indexOfMethod(signature);\n \/\/ Create the dynamic signal is needed\n if (methodIndex == -1) {\n Shiboken::SbkBaseWrapper* self = (Shiboken::SbkBaseWrapper*) Shiboken::BindingManager::instance().retrieveWrapper(source);\n if (!self->containsCppWrapper) {\n qWarning() << \"Invalid Signal signature:\" << signature;\n return false;\n } else {\n PySide::DynamicQMetaObject* dynMetaObj = reinterpret_cast(const_cast(metaObject));\n if (type == QMetaMethod::Signal)\n dynMetaObj->addSignal(signature);\n else\n dynMetaObj->addSlot(signature);\n }\n }\n return true;\n}\n\nbool SignalManager::hasConnectionWith(const QObject *object)\n{\n return m_d->m_globalReceiver.hasConnectionWith(object);\n}\nFill the argument used on metacall for slot functions.\/*\n* This file is part of the PySide project.\n*\n* Copyright (C) 2009-2010 Nokia Corporation and\/or its subsidiary(-ies).\n*\n* Contact: PySide team \n*\n* This library is free software; you can redistribute it and\/or\n* modify it under the terms of the GNU Lesser General Public\n* License as published by the Free Software Foundation; either\n* version 2.1 of the License, or (at your option) any later version.\n*\n* This library is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n* Lesser General Public License for more details.\n*\n* You should have received a copy of the GNU Lesser General Public\n* License along with this library; if not, write to the Free Software\n* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n#include \"signalmanager.h\"\n#include \"pysidesignal.h\"\n#include \"pysideproperty.h\"\n#include \"pysideproperty_p.h\"\n#include \"pyside.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#if QSLOT_CODE != 1 || QSIGNAL_CODE != 2\n#error QSLOT_CODE and\/or QSIGNAL_CODE changed! change the hardcoded stuff to the correct value!\n#endif\n#define PYSIDE_SLOT '1'\n#define PYSIDE_SIGNAL '2'\n#include \"globalreceiver.h\"\n\n#define PYTHON_TYPE \"PyObject\"\n\nnamespace PySide {\n\nstatic int callMethod(QObject* object, int id, void** args);\n\nPyObjectWrapper::PyObjectWrapper()\n :m_me(Py_None)\n{\n Py_INCREF(m_me);\n}\n\nPyObjectWrapper::PyObjectWrapper(PyObject* me)\n : m_me(me)\n{\n Py_INCREF(m_me);\n}\n\nPyObjectWrapper::PyObjectWrapper(const PyObjectWrapper &other)\n : m_me(other.m_me)\n{\n Py_INCREF(m_me);\n}\n\nPyObjectWrapper::~PyObjectWrapper()\n{\n Py_DECREF(m_me);\n}\n\n\nPyObjectWrapper::operator PyObject*() const\n{\n return m_me;\n}\n\n};\n\nnamespace Shiboken {\n\ntemplate<>\nstruct Converter\n{\n static PySide::PyObjectWrapper toCpp(PyObject* obj)\n {\n return PySide::PyObjectWrapper(obj);\n }\n\n static PyObject* toPython(void* obj)\n {\n return toPython(*reinterpret_cast(obj));\n }\n\n static PyObject* toPython(const PySide::PyObjectWrapper& obj)\n {\n Py_INCREF((PyObject*)obj);\n return obj;\n }\n};\n\n};\n\nusing namespace PySide;\n\nstruct SignalManager::SignalManagerPrivate\n{\n GlobalReceiver m_globalReceiver;\n};\n\nstatic void clearSignalManager()\n{\n PySide::SignalManager::instance().clear();\n}\n\nSignalManager::SignalManager() : m_d(new SignalManagerPrivate)\n{\n \/\/ Register Qt primitive typedefs used on signals.\n using namespace Shiboken;\n\n \/\/ Register PyObject type to use in queued signal and slot connections\n qRegisterMetaType(PYTHON_TYPE);\n\n TypeResolver::createValueTypeResolver(PYTHON_TYPE);\n TypeResolver::createValueTypeResolver(\"object\");\n TypeResolver::createValueTypeResolver(\"PySide::PyObjectWrapper\");\n PySide::registerCleanupFunction(clearSignalManager);\n}\n\nvoid SignalManager::clear()\n{\n delete m_d;\n m_d = new SignalManagerPrivate();\n}\n\nSignalManager::~SignalManager()\n{\n delete m_d;\n}\n\nSignalManager& SignalManager::instance()\n{\n static SignalManager me;\n return me;\n}\n\nQObject* SignalManager::globalReceiver()\n{\n return &m_d->m_globalReceiver;\n}\n\nvoid SignalManager::globalReceiverConnectNotify(QObject* source, int slotIndex)\n{\n m_d->m_globalReceiver.connectNotify(source, slotIndex);\n}\n\nvoid SignalManager::globalReceiverDisconnectNotify(QObject* source, int slotIndex)\n{\n m_d->m_globalReceiver.disconnectNotify(source, slotIndex);\n}\n\nvoid SignalManager::addGlobalSlot(const char* slot, PyObject* callback)\n{\n m_d->m_globalReceiver.addSlot(slot, callback);\n}\n\nstatic bool emitShortCircuitSignal(QObject* source, int signalIndex, PyObject* args)\n{\n void* signalArgs[2] = {0, args};\n QMetaObject::activate(source, signalIndex, signalArgs);\n return true;\n}\n\nstatic bool emitNormalSignal(QObject* source, int signalIndex, const char* signal, PyObject* args, const QStringList& argTypes)\n{\n Shiboken::AutoDecRef sequence(PySequence_Fast(args, 0));\n int argsGiven = PySequence_Fast_GET_SIZE(sequence.object());\n if (argsGiven > argTypes.count()) {\n PyErr_Format(PyExc_TypeError, \"%s only accepts %d arguments, %d given!\", signal, argTypes.count(), argsGiven);\n return false;\n }\n\n void** signalArgs = new void*[argsGiven+1];\n void** signalValues = new void*[argsGiven];\n signalArgs[0] = 0;\n\n int i;\n for (i = 0; i < argsGiven; ++i) {\n Shiboken::TypeResolver* typeResolver = Shiboken::TypeResolver::get(qPrintable(argTypes[i]));\n if (typeResolver) {\n typeResolver->toCpp(PySequence_Fast_GET_ITEM(sequence.object(), i), &signalValues[i], true);\n if (Shiboken::TypeResolver::getType(qPrintable(argTypes[i])) == Shiboken::TypeResolver::ObjectType)\n signalArgs[i+1] = &signalValues[i];\n else\n signalArgs[i+1] = signalValues[i];\n } else {\n PyErr_Format(PyExc_TypeError, \"Unknown type used to emit a signal: %s\", qPrintable(argTypes[i]));\n break;\n }\n }\n\n bool ok = i == argsGiven;\n if (ok)\n QMetaObject::activate(source, signalIndex, signalArgs);\n\n \/\/cleanup memory\n for (int j = 0; j < i; ++j)\n Shiboken::TypeResolver::get(qPrintable(argTypes[j]))->deleteObject(signalArgs[j+1]);\n\n delete[] signalArgs;\n delete[] signalValues;\n\n return ok;\n}\n\nbool SignalManager::emitSignal(QObject* source, const char* signal, PyObject* args)\n{\n if (!Signal::checkQtSignal(signal))\n return false;\n signal++;\n\n int signalIndex = source->metaObject()->indexOfSignal(signal);\n if (signalIndex != -1) {\n bool isShortCircuit;\n QStringList argTypes = Signal::getArgsFromSignature(signal, &isShortCircuit);\n\n if (isShortCircuit)\n return emitShortCircuitSignal(source, signalIndex, args);\n else\n return emitNormalSignal(source, signalIndex, signal, args, argTypes);\n }\n return false;\n}\n\nint SignalManager::qt_metacall(QObject* object, QMetaObject::Call call, int id, void** args)\n{\n const QMetaObject* metaObject = object->metaObject();\n PySideProperty* pp = 0;\n PyObject* pp_name = 0;\n QMetaProperty mp;\n Shiboken::TypeResolver* typeResolver = 0;\n PyObject* pySelf = 0;\n\n if (call != QMetaObject::InvokeMetaMethod) {\n mp = metaObject->property(id);\n if (!mp.isValid())\n return id - metaObject->methodCount();\n\n Shiboken::GilState gil;\n pySelf = Shiboken::BindingManager::instance().retrieveWrapper(object);\n Q_ASSERT(pySelf);\n pp_name = PyString_FromString(mp.name());\n pp = Property::getObject(pySelf, pp_name);\n if (!pp) {\n qWarning(\"Invalid property.\");\n Py_XDECREF(pp_name);\n return id - metaObject->methodCount();\n }\n typeResolver = Shiboken::TypeResolver::get(mp.typeName());\n Q_ASSERT(typeResolver);\n }\n\n switch(call) {\n#ifndef QT_NO_PROPERTIES\n case QMetaObject::ReadProperty:\n {\n Shiboken::GilState gil;\n PyObject* value = Property::getValue(pp, pySelf);\n if (value) {\n typeResolver->toCpp(value, &args[0]);\n Py_DECREF(value);\n } else if (PyErr_Occurred()) {\n PyErr_Print(); \/\/ Clear any errors but print them to stderr\n }\n break;\n }\n\n case QMetaObject::WriteProperty:\n {\n Shiboken::GilState gil;\n Shiboken::AutoDecRef value(typeResolver->toPython(args[0]));\n Property::setValue(pp, pySelf, value);\n break;\n }\n\n case QMetaObject::ResetProperty:\n {\n Shiboken::GilState gil;\n Property::reset(pp, pp_name);\n break;\n }\n\n case QMetaObject::QueryPropertyDesignable:\n case QMetaObject::QueryPropertyScriptable:\n case QMetaObject::QueryPropertyStored:\n case QMetaObject::QueryPropertyEditable:\n case QMetaObject::QueryPropertyUser:\n break;\n#endif\n case QMetaObject::InvokeMetaMethod:\n id = callMethod(object, id, args);\n break;\n\n default:\n qWarning(\"Unsupported meta invocation type.\");\n }\n\n if (call == QMetaObject::InvokeMetaMethod)\n id = id - metaObject->methodCount();\n else\n id = id - metaObject->propertyCount();\n\n if (pp || pp_name) {\n Shiboken::GilState gil;\n Py_XDECREF(pp);\n Py_XDECREF(pp_name);\n }\n return id;\n}\n\nstatic int PySide::callMethod(QObject* object, int id, void** args)\n{\n const QMetaObject* metaObject = object->metaObject();\n QMetaMethod method = metaObject->method(id);\n\n if (method.methodType() == QMetaMethod::Signal) {\n \/\/ emit python signal\n QMetaObject::activate(object, id, args);\n } else {\n \/\/ call python slot\n Shiboken::GilState gil;\n QList paramTypes = method.parameterTypes();\n PyObject* self = Shiboken::BindingManager::instance().retrieveWrapper(object);\n PyObject* preparedArgs = NULL;\n Py_ssize_t args_size = paramTypes.count();\n\n if (args_size)\n preparedArgs = PyTuple_New(args_size);\n\n for (int i = 0, max = paramTypes.count(); i < max; ++i) {\n void* data = args[i+1];\n const char* dataType = paramTypes[i].constData();\n\n PyObject* arg = Shiboken::TypeResolver::get(dataType)->toPython(data);\n PyTuple_SET_ITEM(preparedArgs, i, arg);\n }\n\n QString methodName = method.signature();\n methodName = methodName.left(methodName.indexOf('('));\n\n Shiboken::AutoDecRef pyMethod(PyObject_GetAttrString(self, qPrintable(methodName)));\n if (!pyMethod.isNull()) {\n Shiboken::AutoDecRef retval(PyObject_CallObject(pyMethod, preparedArgs));\n if (retval.isNull()) {\n qWarning() << \"Error calling slot\" << methodName;\n PyErr_Print();\n } else {\n const char* returnType = method.typeName();\n if (returnType && (strlen(returnType) > 0))\n Shiboken::TypeResolver::get(returnType)->toCpp(retval, &args[0]);\n }\n } else {\n qWarning() << \"Dynamic slot\" << methodName << \"not found!\";\n }\n Py_XDECREF(preparedArgs);\n }\n return -1;\n}\n\nbool SignalManager::registerMetaMethod(QObject* source, const char* signature, QMetaMethod::MethodType type)\n{\n Q_ASSERT(source);\n const QMetaObject* metaObject = source->metaObject();\n int methodIndex = metaObject->indexOfMethod(signature);\n \/\/ Create the dynamic signal is needed\n if (methodIndex == -1) {\n Shiboken::SbkBaseWrapper* self = (Shiboken::SbkBaseWrapper*) Shiboken::BindingManager::instance().retrieveWrapper(source);\n if (!self->containsCppWrapper) {\n qWarning() << \"Invalid Signal signature:\" << signature;\n return false;\n } else {\n PySide::DynamicQMetaObject* dynMetaObj = reinterpret_cast(const_cast(metaObject));\n if (type == QMetaMethod::Signal)\n dynMetaObj->addSignal(signature);\n else\n dynMetaObj->addSlot(signature);\n }\n }\n return true;\n}\n\nbool SignalManager::hasConnectionWith(const QObject *object)\n{\n return m_d->m_globalReceiver.hasConnectionWith(object);\n}\n<|endoftext|>"} {"text":"\/\/ The K3 Runtime Collections Library.\n\/\/\n\/\/ This file contains definitions for the various operations performed on K3 collections, used by\n\/\/ the generated C++ code. The C++ realizations of K3 Collections will inherit from the\n\/\/ K3::Collection class, providing a suitable content type.\n\/\/\n\/\/ TODO:\n\/\/ - Use routines to perform collection transformations? In particular, investigate\n\/\/ order-of-operations semantics.\n\/\/ - Use container agnostic mutation operations?\n\/\/ - Use bulk mutation operations (iterator-based insertion, for example)?\n\/\/ - Optimize all the unnecessary copies, using std::move?\n#ifndef K3_RUNTIME_COLLECTIONS_H\n#define K3_RUNTIME_COLLECTIONS_H\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace K3 {\n template